#!/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

'''
Probe to check the backlog of unlocked replicas.
'''

import sys

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

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

# select (select rse from "ATLAS_RUCIO".rses where id = rse_id),
#       n
# from
# (SELECT /*+ index_FFS(replicas REPLICAS_TOMBSTONE_IDX) */
#      CASE WHEN ("ATLAS_RUCIO".replicas.tombstone IS NOT NULL) THEN "ATLAS_RUCIO".replicas.rse_id END as rse_id,
#      count(*) as n
# FROM "ATLAS_RUCIO".replicas
# WHERE "ATLAS_RUCIO".replicas.tombstone is not null
# GROUP BY CASE WHEN ("ATLAS_RUCIO".replicas.tombstone IS NOT NULL) THEN "ATLAS_RUCIO".replicas.rse_id END)

if __name__ == "__main__":
    try:
        session = get_session()
        result = session.execute('select  /*+ index_ffs(replicas REPLICAS_TOMBSTONE_IDX) */  count(1) from atlas_rucio.replicas where tombstone is not null').fetchone()[0]
        monitor.record_gauge(stat='reaper.unlocked_replicas',   value=result)
        print result
        result = session.execute('select  /*+ index_ffs(replicas REPLICAS_TOMBSTONE_IDX) */  count(1) from atlas_rucio.replicas where tombstone is not null and tombstone < sysdate - 2/24').fetchone()[0]
        monitor.record_gauge(stat='reaper.expired_replicas',   value=result)
    except:
        sys.exit(UNKNOWN)
    sys.exit(OK)
