notify_service_spec.rb 10.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
# frozen_string_literal: true

require 'spec_helper'

describe Projects::Prometheus::Alerts::NotifyService do
  let_it_be(:project, reload: true) { create(:project) }

  let(:service) { described_class.new(project, nil, payload) }
  let(:token_input) { 'token' }

  let!(:setting) do
    create(:project_incident_management_setting, project: project, send_email: true, create_issue: true)
  end

  let(:subject) { service.execute(token_input) }

  before do
    # We use `let_it_be(:project)` so we make sure to clear caches
    project.clear_memoization(:licensed_feature_available)
  end

  shared_examples 'sends notification email' do
    let(:notification_service) { spy }

    it 'sends a notification for firing alerts only' do
      expect(NotificationService)
        .to receive(:new)
        .and_return(notification_service)

      expect(notification_service)
        .to receive_message_chain(:async, :prometheus_alerts_fired)

33
      expect(subject).to be_success
34 35 36 37 38 39 40 41 42 43 44 45 46
    end
  end

  shared_examples 'processes incident issues' do |amount|
    let(:create_incident_service) { spy }

    it 'processes issues' do
      expect(IncidentManagement::ProcessPrometheusAlertWorker)
        .to receive(:perform_async)
        .with(project.id, kind_of(Hash))
        .exactly(amount).times

      Sidekiq::Testing.inline! do
47
        expect(subject).to be_success
48 49 50 51 52 53 54 55 56
      end
    end
  end

  shared_examples 'does not process incident issues' do
    it 'does not process issues' do
      expect(IncidentManagement::ProcessPrometheusAlertWorker)
        .not_to receive(:perform_async)

57
      expect(subject).to be_success
58 59 60 61 62 63 64 65 66 67 68 69 70 71
    end
  end

  shared_examples 'persists events' do
    let(:create_events_service) { spy }

    it 'persists events' do
      expect(Projects::Prometheus::Alerts::CreateEventsService)
        .to receive(:new)
        .and_return(create_events_service)

      expect(create_events_service)
        .to receive(:execute)

72
      expect(subject).to be_success
73 74 75 76 77 78 79 80
    end
  end

  shared_examples 'notifies alerts' do
    it_behaves_like 'sends notification email'
    it_behaves_like 'persists events'
  end

81
  shared_examples 'no notifications' do |http_status:|
82 83 84 85 86 87 88
    let(:notification_service) { spy }
    let(:create_events_service) { spy }

    it 'does not notify' do
      expect(notification_service).not_to receive(:async)
      expect(create_events_service).not_to receive(:execute)

89 90
      expect(subject).to be_error
      expect(subject.http_status).to eq(http_status)
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    end
  end

  context 'with valid payload' do
    let(:alert_firing) { create(:prometheus_alert, project: project) }
    let(:alert_resolved) { create(:prometheus_alert, project: project) }
    let(:payload_raw) { payload_for(firing: [alert_firing], resolved: [alert_resolved]) }
    let(:payload) { ActionController::Parameters.new(payload_raw).permit! }
    let(:payload_alert_firing) { payload_raw['alerts'].first }
    let(:token) { 'token' }

    context 'with project specific cluster' do
      using RSpec::Parameterized::TableSyntax

      where(:cluster_enabled, :status, :configured_token, :token_input, :result) do
        true  | :installed | token | token | :success
        true  | :installed | nil   | nil   | :success
        true  | :updated   | token | token | :success
        true  | :updating  | token | token | :failure
        true  | :installed | token | 'x'   | :failure
        true  | :installed | nil   | token | :failure
        true  | :installed | token | nil   | :failure
        true  | nil        | token | token | :failure
        false | :installed | token | token | :failure
      end

      with_them do
        before do
          cluster = create(:cluster, :provided_by_user,
                           projects: [project],
                           enabled: cluster_enabled)

          if status
            create(:clusters_applications_prometheus, status,
                   cluster: cluster,
                   alert_manager_token: configured_token)
          end
        end

        case result = params[:result]
        when :success
          it_behaves_like 'notifies alerts'
        when :failure
134
          it_behaves_like 'no notifications', http_status: :unauthorized
135 136 137 138 139 140 141 142 143
        else
          raise "invalid result: #{result.inspect}"
        end
      end
    end

    context 'without project specific cluster' do
      let!(:cluster) { create(:cluster, enabled: true) }

144
      it_behaves_like 'no notifications', http_status: :unauthorized
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
    end

    context 'with manual prometheus installation' do
      using RSpec::Parameterized::TableSyntax

      where(:alerting_setting, :configured_token, :token_input, :result) do
        true  | token | token | :success
        true  | token | 'x'   | :failure
        true  | token | nil   | :failure
        false | nil   | nil   | :success
        false | nil   | token | :failure
      end

      with_them do
        let(:alert_manager_token) { token_input }

        before do
          create(:prometheus_service, project: project)

          if alerting_setting
            create(:project_alerting_setting,
                   project: project,
                   token: configured_token)
          end
        end

        case result = params[:result]
        when :success
          it_behaves_like 'notifies alerts'
        when :failure
175
          it_behaves_like 'no notifications', http_status: :unauthorized
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
        else
          raise "invalid result: #{result.inspect}"
        end
      end
    end

    context 'alert emails' do
      before do
        create(:prometheus_service, project: project)
        create(:project_alerting_setting, project: project, token: token)
      end

      context 'when incident_management_setting does not exist' do
        let!(:setting) { nil }

        it_behaves_like 'persists events'

        it 'does not send notification email', :sidekiq_might_not_need_inline do
          expect_any_instance_of(NotificationService)
            .not_to receive(:async)

