diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2019-10-10 15:06:19 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2019-10-10 15:06:19 +0300 |
commit | 69849c280c5525d132ebaddb1200c390a42ecc06 (patch) | |
tree | 2c6ffc6fd6dc4fa719305f25b475391730389747 /lib/grafana | |
parent | c157f963db87a40a3ba7b94b339530ee83194bc8 (diff) |
Add latest changes from gitlab-org/gitlab@master
Diffstat (limited to 'lib/grafana')
-rw-r--r-- | lib/grafana/client.rb | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/lib/grafana/client.rb b/lib/grafana/client.rb new file mode 100644 index 00000000000..0765630f9bb --- /dev/null +++ b/lib/grafana/client.rb @@ -0,0 +1,67 @@ +# frozen_string_literal: true + +module Grafana + class Client + Error = Class.new(StandardError) + + # @param api_url [String] Base URL of the Grafana instance + # @param token [String] Admin-level API token for instance + def initialize(api_url:, token:) + @api_url = api_url + @token = token + end + + # @param datasource_id [String] Grafana ID for the datasource + # @param proxy_path [String] Path to proxy - ex) 'api/v1/query_range' + def proxy_datasource(datasource_id:, proxy_path:, query: {}) + http_get("#{@api_url}/api/datasources/proxy/#{datasource_id}/#{proxy_path}", query: query) + end + + private + + def http_get(url, params = {}) + response = handle_request_exceptions do + Gitlab::HTTP.get(url, **request_params.merge(params)) + end + + handle_response(response) + end + + def request_params + { + headers: { + 'Authorization' => "Bearer #{@token}", + 'Accept' => 'application/json', + 'Content-Type' => 'application/json' + }, + follow_redirects: false + } + end + + def handle_request_exceptions + yield + rescue Gitlab::HTTP::Error + raise_error 'Error when connecting to Grafana' + rescue Net::OpenTimeout + raise_error 'Connection to Grafana timed out' + rescue SocketError + raise_error 'Received SocketError when trying to connect to Grafana' + rescue OpenSSL::SSL::SSLError + raise_error 'Grafana returned invalid SSL data' + rescue Errno::ECONNREFUSED + raise_error 'Connection refused' + rescue => e + raise_error "Grafana request failed due to #{e.class}" + end + + def handle_response(response) + return response if response.code == 200 + + raise_error "Grafana response status code: #{response.code}" + end + + def raise_error(message) + raise Client::Error, message + end + end +end |