#!/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:
# - Cedric Serfon, <cedric.serfon@cern.ch>, 2014

'''
Probe to check the queues of the transfer service
'''

import os
import sys
from rucio.common.config import config_get
from rucio.common.exception import ServiceUnavailable
from rucio.rse import rsemanager

scheme = 'https'
OK, WARNING, CRITICAL, UNKNOWN = 0, 1, 2, 3
site = sys.argv[1]


try:
    proxy = config_get('nagios', 'proxy')
    os.environ["X509_USER_PROXY"] = proxy
except Exception as e:
    print "Failed to get proxy from rucio.cfg"
    sys.exit(CRITICAL)

try:
    rse_settings = rsemanager.get_rse_info(site)
    dict = rsemanager.select_protocol(rse_settings, operation='write', scheme=scheme)
    basepath = '%s://%s:%s%s' % (dict['scheme'], dict['hostname'], dict['port'], dict['prefix'])
    print 'Testing existence of %s' % basepath
    p = rsemanager.create_protocol(rse_settings, operation='write', scheme='https')
    try:
        p.connect()
    except ServiceUnavailable, e:
        print e
        sys.exit(CRITICAL)
    if not p.exists(basepath):
        sys.exit(CRITICAL)
    p.close()
    print '%s exists' % basepath
except:
    sys.exit(CRITICAL)
sys.exit(OK)
