diff --git a/lib/situation_room/application.ex b/lib/situation_room/application.ex index a0a09b7..d7ea0ca 100644 --- a/lib/situation_room/application.ex +++ b/lib/situation_room/application.ex @@ -15,9 +15,11 @@ defmodule SituationRoom.Application do # Start the PubSub system {Phoenix.PubSub, name: SituationRoom.PubSub}, # Start the Endpoint (http/https) - SituationRoomWeb.Endpoint + SituationRoomWeb.Endpoint, # Start a worker by calling: SituationRoom.Worker.start_link(arg) # {SituationRoom.Worker, arg} + {Finch, name: SituationRoom.Finch}, + SituationRoom.ChecksSupervisor ] # See https://hexdocs.pm/elixir/Supervisor.html diff --git a/lib/situation_room/check/checks_genserver.ex b/lib/situation_room/check/checks_genserver.ex new file mode 100644 index 0000000..e2b8c39 --- /dev/null +++ b/lib/situation_room/check/checks_genserver.ex @@ -0,0 +1,41 @@ +defmodule SituationRoom.ChecksGenServer do + @moduledoc """ + The Genserver for checking sites + """ + use GenServer + require Logger + alias SituationRoom.Site.Check + + def start_link(args) do + GenServer.start_link(__MODULE__, args) + end + + def init(site) do + schedule_site_check(site.interval) + {:ok, site} + end + + def handle_info(:run_check, site) do + handle_check(site) + schedule_site_check(site.interval) + {:noreply, site} + end + + defp handle_check(site) do + case SituationRoom.Site.LiveCheck.run(site.endpoint) do + {:ok, %{response_time: res_time, status: status}} -> + Check.create_check(%{ + "site_id" => site.id, + "response_time" => res_time, + "status_code" => status + }) + + {:error, reason} -> + reason + end + end + + defp schedule_site_check(interval) do + Process.send_after(self(), :run_check, interval) + end +end diff --git a/lib/situation_room/check/checks_supervisor.ex b/lib/situation_room/check/checks_supervisor.ex new file mode 100644 index 0000000..166cd9d --- /dev/null +++ b/lib/situation_room/check/checks_supervisor.ex @@ -0,0 +1,28 @@ +defmodule SituationRoom.ChecksSupervisor do + @moduledoc """ + Supervisor for Site Check GenServers + """ + use Supervisor + + def start_link(opts) do + Supervisor.start_link(__MODULE__, opts) + end + + @impl true + def init(_opts) do + children = + for site <- SituationRoom.Sites.get_all_sites() do + Supervisor.child_spec({SituationRoom.ChecksGenServer, site}, id: site.id) + end + + Supervisor.init(children, strategy: :one_for_one) + end + + # def add_child(site) do + # Supervisor.start_child() + # end + + # def remove_child() do + # Supervisor.delete_child() + # end +end