Monitors API and cron conformance with sentry-elixir's Oban integration, sentry-python and sentry-cli

d42f46b · gmorell · 2026-12-02 02:57

14 files +346 -0

Files changed

added lib/vigil_web/api/v0/monitor_controller.ex
+53 −0
@@ -0,0 +1,53 @@
1 +defmodule VigilWeb.Api.V0.MonitorController do
2 + @moduledoc """
3 + `GET /api/0/organizations/{org}/monitors/`: the cron monitors of the
4 + projects the token can see, in Sentry's shape (sentry-cli's `monitors
5 + list` reads `id`, `slug`, `name` and `status`). One page: there is no
6 + Link header, which sentry-cli reads as the end.
7 + """
8 + use VigilWeb, :controller
9 +
10 + alias Vigil.{Monitors, Projects}
11 + alias Vigil.Monitors.Schedule
12 + alias VigilWeb.Api.Auth
13 +
14 + def index(conn, %{"org" => slug}) do
15 + with {:ok, conn} <- Auth.put_org(conn, slug),
16 + {:ok, conn} <- Auth.require_scope(conn, "project:read") do
17 + project_ids = conn.assigns.current_scope |> Projects.list_visible() |> Enum.map(& &1.id)
18 + json(conn, project_ids |> Monitors.list_for_projects() |> Enum.map(&monitor_json/1))
19 + else
20 + {:error, conn} -> conn
21 + end
22 + end
23 +
24 + defp monitor_json(m) do
25 + %{
26 + id: m.id,
27 + slug: m.slug,
28 + name: m.name,
29 + status: if(m.enabled, do: "active", else: "disabled"),
30 + isMuted: false,
31 + dateCreated: m.inserted_at,
32 + project: %{id: to_string(m.project.dsn_id), slug: m.project.slug, name: m.project.name},
33 + config: %{
34 + schedule_type: to_string(m.schedule_type),
35 + schedule:
36 + if(m.schedule_type == :crontab,
37 + do: m.schedule,
38 + else: [m.interval_value, m.interval_unit]
39 + ),
40 + checkin_margin: m.checkin_margin,
41 + max_runtime: m.max_runtime,
42 + timezone: m.timezone,
43 + failure_issue_threshold: m.failure_threshold,
44 + recovery_threshold: m.recovery_threshold
45 + },
46 + # Vigil's own: the monitor's health and when it's next due.
47 + health: to_string(m.health),
48 + schedule: Schedule.describe(m),
49 + nextCheckIn: m.next_expected_at,
50 + lastCheckIn: m.last_checkin_at
51 + }
52 + end
53 +end
modified lib/vigil_web/router.ex
+3 −0
@@ -62,6 +62,9 @@ defmodule VigilWeb.Router do
62 62 post "/organizations/:org/artifactbundle/assemble", ArtifactController, :assemble
63 63 post "/organizations/:org/releases/:version/assemble", ArtifactController, :assemble_release
64 64
65 + # Cron monitors (slice 7).
66 + get "/organizations/:org/monitors", MonitorController, :index
67 +
65 68 # Anything else: GlitchTip's JSON 404, which sentry-cli reads as
66 69 # "not supported here".
67 70 match :*, "/*path", IndexController, :not_found
added test/support/sdk/sentry_elixir_oban_cron.exs
+61 −0
@@ -0,0 +1,61 @@
1 +# Vigil's own Oban cron jobs, reported through sentry-elixir's Oban cron
2 +# integration, unchanged: the integration listens to Oban's job telemetry,
3 +# so this emits the events Oban emits for a cron job (a job whose meta has
4 +# "cron" and "cron_expr", as Oban's Cron plugin inserts them) without
5 +# running Oban itself. One success (the partition maintenance) and one
6 +# failure (the alert evaluation). Run by VigilWeb.SdkCronConformanceTest;
7 +# the DSN comes from SENTRY_DSN.
8 +Mix.install(
9 + [
10 + {:sentry, path: System.fetch_env!("SENTRY_ELIXIR_PATH")},
11 + {:jason, "~> 1.4"},
12 + {:finch, "~> 0.21"},
13 + {:oban, "~> 2.20"}
14 + ],
15 + config: [
16 + sentry: [
17 + environment_name: "test",
18 + release: "vigil@0.1.0",
19 + integrations: [oban: [cron: [enabled: true]]]
20 + ]
21 + ]
22 +)
23 +
24 +run = fn id, worker, cron_expr, outcome ->
25 + # struct!/2, not %Oban.Job{}: the script is compiled before Mix.install
26 + # fetches Oban.
27 + job =
28 + struct!(Oban.Job,
29 + id: id,
30 + worker: worker,
31 + queue: "maintenance",
32 + args: %{},
33 + attempt: 1,
34 + max_attempts: 1,
35 + meta: %{"cron" => true, "cron_expr" => cron_expr, "cron_name" => worker}
36 + )
37 +
38 + :telemetry.execute([:oban, :job, :start], %{system_time: System.system_time()}, %{job: job})
39 + Process.sleep(20)
40 + duration = System.convert_time_unit(20, :millisecond, :native)
41 +
42 + case outcome do
43 + :success ->
44 + :telemetry.execute([:oban, :job, :stop], %{duration: duration}, %{job: job, state: :success})
45 +
46 + :exception ->
47 + :telemetry.execute([:oban, :job, :exception], %{duration: duration}, %{
48 + job: job,
49 + state: :failure,
50 + kind: :error,
51 + reason: %RuntimeError{message: "evaluation failed"},
52 + stacktrace: []
53 + })
54 + end
55 +end
56 +
57 +run.(101, "Vigil.Partitions.MaintainWorker", "17 3 * * *", :success)
58 +run.(102, "Vigil.Alerts.EvaluateWorker", "* * * * *", :exception)
59 +
60 +Sentry.flush(timeout: 10_000)
61 +IO.puts("done")
added test/vigil_web/api/monitor_api_test.exs
+48 −0
@@ -0,0 +1,48 @@
1 +defmodule VigilWeb.MonitorApiTest do
2 + use VigilWeb.ConnCase, async: true
3 +
4 + import Vigil.AccountsFixtures
5 + import Vigil.OrganizationsFixtures
6 +
7 + alias Vigil.{ApiTokens, Monitors}
8 +
9 + test "monitors of visible projects, in Sentry's shape", %{conn: conn} do
10 + owner = user_fixture()
11 + org = organization_fixture(owner)
12 + project = project_fixture(org_scope(owner, org), %{"name" => "web"})
13 +
14 + Monitors.check_in(project, %{
15 + "monitor_slug" => "nightly",
16 + "status" => "ok",
17 + "monitor_config" => %{"schedule" => %{"type" => "crontab", "value" => "0 3 * * *"}}
18 + })
19 +
20 + {:ok, t} = ApiTokens.create_token(owner, %{label: "cli", scopes: ["project:read"]})
21 +
22 + assert [
23 + %{
24 + "slug" => "nightly",
25 + "status" => "active",
26 + "config" => %{"schedule" => "0 3 * * *"}
27 + }
28 + ] =
29 + conn
30 + |> put_req_header("authorization", "Bearer " <> t.token)
31 + |> get("/api/0/organizations/#{org.slug}/monitors/")
32 + |> json_response(200)
33 +
34 + # A member whose teams don't include the project sees none of it.
35 + member = member_fixture(org, nil, :member)
36 + {:ok, mt} = ApiTokens.create_token(member.user, %{label: "m", scopes: ["project:read"]})
37 +
38 + org = Vigil.Repo.reload!(org)
39 +
40 + body =
41 + build_conn()
42 + |> put_req_header("authorization", "Bearer " <> mt.token)
43 + |> get("/api/0/organizations/#{org.slug}/monitors/")
44 + |> json_response(200)
45 +
46 + if org.open_membership, do: assert([_] = body), else: assert(body == [])
47 + end
48 +end
added test/vigil_web/sdk_cron_conformance_test.exs
+181 −0
@@ -0,0 +1,181 @@
1 +defmodule VigilWeb.SdkCronConformanceTest do
2 + @moduledoc """
3 + Slice 7's exit, with the real clients against a running server:
4 + Vigil's own Oban cron jobs reported through sentry-elixir's Oban
5 + integration (`test/support/sdk/sentry_elixir_oban_cron.exs`) make
6 + monitors, a missed run then opens an incident and alerts; sentry-python's
7 + `monitor` decorator; and sentry-cli's `monitors run` and `monitors list`.
8 + Each is skipped when its checkout or binary is missing.
9 + """
10 + use VigilWeb.ConnCase, async: false
11 + use Oban.Testing, repo: Vigil.Repo
12 +
13 + import Ecto.Query
14 + import Vigil.AccountsFixtures
15 + import Vigil.OrganizationsFixtures
16 +
17 + alias Vigil.{Alerts, ApiTokens, Monitors, Projects, Repo}
18 + alias Vigil.Alerts.Notification
19 + alias Vigil.Monitors.CheckIn
20 +
21 + @elixir_sdk System.get_env(
22 + "SENTRY_ELIXIR_PATH",
23 + Path.expand("~/Development/local/sentry_oss_2019/sentry-elixir")
24 + )
25 +
26 + @python_sdk System.get_env(
27 + "SENTRY_PYTHON_PATH",
28 + Path.expand("~/Development/local/sentry_oss_2019/sentry-python")
29 + )
30 +
31 + @cli System.get_env("SENTRY_CLI") || System.find_executable("sentry-cli")
32 +
33 + setup do
34 + owner = user_fixture()
35 + org = organization_fixture(owner)
36 + scope = org_scope(owner, org)
37 + project = project_fixture(scope, %{"name" => "vigil"})
38 + [key] = Projects.list_keys(project)
39 +
40 + server = start_supervised!({Bandit, plug: VigilWeb.Endpoint, port: 0, ip: :loopback})
41 + {:ok, {_ip, port}} = ThousandIsland.listener_info(server)
42 +
43 + hex = String.replace(key.public_key, "-", "")
44 +
45 + %{
46 + org: org,
47 + scope: scope,
48 + project: project,
49 + url: "http://127.0.0.1:#{port}",
50 + dsn: "http://#{hex}@127.0.0.1:#{port}/#{project.dsn_id}"
51 + }
52 + end
53 +
54 + defp drain(project), do: Vigil.Ingest.Drain.drain(project.id)
55 +
56 + @tag :sdk
57 + @tag timeout: 300_000
58 + test "Vigil's Oban cron jobs through sentry-elixir: monitors, and a missed run alerts", ctx do
59 + if File.exists?(Path.join(@elixir_sdk, "mix.exs")) do
60 + {:ok, _rule} = Alerts.create_rule(ctx.scope, ctx.project, %{name: "Crons", kind: :monitor})
61 + script = Path.expand("../support/sdk/sentry_elixir_oban_cron.exs", __DIR__)
62 +
63 + {out, status} =
64 + System.cmd("elixir", [script],
65 + env: [
66 + {"SENTRY_DSN", ctx.dsn},
67 + {"SENTRY_ELIXIR_PATH", @elixir_sdk},
68 + {"MIX_ENV", "prod"}
69 + ],
70 + stderr_to_stdout: true
71 + )
72 +
73 + assert status == 0, out
74 + drain(ctx.project)
75 +
76 + monitors = Monitors.list_monitors(ctx.project) |> Map.new(&{&1.slug, &1})
77 + maintain = monitors["vigil-partitions-maintain-worker"]
78 + evaluate = monitors["vigil-alerts-evaluate-worker"]
79 + assert maintain && evaluate, "monitors: #{inspect(Map.keys(monitors))}\n#{out}"
80 +
81 + assert {maintain.schedule_type, maintain.schedule} == {:crontab, "17 3 * * *"}
82 + assert maintain.health == :ok
83 +
84 + # Paired: one run each, started and finished.
85 + assert [%CheckIn{status: :ok, duration_ms: ms}] = Monitors.list_check_ins(maintain)
86 + assert ms > 0
87 + assert [%CheckIn{status: :error}] = Monitors.list_check_ins(evaluate)
88 + assert evaluate.health == :error
89 +
90 + # The nightly run doesn't come: missed past the margin, an incident, an alert.
91 + due = maintain.next_expected_at
92 + Monitors.tick(DateTime.add(due, maintain.checkin_margin + 1, :minute))
93 + assert %{health: :error} = Monitors.get_monitor(ctx.project, maintain.slug)
94 +
95 + titles = Repo.all(from n in Notification, select: n.message["title"])
96 + assert "Monitor vigil-partitions-maintain-worker is failing" in titles
97 + assert "Monitor vigil-alerts-evaluate-worker is failing" in titles
98 + else
99 + IO.puts("skipping sentry-elixir Oban crons: no checkout at #{@elixir_sdk}")
100 + end
101 + end
102 +
103 + @tag :sdk
104 + test "sentry-python's monitor decorator", ctx do
105 + if File.dir?(Path.join(@python_sdk, "sentry_sdk")) and System.find_executable("python3") do
106 + script = """
107 + import sentry_sdk
108 + from sentry_sdk.crons import monitor
109 + sentry_sdk.init(dsn=#{inspect(ctx.dsn)}, environment="test")
110 +
111 + @monitor(monitor_slug="py-report", monitor_config={
112 + "schedule": {"type": "interval", "value": 30, "unit": "minute"},
113 + "checkin_margin": 2, "max_runtime": 5})
114 + def report():
115 + return 1
116 +
117 + report()
118 + sentry_sdk.flush(timeout=10)
119 + """
120 +
121 + {out, status} =
122 + System.cmd("python3", ["-c", script],
123 + env: [{"PYTHONPATH", @python_sdk}],
124 + stderr_to_stdout: true
125 + )
126 +
127 + assert status == 0, out
128 + drain(ctx.project)
129 +
130 + assert %{schedule_type: :interval, interval_value: 30, health: :ok} =
131 + m = Monitors.get_monitor(ctx.project, "py-report")
132 +
133 + assert [%CheckIn{status: :ok, environment: "test"}] = Monitors.list_check_ins(m)
134 + else
135 + IO.puts("skipping sentry-python crons: no checkout at #{@python_sdk}")
136 + end
137 + end
138 +
139 + @tag :sdk
140 + test "sentry-cli monitors run and monitors list", ctx do
141 + if @cli do
142 + {:ok, token} =
143 + ApiTokens.create_token(Repo.preload(ctx.scope.user, []), %{
144 + label: "cli",
145 + scopes: ["project:read", "org:read"]
146 + })
147 +
148 + env = [
149 + {"SENTRY_URL", ctx.url},
150 + {"SENTRY_DSN", ctx.dsn},
151 + {"SENTRY_AUTH_TOKEN", token.token},
152 + {"SENTRY_ORG", ctx.org.slug},
153 + {"SENTRY_LOG_LEVEL", "warn"},
154 + {"SENTRY_DISABLE_UPDATE_CHECK", "true"},
155 + {"SENTRY_LOAD_DOTENV", "0"}
156 + ]
157 +
158 + cli = fn args ->
159 + System.cmd(@cli, args, env: env, stderr_to_stdout: true, cd: System.tmp_dir!())
160 + end
161 +
162 + assert {_, 0} = cli.(["monitors", "run", "-s", "*/10 * * * *", "backup", "--", "true"])
163 + assert {_, 1} = cli.(["monitors", "run", "backup", "--", "false"])
164 + drain(ctx.project)
165 +
166 + m = Monitors.get_monitor(ctx.project, "backup")
167 + assert m.schedule == "*/10 * * * *"
168 +
169 + assert m |> Monitors.list_check_ins() |> Enum.map(& &1.status) |> Enum.sort() == [
170 + :error,
171 + :ok
172 + ]
173 +
174 + {out, 0} = cli.(["monitors", "list"])
175 + assert out =~ "backup"
176 + assert out =~ "active"
177 + else
178 + IO.puts("skipping sentry-cli monitors: no sentry-cli on PATH")
179 + end
180 + end
181 +end

Parents: 28e6625