197
          expect(subject).to be_success
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
        end
      end

      context 'when incident_management_setting.send_email is true' do
        it_behaves_like 'notifies alerts'
      end

      context 'incident_management_setting.send_email is false' do
        let!(:setting) do
          create(:project_incident_management_setting, send_email: false, project: project)
        end

        it_behaves_like 'persists events'

        it 'does not send notification' do
          expect(NotificationService).not_to receive(:new)

215
          expect(subject).to be_success
216 217 218 219
        end
      end
    end

220 221 222 223 224 225 226 227
    context 'process Alert Management alerts' do
      let(:process_service) { instance_double(AlertManagement::ProcessPrometheusAlertService) }

      before do
        create(:prometheus_service, project: project)
        create(:project_alerting_setting, project: project, token: token)
      end

228 229 230
      context 'with multiple firing alerts and resolving alerts' do
        let(:payload_raw) do
          payload_for(firing: [alert_firing, alert_firing], resolved: [alert_resolved])
231 232
        end

233
        it 'processes Prometheus alerts' do
234
          expect(AlertManagement::ProcessPrometheusAlertService)
235 236 237 238 239
            .to receive(:new)
            .with(project, nil, kind_of(Hash))
            .exactly(3).times
            .and_return(process_service)
          expect(process_service).to receive(:execute).exactly(3).times
240 241 242 243 244 245

          subject
        end
      end
    end

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    context 'process incident issues' do
      before do
        create(:prometheus_service, project: project)
        create(:project_alerting_setting, project: project, token: token)
      end

      context 'with create_issue setting enabled' do
        before do
          setting.update!(create_issue: true)
        end

        it_behaves_like 'processes incident issues', 2

        context 'multiple firing alerts' do
          let(:payload_raw) do
            payload_for(firing: [alert_firing, alert_firing], resolved: [])
          end

          it_behaves_like 'processes incident issues', 2
        end

        context 'without firing alerts' do
          let(:payload_raw) do
            payload_for(firing: [], resolved: [alert_resolved])
          end

          it_behaves_like 'processes incident issues', 1
        end
      end

      context 'with create_issue setting disabled' do
        before do
          setting.update!(create_issue: false)
        end

        it_behaves_like 'does not process incident issues'
      end
    end
  end

  context 'with invalid payload' do
    context 'without version' do
      let(:payload) { {} }

290
      it_behaves_like 'no notifications', http_status: :unprocessable_entity
291 292 293 294 295
    end

    context 'when version is not "4"' do
      let(:payload) { { 'version' => '5' } }

296
      it_behaves_like 'no notifications', http_status: :unprocessable_entity
297 298 299 300 301
    end

    context 'with missing alerts' do
      let(:payload) { { 'version' => '4' } }

302
      it_behaves_like 'no notifications', http_status: :unauthorized
303 304 305 306 307 308 309 310 311 312
    end

    context 'when the payload is too big' do
      let(:payload) { { 'the-payload-is-too-big' => true } }
      let(:deep_size_object) { instance_double(Gitlab::Utils::DeepSize, valid?: false) }

      before do
        allow(Gitlab::Utils::DeepSize).to receive(:new).and_return(deep_size_object)
      end

313
      it_behaves_like 'no notifications', http_status: :bad_request
314

315 316 317 318 319 320 321
      it 'does not process Prometheus alerts' do
        expect(AlertManagement::ProcessPrometheusAlertService)
          .not_to receive(:new)

        subject
      end

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
      it 'does not process issues' do
        expect(IncidentManagement::ProcessPrometheusAlertWorker)
          .not_to receive(:perform_async)

        subject
      end
    end
  end

  private

  def payload_for(firing: [], resolved: [])
    status = firing.any? ? 'firing' : 'resolved'
    alerts = firing + resolved
    alert_name = alerts.first.title
    prometheus_metric_id = alerts.first.prometheus_metric_id.to_s

    alerts_map = \
      firing.map { |alert| map_alert_payload('firing', alert) } +
      resolved.map { |alert| map_alert_payload('resolved', alert) }

    # See https://prometheus.io/docs/alerting/configuration/#%3Cwebhook_config%3E
    {
      'version' => '4',
      'receiver' => 'gitlab',
      'status' => status,
      'alerts' => alerts_map,
      'groupLabels' => {
        'alertname' => alert_name
      },
      'commonLabels' => {
        'alertname' => alert_name,
        'gitlab' => 'hook',
        'gitlab_alert_id' => prometheus_metric_id
      },
      'commonAnnotations' => {},
      'externalURL' => '',
      'groupKey' => "{}:{alertname=\'#{alert_name}\'}"
    }
  end

  def map_alert_payload(status, alert)
    {
      'status' => status,
      'labels' => {
        'alertname' => alert.title,
        'gitlab' => 'hook',
        'gitlab_alert_id' => alert.prometheus_metric_id.to_s
      },
      'annotations' => {},
      'startsAt' => '2018-09-24T08:57:31.095725221Z',
      'endsAt' => '0001-01-01T00:00:00Z',
      'generatorURL' => 'http://prometheus-prometheus-server-URL'
    }
  end
end