#!/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:
# - Wen Guan, <wguan@cern.ch>, 2014

'''
Probe to check replicas replicating time by hourly.
'''

import datetime
import sys
import time

from rucio.core import monitor
from rucio.db.sqla.session import get_session

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

if __name__ == "__main__":

    scope = "stresstest"

    try:
        session = get_session()
        utctime = datetime.datetime.utcnow()
        utctimeInt = int(time.mktime(utctime.timetuple()))
        timeStart = utctimeInt - 3600
        timeEnd = timeStart + 3600
        timezoneoffset = int((datetime.datetime.now() - datetime.datetime.utcnow()).seconds)

        # replicas time hourly
        sql = "select t2.rse, t1.created_at, t1.timediff from (select  rse_id, created_at, (cast(updated_at as timestamp)- cast(created_at as timestamp)) timediff \
              from atlas_rucio.replicas where scope='tests' and state='A' and \
              updated_at>= to_timestamp('" + str(datetime.datetime.fromtimestamp(timeStart)) + "','YYYY-MM-dd HH24:MI:SS') \
              and updated_at <to_timestamp('" + str(datetime.datetime.fromtimestamp(timeEnd)) + "','YYYY-MM-dd HH24:MI:SS')) t1 \
              join (select id, rse from atlas_rucio.rses where rse not like 'CERN-PROD-RUCIOTEST_DATADISK') t2 on t1.rse_id = t2.id  "
        result = session.execute(sql).fetchall()
        for rse, timeCreate, timeDiff in result:
            timeCreateInt = int(time.mktime(timeCreate.timetuple()))
            timeDiffInt = timeDiff.seconds + timeDiff.days * 24 * 3600
            # print 'replicas.replicating_time.%s %s %d' % (r[0], timeDiffInt, timeCreateInt + timezoneoffset)
            monitor.record_gauge(stat='%s.replicas.replicating_time.%s' % (scope, rse), value=timeDiffInt)
    except:
        sys.exit(UNKNOWN)
    finally:
        session.remove()
    sys.exit(OK)
