diff --git a/apps/lenra/lib/monitor/application_deployment_measurement.ex b/apps/lenra/lib/monitor/application_deployment_measurement.ex new file mode 100644 index 00000000..6c28ce17 --- /dev/null +++ b/apps/lenra/lib/monitor/application_deployment_measurement.ex @@ -0,0 +1,37 @@ +defmodule Lenra.Monitor.ApplicationDeploymentMeasurement do + @moduledoc """ + Lenra.Monitor.ApplicationDeploymentMeasurement is a ecto schema to store measurements of applications deployment. + """ + use Ecto.Schema + import Ecto.Changeset + + alias Lenra.Apps.App + + schema "session_measurement" do + belongs_to(:application, App) + + field(:start_time, :utc_datetime) + field(:end_time, :utc_datetime) + + field(:duration, :integer) + + timestamps() + end + + def changeset(application_deployment_measurement, params \\ %{}) do + application_deployment_measurement + |> cast(params, [:start_time, :end_time, :duration]) + |> validate_required([:start_time, :application_id]) + |> foreign_key_constraint(:application_id) + end + + def new(application_id, params \\ %{}) do + %__MODULE__{application_id: application_id} + |> __MODULE__.changeset(params) + end + + def update(application_deployment_measurement, params) do + application_deployment_measurement + |> changeset(params) + end +end diff --git a/apps/lenra/lib/monitor/application_deployment_monitor.ex b/apps/lenra/lib/monitor/application_deployment_monitor.ex new file mode 100644 index 00000000..872cee46 --- /dev/null +++ b/apps/lenra/lib/monitor/application_deployment_monitor.ex @@ -0,0 +1,48 @@ +defmodule Lenra.Monitor.ApplicationDeploymentMonitor do + @moduledoc """ + The application deployment monitor which monitors the time spent deploying an app. + """ + + use GenServer + use SwarmNamed + + alias Lenra.Telemetry + + require Logger + + def monitor(pid, metadata) do + GenServer.call(__MODULE__, {:monitor, pid, metadata}) + rescue + e -> + Logger.error("#{__MODULE__} fail in monitor with metadata #{inspect(metadata)} and error: #{inspect(e)}") + end + + def start_link(_opts) do + Logger.debug("Start #{__MODULE__}") + GenServer.start_link(__MODULE__, [], name: __MODULE__) + end + + def init(_) do + {:ok, %{}} + end + + def handle_call({:monitor, pid, metadata}, _from, state) do + Logger.debug("#{__MODULE__} monitor #{inspect(pid)} with metadata #{inspect(metadata)}") + + Process.monitor(pid) + + start_time = Map.get(metadata, :start_time) + + {:reply, :ok, Map.put(state, pid, {start_time, metadata})} + end + + def handle_info({:DOWN, _ref, :process, pid, _reason}, state) do + {{start_time, metadata}, new_state} = Map.pop(state, pid) + + Logger.debug("#{__MODULE__} handle down #{inspect(pid)} with metadata #{inspect(metadata)}") + + Telemetry.stop(:app_deployment, start_time, metadata) + + {:noreply, new_state} + end +end