debian-mirror-gitlab/lib/gitlab/metrics/dashboard/importers/prometheus_metrics.rb

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

79 lines
2.4 KiB
Ruby
Raw Normal View History

2020-11-24 15:15:51 +05:30
# frozen_string_literal: true
module Gitlab
module Metrics
module Dashboard
module Importers
class PrometheusMetrics
ALLOWED_ATTRIBUTES = %i(title query y_label unit legend group dashboard_path).freeze
# Takes a JSON schema validated dashboard hash and
# imports metrics to database
def initialize(dashboard_hash, project:, dashboard_path:)
@dashboard_hash = dashboard_hash
@project = project
@dashboard_path = dashboard_path
2021-01-03 14:25:43 +05:30
@affected_environment_ids = []
2020-11-24 15:15:51 +05:30
end
def execute
import
2021-01-03 14:25:43 +05:30
rescue ActiveRecord::RecordInvalid, Dashboard::Transformers::Errors::BaseError
2020-11-24 15:15:51 +05:30
false
end
def execute!
import
end
private
attr_reader :dashboard_hash, :project, :dashboard_path
def import
delete_stale_metrics
create_or_update_metrics
end
# rubocop: disable CodeReuse/ActiveRecord
def create_or_update_metrics
# TODO: use upsert and worker for callbacks?
2021-01-03 14:25:43 +05:30
affected_metric_ids = []
2020-11-24 15:15:51 +05:30
prometheus_metrics_attributes.each do |attributes|
2021-01-03 14:25:43 +05:30
prometheus_metric = PrometheusMetric.find_or_initialize_by(attributes.slice(:dashboard_path, :identifier, :project))
2020-11-24 15:15:51 +05:30
prometheus_metric.update!(attributes.slice(*ALLOWED_ATTRIBUTES))
2021-01-03 14:25:43 +05:30
affected_metric_ids << prometheus_metric.id
2020-11-24 15:15:51 +05:30
end
end
# rubocop: enable CodeReuse/ActiveRecord
def delete_stale_metrics
2021-01-03 14:25:43 +05:30
identifiers_from_yml = prometheus_metrics_attributes.map { |metric_attributes| metric_attributes[:identifier] }
2020-11-24 15:15:51 +05:30
stale_metrics = PrometheusMetric.for_project(project)
.for_dashboard_path(dashboard_path)
.for_group(Enums::PrometheusMetric.groups[:custom])
2021-01-03 14:25:43 +05:30
.not_identifier(identifiers_from_yml)
return unless stale_metrics.exists?
stale_metrics.each_batch { |batch| batch.delete_all }
end
2020-11-24 15:15:51 +05:30
def prometheus_metrics_attributes
@prometheus_metrics_attributes ||= begin
Dashboard::Transformers::Yml::V1::PrometheusMetrics.new(
dashboard_hash,
project: project,
dashboard_path: dashboard_path
).execute
end
end
end
end
end
end
end