#!/usr/bin/env python
# Copyright European Organization for Nuclear Research (CERN) 2013
#
# Licensed under the Apache License, Version 2.0 (the "License");
# You may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Authors:
# - Vincent Garonne, <vincent.garonne@cern.ch>, 2013
# - Cedric Serfon, <cedric.serfon@cern.ch>, 2014

'''
Probe to check Oracle.
'''

import sys

import cx_Oracle

from rucio.common.config import config_get
from rucio.core import monitor

# Exit statuses
OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3

if __name__ == "__main__":

    try:
        sql_connection = config_get('database', 'default')
        user = config_get('database', 'powuseraccount')
        password = config_get('database', 'powuserpassword')
    except:
        print 'Cannot get DB parameters'
        sys.exit(CRITICAL)
    dsn = sql_connection.split('@')[1]
    connection = cx_Oracle.connect(user, password, dsn)
    cursor = connection.cursor()
    try:
        query = '''SELECT mname.metric_name, round(VALUE)
FROM
gv$sysmetric sysm,
v$metricname mname
WHERE
mname.metric_id IN (2004, 2006, 2030, 2145, 2058, 2147, 2000, 2016, 2143, 4000, 2024, 2025)
AND mname.group_id = 2
AND inst_id = 2
AND mname.metric_id = sysm.metric_id
AND mname.group_id = sysm.group_id
ORDER BY inst_id, mname.metric_name, mname.metric_unit'''
        cursor.execute(query)
        for (metric, value) in cursor:
            m = 'oracle.%s' % metric.replace(' ', '_')
            print m, value, ' ',
            monitor.record_gauge(stat=m, value=value)
    except:
        sys.exit(UNKNOWN)
    finally:
        cursor.close()
        connection.close()
        # monitor.record_gauge(stat='judge.waiting_dids', value=result)
        # print result
    sys.exit(OK)
