Example #1
0
def main(argv):

    try:
        yaml_path = './config/backup_file_check_logger.yaml'
        ct.setup_logging(yaml_path)
        linuxInfo = ct.get_server_config(
            './config/backup_file_check_config.txt')

        for info in linuxInfo:

            bfc = backup_file_check(info)
            origin_check_flag = bfc.check_origin_file()
            back_check = False
            if origin_check_flag:
                back_check = bfc.check_backupserver_lastday_file()
            if back_check:
                bfc.del_before_2days_file()

    except Exception:
        logger.error('Faild to check backup file!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)
def main(argv):

    try:
        yaml_path = './config/file_transfer_logger.yaml'
        ct.setup_logging(yaml_path)
        linuxInfo = ct.get_server_config('./config/file_transfer_config.txt')

        #读取输入参数
        ftmethod = ''
        windir = ''
        lindir = ''
        singlefile = ''
        try:
            opts, args = getopt.getopt(
                argv, "hm:w:l:f:",
                ["method=", "windir=", "lindir=", "filename="])
        except getopt.GetoptError:
            print(
                'file_transfer.py -m <method> -w <windir> -l <lindir> -f <filename>'
            )
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print(
                    'file_transfer.py -m <method> -w <windir> -l <lindir> -f <filename>\n \
                    method=upload, means upload file from windows to linux.\n \
                    method=download, means download file from linux to windows. \n \
                    windir=dir, Window dir, The format like this: "D:\\my_project\\python". \n \
                    lindir=dir, Linux dir, The format like this: "/home/trade/temp". \n \
                    filename=filename, options- The single file to upload or download.'
                )
                sys.exit()
            elif opt in ("-m", "--method"):
                ftmethod = arg
            elif opt in ("-w", "--windir"):
                windir = arg
            elif opt in ("-l", "--lindir"):
                lindir = arg
            elif opt in ("-f", "--filename"):
                singlefile = arg

        #多线程处理
        thrlist = range(len(linuxInfo))
        threads = []
        #        singlefile = 'monitor_log_2019-05-30.txt'
        #        ftmethod = 'download'
        if ftmethod == 'upload':
            #                thrlist = range(len(linuxInfo))
            #                threads=[]
            for (i, info) in zip(thrlist, linuxInfo):
                hostip = info[0]
                port = int(info[1])
                username = info[2]
                password = info[3]
                servername = info[4]
                local_upload = info[5]
                local_download = info[6]
                remote_dir = info[7]

                #                    hostip = '192.168.238.7'
                #                    username = '******'
                #                    password = '******'
                #                    port = 22
                #                    local_upload = 'D:/my_project/python/auto_monitor/upload'
                #                    download_dir = 'D:/my_project/python/auto_monitor/download'
                #                    remote_dir = '/home/trade/temp'

                if windir != '':
                    local_upload = windir
                if lindir != '':
                    remote_dir = lindir
                t = MyThread(upload, (
                    local_upload,
                    remote_dir,
                    hostip,
                    port,
                    username,
                    password,
                    singlefile,
                ), upload.__name__ + str(i))
                threads.append(t)
        elif ftmethod == 'download':
            #                thrlist = range(len(linuxInfo))
            #                threads=[]
            for (i, info) in zip(thrlist, linuxInfo):
                hostip = info[0]
                port = int(info[1])
                username = info[2]
                password = info[3]
                servername = info[4]
                local_upload = info[5]
                local_download = info[6]
                remote_dir = info[7]

                if windir != '':
                    local_download = windir
                if lindir != '':
                    remote_dir = lindir
                t = MyThread(download, (
                    local_download,
                    remote_dir,
                    hostip,
                    port,
                    username,
                    password,
                    singlefile,
                ), download.__name__ + str(i))
                threads.append(t)
        else:
            logger.error("method input is invalid! -m upload or -m download?")
            return


#        print "thrcouat3:", threading.active_count()
        for i in thrlist:
            threads[i].start()
        for i in thrlist:
            threads[i].join()

    except Exception:
        logger.error('Faild to transfer file!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)
def main(argv):
    
    try:
        yaml_path = './config/non_trade_monitor_logger.yaml'
        ct.setup_logging(yaml_path)
        #获得log_file目录,不要改变yaml的root设置info_file_handler位置设置,不然获取可能失败
        t = logger.handlers
        log_file = t[1].baseFilename
#        print(log_file)
#        log_file = './mylog/non_trade_monitor_run.log'
        #初始化参数表
        ct.init_sms_control_data()
        #init interval
        inc = 59
        manual_task = ''
        try:
            opts, args = getopt.getopt(argv,"ht:",["task="])
        except getopt.GetoptError:
            print('non_trade_monitor.py -t <task> or you can use -h for help')
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print('non_trade_monitor.py -t <task>\n \
                    (default:python non_trade_monitor.py) means auto work by loops. \n \
                    use -t can input the manul single task.\n \
                    task=["ps","mem","ping","disk","core","xwdm","cleanup","sjdr","self_monitor","follow","ssh_connect","exch_file"].  \n \
                    task="ps" means porcess monitor  \n \
                    task="mem" means memory monitor  \n \
                    task="ping" means ping server monitor  \n \
                    task="disk" means disk monitor  \n \
                    task="core" means core file monitor  \n \
                    task="xwdm" means init VIP_GDH file xwdm check  \n \
                    task="bef_cleanup" means db cleanup check  \n \
                    task="aft_cleanup" means db cleanup check  \n \
                    task="self_monitor" means self check monitor  \n \
                    task="follow" means follow csv file monitor  \n \
                    task="ssh_connect" means ssh connect monitor  \n \
                    task="ssh_excute" means ssh connect monitor  \n \
                    task="bkdb" means backup db monitor  \n \
                    task="clean_dblog" means shrink db log  \n \
                    task="exch_file" means exhcnage file monitor  \n \
                    task="sjdr" means sjdr folder Order file monitor  ' )            
                sys.exit()
            elif opt in ("-t", "--task"):
                manual_task = arg
            if manual_task not in ["ps","mem","ping","disk","core","xwdm","aft_cleanup","bef_cleanup","sjdr","follow","bkdb","clean_dblog","self_monitor","ssh_connect","ssh_excute","exch_file"]:
                logger.info("[task] input is wrong, please try again!")
                sys.exit()
            logger.info('manual_task is:%s' % manual_task)
    #    if inc == 0:
        #task=["ps_port","mem","fpga","db_init","db_trade","errorLog"]
        if manual_task == 'ping':
            logger.info("Start to excute the ping server monitor")
            ping_monitor_task()
        elif manual_task == 'mem':
            logger.info("Start to excute the mem monitor")
            mem_monitor_task()
        elif manual_task == 'disk':
            logger.info("Start to excute the disk monitor")
            disk_monitor_task()
        elif manual_task == 'ps':
            logger.info("Start to excute the ps monitor")
            ps_monitor_task()
        elif manual_task == 'core':
            logger.info("Start to excute the core file monitor")
            core_file_monitor_task()
        elif manual_task == 'xwdm':
            logger.info("Start to excute the xwdm check")
            xwdm_monitor_task()
        elif manual_task == 'aft_cleanup':
            logger.info("Start to excute the cleanup db monitor")
            after_cleanup_db_monitor_task()
        elif manual_task == 'bef_cleanup':
            logger.info("Start to excute the cleanup db monitor")
            before_cleanup_db_monitor_task()
        elif manual_task == 'sjdr':
            logger.info("Start to excute the sjdr monitor")
            sjdr_monitor_task()
        elif manual_task == 'follow':
            logger.info("Start to excute the follow csv monitor")
            follow_monitor_task()
        elif manual_task == 'self_monitor':
            logger.info("Start to excute the self monitor")
            self_log_monitor_task(log_file)
        elif manual_task == 'ssh_connect':
            logger.info("Start to excute the ssh login monitor")
            check_ssh_connect_task()
        elif manual_task == 'ssh_excute':
            logger.info("Start to excute the ssh remote command")
            ssh_remote_command_task()
        elif manual_task == 'bkdb':
            logger.info("Start to excute the backup db monitor")
            backup_db_monitor_task()
        elif manual_task == 'clean_dblog':
            logger.info("Start to excute the shrink db log monitor")
            shrink_dblog_monitor_task()
        elif manual_task == 'exch_file':
            logger.info("Start to excute the exchange file monitor")
            exchange_file_monitor_task()
        else:
            # 只执行一次的任务,fpga监控,数据库资金等信息监控
#            fpga_task()
#            db_init_monitor_task()
            print("input error")
            sys.exit()
            #自动监控暂时不做20190814,下面代码无效
            while True:
                     
                start_time = '15:59'
                end_time = '08:30'
                #监控时间点列表
                ps_monitor_minites = ['10','20','30','40','50','00']
#                test_minites = ['12','41','05','07','09','00']          
                mem_monitor_minites = ['20','50']
                db_monitor_minites = ['26','36','46','56','06','16']
                now_Mtime = dt.datetime.now().strftime('%M')
                now_time = dt.datetime.now().strftime('%H:%M')
                if (ct.time_check(start_time, '23:59') or ct.time_check('00:00', end_time)):
                   
                    if (now_time in ['16:00','17:00','21:00','07:00','08:00']):
                        #自己检查自己是否存活
                        self_log_monitor_task(log_file)
                    else:
                        logger.debug("Not to excute self check")
                    #每个01分检查一次。
                    if (now_Mtime == '01'):
                        #10分钟一次,端口和进程监控,错误日志监控
                        ping_monitor_task()
                    else:
                        logger.info("It's not time to excute the ping monitor")
                        
#                    if (now_Mtime in db_monitor_minites) and ct.trade_check():
#                        #10分钟一次,数据库盘中监控
#                        db_trade_monitor_task()
#                    else:
#                        logger.info("It's not time to excute the db monitor")
#    #                now_time = dt.datetime.now().strftime('%H:%M')
                        
                    if (now_Mtime in mem_monitor_minites):
                        #30分钟一次,服务器内存监控
                        mem_monitor_task()
                    else:
                        logger.info("It's not time to excute the mem monitor")            
                    
                    if (ct.time_check('08:00', '15:32')):
                        logger.info("Exit non trade monitor")
                        break
                                   
                else:
                    logger.info("It's not time to excute the non trade monitor")
                time.sleep(inc)
    except Exception:
        logger.error('Faild to run non_trade_monitor!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)
Example #4
0
def main(argv):
  
    try:
        yaml_path = './config/file_transfer_logger.yaml'
        ct.setup_logging(yaml_path)
        linuxInfo = ct.get_server_config('./config/file_transfer_config.txt')
        
        #读取输入参数
        ftmethod = ''
        windir = ''
        lindir = ''
        singlefile = ''
        try:
            opts, args = getopt.getopt(argv,"hm:l:r:f:",["method=", "local_dir=", "remote_dir=" ,"filename="])
        except getopt.GetoptError:
            print('file_transfer.py -m <method> -l <local_dir> -r <remote_dir> -f <filename>')
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print('file_transfer.py -m <method> -w <windir> -l <lindir> -f <filename>\n \
                    method=upload, means upload file from windows to linux.\n \
                    method=download, means download file from linux to windows. \n \
                    windir=dir, Window dir, The format like this: "D:\\my_project\\python". \n \
                    lindir=dir, Linux dir, The format like this: "/home/trade/temp". \n \
                    filename=filename, options- The single file to upload or download.'  )       
                sys.exit()
            elif opt in ("-m", "--method"):
                ftmethod = arg
            elif opt in ("-l", "--local_dir"):
                windir = arg
            elif opt in ("-r", "--remote_dir"):
                lindir = arg
            elif opt in ("-f", "--filename"):
                singlefile = arg

        
#            hostip = '192.168.238.7'
#            username = '******'
#            password = '******'
#            port = 22
#            local_upload = 'D:/my_project/python/auto_monitor/upload'
#            download_dir = 'D:/my_project/python/auto_monitor/download'
#            remote_dir = '/home/trade/temp'
            
          
#        singlefile = 'monitor_log_2019-05-30.txt'
#        ftmethod = 'download'
        if ftmethod == 'upload':
            for info in linuxInfo:               
                hostip = info[0]
                port = int(info[1])
                username = info[2]
                password = info[3]
                local_upload = info[5]
                local_download = info[6]
                remote_dir = info[7]
                
                if windir !='':
                    local_upload = windir
                if lindir !='':
                    remote_dir = lindir
                upload(local_upload, remote_dir, hostip, port, username, password, singlefile)
        elif ftmethod == 'download':
            for info in linuxInfo:               
                hostip = info[0]
                port = int(info[1])
                username = info[2]
                password = info[3]
                local_upload = info[5]
                local_download = info[6]
                remote_dir = info[7]
                
                if windir !='':
                    local_download = windir
                if lindir !='':
                    remote_dir = lindir
                download(local_download, remote_dir, hostip, port, username, password, singlefile)
        else:
            logger.error("method input is invalid! -m upload or -m download?")
        
    except Exception:
        logger.error('Faild to transfer file!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)
Example #5
0
def main(argv):

    try:
        yaml_path = './config/trade_monitor_logger.yaml'
        ct.setup_logging(yaml_path)
        #        #初始化参数表
        #        init_data()
        #        #init interval
        #        inc = 59
        #        #清除tempdate的数据库表记录条数文件。启动时执行一次。
        #        if os.path.isdir("./tempdata"):
        #            for filename in os.listdir('./tempdata'):
        #                os.remove('./tempdata/' + filename)
        #        else:
        #            os.mkdir("./tempdata")
        manual_task = ''
        try:
            opts, args = getopt.getopt(argv, "ht:", ["task="])
        except getopt.GetoptError:
            print('trade_monitor.py -t <task> or you can use -h for help')
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print('python trade_monitor.py -t <task>\n \
                    parameter -t comment: \n \
                    use -t can input the manul single task.\n \
                    task=["ps_port","mem","fpga","db_init","db_trade","mdapi_qry","traderapi_qmd","login_front","errorLog"].  \n \
                    task="ps_port" means porcess and port monitor  \n \
                    task="mem" means memory monitor  \n \
                    task="db_trade" means db trading data monitor  \n \
                    task="errorLog" means file error log monitor  \n \
                    task="mdapi_qry" means mdapi qry market data monitor  \n \
                    task="traderapi_qmd" means mdapi qry market data monitor  \n \
                    task="login_front" means tradeapi login front monitor  \n \
                    task="tcp_con" means tcp connect count monitor  \n \
                    task="self_monitor" means self check monitor  \n \
                    task="smss" means check the sms send status  \n \
                    task="sms0" means set sms total_count=0  \n \
                    task="sms100" means set sms total_count=100  \n \
                    No parameter comment: \n \
                    (default:python trade_monitor.py) means auto work by loops. \n \
                    ps_port_monitor_minites = ["10","20","30","40","50","00"] \n \
                    mem_monitor_minites = ["20","50"] \n \
                    db_monitor_minites = ["26","36","46","56","06","16"] \n \
                    slef_check_mitnits = ["09:00","10:00","11:00","13:00","14:00"] \n \
                    fpga_monitor and db_init_monitor just execute once on beginning '
                      )
                sys.exit()
            elif opt in ("-t", "--task"):
                manual_task = arg
            if manual_task not in [
                    "ps_port", "mem", "fpga", "db_init", "db_trade",
                    "errorLog", "mdapi_qry", "traderapi_qmd", "login_front",
                    "tcp_con", "self_monitor", "smss", "sms0", "sms100"
            ]:
                logger.warning("[task] input is wrong, please try again!")
                sys.exit()
            logger.info('manual_task is:%s' % manual_task)
    #    if inc == 0:
    #task=["ps_port","mem","fpga","db_init","db_trade","errorLog"]
        if manual_task == 'ps_port':
            logger.info("Start to excute the ps_port monitor")
            port_process_task()
        elif manual_task == 'mem':
            logger.info("Start to excute the mem monitor")
            mem_monitor_task()
        elif manual_task == 'self_monitor':
            logger.info("Start to excute the self monitor")
            self_log_monitor_task()
        elif manual_task == 'db_trade':
            logger.info("Start to excute the db_trade monitor")
            db_trade_monitor_task()
        elif manual_task == 'errorLog':
            logger.info("Start to excute the errorLog monitor")
            errorLog_monitor_task()
        elif manual_task == 'mdapi_qry':
            logger.info("Start to excute the mdapi qry_market_data monitor")
            mdapi_monitor_qry_task()
        elif manual_task == 'tcp_con':
            logger.info("Start to excute the tcp connect count monitor")
            tcp_connect_monitor_task()
        elif manual_task == 'traderapi_qmd':
            logger.info(
                "Start to excute the traderapi qry_market_data monitor")
            traderapi_QMD_monitor_task()
        elif manual_task == 'login_front':
            logger.info("Start to excute the traderapi login_front monitor")
            traderapi_login_front_monitor_task()
        elif manual_task == 'smss':
            logger.info("查看发送短信状态")
            ct.sms_switch('status')
        elif manual_task == 'sms0':
            logger.info("关闭发送短信功能")
            ct.sms_switch(0)
        elif manual_task == 'sms100':
            logger.info("打开发送短信功能")
            ct.sms_switch(200)
        else:
            # 只执行一次的任务,fpga监控,数据库资金等信息监控
            print("Input python trade_monitor_tasks.py -h for help")

    except Exception:
        logger.error('Faild to run trade_monitor_tasks!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)
Example #6
0
def main(argv):

    try:
        yaml_path = './config/api_monitor_logger.yaml'
        ct.setup_logging(yaml_path)

        with open('./config/api_monitor_config.json', 'r') as f:
            JsonData = json.load(f)
            logger.debug(JsonData)

        manual_task = ''
        try:
            opts, args = getopt.getopt(argv, "ht:", ["task="])
        except getopt.GetoptError:
            print(
                'sppytraderapi_check.py -t <task> or you can use -h for help')
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print('python tradeapi_monitor.py -t <task>\n \
                    parameter -t comment: \n \
                    use -t can input the manul single task.\n \
                    task=["qry_market_data","mem","fpga","db_init","db_trade","errorLog"].  \n \
                    task="qry_market_data" means porcess and port monitor  \n \
                    task="login_front" means login_front monitor  \n \
                    task="qry_security" means memory monitor  \n \
                    task="db_trade" means db trading data monitor  \n \
                    task="errorLog" means file error log monitor  \n \
                    task="self_monitor" means self check monitor  \n \
                    task="smss" means check the sms send status  \n \
                    task="sms0" means set sms total_count=0  \n \
                    fpga_monitor and db_init_monitor just execute once on beginning '
                      )
                sys.exit()
            elif opt in ("-t", "--task"):
                manual_task = arg

        if manual_task not in [
                "qry_market_data", "qry_security", "login_front"
        ]:
            logger.warning("[task] input is wrong, please try again!")
            sys.exit()

        else:
            logger.info('manual_task is:%s' % manual_task)
            logger.info("Start to excute the api monitor")
            TraderApi_CheckData = JsonData['PyTraderApi']
            check_result_list = []
            for CheckData in TraderApi_CheckData:
                front_addresses = CheckData['front_addresses']
                CheckData.pop('front_addresses')
                for address in front_addresses:
                    #print("address:",address)
                    CheckData['address'] = address
                    #print("CheckData:",CheckData)
                    check_flag = run_app(manual_task, CheckData)
                    check_result_list.append(check_flag)
            check_result = (sum(check_result_list) == len(check_result_list))
            if check_result:
                msg = "Ok,所有服务器 traderapi行情查询 返回结果正确!"
                logger.info(msg)
                ct.send_sms_control("NoLimit", msg)
            else:
                logger.info("Error: 有服务器 traderapi行情查询 返回结果不正确!")

    except Exception:
        logger.error('Faild to run trade api monitor!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)
Example #7
0
def main(argv):

    try:
        yaml_path = './config/trade_monitor_logger.yaml'
        ct.setup_logging(yaml_path)
        #初始化参数表
        #        init_data()
        ct.init_sms_control_data()
        #init interval
        inc = 59
        #清除tempdate的数据库表记录条数文件。启动时执行一次。
        if os.path.isdir("./tempdata"):
            for filename in os.listdir('./tempdata'):
                os.remove('./tempdata/' + filename)
        else:
            os.mkdir("./tempdata")
        manual_task = ''
        try:
            opts, args = getopt.getopt(argv, "ht:", ["task="])
        except getopt.GetoptError:
            print('trade_monitor.py -t <task> or you can use -h for help')
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print('python trade_monitor.py -t <task>\n \
                    parameter -t comment: \n \
                    use -t can input the manul single task.\n \
                    task=["ps_port","mem","fpga","db_init","db_trade","errorLog"].  \n \
                    task="ps_port" means porcess and port monitor  \n \
                    task="mem" means memory monitor  \n \
                    task="fpga" means fpga file monitor  \n \
                    task="db_init" means db init data monitor  \n \
                    task="db_trade" means db trading data monitor  \n \
                    task="errorLog" means file error log monitor  \n \
                    task="smss" means check the sms send status  \n \
                    task="sms0" means set sms total_count=0  \n \
                    task="sms100" means set sms total_count=100  \n \
                    No parameter comment: \n \
                    (default:python trade_monitor.py) means auto work by loops. \n \
                    ps_port_monitor_minites = ["10","20","30","40","50","00"] \n \
                    mem_monitor_minites = ["20","50"] \n \
                    db_monitor_minites = ["26","36","46","56","06","16"] \n \
                    slef_check_mitnits = ["09:00","10:00","11:00","13:00","14:00"] \n \
                    fpga_monitor and db_init_monitor just execute once on beginning '
                      )
                sys.exit()
            elif opt in ("-t", "--task"):
                manual_task = arg
            if manual_task not in [
                    "ps_port", "mem", "fpga", "db_init", "db_trade",
                    "errorLog", "self_monitor", "smss", "sms0", "sms100"
            ]:
                logger.error("[task] input is wrong, please try again!")
                sys.exit()
            logger.info('manual_task is:%s' % manual_task)
    #    if inc == 0:
    #task=["ps_port","mem","fpga","db_init","db_trade","errorLog"]
        if manual_task == 'ps_port':
            logger.info("Start to excute the ps_port monitor")
            port_process_task()
        elif manual_task == 'mem':
            logger.info("Start to excute the mem monitor")
            mem_monitor_task()
        elif manual_task == 'self_monitor':
            logger.info("Start to excute the self monitor")
            self_log_monitor_task()
        elif manual_task == 'fpga':
            logger.info("Start to excute the fpga monitor")
            fpga_task()
        elif manual_task == 'db_init':
            logger.info("Start to excute the db_init monitor")
            db_init_monitor_task()
        elif manual_task == 'db_trade':
            logger.info("Start to excute the db_trade monitor")
            db_trade_monitor_task()
        elif manual_task == 'errorLog':
            logger.info("Start to excute the errorLog monitor")
            errorLog_monitor_task()
        elif manual_task == 'smss':
            logger.info("查看发送短信状态")
            ct.sms_switch('status')
        elif manual_task == 'sms0':
            logger.info("关闭发送短信功能")
            ct.sms_switch(0)
        elif manual_task == 'sms100':
            logger.info("打开发送短信功能")
            ct.sms_switch(100)
        else:
            # 只执行一次的任务,fpga监控,数据库资金等信息监控
            #20200728,暂停fpga监控
            #fpga_task()
            db_init_monitor_task()
            while True:
                start_time = '08:50'
                end_time = '15:30'
                #监控时间点列表
                ps_monitor_minites = ['10', '20', '30', '40', '50', '00']
                #                test_minites = ['12','41','05','07','09','00']
                mem_monitor_minites = ['20', '50']
                db_monitor_minites = ['26', '36', '46', '56', '06', '16']
                #                now_Htime = dt.datetime.now().strftime('%H')
                now_Mtime = dt.datetime.now().strftime('%M')
                now_time = dt.datetime.now().strftime('%H:%M')
                if (ct.time_check(start_time, end_time)):

                    if (now_time in [
                            '08:59', '09:59', '10:59', '11:59', '12:59',
                            '13:59', '14:59'
                    ]):
                        #自己检查自己是否存活
                        self_log_monitor_task()
                    else:
                        logger.info("Not to excute self check")

                    if (now_Mtime in ps_monitor_minites):
                        #10分钟一次,端口和进程监控,错误日志监控
                        port_process_task()
                        errorLog_monitor_task()
                    else:
                        logger.info("It's not time to excute the ps monitor")

                    if (now_Mtime in db_monitor_minites) and ct.trade_check():
                        #10分钟一次,数据库盘中监控
                        db_trade_monitor_task()
                    else:
                        logger.info("It's not time to excute the db monitor")
    #                now_time = dt.datetime.now().strftime('%H:%M')

                    if (now_Mtime in mem_monitor_minites):
                        #30分钟一次,服务器内存监控
                        mem_monitor_task()
                    else:
                        logger.info("It's not time to excute the mem monitor")

                    if (ct.time_check('15:30', '21:32')):
                        logger.info("Exit trade monitor")
                        break

                else:
                    logger.info("It's not time to excute the trade monitor")
                time.sleep(inc)
    except Exception:
        logger.error('Faild to run trade_monitor!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)
def main(argv):

    try:
        yaml_path = './config/db_check_logger.yaml'
        ct.setup_logging(yaml_path)

        with open('./config/table_check.json', 'r') as f:
            Jsonlist = json.load(f)
            logger.debug(Jsonlist)

        #init interval
        inc = 600
        modul = ''
        try:
            opts, args = getopt.getopt(argv, "hl:e:",
                                       ["loopsecends=", "excute="])
        except getopt.GetoptError:
            print('db_monitor.py -l <loopsecends> -e <excute>')
            sys.exit(2)
        for opt, arg in opts:
            if opt == '-h':
                print('db_monitor.py -l <loopsecends> -e <excute>\n \
                    loopsecends=0 means no loop and just run once.\n \
                    loopsecends=N means loop interval is N second. \n \
                    (default:python db_monitor.py) means loop interval is 600 seconds. \n \
                    excute=before means excute the before trade db monitor. \n \
                    excute=trading means excute the trading db monitor. \n \
                    excute is Null means excute before and trading db monitor.'
                      )
                sys.exit()
            elif opt in ("-l", "--loopsecends"):
                inc = int(arg)
            elif opt in ("-e", "--excute"):
                modul = arg
            logger.info('interval is: %d' % inc)
            logger.info('modull is:s: %s' % modul)
        if inc == 0:
            if modul == 'before' or modul == '':
                #before trade montior
                logger.info("Start to excute the before trade monitor")
                thrlist = range(len(Jsonlist))
                threads = []
                for (i, info) in zip(thrlist, Jsonlist):
                    #print("alltask.__name__:", alltask.__name__)
                    t = MyThread(before_trade_monitor, (info, ),
                                 before_trade_monitor.__name__ + str(i))
                    threads.append(t)

                for i in thrlist:
                    threads[i].start()
                for i in thrlist:
                    threads[i].join()
                    threadResult = threads[i].get_result()
                    sysstr = platform.system()
                    if (not threadResult) and (sysstr == "Windows"):
                        ct.readTexts("Database trade before Worning")
            if modul == 'trading' or modul == '':
                #trading monitor
                #delete all tempdata/*.json
                if os.path.isdir("./tempdata"):
                    for filename in os.listdir('./tempdata'):
                        os.remove('./tempdata/' + filename)
                else:
                    os.mkdir("./tempdata")
                logger.info("Start to excute the trading_monitor")
                thrlist = range(len(Jsonlist))
                threads = []
                for (i, info) in zip(thrlist, Jsonlist):
                    t = MyThread(trading_monitor, (info, ),
                                 trading_monitor.__name__ + str(i))
                    threads.append(t)
#                print "thrcouat3:", threading.active_count()
                for i in thrlist:
                    threads[i].start()
                for i in thrlist:
                    threads[i].join()
                    trading_check = threads[i].get_result()
                    if (not trading_check) and (sysstr == "Windows"):
                        ct.readTexts("Database trading Worning")
        elif inc > 20:
            #before trade montior
            logger.info("Start to excute the before trade monitor")
            thrlist = range(len(Jsonlist))
            threads = []
            for (i, info) in zip(thrlist, Jsonlist):
                #print("alltask.__name__:", alltask.__name__)
                t = MyThread(before_trade_monitor, (info, ),
                             before_trade_monitor.__name__ + str(i))
                threads.append(t)

            for i in thrlist:
                threads[i].start()
            for i in thrlist:
                threads[i].join()
                threadResult = threads[i].get_result()
                sysstr = platform.system()
                if (not threadResult) and (sysstr == "Windows"):
                    ct.readTexts("Database trade before Worning")
#            print "thrcount:", threading.active_count()

#trading monitor
#delete all tempdata/*.json
            if os.path.isdir("./tempdata"):
                for filename in os.listdir('./tempdata'):
                    os.remove('./tempdata/' + filename)
            else:
                os.mkdir("./tempdata")
            while True:
                #            while False:
                if (ct.trade_check()):
                    logger.info("Start to excute the trading_monitor")
                    thrlist = range(len(Jsonlist))
                    threads = []
                    for (i, info) in zip(thrlist, Jsonlist):
                        t = MyThread(trading_monitor, (info, ),
                                     trading_monitor.__name__ + str(i))
                        threads.append(t)
                    for i in thrlist:
                        threads[i].start()
                    for i in thrlist:
                        threads[i].join()
                        trading_check = threads[i].get_result()
                        if (not trading_check) and (sysstr == "Windows"):
                            ct.readTexts("Database trading Worning")


#                    print "thrcouat3:", threading.active_count()
                    time.sleep(inc - 20)
                    if (ct.time_check('15:00', '15:12')):
                        logger.info("exit to monitor")
                        break
                else:
                    logger.info("It's not time to trading monitor")
                time.sleep(20)
        else:
            logger.error(
                "Input parameter error: The interval must greater than 20!")
    except Exception:
        logger.error('Faild to run monitor db!', exc_info=True)
    finally:
        for handler in logger.handlers:
            logger.removeHandler(handler)