Commit 43435944 authored by Reuben Pereira's avatar Reuben Pereira Committed by Sean McGivern

Add ability to do variable substitution

- In prometheus proxy api, allow variables to be replaced. For example,
if 'up{env="%{ci_environment_slug}"}' is passed to the endpoint, it
becomes 'up{env="production"}' before being sent to prometheus.
parent e7c9bcec
......@@ -7,9 +7,9 @@ class Projects::Environments::PrometheusApiController < Projects::ApplicationCon
def proxy
result = Prometheus::ProxyService.new(
environment,
request.method,
params[:proxy_path],
params.permit!
proxy_method,
proxy_path,
proxy_params
).execute
if result.nil?
......@@ -31,7 +31,30 @@ class Projects::Environments::PrometheusApiController < Projects::ApplicationCon
private
def query_context
Gitlab::Prometheus::QueryVariables.call(environment)
end
def environment
@environment ||= project.environments.find(params[:id])
end
def proxy_method
request.method
end
def proxy_path
params[:proxy_path]
end
def proxy_params
substitute_query_variables(params).permit!
end
def substitute_query_variables(params)
query = params[:query]
return params unless query
params.merge(query: query % query_context)
end
end
......@@ -14,6 +14,7 @@ describe Projects::Environments::PrometheusApiController do
describe 'GET #proxy' do
let(:prometheus_proxy_service) { instance_double(Prometheus::ProxyService) }
let(:expected_params) do
ActionController::Parameters.new(
environment_params(
......@@ -47,6 +48,38 @@ describe Projects::Environments::PrometheusApiController do
expect(response).to have_gitlab_http_status(:ok)
expect(json_response).to eq(prometheus_json_body)
end
context 'with format string' do
before do
expected_params[:query] = %{up{environment="#{environment.slug}"}}
end
it 'replaces variables with values' do
get :proxy, params: environment_params.merge(query: 'up{environment="%{ci_environment_slug}"}')
expect(Prometheus::ProxyService).to have_received(:new)
.with(environment, 'GET', 'query', expected_params)
end
context 'with nil query' do
let(:params_without_query) do
params = environment_params
params.delete(:query)
params
end
before do
expected_params.delete(:query)
end
it 'does not raise error' do
get :proxy, params: params_without_query
expect(Prometheus::ProxyService).to have_received(:new)
.with(environment, 'GET', 'query', expected_params)
end
end
end
end
context 'with nil result' do
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment