defmodule HAHandler.DRBD.Watcher do # TODO: add support for SSH public keys authentication. use GenServer require Logger def start_link(opts) do GenServer.start_link(__MODULE__, opts) end defp connect(hostname, password) do case :inet.gethostbyname(to_charlist(hostname), :inet6) do {:ok, {:hostent, _name, _aliases, _addrtype, _length, [addr]}} -> SSHEx.connect( ip: addr, user: 'root', password: password, silently_accept_hosts: true ) err -> err end end @impl true def init(opts) do hostname = Keyword.get(opts, :hostname) password = Keyword.get(opts, :password) case connect(hostname, password) do {:ok, pid} -> state = %{ backend: pid, hostname: hostname, password: password } {:ok, state} {:error, err} -> # Wait for 10 seconds so that the supervisor does not loop on dead node # (and reach the max_restart threshold / stop trying). Process.sleep(10_000) {:error, err} end end @impl true def handle_call({:execute, cmd}, _from, %{backend: backend} = state) do case SSHEx.run(backend, cmd) do {:ok, _output, _status} = reply-> {:reply, reply, state} {:error, _err} = reply -> {:error, reply, state} end end end