-
Notifications
You must be signed in to change notification settings - Fork 816
/
pgbouncer.py
175 lines (139 loc) · 6.38 KB
/
pgbouncer.py
1
2
3
4
5
6
7
8
9
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""Pgbouncer check
Collects metrics from the pgbouncer database.
"""
from checks import AgentCheck, CheckException
import psycopg2 as pg
class ShouldRestartException(Exception): pass
class PgBouncer(AgentCheck):
"""Collects metrics from pgbouncer
"""
RATE = AgentCheck.rate
GAUGE = AgentCheck.gauge
DB_NAME = 'pgbouncer'
SERVICE_CHECK_NAME = 'pgbouncer.can_connect'
STATS_METRICS = {
'descriptors': [
('database', 'db'),
],
'metrics': {
'total_requests': ('pgbouncer.stats.requests_per_second', RATE),
'total_received': ('pgbouncer.stats.bytes_received_per_second', RATE),
'total_sent': ('pgbouncer.stats.bytes_sent_per_second', RATE),
'total_query_time': ('pgbouncer.stats.total_query_time', GAUGE),
'avg_req': ('pgbouncer.stats.avg_req', GAUGE),
'avg_recv': ('pgbouncer.stats.avg_recv', GAUGE),
'avg_sent': ('pgbouncer.stats.avg_sent', GAUGE),
'avg_query': ('pgbouncer.stats.avg_query', GAUGE),
},
'query': """SHOW STATS""",
}
POOLS_METRICS = {
'descriptors': [
('database', 'db'),
('user', 'user'),
],
'metrics': {
'cl_active': ('pgbouncer.pools.cl_active', GAUGE),
'cl_waiting': ('pgbouncer.pools.cl_waiting', GAUGE),
'sv_active': ('pgbouncer.pools.sv_active', GAUGE),
'sv_idle': ('pgbouncer.pools.sv_idle', GAUGE),
'sv_used': ('pgbouncer.pools.sv_used', GAUGE),
'sv_tested': ('pgbouncer.pools.sv_tested', GAUGE),
'sv_login': ('pgbouncer.pools.sv_login', GAUGE),
'maxwait': ('pgbouncer.pools.maxwait', GAUGE),
},
'query': """SHOW POOLS""",
}
def __init__(self, name, init_config, agentConfig, instances=None):
AgentCheck.__init__(self, name, init_config, agentConfig, instances)
self.dbs = {}
def _get_service_checks_tags(self, host, port):
service_checks_tags = [
"host:%s" % host,
"port:%s" % port,
"db:%s" % self.DB_NAME
]
return service_checks_tags
def _collect_stats(self, db, instance_tags):
"""Query pgbouncer for various metrics
"""
metric_scope = [self.STATS_METRICS, self.POOLS_METRICS]
try:
cursor = db.cursor()
for scope in metric_scope:
cols = scope['metrics'].keys()
try:
query = scope['query']
self.log.debug("Running query: %s" % query)
cursor.execute(query)
results = cursor.fetchall()
except pg.Error, e:
self.log.warning("Not all metrics may be available: %s" % str(e))
continue
for row in results:
if row[0] == self.DB_NAME:
continue
desc = scope['descriptors']
assert len(row) == len(cols) + len(desc)
tags = instance_tags[:]
tags += ["%s:%s" % (d[0][1], d[1]) for d in zip(desc, row[:len(desc)])]
values = zip([scope['metrics'][c] for c in cols], row[len(desc):])
[v[0][1](self, v[0][0], v[1], tags=tags) for v in values]
if not results:
self.warning('No results were found for query: "%s"' % query)
cursor.close()
except pg.Error, e:
self.log.error("Connection error: %s" % str(e))
raise ShouldRestartException
def _get_connection(self, key, host, port, user, password, use_cached=True):
"Get and memoize connections to instances"
if key in self.dbs and use_cached:
return self.dbs[key]
elif host != "" and user != "":
try:
if host == 'localhost' and password == '':
# Use ident method
connection = pg.connect("user=%s dbname=%s" % (user, self.DB_NAME))
elif port != '':
connection = pg.connect(host=host, port=port, user=user,
password=password, database=self.DB_NAME)
else:
connection = pg.connect(host=host, user=user, password=password,
database=self.DB_NAME)
connection.set_isolation_level(pg.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
self.log.debug('pgbouncer status: %s' % AgentCheck.OK)
except Exception:
message = u'Cannot establish connection to pgbouncer://%s:%s/%s' % (host, port, self.DB_NAME)
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.CRITICAL,
tags=self._get_service_checks_tags(host, port), message=message)
self.log.debug('pgbouncer status: %s' % AgentCheck.CRITICAL)
pass
else:
if not host:
raise CheckException("Please specify a PgBouncer host to connect to.")
elif not user:
raise CheckException("Please specify a user to connect to PgBouncer as.")
self.dbs[key] = connection
return connection
def check(self, instance):
host = instance.get('host', '')
port = instance.get('port', '')
user = instance.get('username', '')
password = instance.get('password', '')
tags = instance.get('tags', [])
key = '%s:%s' % (host, port)
if tags is None:
tags = []
else:
tags = list(set(tags))
try:
db = self._get_connection(key, host, port, user, password)
self._collect_stats(db, tags)
except ShouldRestartException:
self.log.info("Resetting the connection")
db = self._get_connection(key, host, port, user, password, use_cached=False)
self._collect_stats(db, tags)
message = u'Established connection to pgbouncer://%s:%s/%s' % (host, port, self.DB_NAME)
self.service_check(self.SERVICE_CHECK_NAME, AgentCheck.OK,
tags=self._get_service_checks_tags(host, port), message=message)
self.log.debug('pgbouncer status: %s' % AgentCheck.OK)