remote_mirrors.rb 2.06 KB
Newer Older
Ahmad Sherif's avatar
Ahmad Sherif committed
1
module GitLab
2
  module Exporter
Ahmad Sherif's avatar
Ahmad Sherif committed
3 4 5 6
    module Database
      # A helper class to collect remote mirrors metrics.
      class RemoteMirrorsCollector < Base
        QUERY = <<~SQL.freeze
7 8 9
          SELECT project_id, url,
          EXTRACT(EPOCH FROM last_successful_update_at) AS last_successful_update_at,
          EXTRACT(EPOCH FROM last_update_at) AS last_update_at
Ahmad Sherif's avatar
Ahmad Sherif committed
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
          FROM remote_mirrors WHERE project_id IN (%s) AND enabled = 't'
        SQL

        def initialize(args)
          super(args)

          @project_ids = args[:project_ids]
        end

        def run
          return if @project_ids.nil? || @project_ids.empty?

          execute(QUERY % [@project_ids.join(",")]) # rubocop:disable Style/FormatString
        end

        private

        def execute(query)
          with_connection_pool do |conn|
            conn.exec(query)
          end
        rescue PG::UndefinedTable, PG::UndefinedColumn
          nil
        end
      end

      # The prober which is called when gathering metrics
      class RemoteMirrorsProber
        def initialize(opts, metrics: PrometheusMetrics.new)
          @metrics = metrics
          @collector = RemoteMirrorsCollector.new(
            connection_string: opts[:connection_string],
            project_ids: opts[:project_ids]
          )
        end

46
        def probe_db # rubocop:disable Metrics/MethodLength
Ahmad Sherif's avatar
Ahmad Sherif committed
47 48 49 50
          results = @collector.run
          results.to_a.each do |row|
            @metrics.add(
              "project_remote_mirror_last_successful_update_time_seconds",
51 52 53 54 55 56 57
              row["last_successful_update_at"].to_i,
              project_id: row["project_id"],
              url: row["url"]
            )
            @metrics.add(
              "project_remote_mirror_last_update_time_seconds",
              row["last_update_at"].to_i,
Ahmad Sherif's avatar
Ahmad Sherif committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
              project_id: row["project_id"],
              url: row["url"]
            )
          end

          self
        rescue PG::ConnectionBad
          self
        end

        def write_to(target)
          target.write(@metrics.to_s)
        end
      end
    end
  end
end