#!/usr/bin/env python
#-*- coding: utf-8 -*-
import re

__author__ = 'mah'
__email__ = 'andrew.makhotin@gmail.com'
import os
from shutil import copyfile
import urllib
import subprocess
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler
import MySQLdb as mdb
import time
import pexpect
import logging
import sys
import logging
import logging.handlers




logger = logging.getLogger('Logging for check_sound')
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler = logging.handlers.RotatingFileHandler('/var/log/eservices/check_sound.log',
                                               maxBytes=(1048576 * 5),
                                               backupCount=5)
handler.setFormatter(formatter)
consolehandler = logging.StreamHandler()  # for stdout
consolehandler.setFormatter(formatter)
logger.addHandler(consolehandler)
logger.addHandler(handler)

class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

host = '10.0.0.7'
port = 8089


dbhost = '10.185.0.136'
dbuser = 'program_user'
dbpasswd = 'sha4REP9'
dbbase = 'program'

server = SimpleXMLRPCServer((host, port), requestHandler=RequestHandler)
server.register_introspection_functions()


def parser_log(log_file, pos=-2000):
    print os.getcwd()
    pat = re.compile('(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s.\s-\s\[(.*)\].*login=(\d{1,})&pass=(\d{1,})')
    try:
        with open(log_file, 'r') as f:
            f.seek(pos, 2)
            for s in f:
                res = pat.match(s.strip())
                if res:
                    print res.groups()
    except ValueError:
        print 'End of file'
    except KeyboardInterrupt:
        print 'Exit...'
        os._exit(0)


server.register_function(parser_log, 'parser_log')


if __name__ == '__main__':
    logger.info('Start xml server')
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print 'Exit...'
        sys.exit(0)

