#!/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 stress test replicating time statistics every 2 hours.
'''

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 * 2
        timeEnd = timeStart + 3600 * 2
        timezoneoffset = int((datetime.datetime.now() - datetime.datetime.utcnow()).seconds)

        # replicas time hourly
        sql = "select t2.rse, t1.timediff from (select  rse_id, (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  \
               order by rse, timediff"
        result = session.execute(sql).fetchall()

        for rse, timediff in result:
            # print 'replicas.replicating_time.statistics.%s %s' % (rse, timediff)
            timediffInt = timediff.seconds + timediff.days * 24 * 3600
            monitor.record_timer(stat='%s.replicas.replicating_time.statistics.2hours.%s' % (scope, rse), time=timediffInt)

    except:
        sys.exit(UNKNOWN)
    finally:
        session.remove()
    sys.exit(OK)
