5.4 KiB · text History 3208487
defmodule VigilWeb.Telemetry do
  use Supervisor
  import Telemetry.Metrics

  def start_link(arg) do
    Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
  end

  @impl true
  def init(_arg) do
    children = [
      # Telemetry poller will execute the given period measurements
      # every 10_000ms. Learn more here: https://telemetry-metrics.hexdocs.pm
      {:telemetry_poller, measurements: periodic_measurements(), period: 10_000},
      # /metrics (VigilWeb.Metrics) reads this reporter's ETS tables.
      {TelemetryMetricsPrometheus.Core, metrics: prometheus_metrics(), name: :vigil_prometheus}
    ]

    Supervisor.init(children, strategy: :one_for_one)
  end

  def metrics do
    [
      # Phoenix Metrics
      summary("phoenix.endpoint.start.system_time",
        unit: {:native, :millisecond}
      ),
      summary("phoenix.endpoint.stop.duration",
        unit: {:native, :millisecond}
      ),
      summary("phoenix.router_dispatch.start.system_time",
        tags: [:route],
        unit: {:native, :millisecond}
      ),
      summary("phoenix.router_dispatch.exception.duration",
        tags: [:route],
        unit: {:native, :millisecond}
      ),
      summary("phoenix.router_dispatch.stop.duration",
        tags: [:route],
        unit: {:native, :millisecond}
      ),
      summary("phoenix.socket_connected.duration",
        unit: {:native, :millisecond}
      ),
      sum("phoenix.socket_drain.count"),
      summary("phoenix.channel_joined.duration",
        unit: {:native, :millisecond}
      ),
      summary("phoenix.channel_handled_in.duration",
        tags: [:event],
        unit: {:native, :millisecond}
      ),

      # Database Metrics
      summary("vigil.repo.query.total_time",
        unit: {:native, :millisecond},
        description: "The sum of the other measurements"
      ),
      summary("vigil.repo.query.decode_time",
        unit: {:native, :millisecond},
        description: "The time spent decoding the data received from the database"
      ),
      summary("vigil.repo.query.query_time",
        unit: {:native, :millisecond},
        description: "The time spent executing the query"
      ),
      summary("vigil.repo.query.queue_time",
        unit: {:native, :millisecond},
        description: "The time spent waiting for a database connection"
      ),
      summary("vigil.repo.query.idle_time",
        unit: {:native, :millisecond},
        description:
          "The time the connection spent waiting before being checked out for the query"
      ),

      # VM Metrics
      summary("vm.memory.total", unit: {:byte, :kilobyte}),
      summary("vm.total_run_queue_lengths.total"),
      summary("vm.total_run_queue_lengths.cpu"),
      summary("vm.total_run_queue_lengths.io")
    ]
  end

  @doc """
  What `/metrics` exports, in Prometheus terms: request and query times
  as histograms, ingest and Oban counts, backlog and VM gauges.
  """
  def prometheus_metrics do
    ms = [buckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10_000]]

    [
      distribution("phoenix.router_dispatch.stop.duration",
        tags: [:route],
        unit: {:native, :millisecond},
        reporter_options: ms
      ),
      distribution("phoenix.endpoint.stop.duration",
        unit: {:native, :millisecond},
        reporter_options: ms
      ),
      distribution("vigil.repo.query.total_time",
        unit: {:native, :millisecond},
        reporter_options: ms
      ),
      sum("vigil.ingest.accepted.count",
        tags: [:type],
        description: "Envelope items accepted into the buffer"
      ),
      distribution("vigil.ingest.processed.duration",
        tags: [:type, :result],
        unit: {:native, :millisecond},
        reporter_options: ms,
        description: "Buffered items processed, by type and result"
      ),
      distribution("oban.job.stop.duration",
        tags: [:queue, :state],
        tag_values: &%{queue: &1.queue, state: &1.state},
        unit: {:native, :millisecond},
        reporter_options: ms
      ),
      counter("oban.job.exception.duration",
        tags: [:queue],
        tag_values: &%{queue: &1.queue},
        description: "Oban jobs that raised"
      ),
      last_value("vigil.backlog.ingest_pending", description: "Buffered items waiting"),
      last_value("vigil.backlog.oban_available",
        tags: [:queue],
        description: "Oban jobs ready to run"
      ),
      last_value("vm.memory.total", unit: :byte),
      last_value("vm.total_run_queue_lengths.total"),
      last_value("vm.system_counts.process_count")
    ]
  end

  defp periodic_measurements do
    [{__MODULE__, :backlog, []}]
  end

  @doc false
  # The ingest buffer and Oban queues, for /metrics. Off where there is no
  # database to ask (config :vigil, :backlog_metrics, false: tests).
  def backlog do
    if Application.get_env(:vigil, :backlog_metrics, true) do
      import Ecto.Query

      pending =
        Vigil.Repo.aggregate(
          from(i in Vigil.Ingest.BufferedItem, where: i.state == :pending),
          :count
        )

      :telemetry.execute([:vigil, :backlog], %{ingest_pending: pending}, %{})

      from(j in "oban_jobs",
        where: j.state == "available",
        group_by: j.queue,
        select: {j.queue, count()}
      )
      |> Vigil.Repo.all()
      |> Enum.each(fn {queue, n} ->
        :telemetry.execute([:vigil, :backlog], %{oban_available: n}, %{queue: queue})
      end)
    end
  rescue
    # The database being away mustn't take the poller down.
    _ -> :ok
  end
end