def SvcStop(self): printf("*******ServiceDataCommCenter stop", True) set_center_stop() while check_center_stop(): time.sleep(1) killall_pid() if check_center_stop(): return delete_server_key() self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) sys.stopservice = "true" win32event.SetEvent(self.hWaitStop)
def delete_tempcmd(dev, devcmd_list, d_server, acmd=None): #从字典缓存中删除临时命令 try: if devcmd_list: if acmd: d_server.delete_sub_dict("TEMP_CMD", dev.id, acmd) #执行成功或执行超时的命令,从字典缓存中删除 else: #进程中取出该设备的命令后或者删除设备时,将该设备的命令缓存清空 d_server.delete_sub_dict("TEMP_CMD", dev.id) # else: #write_log('---- delete_tempcmd devcmd_list is None in =%d'%dev.id) except Exception, e: printf('---except--delete_tempcmd--e=%s' % e, True) pass
def acc_cdata_post(request, device, d_server=None): from mysite import settings from mysite.iclock.devview import STAMPS raw_Data = request.raw_post_data #print "raw_Data:%s"%raw_Data #print request.META.items() if not raw_Data: raw_Data = request.META['raw_post_data'] #print settings.ENCRYPT #logger.error(raw_Data) if settings.ENCRYPT: import lzo rawData = lzo.bufferDecrypt(raw_Data, device.sn) else: rawData = raw_Data #print '---raw_Data=',raw_Data stamp=None for s in STAMPS: stamp=request.REQUEST.get(s, None) if not (stamp is None): stamp_name=STAMPS[s] break # print stamp_name,'======stamp_name' if stamp is None: return "UNKNOWN" msg=None if stamp_name == 'log_stamp': c, ec, msg = cdata_post_acc_trans_state(device, rawData, d_server) else: c = 0 #push下发开关门命令---darcy20110803 try: c = d_server.pop_from_dict("GLOBAL_APB_CMD_%s"%device.sn) or "" except Exception, e: from traceback import print_exc print_exc() printf('------send push e=%d'%e, True)
def connect(self): params="" if (self.hcommpro>0): return {"result":self.hcommpro,"data":str(self.hcommpro)} if (self.comminfo["comm_type"] == 1): params=u"protocol=TCP,ipaddress=%s,port=%d,timeout=4000,passwd=%s"%(self.comminfo["ipaddress"], self.comminfo["ip_port"], self.comminfo["password"]) elif (self.comminfo["comm_type"] == 2): params=u"protocol=RS485,port=%s,baudrate=%sbps,deviceid=%d,timeout=4000,passwd=%s"%(self.comminfo["com_port"], self.comminfo["baudrate"], self.comminfo["com_address"], self.comminfo["password"]) constr = create_string_buffer(params) #print params self.hcommpro = self.commpro.Connect(constr) printf("13. dev=%s, ret=%d"%(params, self.hcommpro)) #print "Connect....",self.hcommpro if(self.hcommpro>0): self.connected = True else: error=self.get_last_error(); if error>0: error = 0 - error self.hcommpro=error self.connected = False return {"result":self.hcommpro,"data":str(self.hcommpro)}
def run_acc_dictmanager(): from redis_self.filequeue import SyncDict, FileQueue from mysite.utils import printf from mysite.iaccess.linux_or_win import run_commend try: #raw_input("Press any key to start server".center(50, "-")) #print '--server started--' q_server = FileQueue() printf("-svr8000--pid=%s" % os.getpid(), True) pid = q_server.get_from_file("DICT_SERVER_PID") #print '--pid2=',pid if pid: process_info = os.popen(run_commend(1) % pid).read() #print '---process_info=',process_info if run_commend(3) in process_info.lower(): os.system(run_commend(2) % pid) #启动时收尸 q_server.set_to_file("DICT_SERVER_PID", "%d" % (os.getpid())) q_server.connection.disconnect() except Exception, e: import traceback traceback.print_exc()
def get_transaction(self, newlog=True, file_buffer=None, file_len=None): if (self.hcommpro <= 0) and newlog != "SD":#通过SD卡获取记录时不需要连接设备 return {'result':ERROR_COMM_HANDLE,'data':''} #communication error log="" ret = -1007 str_buf_len = 8*1024*1024 str_buf = create_string_buffer(str_buf_len) try: if newlog: if newlog == "SD": ret = self.commpro.ProcessBackupData(file_buffer, file_len, str_buf, str_buf_len) else: write_log("-----devcomm before GetDeviceData newlog device:%s pid=%d"%(self.comminfo["ipaddress"], os.getpid())) ret = self.commpro.GetDeviceData(self.hcommpro, str_buf, str_buf_len, "transaction", "*", "", "NewRecord"); write_log("-----devcomm after GetDeviceData newlog device:%s pid=%d"%(self.comminfo["ipaddress"], os.getpid())) else: write_log("-----devcomm before GetDeviceData all logs device:%s pid=%d"%(self.comminfo["ipaddress"], os.getpid())) ret = self.commpro.GetDeviceData(self.hcommpro, str_buf, str_buf_len, "transaction", "*", "", ""); write_log("-----devcomm after GetDeviceData all logs device:%s pid=%d"%(self.comminfo["ipaddress"], os.getpid())) except Exception,e: printf("-----devcomm before GetDeviceData newlog device:%s e:%s"%(self.comminfo["ipaddress"], e), True) return {"result":ret, "data":""}
def set_center_stop(): fqpath = "%s/_fqueue/" % (os.getcwd()) printf("*********%s" % fqpath, True) q_server = queqe_server_path(fqpath) len = q_server.llen(CENTER_PROCE_LIST) printf("****************%d" % len) for i in range(0, len, 1): proce_name = q_server.lindex(CENTER_PROCE_LIST, i) proce_server_key = "%s_SERVER" % proce_name printf("********%s" % proce_server_key) q_server.set(proce_server_key, "STOP") q_server.connection.disconnect()
def check_center_stop(d_server, processes): #Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. try: for process in processes: process_status = d_server.get_from_dict( "%s_SERVER" % process) #如Net0_SERVER #要么为stop要么为空 #printf("--process_status=%s"%process_status, True) if process_status: #多个进程,只要有一个还没被停掉,就返回True printf("check_center_stop--True--", True) return True printf("check_center_stop---False-", True) return False #全部停掉了,返回False except Exception, e: printf("--check_center_stop-e=%s" % e, True)
def killall_pid(d_server, q_server, processes): try: fqpath = "%s/_fqueue/" % (os.getcwd()) main_pid = q_server.get_from_file("CENTER_MAIN_PID") printf("main_pid============%s" % main_pid, True) os.system("taskkill /PID %s /F /T" % main_pid) if processes: for process in processes: #强制杀子进程 chilren_pid = q_server.get_from_file("PROCESS_%s_PID" % process) printf("chilren_pid============%s" % chilren_pid, True) os.system("taskkill /PID %s /F /T" % chilren_pid) d_server.delete_dict("CENTER_RUNING") except Exception, e: printf("killall_pid e=======%s" % e, True)
def run(self): from mysite.iclock.cache_cmds import TEMP_CMD_KEY print '----run push process temp cmd====' while True: timeout = 0 temp_cmd_obj = None while True: temp_cmd_lock = cache.get("TEMP_CMD_LOCK_PUSH") if temp_cmd_lock: timeout = timeout+1 if timeout > 300: printf("-process_temp_cmd---push---timeout***break-", True) break time.sleep(0.5) continue else: cache.set("TEMP_CMD_LOCK_PUSH", 1) temp_cmd_list = cache.get(TEMP_CMD_KEY) #print temp_cmd_list,'======temp_cmd_list==key=',cache.get(TEMP_CMD_KEY) if temp_cmd_list: temp_cmd_obj = temp_cmd_list.pop() cache.set(TEMP_CMD_KEY, temp_cmd_list) cache.set("TEMP_CMD_LOCK_PUSH", 0) break if temp_cmd_obj: device = temp_cmd_obj.SN ipaddress = device.ipaddress params = "" device_server_info = "%s:8370"%ipaddress #device_server_info = "192.168.8.41:80" conn = httplib.HTTPConnection(device_server_info) headers = {"Content-type": "application/x-www-form-urlencoded;charset=gb2312","Accept": "application/json, text/javascript, */*"} try: conn.timeout = 50 conn.request('GET', "?urgCmd=%s"%temp_cmd_obj.CmdContent, params, headers) #conn.request('GET', "?urgCmd=GET OPTION NetMask,GATEIPAddress", params, headers) #conn.request('GET', "/accounts/login/", params, headers) print '--------conn send request--dir==%s'%dir(conn) except Exception, e: print '---conn.request-error=%s'%e temp_cmd_obj.CmdReturn = -10060#发送请求失败 temp_cmd_obj.save() conn.close() write_log('---conn.request-error=%s'%e) time.sleep(1.5) continue print '========before get response==' ret = None try: ret = conn.getresponse() except Exception, e: print '============get response error=%s'%e pass print '========after get response==%s'%ret ret_read = ret.read() print ret.status,'============ret.status' print ret_read, '-------ret_read' ret_dict = {} if ret.status == 200: rets = ret_read.split('&') print '========rets==',rets ret_return = rets[0] ret_dict[ret_return.split('=')[0]] = ret_return.split('=')[1] if ret_dict["Return"] >= 0: from mysite.iaccess.dev_comm_center import G_DEVICE_GET_OPTION if temp_cmd_obj.CmdContent.startswith("DATA QUERY transaction") > 0: from dev_comm_center import process_event_log try: process_event_log(device, ret_dict["Result"]) except Exception, e: printf("PUSH****process_event_log-=-=%s"%e, True) pass elif temp_cmd_obj.CmdContent.startswith(G_DEVICE_GET_OPTION) > 0: ret_result = rets[1].split('Result=') if len(ret_result) > 0: ret_result = ret_result[1].split('=') print '=====ret_result=!!!',ret_result for r in ret_result: rets = r.split('=') ret_dict[rets[0]] = rets[1]#待处理 print '&&&&&&&&ret_dict===', ret_dict temp_cmd_obj.CmdReturn = ret_dict["Return"]
'log_id': logid, 'all_id': rtid_all, #无效 'alarm_id': rtid_alarm, 'log_count': log_count, #返回的有效的记录条数,用于改变logid 'data': cdatas, 'door_states': door_states["data"], #门状态数据 } #print '----00031' #print "**########**cc=",cc rtdata = simplejson.dumps(cc) #print '----00032' return HttpResponse(smart_str(rtdata)) except Exception, e: print_exc() print '---get rt log e=', e printf('----e=%s' % e, True) return HttpResponse(smart_str(rtdata)) #进行设备监控--iclock #新增-删除设备后请先手动刷新页面 @login_required def get_device_monitor(request): try: global g_monitor_server if not g_monitor_server: g_monitor_server = start_dict_server() service_enable = check_service_commcenter(g_monitor_server) dev_monitor_list = g_monitor_server.get_from_dict("DEV_MONITOR_LIST") device_added = g_monitor_server.get_from_dict(
def __init__(self, configFile='attsite.ini'): #global sync_dict os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' p=os.getcwd() self.p=p # os.environ['PATH']="%(p)s\\Apache2\\bin;%(p)s\\Python25;%(p)s\\mssql"%{"p":p}+os.environ['PATH'] # newpath="%INSTALL_PATH%\\mssql;%INSTALL_PATH%\\mssql\\win32;%INSTALL_PATH%\\mssql\\win32\\lib;%INSTALL_PATH%\\Python25;%INSTALL_PATH%\\Python25\\Lib\\site-packages;%INSTALL_PATH%".replace('%INSTALL_PATH%',p).split(";") # for p in newpath: # if p not in sys.path: # sys.path.append(p) # print "sys.path:", sys.path self.address='0.0.0.0:80' self.numthreads=10 self.queue_size=200 self.port=80 self.fcgiPort=10026 self.WebPort=20001 self.portcount=1#cpu_count() self.webportcount=1#cpu_count() if os.path.exists(p+"/"+configFile+".dev"): configFile+=".dev" if os.path.exists(p+"/"+configFile): cfg=dict4ini.DictIni(p+"/"+configFile, values={'Options': {'Port':80, 'IPAddress':'0.0.0.0', 'Type': self.server_type, 'NumThreads': 10, 'QueueSize': 200, 'FcgiPort': 10026, }}) self.port=cfg.Options.Port self.address="%s:%s"%(cfg.Options.IPAddress, cfg.Options.Port) self.server_type=cfg.Options.Type self.numthreads=cfg.Options.NumThreads self.queue_size=cfg.Options.QueueSize self.fcgiPort=cfg.Options.FcgiPort # print "address=%s,number of threads=%s,queue size=%s"%(self.address,self.numthreads,self.queue_size) print "Start Automatic Data Master Server ... ...\nOpen your web browser and go http://%s"%(self.address.replace("0.0.0.0","127.0.0.1"))+"/" if EN_POS: from mysite.pos.pos_ic.ic_sync_action import init_pos_batch init_pos_batch() from mysite.utils import printf # from mysite.iaccess.linux_or_win import run_commend # printf("start now", True) # try: ## from redis_self.filequeue import FileQueue ## q_server = FileQueue() ## main_pid = q_server.get_from_file("WEB_SERVER_PID") ## #print '--pid2=',pid ## if main_pid: ## main_process_info = os.popen(run_commend(1) % main_pid).read() ## if run_commend(3) in main_process_info.lower(): ## os.system(run_commend(2) % main_pid)#启动时收尸 ## ## q_server.set_to_file("WEB_SERVER_PID", "%d"%(os.getpid())) ## from mysite import settings ## if "mysite.iaccess" in settings.INSTALLED_APPS: ## p = Process(target=run_acc_dictmanager, args=(q_server,)) ## p.start() # #启动时检测数据库版本和当前软件版本是否一致,不一致则同步数据库 # SyncDB().start() # except Exception, e: # printf('------e=%s'%e, True) printf("init finished", True)
def check_center_stop(): fqpath = "%s/_fqueue/" % (os.getcwd()) fn = "%s*_SERVER" % (fqpath) filelist = glob.glob(fn) printf("*********filelist=%s" % filelist) return len(filelist) != 0
def SvcStop(self): printf("*******ServiceDataCommCenter stop", True) os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' fqpath = "%s/_fqueue/" % (os.getcwd()) q_server = FileQueue(path=fqpath) d_server = DictQueue() try: processes = d_server.get_from_dict( CENTER_PROCE_LIST) #如果python异常终止,该值返回None printf("******* processes=%s" % processes, True) if processes: for process in processes: process_server_key = "%s_SERVER" % process d_server.set_to_dict(process_server_key, "STOP") start_time = datetime.datetime.now() while check_center_stop(d_server, processes): end_time = datetime.datetime.now() time_delta = (end_time - start_time).seconds if time_delta > 10: #10秒钟停不下来,直接杀进程 printf("*******ServiceDataCommCenter stop 10s break", True) break time.sleep(1) self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) sys.stopservice = "true" win32event.SetEvent(self.hWaitStop) printf("*******before killall_pid", True) killall_pid(d_server, q_server, processes) #避免关闭服务器时重启服务 printf("*******after killall_pid", True) except Exception, e: printf("ServiceDataCommCenter error=%s" % e, True)