application.ex 1.51 KB
Newer Older
1
defmodule FastHtml.Application do
2
  @moduledoc false
Lukas Rieder's avatar
Lukas Rieder committed
3 4 5

  use Application

6
  def random_sname, do: :crypto.strong_rand_bytes(4) |> Base.encode16(case: :lower)
7

Lukas Rieder's avatar
Lukas Rieder committed
8
  def start(_type, _args) do
9 10 11
    case maybe_setup_node() do
      {:error, message} -> raise message
      _ -> :ok
Lukas Rieder's avatar
Lukas Rieder committed
12
    end
rinpatch's avatar
rinpatch committed
13

14
    Supervisor.start_link([FastHtml.Cnode], strategy: :one_for_one, name: FastHtml.Supervisor)
Lukas Rieder's avatar
Lukas Rieder committed
15
  end
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

  defp maybe_setup_node() do
    with {_, false} <- {:alive, Node.alive?()},
         {:ok, epmd_path} <- find_epmd(),
         :ok <- start_epmd(epmd_path),
         {:ok, _pid} = pid_tuple <- start_node() do
      pid_tuple
    else
      {:alive, _} ->
        :ok

      {:error, _} = e ->
        e
    end
  end

  defp find_epmd() do
    case System.find_executable("epmd") do
      nil ->
        {:error,
         "Could not find epmd executable. Please ensure the location it's in is present in your PATH or start epmd manually beforehand"}

      executable ->
        {:ok, executable}
    end
  end

  defp start_epmd(path) do
    case System.cmd(path, ["-daemon"]) do
45 46
      {_result, 0} -> :ok
      {_result, exit_code} -> {:error, "Could not start epmd, exit code: #{exit_code}"}
47 48 49
    end
  end

50 51 52 53 54 55 56 57 58 59 60 61
  defp hostname() do
    {:ok, ifaddrs} = :inet.getifaddrs()

    ifaddrs
    |> Enum.filter(fn {_name, value} -> :loopback in Keyword.get(value, :flags) end)
    |> Enum.at(0)
    |> elem(1)
    |> Keyword.get(:addr)
    |> :inet.ntoa()
    |> to_string()
  end

62
  defp start_node() do
63
    Node.start(:"master_#{random_sname()}@#{hostname()}")
64
  end
Lukas Rieder's avatar
Lukas Rieder committed
65
end