defmodule Kvasir.AgentServer.Command.Handler do alias Kvasir.AgentServer.Metrics import Kvasir.AgentServer.Util, only: [recommended_listener_config: 1] @spec child_spec(Keyword.t()) :: :supervisor.child_spec() def child_spec(opts \\ []) do agent = opts[:agent] || raise "Command handlers need to be given a agent." port = opts[:port] || agent.opts[:port] || raise "Command handlers need to be given a port." id = opts[:id] || make_ref() config = recommended_listener_config(port: port) metrics = agent_metrics(agent, System.get_env("STATSD_URL")) # Apply to not warn for client only apply(:ranch, :child_spec, [ id, :ranch_tcp, config, Kvasir.AgentServer.Command.Protocol, {agent, metrics} ]) end @spec agent_metrics(map, String.t() | nil) :: fun | false defp agent_metrics(agent, url) defp agent_metrics(_agent, nil), do: false defp agent_metrics(agent, url) do {:ok, socket, header} = Metrics.open(url) fqdn = :net_adm.localhost() |> :net_adm.dns_hostname() |> elem(1) |> to_string() |> String.trim() |> String.downcase() tags = [ "host:#{fqdn}", "agent:#{String.downcase(inspect(agent.agent))}", "topic:#{agent.id}", unless agent.partition == "*" do m = agent.partition |> String.split(" ") |> List.last() |> String.trim("\"") "partition:#{m}" end, System.get_env("STATSD_TAGS") ] |> Enum.reject(&is_nil/1) |> Enum.join(",") static = "kvasir.agent_server.commands:1|c|##{tags},command:" prefix = IO.iodata_to_binary([header, static]) fn %c{} -> Port.command(socket, prefix <> c.__command__(:type)) end end end