6.1 KiB · text History 3208487
defmodule VigilWeb.SdkCronConformanceTest do
  @moduledoc """
  Slice 7's exit, with the real clients against a running server:
  Vigil's own Oban cron jobs reported through sentry-elixir's Oban
  integration (`test/support/sdk/sentry_elixir_oban_cron.exs`) make
  monitors, a missed run then opens an incident and alerts; sentry-python's
  `monitor` decorator; and sentry-cli's `monitors run` and `monitors list`.
  Each is skipped when its checkout or binary is missing.
  """
  use VigilWeb.ConnCase, async: false
  use Oban.Testing, repo: Vigil.Repo

  import Ecto.Query
  import Vigil.AccountsFixtures
  import Vigil.OrganizationsFixtures

  alias Vigil.{Alerts, ApiTokens, Monitors, Projects, Repo}
  alias Vigil.Alerts.Notification
  alias Vigil.Monitors.CheckIn

  @elixir_sdk System.get_env(
                "SENTRY_ELIXIR_PATH",
                Path.expand("~/Development/local/sentry_oss_2019/sentry-elixir")
              )

  @python_sdk System.get_env(
                "SENTRY_PYTHON_PATH",
                Path.expand("~/Development/local/sentry_oss_2019/sentry-python")
              )

  @cli System.get_env("SENTRY_CLI") || System.find_executable("sentry-cli")

  setup do
    owner = user_fixture()
    org = organization_fixture(owner)
    scope = org_scope(owner, org)
    project = project_fixture(scope, %{"name" => "vigil"})
    [key] = Projects.list_keys(project)

    server = start_supervised!({Bandit, plug: VigilWeb.Endpoint, port: 0, ip: :loopback})
    {:ok, {_ip, port}} = ThousandIsland.listener_info(server)

    hex = String.replace(key.public_key, "-", "")

    %{
      org: org,
      scope: scope,
      project: project,
      url: "http://127.0.0.1:#{port}",
      dsn: "http://#{hex}@127.0.0.1:#{port}/#{project.dsn_id}"
    }
  end

  defp drain(project), do: Vigil.Ingest.Drain.drain(project.id)

  @tag :sdk
  @tag timeout: 300_000
  test "Vigil's Oban cron jobs through sentry-elixir: monitors, and a missed run alerts", ctx do
    if File.exists?(Path.join(@elixir_sdk, "mix.exs")) do
      {:ok, _rule} = Alerts.create_rule(ctx.scope, ctx.project, %{name: "Crons", kind: :monitor})
      script = Path.expand("../support/sdk/sentry_elixir_oban_cron.exs", __DIR__)

      {out, status} =
        System.cmd("elixir", [script],
          env: [
            {"SENTRY_DSN", ctx.dsn},
            {"SENTRY_ELIXIR_PATH", @elixir_sdk},
            {"MIX_ENV", "prod"}
          ],
          stderr_to_stdout: true
        )

      assert status == 0, out
      drain(ctx.project)

      monitors = Monitors.list_monitors(ctx.project) |> Map.new(&{&1.slug, &1})
      maintain = monitors["vigil-partitions-maintain-worker"]
      evaluate = monitors["vigil-alerts-evaluate-worker"]
      assert maintain && evaluate, "monitors: #{inspect(Map.keys(monitors))}\n#{out}"

      assert {maintain.schedule_type, maintain.schedule} == {:crontab, "17 3 * * *"}
      assert maintain.health == :ok

      # Paired: one run each, started and finished.
      assert [%CheckIn{status: :ok, duration_ms: ms}] = Monitors.list_check_ins(maintain)
      assert ms > 0
      assert [%CheckIn{status: :error}] = Monitors.list_check_ins(evaluate)
      assert evaluate.health == :error

      # The nightly run doesn't come: missed past the margin, an incident, an alert.
      due = maintain.next_expected_at
      Monitors.tick(DateTime.add(due, maintain.checkin_margin + 1, :minute))
      assert %{health: :error} = Monitors.get_monitor(ctx.project, maintain.slug)

      titles = Repo.all(from n in Notification, select: n.message["title"])
      assert "Monitor vigil-partitions-maintain-worker is failing" in titles
      assert "Monitor vigil-alerts-evaluate-worker is failing" in titles
    else
      IO.puts("skipping sentry-elixir Oban crons: no checkout at #{@elixir_sdk}")
    end
  end

  @tag :sdk
  test "sentry-python's monitor decorator", ctx do
    if File.dir?(Path.join(@python_sdk, "sentry_sdk")) and System.find_executable("python3") do
      script = """
      import sentry_sdk
      from sentry_sdk.crons import monitor
      sentry_sdk.init(dsn=#{inspect(ctx.dsn)}, environment="test")

      @monitor(monitor_slug="py-report", monitor_config={
          "schedule": {"type": "interval", "value": 30, "unit": "minute"},
          "checkin_margin": 2, "max_runtime": 5})
      def report():
          return 1

      report()
      sentry_sdk.flush(timeout=10)
      """

      {out, status} =
        System.cmd("python3", ["-c", script],
          env: [{"PYTHONPATH", @python_sdk}],
          stderr_to_stdout: true
        )

      assert status == 0, out
      drain(ctx.project)

      assert %{schedule_type: :interval, interval_value: 30, health: :ok} =
               m = Monitors.get_monitor(ctx.project, "py-report")

      assert [%CheckIn{status: :ok, environment: "test"}] = Monitors.list_check_ins(m)
    else
      IO.puts("skipping sentry-python crons: no checkout at #{@python_sdk}")
    end
  end

  @tag :sdk
  test "sentry-cli monitors run and monitors list", ctx do
    if @cli do
      {:ok, token} =
        ApiTokens.create_token(Repo.preload(ctx.scope.user, []), %{
          label: "cli",
          scopes: ["project:read", "org:read"]
        })

      env = [
        {"SENTRY_URL", ctx.url},
        {"SENTRY_DSN", ctx.dsn},
        {"SENTRY_AUTH_TOKEN", token.token},
        {"SENTRY_ORG", ctx.org.slug},
        {"SENTRY_LOG_LEVEL", "warn"},
        {"SENTRY_DISABLE_UPDATE_CHECK", "true"},
        {"SENTRY_LOAD_DOTENV", "0"}
      ]

      cli = fn args ->
        System.cmd(@cli, args, env: env, stderr_to_stdout: true, cd: System.tmp_dir!())
      end

      assert {_, 0} = cli.(["monitors", "run", "-s", "*/10 * * * *", "backup", "--", "true"])
      assert {_, 1} = cli.(["monitors", "run", "backup", "--", "false"])
      drain(ctx.project)

      m = Monitors.get_monitor(ctx.project, "backup")
      assert m.schedule == "*/10 * * * *"

      assert m |> Monitors.list_check_ins() |> Enum.map(& &1.status) |> Enum.sort() == [
               :error,
               :ok
             ]

      {out, 0} = cli.(["monitors", "list"])
      assert out =~ "backup"
      assert out =~ "active"
    else
      IO.puts("skipping sentry-cli monitors: no sentry-cli on PATH")
    end
  end
end