#!/usr/bin/env python

'''This monitors the status of EPICS V4 services every 5 minutes'''

import argparse
import json
import os
import subprocess
import time
 
from datetime import datetime

def print_to_log(logfile, logstr):
    try:
        print>>logfile,    logstr
        logfile.flush()
        os.fsync(logfile.fileno())
    except OSError as e:
        print 'Error code {}: {}, {}'.format(e.errno, e.strerror, e.filename)    

def test_v4_service(cmd_list, status_pv, logfile):
    status_codes = { 'V4_SERVICE_OK': 0, 'V4_SERVICE_ERROR': 1 }

    try:
        print_to_log(logfile, 'Running: ' + ' '.join(cmd_list))
        retcode = subprocess.call(cmd_list, stdout=logfile, stderr=subprocess.STDOUT)
        logfile.flush()
        os.fsync(logfile.fileno())
        print_to_log(logfile, 'Returned status {}'.format(retcode))
        if retcode == 0:
            set_v4_status_pv(status_pv, status_codes['V4_SERVICE_OK'], logfile)
        else:
            set_v4_status_pv(status_pv, status_codes['V4_SERVICE_ERROR'], logfile)            
    except OSError as e:
        print_to_log(logfile, 'test_v4_service error code {}: {}, {}'.format(e.errno, e.strerror, e.filename))
        set_v4_status_pv(status_pv, status_codes['V4_SERVICE_ERROR'], logfile)            
    
def set_v4_status_pv(status_pv, status_code, logfile):
    cmd_list = [ 'pvput', '-p', 'ca', str(status_pv), str(status_code) ]

    try:
        print_to_log(logfile, 'Running: ' + ' '.join(cmd_list))
        retcode = subprocess.call(cmd_list, stdout=logfile, stderr=subprocess.STDOUT)
        logfile.flush()
        os.fsync(logfile.fileno())
        if retcode != 0:     
            print_to_log(logfile, 'Error setting V4 service status PV {}'.format(status_pv))
    except OSError as e:
        print_to_log(logfile, 'set_v4_status_pv error code {}: {}, {}'.format(e.errno, e.strerror, e.filename))
    
    print_to_log(logfile, '\n\n')

def main():
    parser = argparse.ArgumentParser(prog='v4_service_monitor', description='Script to test basic functionality of EPICS V4 services')
    parser.add_argument('services', metavar='services', help='A JSON file containing the EPICS V4 services to be monitored')
    parser.add_argument('--logfile', metavar='filepath', required=False, default='/tmp/v4_service_monitor.log', help='Log file for daemon')

    args = parser.parse_args()

    try:
        with open(args.logfile, 'w') as logfile:
            try:
                current_datetime = 'Checking V4 services {}\n'.format(datetime.now())
                underline_str = str('='*len(current_datetime))[:len(current_datetime)]
                print_to_log(logfile, underline_str)
                print_to_log(logfile, current_datetime)

                json_data = {}
                if os.path.exists(args.services):
                    with open(args.services) as f:
                        json_data = json.load(f)
            except OSError as e:
                print_to_log(logfile, '{} returned error code {}: {} {}'.format(parser.prog, e.errno, e.filename, e.strerror))

            if json_data:    
                for service in json_data['services']:
                    test_args = [arg['arg'].encode('utf-8') for arg in service['test_args'] if isinstance(arg['arg'], unicode)]
                    cmd_list = ['eget'] + test_args            
                    print_to_log(logfile, 'Testing ' + service['service_name'] + ' service: ')
                            
                    status_pv = service['status_pv']
                    
                    test_v4_service(cmd_list, status_pv, logfile)        

            else:
                print_to_log(logfile, 'No services found')

            print_to_log(logfile, '\n\n')

    except IOError as e:
        print_to_log(logfile, '{} returned error code {}: {} {}'.format(parser.prog, e.errno, e.filename, e.strerror))

if __name__ == '__main__':
    main()
