File: //usr/lib/python2.7/site-packages/lap/pgsql.py
import psycopg2
import yaml
import os
def __run__(params):
conn = None
try:
os.environ['PGPASSFILE'] = params.get('pgpassfile')
thresolds = yaml.load(params.get('thresholds'))
conn = psycopg2.connect(host=params.get('host'),
port=int(params.get('port')),
database=params.get('dbname'),
user=params.get('user'))
cursor = conn.cursor()
# we connected, so posgtres is working, now some additional tests
# get number of connections
cursor.execute("select count(1) from pg_stat_activity")
current_connections = cursor.fetchone()[0]
cursor.execute("""select name, setting
from pg_settings
where name = 'max_connections'""")
max_connections = cursor.fetchone()[1]
percent = float(current_connections) / float(max_connections)
percent = percent * 100
if percent > thresolds['critical']:
return [2, 'CRITICAL: {0}% of connections in use'.format(percent)]
elif percent > thresolds['warning']:
return [1, 'WARNING: {0}% of connections in use'.format(percent)]
else:
return [0, 'OK: {0}% of connections in use'.format(percent)]
except Exception, e:
return [2, 'CRITICAL: {0}'.format(str(e).replace('\n', ' '))]
finally:
try:
if conn:
conn.close()
except:
# finally clause, don't bother about errors here
pass