feat(server): host channel with token auth and metric events
This commit is contained in:
parent
d9a52db4ea
commit
61595e0293
3 changed files with 182 additions and 0 deletions
64
server/lib/server_web/channels/host_channel.ex
Normal file
64
server/lib/server_web/channels/host_channel.ex
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
defmodule ServerWeb.HostChannel do
|
||||
use ServerWeb, :channel
|
||||
require Logger
|
||||
|
||||
alias Server.Hosts
|
||||
|
||||
@impl true
|
||||
def join("host:" <> name, params, socket) when name != "" do
|
||||
token = Map.get(params, "token", "")
|
||||
agent_version = Map.get(params, "agent_version")
|
||||
|
||||
case Hosts.authenticate(name, token) do
|
||||
{:ok, host} ->
|
||||
{:ok, _} = Hosts.mark_online(host, agent_version)
|
||||
Logger.info("agent joined host:#{name}")
|
||||
|
||||
socket =
|
||||
socket
|
||||
|> assign(:host_id, host.id)
|
||||
|> assign(:host_name, name)
|
||||
|
||||
{:ok, socket}
|
||||
|
||||
{:error, :unknown_host} ->
|
||||
{:error, %{reason: "unknown_host"}}
|
||||
|
||||
{:error, :invalid_token} ->
|
||||
{:error, %{reason: "invalid_token"}}
|
||||
end
|
||||
end
|
||||
|
||||
def join(_topic, _params, _socket), do: {:error, %{reason: "bad_topic"}}
|
||||
|
||||
@impl true
|
||||
def handle_in("metric:fast", payload, socket) do
|
||||
Logger.info("metric:fast host=#{socket.assigns.host_name} data=#{inspect(payload["data"])}")
|
||||
{:reply, :ok, socket}
|
||||
end
|
||||
|
||||
def handle_in("metric:medium", payload, socket) do
|
||||
Logger.info("metric:medium host=#{socket.assigns.host_name} payload=#{inspect(payload)}")
|
||||
{:reply, :ok, socket}
|
||||
end
|
||||
|
||||
def handle_in("metric:slow", payload, socket) do
|
||||
Logger.info("metric:slow host=#{socket.assigns.host_name} payload=#{inspect(payload)}")
|
||||
{:reply, :ok, socket}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def terminate(_reason, socket) do
|
||||
case socket.assigns[:host_id] do
|
||||
nil ->
|
||||
:ok
|
||||
|
||||
id ->
|
||||
with host when not is_nil(host) <- Server.Repo.get(Server.Schema.Host, id) do
|
||||
Hosts.mark_offline(host)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
end
|
||||
end
|
||||
Loading…
Add table
Add a link
Reference in a new issue