#!/usr/bin/env python3
# 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
# - Thomas Beermann, <thomas.beermann@cern.ch>, 2019
# - Eric Vaandering, <ewv@fnal.gov>, 2020-2022

"""
Probe to check the backlog of expired rules.
"""

import sys
import traceback

from prometheus_client import CollectorRegistry, Gauge
from rucio.db.sqla.session import BASE, get_session

from utils import common

PrometheusPusher = common.PrometheusPusher
probe_metrics = common.probe_metrics

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

if BASE.metadata.schema:
    schema = BASE.metadata.schema + '.'
else:
    schema = ''

if __name__ == "__main__":
    try:
        registry = CollectorRegistry()
        session = get_session()
        with PrometheusPusher(registry, job_name='check_expired_rules') as prometheus_config:
            prefix: str = prometheus_config['prefix']
            expired_rules = 'select count(1) from {schema}rules where expires_at < sys_extract_utc(localtimestamp)'.format(schema=schema)
            result = session.execute(expired_rules).fetchone()[0]
            probe_metrics.gauge('judge.expired_rules').set(result)
            Gauge(prefix + 'judge_expired_rules', '', registry=registry).set(result)
            lifetimed_rules = 'select count(1) from {schema}rules where expires_at > sys_extract_utc(localtimestamp)'.format(schema=schema)
            result = session.execute(lifetimed_rules).fetchone()[0]
            print(result)
            probe_metrics.gauge('judge.lifetimed_rules').set(result)
            Gauge(prefix + 'judge_lifetimed_rules', '', registry=registry).set(result)

    except:
        print(traceback.format_exc())
        sys.exit(UNKNOWN)
    sys.exit(OK)
