summaryrefslogtreecommitdiff
path: root/lib/gitlab/alerting/notification_payload_parser.rb
blob: ce04205a1ba183583963e5dacd93ba8d9ef80482 (plain)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# frozen_string_literal: true

module Gitlab
  module Alerting
    class NotificationPayloadParser
      BadPayloadError = Class.new(StandardError)

      DEFAULT_TITLE = 'New: Incident'
      DEFAULT_SEVERITY = 'critical'

      def initialize(payload, project)
        @payload = payload.to_h.with_indifferent_access
        @project = project
      end

      def self.call(payload, project)
        new(payload, project).call
      end

      def call
        {
          'annotations' => annotations,
          'startsAt' => starts_at
        }.compact
      end

      private

      attr_reader :payload, :project

      def title
        payload[:title].presence || DEFAULT_TITLE
      end

      def severity
        payload[:severity].presence || DEFAULT_SEVERITY
      end

      def fingerprint
        Gitlab::AlertManagement::Fingerprint.generate(payload[:fingerprint])
      end

      def annotations
        primary_params
          .reverse_merge(flatten_secondary_params)
          .transform_values(&:presence)
          .compact
      end

      def primary_params
        {
          'title' => title,
          'description' => payload[:description],
          'monitoring_tool' => payload[:monitoring_tool],
          'service' => payload[:service],
          'hosts' => hosts.presence,
          'severity' => severity,
          'fingerprint' => fingerprint,
          'environment' => environment
        }
      end

      def hosts
        Array(payload[:hosts]).reject(&:blank?)
      end

      def current_time
        Time.current.change(usec: 0).rfc3339
      end

      def starts_at
        Time.parse(payload[:start_time].to_s).rfc3339
      rescue ArgumentError
        current_time
      end

      def environment
        environment_name = payload[:gitlab_environment_name]

        return unless environment_name

        EnvironmentsFinder.new(project, nil, { name: environment_name })
          .find
          &.first
      end

      def secondary_params
        payload.except(:start_time)
      end

      def flatten_secondary_params
        Gitlab::Utils::SafeInlineHash.merge_keys!(secondary_params)
      rescue ArgumentError
        raise BadPayloadError, 'The payload is too big'
      end
    end
  end
end

Gitlab::Alerting::NotificationPayloadParser.prepend_if_ee('EE::Gitlab::Alerting::NotificationPayloadParser')