neiam
/vigil
public · Issues · Pulls · Labels · Forks · Compare · Actions success · Badges · Packages
⭐
Log in to mark this repository.
Health (/_health/, /api/0/internal/health/), Prometheus /metrics, ingest telemetry
e8c687c · gmorell · 2026-12-02 03:44
Files changed
modified
config/runtime.exs
+10
−0
@@ -167,3 +167,13 @@ if bucket = System.get_env("S3_BUCKET") do
| 167 | 167 | access_key_id: System.fetch_env!("S3_ACCESS_KEY_ID"), |
| 168 | 168 | secret_access_key: System.fetch_env!("S3_SECRET_ACCESS_KEY") |
| 169 | 169 | end |
| 170 | + | |
| 171 | +# /metrics (VigilWeb.HealthPlug): behind a bearer token, or open on a | |
| 172 | +# private network, or off (the default). | |
| 173 | +if token = System.get_env("METRICS_TOKEN") do | |
| 174 | + config :vigil, :metrics_token, token | |
| 175 | +end | |
| 176 | + | |
| 177 | +if System.get_env("METRICS_PUBLIC") in ~w(true 1) do | |
| 178 | + config :vigil, :metrics_public, true | |
| 179 | +end |
modified
config/test.exs
+3
−0
@@ -69,3 +69,6 @@ config :vigil, Vigil.Storage.Local,
| 69 | 69 | config :vigil, :uptime_opts, |
| 70 | 70 | req_options: [plug: {Req.Test, Vigil.Uptime.Checker}], |
| 71 | 71 | resolver: &Vigil.TestResolver.public/1 |
| 72 | + | |
| 73 | +# No periodic backlog queries against the sandboxed test database. | |
| 74 | +config :vigil, :backlog_metrics, false |
modified
lib/vigil/ingest.ex
+5
−0
@@ -89,6 +89,11 @@ defmodule Vigil.Ingest do
| 89 | 89 | rows -> |
| 90 | 90 | {n, _} = Repo.insert_all(BufferedItem, rows) |
| 91 | 91 | {:ok, _} = Drain.enqueue(target.project_id) |
| 92 | + | |
| 93 | + for {type, count} <- Enum.frequencies_by(rows, & &1.type) do | |
| 94 | + :telemetry.execute([:vigil, :ingest, :accepted], %{count: count}, %{type: type}) | |
| 95 | + end | |
| 96 | + | |
| 92 | 97 | n |
| 93 | 98 | end |
| 94 | 99 | end |
modified
lib/vigil/ingest/drain.ex
+8
−0
@@ -69,12 +69,20 @@ defmodule Vigil.Ingest.Drain do
| 69 | 69 | end |
| 70 | 70 | |
| 71 | 71 | defp handle(item) do |
| 72 | + started = System.monotonic_time() | |
| 73 | + | |
| 72 | 74 | result = |
| 73 | 75 | case Processor.for_type(item.type) do |
| 74 | 76 | nil -> :defer |
| 75 | 77 | processor -> run(processor, item) |
| 76 | 78 | end |
| 77 | 79 | |
| 80 | + :telemetry.execute( | |
| 81 | + [:vigil, :ingest, :processed], | |
| 82 | + %{duration: System.monotonic_time() - started}, | |
| 83 | + %{type: item.type, result: if(match?({:error, _}, result), do: :error, else: result)} | |
| 84 | + ) | |
| 85 | + | |
| 78 | 86 | case result do |
| 79 | 87 | :ok -> |
| 80 | 88 | Repo.delete!(item) |
modified
lib/vigil_web/endpoint.ex
+4
−0
@@ -43,6 +43,10 @@ defmodule VigilWeb.Endpoint do
| 43 | 43 | plug Plug.RequestId |
| 44 | 44 | plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint] |
| 45 | 45 | |
| 46 | + # /_health/, /api/0/internal/health/ and /metrics (VigilWeb.HealthPlug): | |
| 47 | + # no session, no parsers. | |
| 48 | + plug VigilWeb.HealthPlug | |
| 49 | + | |
| 46 | 50 | # Sentry SDKs' ingest (/api/<dsn_id>/envelope/ and friends): raw bodies, |
| 47 | 51 | # no parsers, no session. Anything else passes through. |
| 48 | 52 | plug VigilWeb.IngestPlug |
added
lib/vigil_web/health_plug.ex
+121
−0
@@ -0,0 +1,121 @@
| 1 | +defmodule VigilWeb.HealthPlug do | |
| 2 | + @moduledoc """ | |
| 3 | + Operational endpoints, answered in the Endpoint ahead of sessions and | |
| 4 | + parsers: | |
| 5 | + | |
| 6 | + * `GET /_health/`: liveness. 200 `ok` while the VM serves requests; | |
| 7 | + touches nothing else, so a slow database doesn't get the pod killed. | |
| 8 | + * `GET /api/0/internal/health/`: readiness, in Sentry's shape | |
| 9 | + (`{"problems": [...], "healthy": {...}}`): the database answers, | |
| 10 | + Oban is running, and the ingest buffer isn't badly backed up. 503 | |
| 11 | + with the problems otherwise. | |
| 12 | + * `GET /metrics`: Prometheus text (`VigilWeb.Telemetry.prometheus_metrics/0`). | |
| 13 | + Served only when configured: with `METRICS_TOKEN` set it needs | |
| 14 | + `Authorization: Bearer <token>`; with `METRICS_PUBLIC=true` it is | |
| 15 | + open (for a scrape over a private network); otherwise 404. | |
| 16 | + """ | |
| 17 | + @behaviour Plug | |
| 18 | + | |
| 19 | + import Plug.Conn | |
| 20 | + | |
| 21 | + @backlog_warn 50_000 | |
| 22 | + | |
| 23 | + @impl Plug | |
| 24 | + def init(opts), do: opts | |
| 25 | + | |
| 26 | + @impl Plug | |
| 27 | + def call(%{method: "GET", path_info: ["_health"]} = conn, _opts) do | |
| 28 | + conn |> put_resp_content_type("text/plain") |> send_resp(200, "ok") |> halt() | |
| 29 | + end | |
| 30 | + | |
| 31 | + def call(%{method: "GET", path_info: ["api", "0", "internal", "health"]} = conn, _opts) do | |
| 32 | + checks = %{ | |
| 33 | + "database" => check(&database/0), | |
| 34 | + "oban" => check(&oban/0), | |
| 35 | + "ingest_backlog" => check(&backlog/0) | |
| 36 | + } | |
| 37 | + | |
| 38 | + problems = | |
| 39 | + for {name, {:error, why}} <- checks, do: %{id: name, message: why, severity: "critical"} | |
| 40 | + | |
| 41 | + healthy = Map.new(checks, fn {name, result} -> {name, result == :ok} end) | |
| 42 | + | |
| 43 | + conn | |
| 44 | + |> put_resp_content_type("application/json") | |
| 45 | + |> send_resp( | |
| 46 | + if(problems == [], do: 200, else: 503), | |
| 47 | + Jason.encode!(%{problems: problems, healthy: healthy}) | |
| 48 | + ) | |
| 49 | + |> halt() | |
| 50 | + end | |
| 51 | + | |
| 52 | + def call(%{method: "GET", path_info: ["metrics"]} = conn, _opts) do | |
| 53 | + case metrics_access(conn) do | |
| 54 | + :ok -> | |
| 55 | + conn | |
| 56 | + |> put_resp_content_type("text/plain; version=0.0.4") | |
| 57 | + |> send_resp(200, TelemetryMetricsPrometheus.Core.scrape(:vigil_prometheus)) | |
| 58 | + |> halt() | |
| 59 | + | |
| 60 | + :unauthorized -> | |
| 61 | + conn |> send_resp(401, "unauthorized") |> halt() | |
| 62 | + | |
| 63 | + :off -> | |
| 64 | + conn |> send_resp(404, "not found") |> halt() | |
| 65 | + end | |
| 66 | + end | |
| 67 | + | |
| 68 | + def call(conn, _opts), do: conn | |
| 69 | + | |
| 70 | + defp check(fun) do | |
| 71 | + fun.() | |
| 72 | + rescue | |
| 73 | + e -> {:error, Exception.message(e)} | |
| 74 | + end | |
| 75 | + | |
| 76 | + defp database do | |
| 77 | + Vigil.Repo.query!("SELECT 1", [], timeout: 2_000) | |
| 78 | + :ok | |
| 79 | + end | |
| 80 | + | |
| 81 | + defp oban do | |
| 82 | + case Oban.Registry.whereis(Oban) do | |
| 83 | + pid when is_pid(pid) -> :ok | |
| 84 | + _ -> {:error, "Oban isn't running"} | |
| 85 | + end | |
| 86 | + end | |
| 87 | + | |
| 88 | + defp backlog do | |
| 89 | + import Ecto.Query | |
| 90 | + | |
| 91 | + pending = | |
| 92 | + Vigil.Repo.aggregate( | |
| 93 | + from(i in Vigil.Ingest.BufferedItem, where: i.state == :pending), | |
| 94 | + :count, timeout: 2_000) | |
| 95 | + | |
| 96 | + if pending < @backlog_warn, | |
| 97 | + do: :ok, | |
| 98 | + else: {:error, "#{pending} ingest items waiting"} | |
| 99 | + end | |
| 100 | + | |
| 101 | + defp metrics_access(conn) do | |
| 102 | + token = Application.get_env(:vigil, :metrics_token) | |
| 103 | + | |
| 104 | + cond do | |
| 105 | + is_binary(token) and token != "" -> | |
| 106 | + case get_req_header(conn, "authorization") do | |
| 107 | + ["Bearer " <> given] -> | |
| 108 | + if Plug.Crypto.secure_compare(String.trim(given), token), do: :ok, else: :unauthorized | |
| 109 | + | |
| 110 | + _ -> | |
| 111 | + :unauthorized | |
| 112 | + end | |
| 113 | + | |
| 114 | + Application.get_env(:vigil, :metrics_public, false) -> | |
| 115 | + :ok | |
| 116 | + | |
| 117 | + true -> | |
| 118 | + :off | |
| 119 | + end | |
| 120 | + end | |
| 121 | +end |
modified
lib/vigil_web/telemetry.ex
+86
−7
@@ -11,9 +11,9 @@ defmodule VigilWeb.Telemetry do
| 11 | 11 | children = [ |
| 12 | 12 | # Telemetry poller will execute the given period measurements |
| 13 | 13 | # every 10_000ms. Learn more here: https://telemetry-metrics.hexdocs.pm |
| 14 | − {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} | |
| 15 | − # Add reporters as children of your supervision tree. | |
| 16 | − # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} | |
| 14 | + {:telemetry_poller, measurements: periodic_measurements(), period: 10_000}, | |
| 15 | + # /metrics (VigilWeb.Metrics) reads this reporter's ETS tables. | |
| 16 | + {TelemetryMetricsPrometheus.Core, metrics: prometheus_metrics(), name: :vigil_prometheus} | |
| 17 | 17 | ] |
| 18 | 18 | |
| 19 | 19 | Supervisor.init(children, strategy: :one_for_one) |
@@ -83,11 +83,90 @@ defmodule VigilWeb.Telemetry do
| 83 | 83 | ] |
| 84 | 84 | end |
| 85 | 85 | |
| 86 | − defp periodic_measurements do | |
| 86 | + @doc """ | |
| 87 | + What `/metrics` exports, in Prometheus terms: request and query times | |
| 88 | + as histograms, ingest and Oban counts, backlog and VM gauges. | |
| 89 | + """ | |
| 90 | + def prometheus_metrics do | |
| 91 | + ms = [buckets: [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10_000]] | |
| 92 | + | |
| 87 | 93 | [ |
| 88 | − # A module, function and arguments to be invoked periodically. | |
| 89 | − # This function must call :telemetry.execute/3 and a metric must be added above. | |
| 90 | − # {VigilWeb, :count_users, []} | |
| 94 | + distribution("phoenix.router_dispatch.stop.duration", | |
| 95 | + tags: [:route], | |
| 96 | + unit: {:native, :millisecond}, | |
| 97 | + reporter_options: ms | |
| 98 | + ), | |
| 99 | + distribution("phoenix.endpoint.stop.duration", | |
| 100 | + unit: {:native, :millisecond}, | |
| 101 | + reporter_options: ms | |
| 102 | + ), | |
| 103 | + distribution("vigil.repo.query.total_time", | |
| 104 | + unit: {:native, :millisecond}, | |
| 105 | + reporter_options: ms | |
| 106 | + ), | |
| 107 | + sum("vigil.ingest.accepted.count", | |
| 108 | + tags: [:type], | |
| 109 | + description: "Envelope items accepted into the buffer" | |
| 110 | + ), | |
| 111 | + distribution("vigil.ingest.processed.duration", | |
| 112 | + tags: [:type, :result], | |
| 113 | + unit: {:native, :millisecond}, | |
| 114 | + reporter_options: ms, | |
| 115 | + description: "Buffered items processed, by type and result" | |
| 116 | + ), | |
| 117 | + distribution("oban.job.stop.duration", | |
| 118 | + tags: [:queue, :state], | |
| 119 | + tag_values: &%{queue: &1.queue, state: &1.state}, | |
| 120 | + unit: {:native, :millisecond}, | |
| 121 | + reporter_options: ms | |
| 122 | + ), | |
| 123 | + counter("oban.job.exception.duration", | |
| 124 | + tags: [:queue], | |
| 125 | + tag_values: &%{queue: &1.queue}, | |
| 126 | + description: "Oban jobs that raised" | |
| 127 | + ), | |
| 128 | + last_value("vigil.backlog.ingest_pending", description: "Buffered items waiting"), | |
| 129 | + last_value("vigil.backlog.oban_available", | |
| 130 | + tags: [:queue], | |
| 131 | + description: "Oban jobs ready to run" | |
| 132 | + ), | |
| 133 | + last_value("vm.memory.total", unit: :byte), | |
| 134 | + last_value("vm.total_run_queue_lengths.total"), | |
| 135 | + last_value("vm.system_counts.process_count") | |
| 91 | 136 | ] |
| 92 | 137 | end |
| 138 | + | |
| 139 | + defp periodic_measurements do | |
| 140 | + [{__MODULE__, :backlog, []}] | |
| 141 | + end | |
| 142 | + | |
| 143 | + @doc false | |
| 144 | + # The ingest buffer and Oban queues, for /metrics. Off where there is no | |
| 145 | + # database to ask (config :vigil, :backlog_metrics, false: tests). | |
| 146 | + def backlog do | |
| 147 | + if Application.get_env(:vigil, :backlog_metrics, true) do | |
| 148 | + import Ecto.Query | |
| 149 | + | |
| 150 | + pending = | |
| 151 | + Vigil.Repo.aggregate( | |
| 152 | + from(i in Vigil.Ingest.BufferedItem, where: i.state == :pending), | |
| 153 | + :count | |
| 154 | + ) | |
| 155 | + | |
| 156 | + :telemetry.execute([:vigil, :backlog], %{ingest_pending: pending}, %{}) | |
| 157 | + | |
| 158 | + from(j in "oban_jobs", | |
| 159 | + where: j.state == "available", | |
| 160 | + group_by: j.queue, | |
| 161 | + select: {j.queue, count()} | |
| 162 | + ) | |
| 163 | + |> Vigil.Repo.all() | |
| 164 | + |> Enum.each(fn {queue, n} -> | |
| 165 | + :telemetry.execute([:vigil, :backlog], %{oban_available: n}, %{queue: queue}) | |
| 166 | + end) | |
| 167 | + end | |
| 168 | + rescue | |
| 169 | + # The database being away mustn't take the poller down. | |
| 170 | + _ -> :ok | |
| 171 | + end | |
| 93 | 172 | end |
modified
mix.exs
+2
−0
@@ -79,6 +79,8 @@ defmodule Vigil.MixProject do
| 79 | 79 | # credentials. |
| 80 | 80 | {:neiam_auth, git: "https://gg.neiam.co/neiam/neiam_auth.git", tag: "v0.4.0"}, |
| 81 | 81 | {:telemetry_metrics, "~> 1.0"}, |
| 82 | + # /metrics in Prometheus format (VigilWeb.Metrics). | |
| 83 | + {:telemetry_metrics_prometheus_core, "~> 1.2"}, | |
| 82 | 84 | {:telemetry_poller, "~> 1.0"}, |
| 83 | 85 | {:gettext, "~> 1.0"}, |
| 84 | 86 | {:jason, "~> 1.2"}, |
modified
mix.lock
+1
−0
@@ -46,6 +46,7 @@
| 46 | 46 | "tailwind": {:hex, :tailwind, "0.5.2", "d8bc230361fd3e14b495043c364aefddfac2ad4bf2eada380f458e9a15cb2e20", [:mix], [], "hexpm", "e0e5fd9799fb9231b97e52ce074d9ff509043d1946713a71fbc608e81eff7e66"}, |
| 47 | 47 | "telemetry": {:hex, :telemetry, "1.4.3", "d0333fa869361e6833d6ff8e806ff4d8553fe1332fcce0af86c7381951a1dc2f", [:rebar3], [], "hexpm", "17a63581cf2e832a238287f5fe6811e8ca1f333249f1376ad653164a3c4770d4"}, |
| 48 | 48 | "telemetry_metrics": {:hex, :telemetry_metrics, "1.2.0", "7632c19c01d88d8aaca5da1a0e8912f5af39b79e7c08a2c253aeb3c14c2c957e", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "71dde12fc29b58b9c77ec17ec319109e5ca848d010fc1965ed4463bba1837c07"}, |
| 49 | + "telemetry_metrics_prometheus_core": {:hex, :telemetry_metrics_prometheus_core, "1.2.1", "c9755987d7b959b557084e6990990cb96a50d6482c683fb9622a63837f3cd3d8", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}, {:telemetry_metrics, "~> 0.6 or ~> 1.0", [hex: :telemetry_metrics, repo: "hexpm", optional: false]}], "hexpm", "5e2c599da4983c4f88a33e9571f1458bf98b0cf6ba930f1dc3a6e8cf45d5afb6"}, | |
| 49 | 50 | "telemetry_poller": {:hex, :telemetry_poller, "1.3.0", "d5c46420126b5ac2d72bc6580fb4f537d35e851cc0f8dbd571acf6d6e10f5ec7", [:rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "51f18bed7128544a50f75897db9974436ea9bfba560420b646af27a9a9b35211"}, |
| 50 | 51 | "telemetry_registry": {:hex, :telemetry_registry, "0.3.2", "701576890320be6428189bff963e865e8f23e0ff3615eade8f78662be0fc003c", [:mix, :rebar3], [{:telemetry, "~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "e7ed191eb1d115a3034af8e1e35e4e63d5348851d556646d46ca3d1b4e16bab9"}, |
| 51 | 52 | "thousand_island": {:hex, :thousand_island, "1.6.0", "d6ad7c2220c96a270cc8ca1586ec4d8bde648a4a3a53f003ce093f41beec0288", [:mix], [{:telemetry, "~> 0.4 or ~> 1.0", [hex: :telemetry, repo: "hexpm", optional: false]}], "hexpm", "4d4720470f091fc21a1311777c2ac66916c43621bffc068590c9f9bb3cd057a3"}, |
added
test/vigil_web/health_plug_test.exs
+41
−0
@@ -0,0 +1,41 @@
| 1 | +defmodule VigilWeb.HealthPlugTest do | |
| 2 | + # Changes app env for /metrics access: not alongside other tests. | |
| 3 | + use VigilWeb.ConnCase, async: false | |
| 4 | + | |
| 5 | + test "liveness, and readiness in Sentry's shape", %{conn: conn} do | |
| 6 | + assert conn |> get("/_health/") |> response(200) == "ok" | |
| 7 | + | |
| 8 | + assert %{"problems" => [], "healthy" => %{"database" => true, "oban" => true}} = | |
| 9 | + build_conn() |> get("/api/0/internal/health/") |> json_response(200) | |
| 10 | + end | |
| 11 | + | |
| 12 | + test "/metrics is off by default, behind a token, or public" do | |
| 13 | + assert build_conn() |> get("/metrics") |> response(404) | |
| 14 | + | |
| 15 | + Application.put_env(:vigil, :metrics_token, "s3cret") | |
| 16 | + on_exit(fn -> Application.delete_env(:vigil, :metrics_token) end) | |
| 17 | + | |
| 18 | + assert build_conn() |> get("/metrics") |> response(401) | |
| 19 | + | |
| 20 | + assert build_conn() | |
| 21 | + |> put_req_header("authorization", "Bearer wrong") | |
| 22 | + |> get("/metrics") | |
| 23 | + |> response(401) | |
| 24 | + | |
| 25 | + :telemetry.execute([:vigil, :ingest, :accepted], %{count: 3}, %{type: "event"}) | |
| 26 | + | |
| 27 | + body = | |
| 28 | + build_conn() | |
| 29 | + |> put_req_header("authorization", "Bearer s3cret") | |
| 30 | + |> get("/metrics") | |
| 31 | + |> response(200) | |
| 32 | + | |
| 33 | + assert body =~ ~s(vigil_ingest_accepted_count{type="event"}) | |
| 34 | + assert body =~ "vigil_repo_query_total_time" | |
| 35 | + | |
| 36 | + Application.delete_env(:vigil, :metrics_token) | |
| 37 | + Application.put_env(:vigil, :metrics_public, true) | |
| 38 | + on_exit(fn -> Application.delete_env(:vigil, :metrics_public) end) | |
| 39 | + assert build_conn() |> get("/metrics") |> response(200) | |
| 40 | + end | |
| 41 | +end |
Parents: 76dee78