defmodule ApiBridge do @moduledoc """ Module for rpc call remote api@node functions. """ @defualt_rpc_timeout 3000 @doc """ rpc macro for api call """ defmacro rpc(exp, timeout \\ @defualt_rpc_timeout) do rpc_node = rpc_nodename('api') {{:., _, [module, function]}, _, args} = exp quote do :rpc.call(unquote(rpc_node), unquote(module), unquote(function), unquote(args), unquote(timeout)) end end @doc """ rpc macro for api call, throw RuntimeError if {:error, _} returned. """ defmacro rpc!(exp, timeout \\ @defualt_rpc_timeout) do rpc_node = rpc_nodename('api') {{:., _, [module, function]}, _, args} = exp quote do case :rpc.call(unquote(rpc_node), unquote(module), unquote(function), unquote(args), unquote(timeout)) do {:ok, result} -> result {:error, reason} -> raise "rpc #{unquote(module)}:#{unquote(function)}/#{unquote(length(args))} error: #{reason}" end end end # priv @doc """ > config :server, ApiBridge, rpc_node: "127.0.0.1" """ defp config(key) do Application.get_env(:server, ApiBridge)[key] end @doc """ return a rpc node name with prefix, use eth0 ip if rpc_node not exist """ defp rpc_nodename(prefix) do str_ip = case config(:rpc_node) do nil -> {:ok, [{:addr, tmp_ip}]} = :inet.ifget('eth0', [:addr]); :inet_parse.ntoa(tmp_ip) conf_ip -> conf_ip end String.to_atom(to_string(prefix) <> "@" <> to_string(str_ip)) end end