Class: GitLab::Exporter::Database::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab_exporter/database/base.rb

Overview

An abstract class for interacting with DB

It takes a connection string (e.g. “dbname=test port=5432”)

Constant Summary collapse

POOL_SIZE =
3
POOL_TIMEOUT =

This timeout is configured to higher interval than scrapping of Prometheus to ensure that connection is kept instead of needed to be re-initialized

90

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(connection_string:, logger: nil, **opts) ⇒ Base

rubocop:disable Lint/UnusedMethodArgument



44
45
46
47
# File 'lib/gitlab_exporter/database/base.rb', line 44

def initialize(connection_string:, logger: nil, **opts) # rubocop:disable Lint/UnusedMethodArgument
  @connection_string = connection_string
  @logger = logger
end

Class Method Details

.configure_type_map_for_results(conn) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/gitlab_exporter/database/base.rb', line 28

def self.configure_type_map_for_results(conn)
  tm = PG::BasicTypeMapForResults.new(conn)

  # Remove warning message:
  # Warning: no type cast defined for type "name" with oid 19.
  # Please cast this type explicitly to TEXT to be safe for future changes.
  # Warning: no type cast defined for type "regproc" with oid 24.
  # Please cast this type explicitly to TEXT to be safe for future changes.
  [{ "type": "text", "oid": 19 }, { "type": "int4", "oid": 24 }].each do |value|
    old_coder = tm.coders.find { |c| c.name == value[:type] }
    tm.add_coder(old_coder.dup.tap { |c| c.oid = value[:oid] })
  end

  conn.type_map_for_results = tm
end

.connection_poolObject



18
19
20
21
22
23
24
25
26
# File 'lib/gitlab_exporter/database/base.rb', line 18

def self.connection_pool
  @@connection_pool ||= Hash.new do |h, connection_string| # rubocop:disable Style/ClassVars
    h[connection_string] = ConnectionPool.new(size: POOL_SIZE, timeout: POOL_TIMEOUT) do
      PG.connect(connection_string).tap do |conn|
        configure_type_map_for_results(conn)
      end
    end
  end
end

Instance Method Details

#connection_poolObject



53
54
55
# File 'lib/gitlab_exporter/database/base.rb', line 53

def connection_pool
  self.class.connection_pool[@connection_string]
end

#runObject



49
50
51
# File 'lib/gitlab_exporter/database/base.rb', line 49

def run
  fail NotImplemented
end

#with_connection_poolObject



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/gitlab_exporter/database/base.rb', line 57

def with_connection_pool
  connection_pool.with do |conn|
    yield conn
  rescue PG::UnableToSend => e
    @logger.warn "Error sending to the database: #{e}" if @logger
    conn.reset
    raise e
  end
rescue PG::Error => e
  @logger.error "Error connecting to the database: #{e}" if @logger
  raise e
end