#!/usr/bin/env python
'''Determine the current OutOfMemory count in the specified set of appliances and compare it with the last time.
The state from last time is stored in the specified file.
The file is a JSON dict; keys are machine_component and value is a count of OutOfMemory exceptions
If we detect more OutOfMemory erros than before, we send an email
'''

import os
import sys
import argparse
import json
import subprocess
from recordOutOfMemory import *
import emailHandler

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("user", help="The userid to use for the SSH connection")
    parser.add_argument("file", help="The file contains the JSON repr of the exception count dict")
    parser.add_argument("machines", help="The list of appserver machines machine running the archiver appliance(s)", nargs="+")
    args = parser.parse_args()
    previousExceptionCounts = {}
    if not os.path.exists(args.file):
        print "File does not exist yet. Creating a new file", args.file
        with open(args.file, 'w') as f:
            json.dump({}, f)

    with open(args.file, 'r') as f:
        previousExceptionCounts = json.load(f)
    for machine in args.machines:
        determineAndRecordOutOfMemoryCount(machine, args.user, args.file)
    currentExceptionCounts = {}
    with open(args.file, 'r') as f:
        currentExceptionCounts = json.load(f)
    emailMsg = ""
    for machine in args.machines:
        for component in ['engine', 'etl', 'mgmt', 'retrieval']:
            exceptionCountKey = machine + "_" + component
            if exceptionCountKey not in previousExceptionCounts:
                #print "Did not find previous count for " + exceptionCountKey
                previousExceptionCountForComponent = 0
            else:
                previousExceptionCountForComponent = int(previousExceptionCounts[exceptionCountKey])
            if int(currentExceptionCounts[exceptionCountKey]) > previousExceptionCountForComponent:
                line = "\nComponent {0} in machine {1} has more OutOfMemory errors {2} than before {3}".format(component, machine, currentExceptionCounts[exceptionCountKey], previousExceptionCountForComponent)
                emailMsg = emailMsg + line
    if emailMsg:
        emailSubject = "Archiver OutOfMemory errors"
        emailHandler.sendEmail(emailSubject, emailMsg, [])

        
