summaryrefslogtreecommitdiff
path: root/app/services/metrics/dashboard/grafana_metric_embed_service.rb
blob: 44b58ad9729e0bf4da2c2369d000491df82d0771 (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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# frozen_string_literal: true

# Responsible for returning a gitlab-compatible dashboard
# containing info based on a grafana dashboard and datasource.
#
# Use Gitlab::Metrics::Dashboard::Finder to retrive dashboards.
module Metrics
  module Dashboard
    class GrafanaMetricEmbedService < ::Metrics::Dashboard::BaseService
      include ReactiveCaching

      SEQUENCE = [
        ::Gitlab::Metrics::Dashboard::Stages::GrafanaFormatter
      ].freeze

      self.reactive_cache_key = ->(service) { service.cache_key }
      self.reactive_cache_lease_timeout = 30.seconds
      self.reactive_cache_refresh_interval = 30.minutes
      self.reactive_cache_lifetime = 30.minutes
      self.reactive_cache_worker_finder = ->(_id, *args) { from_cache(*args) }

      class << self
        # Determines whether the provided params are sufficient
        # to uniquely identify a grafana dashboard.
        def valid_params?(params)
          [
            params[:embedded],
            params[:grafana_url]
          ].all?
        end

        def from_cache(project_id, user_id, grafana_url)
          project = Project.find(project_id)
          user = User.find(user_id)

          new(project, user, grafana_url: grafana_url)
        end
      end

      def get_dashboard
        with_reactive_cache(*cache_key) { |result| result }
      end

      # Inherits the primary logic from the parent class and
      # maintains the service's API while including ReactiveCache
      def calculate_reactive_cache(*)
        # This is called with explicit parentheses to prevent
        # the params passed to #calculate_reactive_cache from
        # being passed to #get_dashboard (which accepts none)
        ::Metrics::Dashboard::BaseService
          .instance_method(:get_dashboard)
          .bind(self)
          .call() # rubocop:disable Style/MethodCallWithoutArgsParentheses
      end

      def cache_key(*args)
        [project.id, current_user.id, grafana_url]
      end

      # Required for ReactiveCaching; Usage overridden by
      # self.reactive_cache_worker_finder
      def id
        nil
      end

      private

      def get_raw_dashboard
        raise MissingIntegrationError unless client

        grafana_dashboard = fetch_dashboard
        datasource = fetch_datasource(grafana_dashboard)

        params.merge!(grafana_dashboard: grafana_dashboard, datasource: datasource)

        {}
      end

      def fetch_dashboard
        uid = GrafanaUidParser.new(grafana_url, project).parse
        raise DashboardProcessingError.new('Dashboard uid not found') unless uid

        response = client.get_dashboard(uid: uid)

        parse_json(response.body)
      end

      def fetch_datasource(dashboard)
        name = DatasourceNameParser.new(grafana_url, dashboard).parse
        raise DashboardProcessingError.new('Datasource name not found') unless name

        response = client.get_datasource(name: name)

        parse_json(response.body)
      end

      def grafana_url
        params[:grafana_url]
      end

      def client
        project.grafana_integration&.client
      end

      def allowed?
        Ability.allowed?(current_user, :read_project, project)
      end

      def sequence
        SEQUENCE
      end

      def parse_json(json)
        JSON.parse(json, symbolize_names: true)
      rescue JSON::ParserError
        raise DashboardProcessingError.new('Grafana response contains invalid json')
      end
    end

    # Identifies the uid of the dashboard based on url format
    class GrafanaUidParser
      def initialize(grafana_url, project)
        @grafana_url, @project = grafana_url, project
      end

      def parse
        @grafana_url.match(uid_regex) { |m| m.named_captures['uid'] }
      end

      private

      # URLs are expected to look like https://domain.com/d/:uid/other/stuff
      def uid_regex
        base_url = @project.grafana_integration.grafana_url.chomp('/')

        %r{^(#{Regexp.escape(base_url)}\/d\/(?<uid>.+)\/)}x
      end
    end

    # Identifies the name of the datasource for a dashboard
    # based on the panelId query parameter found in the url
    class DatasourceNameParser
      def initialize(grafana_url, grafana_dashboard)
        @grafana_url, @grafana_dashboard = grafana_url, grafana_dashboard
      end

      def parse
        @grafana_dashboard[:dashboard][:panels]
          .find { |panel| panel[:id].to_s == query_params[:panelId] }
          .try(:[], :datasource)
      end

      private

      def query_params
        Gitlab::Metrics::Dashboard::Url.parse_query(@grafana_url)
      end
    end
  end
end