#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2009-2012 Red Hat, Inc.
#
# 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
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# This utility script is designed to query the mongodb database
# for sampled records of accounting groups.

# uses pymongo - http://pypi.python.org/pypi/pymongo/
import pymongo
from datetime import timedelta, datetime
from sys import exit, argv
import time, pwd, os
from optparse import OptionParser
from dateutil import *
from dateutil.parser import *

# NOTE: the 1.9 pymongo driver does implicit localtime conversion when
# dates are used in a query so we must compensate, eventhough the dates
# ARE already stored in localtime in 1.6.4 mongodb
# mongodb 1.7+ uses ISODate to address this
UTC_DIFF = datetime.utcnow() - datetime.now()
DEFAULT_START_DT = str(datetime.utcnow()-UTC_DIFF-timedelta(hours=24))
DEFAULT_END_DT = str(datetime.utcnow()-UTC_DIFF)

DATE_FORMAT ='%d-%m-%Y %H:%M'

verbose = False

def print_latest_users():
    latest = stats['samples.accountant'].find().sort('ts',pymongo.DESCENDING).limit(1)[0]['ts']
    print "Latest update:", latest-UTC_DIFF
    print "USER".ljust(50),"GROUP".ljust(20),"PRIO".rjust(8),"RES".rjust(10),"BEGIN USAGE".rjust(20),"LAST USAGE".rjust(20)
    for user in stats['samples.accountant'].find({'ts':latest}).sort('prio',pymongo.ASCENDING):
        print str(user['n']).ljust(50), str(user['ag']).ljust(20), \
        str("%.2f" % round(user['prio'],2)).rjust(8),str(user['ru']).rjust(10),(user['bu']-UTC_DIFF).strftime(DATE_FORMAT).rjust(20),\
            (user['lu']-UTC_DIFF).strftime(DATE_FORMAT).rjust(20)

def print_user(start,end,user):
    print "USER:", user
    print "TIMESTAMP".ljust(30),"PRIO".ljust(10),"FACTOR".rjust(8),"QUOTA".rjust(8),"RES".rjust(8)
    for rec in stats['samples.accountant'].find({'n':user,'ts':{'$gte': parse(start)+UTC_DIFF, \
                '$lt': parse(end)+UTC_DIFF}}).sort('ts',pymongo.DESCENDING):
        print str(rec['ts']-UTC_DIFF).ljust(30), str(rec['prio']).ljust(10),str(rec['fac']).rjust(8),\
            str(rec['cq']).rjust(8),str(rec['ru']).rjust(8)

parser = OptionParser(description='Query Condor ODS for accounting group data')
parser.add_option('-v','--verbose', action="store_true",default=False, help='enable logging')
parser.add_option('-s','--server', action="store", dest='server',
                    default='localhost',
                    help='mongodb database server location: e.g., somehost, localhost:2011')
parser.add_option('-f','--from', dest="start", help='records from datetime in ISO8601 format e.g., \'2011-09-29 12:03\'', default=DEFAULT_START_DT)
parser.add_option('-t','--to', dest="end", help='records to datetime in ISO8601 format e.g., \'2011-09-30T17:16\'',default=DEFAULT_END_DT)
parser.add_option('-U','--user', dest="user", help='report using specific user in start to end range')
(options, args) =  parser.parse_args()

verbose = options.verbose

try:
    connection = pymongo.Connection(options.server)
    stats = connection.condor_stats
    raw = connection.condor_raw
except Exception, e:
    print e
    exit(1)

if verbose:
    print 'from:\t', options.start
    print 'to:\t', options.end

if options.user:
    print_user(options.start,options.end,options.user)
else:
    print_latest_users()
