#!/usr/bin/python
""" MODULE IMPORTS """
""" THIS SCRIPT REQUIRES PSYCOPG2 - INSTALL WITH - 'sudo yum install python-psycopg2' """
import psycopg2
import string
import datetime
import time
import optparse
import sys
import os
import getpass
""" NAGIOS API RETURN CODES """
nag_ret_dict = {'NagOk': 0,
'NagWarn': 1,
'NagCrit': 2,
'NagUnknown': 3}
""" COMMAND LINE OPTION PARSING """
usage = "USAGE: python %prog -d DATABASE -u DB_USER -H REMOTE_HOST -p DB_PASSWORD -w -2 -c -3"
parser = optparse.OptionParser(usage=usage)
parser.add_option('-d', action="store", default="postgres", help="Database selection", type="string")
parser.add_option('-u', action="store", default="postgres", help="DB User", type="string")
parser.add_option('-H', action="store", default="localhost", help="DB Host system", type="string")
parser.add_option('-p', action="store", default="", help="DB Password", type="string")
parser.add_option('-c', action="store", default="-3", help="Critical Date Thresh -nn", type="int")
parser.add_option('-w', action="store", default="-2", help="Warning Date Thresh -nn", type="int")
options, args = parser.parse_args()
""" ARG COUNT CHECK """
if len(sys.argv[1:]) == 0:
parser.print_help()
sys.exit(nag_ret_dict['NagCrit'])
""" TEST DATABASE CONNECTION """
try:
conn = psycopg2.connect("dbname='%s' user='%s' host='%s' password='%s'" \
% (options.d, options.u, options.H, options.p))
except psycopg2.DatabaseError, e:
print e
sys.exit(nag_ret_dict['NagCrit'])
""" LOCAL SCOPE FUNCTIONS """
def query_pg_for_date():
try:
cur = conn.cursor()
cur.execute("""select date, count(*) From table group by date order by date desc limit 1;""")
row = cur.fetchone()
date_s = row[0]
cur.close()
conn.close()
return date_s.strftime("%Y%m%d")
except psycopg2.DatabaseError, e:
print ( 'Error %s' % e )
parser.print_help()
sys.exit(nag_ret_dict['nagiCrit'])
def get_date_now():
date_now = time.strftime("%Y%m%d")
return date_now.split()[0]
""" MAIN FUNCTION """
def main():
queryDate = datetime.datetime.strptime(str(query_pg_for_date()), "%Y%m%d")
actualDate = datetime.datetime.strptime(str(get_date_now()), "%Y%m%d")
deltaCrit = datetime.timedelta(days=options.c)
deltaWarn = datetime.timedelta(days=options.w)
diff = queryDate - actualDate
print("DATETIME NEGATIVE DELTA: [%s]") % diff
print("DATETIME NOW: [%s]") % actualDate
print("DATETIME NOW OF QUERY: [%s]") % queryDate
print("DATETIME CRIT VALUE: [%s]") % deltaCrit
print("DATETIME WARN VALUE: [%s]") % deltaWarn
""" DEFINE LOGIC """
if diff <= deltaCrit:
print("NAGIOS CRIT: [%s] is greater or equal to [%s]") % (diff, deltaCrit)
sys.exit(nag_ret_dict['NagCrit'])
elif diff <= deltaWarn:
print("NAGIOS WARN: [%s] is greater than or equal to [%s]") % (diff, deltaWarn)
sys.exit(nag_ret_dict['NagWarn'])
else:
print("NAGIOS OK: [%s] is less than or equal to [%s]") % (diff, deltaCrit)
sys.exit(nag_ret_dict['NagOk'])
if __name__ == "__main__":
main()