71 lines
2 KiB
Elixir
71 lines
2 KiB
Elixir
defmodule Towerops.Monitoring.Supervisor do
|
|
@moduledoc """
|
|
Supervisor for managing equipment monitoring workers.
|
|
"""
|
|
use Supervisor
|
|
|
|
alias Towerops.Monitoring.EquipmentMonitor
|
|
|
|
def start_link(init_arg) do
|
|
Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
|
|
end
|
|
|
|
@impl true
|
|
def init(_init_arg) do
|
|
children = [
|
|
# Registry for naming monitor processes
|
|
{Registry, keys: :unique, name: Towerops.Monitoring.Registry},
|
|
# DynamicSupervisor for monitor workers
|
|
{DynamicSupervisor, name: Towerops.Monitoring.DynamicSupervisor, strategy: :one_for_one}
|
|
]
|
|
|
|
# Start all monitors after supervisor is initialized (but not in test mode)
|
|
# In test mode, the Repo uses Sandbox pool which we can detect
|
|
if !test_mode?() do
|
|
Task.start(fn ->
|
|
# Wait briefly for the supervisor tree to be fully initialized
|
|
Process.sleep(100)
|
|
start_all_monitors()
|
|
end)
|
|
end
|
|
|
|
Supervisor.init(children, strategy: :one_for_one)
|
|
end
|
|
|
|
@doc """
|
|
Starts monitoring for a specific equipment.
|
|
"""
|
|
def start_monitor(equipment_id) do
|
|
spec = {EquipmentMonitor, equipment_id}
|
|
|
|
DynamicSupervisor.start_child(Towerops.Monitoring.DynamicSupervisor, spec)
|
|
end
|
|
|
|
@doc """
|
|
Stops monitoring for a specific equipment.
|
|
"""
|
|
def stop_monitor(equipment_id) do
|
|
case Registry.lookup(Towerops.Monitoring.Registry, equipment_id) do
|
|
[{pid, _}] ->
|
|
DynamicSupervisor.terminate_child(Towerops.Monitoring.DynamicSupervisor, pid)
|
|
|
|
[] ->
|
|
:ok
|
|
end
|
|
end
|
|
|
|
@doc """
|
|
Starts monitors for all equipment that has monitoring enabled.
|
|
"""
|
|
def start_all_monitors do
|
|
Enum.each(Towerops.Equipment.list_monitored_equipment(), fn equipment ->
|
|
start_monitor(equipment.id)
|
|
end)
|
|
end
|
|
|
|
# Check if running in test mode by inspecting the Repo pool configuration
|
|
defp test_mode? do
|
|
config = Application.get_env(:towerops, Towerops.Repo, [])
|
|
Keyword.get(config, :pool) == Ecto.Adapters.SQL.Sandbox
|
|
end
|
|
end
|