Skip to content

Commit

Permalink
Example of parallel remote tasks
Browse files Browse the repository at this point in the history
  • Loading branch information
pmeinhardt committed Dec 15, 2020
1 parent 55827b8 commit 9051dca
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
53 changes: 53 additions & 0 deletions examples/parallel.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
defaults = [user: "deploy", password: "deploy", silently_accept_hosts: true]

hosts =
[{"127.0.0.1", port: 2222}, {"127.0.0.1", port: 2223}]
|> Enum.map(fn {name, options} -> {name, Keyword.merge(defaults, options)} end)

conns = Enum.map(hosts, fn {name, options} ->
{:ok, conn} = SSHKit.connect(name, options)
conn
end)

label = fn conn -> Enum.join([conn.host, conn.port], ":") end

tasks =
Enum.map(conns, fn conn ->
Task.async(fn ->
{:ok, chan} = SSHKit.run(conn, "uptime")

chan
|> SSHKit.stream()
|> Enum.reduce(nil, fn
{:stdout, chan, output}, acc ->
IO.write("[#{label.(chan.connection)}] (stdout) #{output}")
acc

{:stderr, chan, output}, acc ->
IO.write("[#{label.(chan.connection)}] (stderr) #{output}")
acc

{:exit, _, status}, _ ->
status

_, acc ->
acc
end)
end)
end)

okay? = fn status -> status == 0 end

results = Enum.map(tasks, &Task.await/1)

unless Enum.all?(results, okay?) do
results
|> Enum.with_index()
|> Enum.filter(fn {status, _} -> !okay?.(status) end)
|> Enum.each(fn {status, index} ->
conn = Enum.at(conns, index)
IO.puts("[#{label.(conn)}] exited with status #{status}")
end)
end

:ok = Enum.each(conns, &SSHKit.close/1)
2 changes: 0 additions & 2 deletions examples/stream.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# TODO: Multiple hosts?

{:ok, conn} = SSHKit.connect("127.0.0.1", port: 2222, user: "deploy", password: "deploy", silently_accept_hosts: true)

{:ok, chan} = SSHKit.run(conn, ~S(echo "Who's there?"; read name; echo "Hello $name"))
Expand Down

0 comments on commit 9051dca

Please sign in to comment.