diff options
Diffstat (limited to 'app/services/prometheus/proxy_variable_substitution_service.rb')
-rw-r--r-- | app/services/prometheus/proxy_variable_substitution_service.rb | 48 |
1 files changed, 24 insertions, 24 deletions
diff --git a/app/services/prometheus/proxy_variable_substitution_service.rb b/app/services/prometheus/proxy_variable_substitution_service.rb index 240586c8419..aa3a09ba05c 100644 --- a/app/services/prometheus/proxy_variable_substitution_service.rb +++ b/app/services/prometheus/proxy_variable_substitution_service.rb @@ -4,11 +4,20 @@ module Prometheus class ProxyVariableSubstitutionService < BaseService include Stepable + VARIABLE_INTERPOLATION_REGEX = / + {{ # Variable needs to be wrapped in these chars. + \s* # Allow whitespace before and after the variable name. + (?<variable> # Named capture. + \w+ # Match one or more word characters. + ) + \s* + }} + /x.freeze + steps :validate_variables, :add_params_to_result, :substitute_params, - :substitute_ruby_variables, - :substitute_liquid_variables + :substitute_variables def initialize(environment, params = {}) @environment, @params = environment, params.deep_dup @@ -46,37 +55,28 @@ module Prometheus success(result) end - def substitute_liquid_variables(result) + def substitute_variables(result) return success(result) unless query(result) - result[:params][:query] = - TemplateEngines::LiquidService.new(query(result)).render(full_context) + result[:params][:query] = gsub(query(result), full_context) success(result) - rescue TemplateEngines::LiquidService::RenderError => e - error(e.message) end - def substitute_ruby_variables(result) - return success(result) unless query(result) - - # The % operator doesn't replace variables if the hash contains string - # keys. - result[:params][:query] = query(result) % predefined_context.symbolize_keys - - success(result) - rescue TypeError, ArgumentError => exception - log_error(exception.message) - Gitlab::ErrorTracking.track_exception(exception, { - template_string: query(result), - variables: predefined_context - }) - - error(_('Malformed string')) + def gsub(string, context) + # Search for variables of the form `{{variable}}` in the string and replace + # them with their value. + string.gsub(VARIABLE_INTERPOLATION_REGEX) do |match| + # Replace with the value of the variable, or if there is no such variable, + # replace the invalid variable with itself. So, + # `up{instance="{{invalid_variable}}"}` will remain + # `up{instance="{{invalid_variable}}"}` after substitution. + context.fetch($~[:variable], match) + end end def predefined_context - @predefined_context ||= Gitlab::Prometheus::QueryVariables.call(@environment) + Gitlab::Prometheus::QueryVariables.call(@environment).stringify_keys end def full_context |