elstat/lib/manager.ex

81 lines
1.8 KiB
Elixir
Raw Normal View History

2018-06-11 07:24:16 +00:00
defmodule Elstat.Error.Service do
defexception message: "default message"
end
defmodule Elstat.ServiceWorker do
require Logger
def start_link(service) do
Logger.info "spawning worker for #{inspect service.id}"
worker_pid = spawn(fn ->
worker_func(service)
end)
{:ok, worker_pid}
end
def worker_func(service) do
adapter = service.adapter
result = adapter.check(service.adapter_opts)
Logger.info "result from #{inspect adapter} #{inspect service.id}: #{inspect result}"
man_pid = :global.whereis_name Elstat.Manager
send man_pid, {:service_info, {service.id, result}}
Process.sleep(service.poll * 1000)
worker_func(service)
end
end
defmodule Elstat.Manager do
@moduledoc """
Elstat's service manager.
"""
use GenServer
require Logger
def start_link(opts) do
GenServer.start_link(__MODULE__, :ok, [name: {:global, Elstat.Manager}] ++ opts)
end
def build_services() do
services = Application.fetch_env!(:elstat, :services)
workers = services
|> Enum.map(fn service ->
service_id = service.id
# each service worker will enter an infinite loop
# polling the service (via an adapter) and giving
# information back to the manager, so it can
# process and show those via its API.
%{
id: service_id,
start: {Elstat.ServiceWorker, :start_link, [service]}
}
end)
# spawn the managere alongside service workers
[ Elstat.Manager | workers]
end
# server callbacks
def init(:ok) do
services = Application.fetch_env!(:elstat, :services)
# TODO : send data to db
{:ok, %{
services: services,
}}
end
def handle_info({:service_info, data}, state) do
Logger.debug "got service data! #{inspect data}"
{:noreply, state}
end
end