debian-mirror-gitlab/lib/gitlab/database/reindexing/grafana_notifier.rb

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

85 lines
2.4 KiB
Ruby
Raw Normal View History

2021-03-08 18:12:59 +05:30
# frozen_string_literal: true
module Gitlab
module Database
module Reindexing
# This can be used to send annotations for reindexing to a Grafana API
class GrafanaNotifier
2022-06-21 17:19:12 +05:30
def initialize(api_key: nil, api_url: nil, additional_tag: nil)
@api_key = api_key || default_api_key
@api_url = api_url || default_api_url
@additional_tag = additional_tag || default_additional_tag
2021-03-08 18:12:59 +05:30
end
def notify_start(action)
return unless enabled?
payload = base_payload(action).merge(
text: "Started reindexing of #{action.index.name} on #{action.index.tablename}"
)
annotate(payload)
end
def notify_end(action)
return unless enabled?
payload = base_payload(action).merge(
text: "Finished reindexing of #{action.index.name} on #{action.index.tablename} (#{action.state})",
timeEnd: (action.action_end.utc.to_f * 1000).to_i,
isRegion: true
)
annotate(payload)
end
private
2022-06-21 17:19:12 +05:30
def default_api_key
Gitlab::CurrentSettings.database_grafana_api_key || ENV['GITLAB_GRAFANA_API_KEY']
end
def default_api_url
Gitlab::CurrentSettings.database_grafana_api_url || ENV['GITLAB_GRAFANA_API_URL']
end
def default_additional_tag
Gitlab::CurrentSettings.database_grafana_tag || ENV['GITLAB_REINDEXING_GRAFANA_TAG'] || Rails.env
end
2021-03-08 18:12:59 +05:30
def base_payload(action)
{
time: (action.action_start.utc.to_f * 1000).to_i,
2022-06-21 17:19:12 +05:30
tags: ['reindex', @additional_tag.presence, action.index.tablename, action.index.name].compact
2021-03-08 18:12:59 +05:30
}
end
def annotate(payload)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer #{@api_key}"
}
success = Gitlab::HTTP.post("#{@api_url}/api/annotations", body: payload.to_json, headers: headers, allow_local_requests: true).success?
log_error("Response code #{response.code}") unless success
success
2021-06-08 01:23:25 +05:30
rescue StandardError => err
2021-03-08 18:12:59 +05:30
log_error(err)
false
end
def log_error(err)
Gitlab::AppLogger.warn("Unable to notify Grafana from #{self.class}: #{err}")
end
def enabled?
!(@api_url.blank? || @api_key.blank?)
end
end
end
end
end