summaryrefslogtreecommitdiff
path: root/app/services/prometheus/proxy_variable_substitution_service.rb
blob: 4a6678ec2376dce72b12ec249737f2107233c31b (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
# frozen_string_literal: true

module Prometheus
  class ProxyVariableSubstitutionService < BaseService
    include Stepable

    steps :add_params_to_result, :substitute_ruby_variables

    def initialize(environment, params = {})
      @environment, @params = environment, params.deep_dup
    end

    def execute
      execute_steps
    end

    private

    def add_params_to_result(result)
      result[:params] = params

      success(result)
    end

    def substitute_ruby_variables(result)
      return success(result) unless query

      # The % operator doesn't replace variables if the hash contains string
      # keys.
      result[:params][:query] = query % predefined_context.symbolize_keys

      success(result)
    rescue TypeError, ArgumentError => exception
      log_error(exception.message)
      Gitlab::Sentry.track_exception(exception, extra: {
        template_string: query,
        variables: predefined_context
      })

      error(_('Malformed string'))
    end

    def predefined_context
      @predefined_context ||= Gitlab::Prometheus::QueryVariables.call(@environment)
    end

    def query
      params[:query]
    end
  end
end