dotfiles/app/lib/prymn_web/live/server_live/show.ex
Nikos Papadakis be7f584010
app: a nice poc background connection with the agent
Dynamically supervise a GRPC connection and keep it alive for a while,
using a timeout to kill the process on inactivity.

The Connection GenServer keeps the connection alive, while listening to
a health stream from the GRPC endpoint, notifying any subscribed
listeners about changes to health.

This health is then propagated to the main servers page.

Also create a looping get_sys_info which retrieves some basic system
information.
2023-08-26 00:51:04 +03:00

56 lines
1.5 KiB
Elixir

defmodule PrymnWeb.ServerLive.Show do
use PrymnWeb, :live_view
alias Prymn.{Agents, Servers}
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _, socket) do
server = Servers.get_server!(id)
pid = self()
if connected?(socket) do
Agents.start_connection_or_keep_alive(server.public_ip)
Task.start_link(fn -> get_sys_info(pid, server.public_ip) end)
end
{:noreply,
socket
|> assign(:page_title, server.name)
|> assign(:server, server)
|> assign(:uptime, 0)
|> assign(:cpus, [])
|> assign(:total_memory, 0)
|> assign(:used_memory, 0)
|> assign(:registration_command, Servers.create_setup_command(server))}
end
@impl true
def handle_info(%PrymnProto.Prymn.SysInfoResponse{} = response, socket) do
{:noreply,
socket
|> assign(:uptime, response.uptime)
|> assign(
:used_memory,
bytes_to_gigabytes(response.mem_total_bytes - response.mem_avail_bytes)
)
|> assign(:total_memory, bytes_to_gigabytes(response.mem_total_bytes))
|> assign(:cpus, response.cpus)}
end
defp bytes_to_gigabytes(bytes) do
Float.round(bytes / Integer.pow(1024, 3), 2)
end
defp get_sys_info(from, host_address) do
channel = Agents.get_channel(host_address)
{:ok, reply} = PrymnProto.Prymn.Agent.Stub.get_sys_info(channel, %Google.Protobuf.Empty{})
send(from, reply)
Process.sleep(:timer.seconds(2))
get_sys_info(from, host_address)
end
end