用kafka接收消息
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

579 lines
29KB

  1. import numpy as np
  2. import time,ast,copy
  3. from flask import request, Flask,jsonify
  4. import base64,cv2,os,sys,json
  5. #sys.path.extend(['../yolov5'])
  6. #from Send_tranfer import b64encode_function,JsonSend,name_dic,nameID_dic,getLogFileFp
  7. from segutils.segmodel import SegModel,get_largest_contours
  8. from models.experimental import attempt_load
  9. from utils.datasets import LoadStreams, LoadImages
  10. from utils.torch_utils import select_device, load_classifier, time_synchronized
  11. from queRiver import get_labelnames,get_label_arrays,post_process_,save_problem_images,time_str
  12. import subprocess as sp
  13. import matplotlib.pyplot as plt
  14. import torch,random,string
  15. import multiprocessing
  16. from multiprocessing import Process,Queue
  17. import traceback
  18. from kafka import KafkaProducer, KafkaConsumer,TopicPartition
  19. from kafka.errors import kafka_errors
  20. #torch.multiprocessing.set_start_method('spawn')
  21. import utilsK
  22. from utilsK.GPUtils import *
  23. from utilsK.masterUtils import *
  24. from utilsK.sendUtils import create_status_msg,update_json
  25. #from utilsK.modelEval import onlineModelProcsss
  26. import random,string
  27. from Send_tranfer_oss import msg_dict_on,msg_dict_off
  28. process_id=0
  29. def onlineModelProcess(parIn ):
  30. DEBUG=False
  31. streamName = parIn['streamName']
  32. childCallback=parIn['callback']
  33. outStrList={}
  34. channelIndex=parIn['channelIndex']
  35. #try:
  36. for wan in ['test']:
  37. jsonfile=parIn['modelJson']
  38. with open(jsonfile,'r') as fp:
  39. parAll = json.load(fp)
  40. Detweights=parAll['gpu_process']['det_weights']
  41. seg_nclass = parAll['gpu_process']['seg_nclass']
  42. Segweights = parAll['gpu_process']['seg_weights']
  43. StreamRecoveringTime=int(parAll['StreamRecoveringTime'])
  44. videoSave = parAll['AI_video_save']
  45. imageTxtFile = parAll['imageTxtFile']
  46. taskId,msgId = streamName.split('-')[1:3]
  47. inSource,outSource=parIn['inSource'],parIn['outSource']
  48. ##构建日志文件
  49. if outSource != 'NO':
  50. logdir = parAll['logChildProcessOnline']
  51. waitingTime=parAll['StreamWaitingTime']
  52. else:
  53. logdir = parAll['logChildProcessOffline']
  54. waitingTime=5
  55. logname='gpuprocess.log'
  56. fp_log=create_logFile(logdir=logdir,name=logname)
  57. logger=logdir.replace('/','.')+'.'+logname
  58. kafka_par=parIn['kafka_par']
  59. producer = KafkaProducer(bootstrap_servers=kafka_par['server'],value_serializer=lambda v: v.encode('utf-8'),metadata_max_age_ms=120000)
  60. ####要先检查视频的有效性
  61. ###开始的时候,如果在线任务没有流,要发送的心跳消息,msg_h,
  62. msg_h= copy.deepcopy(msg_dict_off);
  63. msg_h['status']='waiting';msg_h['msg_id']=msgId
  64. thread='master:gpuprocess-%s'%(msgId)
  65. if outSource == 'NO':
  66. msg_h['type']=1
  67. Stream_ok,_= get_fps_rtmp(inSource,video=True)
  68. else:
  69. msg_h['type']=2
  70. msg_h_d = json.dumps(msg_h, ensure_ascii=False)
  71. outStrList=get_infos(taskId, msgId,msg_h_d,key_str='waiting stream or video, send heartbeat')
  72. Stream_ok=check_stream(inSource,producer,kafka_par,msg_h_d,outStrList,fp_log,logger,line=sys._getframe().f_lineno,thread=thread ,timeMs=waitingTime)
  73. if Stream_ok:###发送开始信号
  74. msg_h['status']='running'
  75. msg_h_d = json.dumps(msg_h, ensure_ascii=False)
  76. outStrList= get_infos(taskId, msgId,msg_h_d,key_str='informing stream/video is ok')
  77. send_kafka(producer,kafka_par,msg_h_d,outStrList,fp_log,line=sys._getframe().f_lineno,logger=logger,thread=thread );
  78. else:
  79. ####检测离线视频是否有效,无效要报错
  80. outstr='offline vedio or live stream Error:%s '%(inSource)
  81. #outstr=wrtiteLog(fp_log,outstr);print( outstr);
  82. writeELK_log(msg=outstr,fp=fp_log,level='ERROR',line=sys._getframe().f_lineno,logger=logger)
  83. msg_h['error']='Stream or video ERROR';msg_h['status']='failed';
  84. msg_h_d = json.dumps(msg_h, ensure_ascii=False);
  85. outStrList= get_infos(taskId, msgId,msg_h_d,key_str='informing invaid video or stream success')
  86. send_kafka(producer,kafka_par,msg_h_d,outStrList,fp_log ,line=sys._getframe().f_lineno,logger=logger,thread=thread );
  87. childCallback.send(' offline vedio or live stream Error')
  88. continue
  89. if (inSource.endswith('.MP4')) or (inSource.endswith('.mp4')):
  90. fps,outW,outH,totalcnt=get_fps_rtmp(inSource,video=True)[1][0:4];
  91. else:
  92. fps,outW,outH,totalcnt=get_fps_rtmp(inSource,video=False)[1][0:4]
  93. fps = int(fps+0.5)
  94. if fps>30: fps=25 ###线下测试时候,有时候读帧率是9000,明显不符合实际,所以加这个判断。
  95. if outSource != 'NO':
  96. command=['/usr/bin/ffmpeg','-y','-f', 'rawvideo','-vcodec','rawvideo','-pix_fmt', 'bgr24',
  97. '-s', "{}x{}".format(outW,outH),# 图片分辨率
  98. '-r', str(fps),# 视频帧率
  99. '-i', '-','-c:v',
  100. 'libx264',
  101. '-pix_fmt', 'yuv420p',
  102. '-f', 'flv',outSource
  103. ]
  104. video_flag = videoSave['onLine']
  105. logdir = parAll['logChildProcessOnline']
  106. waitingTime=parAll['StreamWaitingTime']
  107. else:
  108. video_flag = videoSave['offLine'] ;logdir = parAll['logChildProcessOffline']
  109. waitingTime=5
  110. device = select_device(parIn['device'])
  111. half = device.type != 'cpu' # half precision only supported on CUDA
  112. model = attempt_load(Detweights, map_location=device) # load FP32 model
  113. if half: model.half()
  114. segmodel = SegModel(nclass=seg_nclass,weights=Segweights,device=device)
  115. ##后处理参数
  116. par=parAll['post_process']
  117. conf_thres,iou_thres,classes=par['conf_thres'],par['iou_thres'],par['classes']
  118. outImaDir = par['outImaDir']
  119. outVideoDir = par['outVideoDir']
  120. labelnames=par['labelnames']
  121. rainbows=par['rainbows']
  122. fpsample = par['fpsample']
  123. names=get_labelnames(labelnames)
  124. label_arraylist = get_label_arrays(names,rainbows,outfontsize=40)
  125. #dataset = LoadStreams(inSource, img_size=640, stride=32)
  126. childCallback.send('####model load success####')
  127. print('#####line153:',outVideoDir,video_flag)
  128. if (outVideoDir!='NO') : ####2022.06.27新增在线任务也要传AI视频和原始视频
  129. if video_flag:
  130. msg_id = streamName.split('-')[2]
  131. save_path = os.path.join(outVideoDir,msg_id+'.MP4')
  132. vid_writer = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (outW,outH))
  133. if vid_writer.isOpened(): outstr='touch video success:%s'%(save_path);level='INFO'
  134. else:outstr='touch video failed:%s'%(save_path);level='ERROR'
  135. writeELK_log(msg=outstr,fp=fp_log,level=level,line=sys._getframe().f_lineno,logger=logger)
  136. else:
  137. msg_id = streamName.split('-')[2]
  138. save_path_OR = os.path.join(outVideoDir,msg_id+'_OR.MP4')
  139. vid_writer_OR = cv2.VideoWriter(save_path_OR, cv2.VideoWriter_fourcc(*'mp4v'), fps, (outW,outH))
  140. save_path_AI = os.path.join(outVideoDir,msg_id+'_AI.MP4')
  141. vid_writer_AI = cv2.VideoWriter(save_path_AI, cv2.VideoWriter_fourcc(*'mp4v'), fps, (outW,outH))
  142. if vid_writer_AI.isOpened() and vid_writer_OR.isOpened() :outstr='touch video success:%s,%s'%(save_path_OR,save_path_AI);level='INFO'
  143. else:outstr='touch video failed:%s,%s, fps:%d ,%d , %d'%(save_path_OR,save_path_AI,fps,outW,outH);level='ERROR'
  144. writeELK_log(msg=outstr,fp=fp_log,level=level,line=sys._getframe().f_lineno,logger=logger)
  145. iframe = 0;post_results=[];time_beg=time.time()
  146. t00=time.time()
  147. time_kafka0=time.time()
  148. Pushed_Flag=False
  149. while True:
  150. try:
  151. dataset = LoadStreams(inSource, img_size=640, stride=32)
  152. # 管道配置,其中用到管道
  153. if outSource !='NO' and (not Pushed_Flag):
  154. ppipe = sp.Popen(command, stdin=sp.PIPE);Pushed_Flag = True
  155. for path, img, im0s, vid_cap in dataset:
  156. t0= time_synchronized()
  157. if outSource == 'NO':###如果不推流,则显示进度条。离线不推流
  158. view_bar(iframe,totalcnt,time_beg ,parIn['process_uid'] )
  159. streamCheckCnt=0
  160. ###直播和离线都是1分钟发一次消息
  161. time_kafka1 = time.time()
  162. if time_kafka1 - time_kafka0 >60:
  163. time_kafka0 = time_kafka1
  164. ###发送状态信息waiting
  165. msg = copy.deepcopy(msg_dict_off);
  166. msg['msg_id']= msgId;
  167. if outSource == 'NO':
  168. msg['progressbar']= '%.4f'%(iframe*1.0/totalcnt)
  169. msg['type']=1
  170. else:
  171. msg['progressbarOn']= str(iframe)
  172. msg['type']=2
  173. msg = json.dumps(msg, ensure_ascii=False)
  174. outStrList= get_infos(taskId, msgId,msg,key_str='processing send progressbar or online heartbeat')
  175. send_kafka(producer,kafka_par,msg,outStrList,fp_log,line=sys._getframe().f_lineno,logger=logger,thread=thread );
  176. time0=time.time()
  177. iframe +=1
  178. time1=time.time()
  179. img = torch.from_numpy(img).to(device)
  180. img = img.half() if half else img.float() # uint8 to fp16/32
  181. img /= 255.0 # 0 - 255 to 0.0 - 1.0
  182. timeseg0 = time.time()
  183. seg_pred,segstr = segmodel.eval(im0s[0] )
  184. timeseg1 = time.time()
  185. t1= time_synchronized()
  186. pred = model(img,augment=False)[0]
  187. time4 = time.time()
  188. datas = [path, img, im0s, vid_cap,pred,seg_pred,iframe]
  189. p_result,timeOut = post_process_(datas,conf_thres, iou_thres,names,label_arraylist,rainbows,iframe)
  190. t2= time_synchronized()
  191. #print('###line138:',timeOut,outSource,outVideoDir)
  192. ##每隔 fpsample帧处理一次,如果有问题就保存图片
  193. if (iframe % fpsample == 0) and (len(post_results)>0) :
  194. parImage=save_problem_images(post_results,iframe,names,streamName=streamName,outImaDir='problems/images_tmp',imageTxtFile=imageTxtFile)
  195. post_results=[]
  196. if len(p_result[2] )>0: ##
  197. post_results.append(p_result)
  198. t3= time_synchronized()
  199. image_array = p_result[1]
  200. if outSource!='NO':
  201. ppipe.stdin.write(image_array.tobytes())
  202. if (outVideoDir!='NO'):
  203. if video_flag: ret = vid_writer.write(image_array)
  204. else:
  205. time_w0=time.time()
  206. ret = vid_writer_AI.write(image_array)
  207. ret = vid_writer_OR.write(im0s[0])
  208. time_w1=time.time()
  209. #if not ret:
  210. # print('\n write two videos time:%f ms'%(time_w1-time_w0)*1000,ret)
  211. t4= time_synchronized()
  212. timestr2 = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
  213. if iframe%100==0:
  214. outstr='%s,,read:%.1f ms,copy:%.1f, infer:%.1f ms, detinfer:%.1f ms,draw:%.1f ms, save:%.1f ms total:%.1f ms \n'%(timestr2,(t0 - t00)*1000,(timeseg0-t0)*1000, (t1 - timeseg0)*1000,(t2-t1)*1000, (t3 - t2)*1000,(t4-t3)*1000, (t4-t00)*1000)
  215. #wrtiteLog(fp_log,outstr);
  216. writeELK_log(msg=outstr,fp=fp_log,line=sys._getframe().f_lineno,logger=logger,printFlag=False)
  217. #print(outstr)
  218. t00 = t4;
  219. except Exception as e:
  220. #if outSource:###推流才有如下
  221. streamCheckCnt+=1;taskEnd=False
  222. if streamCheckCnt==1:timeBreak0=time.time();time_kafka0 = time.time()
  223. timeBreak1=time.time();
  224. if timeBreak1-timeBreak0 >5 and Pushed_Flag:###流断开5秒后,要关闭推流
  225. ppipe.kill();Pushed_Flag=False
  226. writeELK_log(msg='stream pip is killed ',fp=fp_log,line=sys._getframe().f_lineno,logger=logger)
  227. ###读接口,看看任务有没有结束
  228. ChanellInfos,taskEnd=query_channel_status(channelIndex)
  229. ####taskEnd######################DEBUG
  230. #taskEnd=False
  231. if timeBreak1-timeBreak0 >StreamRecoveringTime : ##默认30分钟内,流没有恢复的话,就断开。
  232. taskEnd=True
  233. outstr_channel='%s ,taskEnd:%s'%(ChanellInfos,taskEnd)
  234. writeELK_log(msg=outstr_channel,fp=fp_log,line=sys._getframe().f_lineno,logger=logger)
  235. if outSource == 'NO':#离线没有推流
  236. taskEnd=True
  237. if taskEnd:
  238. if timeBreak1-timeBreak0 > 60:###超时结束
  239. writeTxtEndFlag(outImaDir,streamName,imageTxtFile,endFlag='超时结束')
  240. else:
  241. writeTxtEndFlag(outImaDir,streamName,imageTxtFile,endFlag='结束')
  242. if (outVideoDir!='NO'):
  243. if video_flag:vid_writer.release()
  244. else:
  245. vid_writer_OR.release();
  246. vid_writer_AI.release();
  247. outstr='Task ends:%.1f , msgid:%s,taskID:%s '%(timeBreak1-timeBreak0,taskId,msgId)
  248. writeELK_log(msg=outstr,fp=fp_log,line=sys._getframe().f_lineno,logger=logger)
  249. break
  250. ##执行到这里的一定是在线任务,在等待流的过程中要发送waiting
  251. time_kafka1 = time.time()
  252. if time_kafka1-time_kafka0>60:
  253. msg_res = copy.deepcopy(msg_dict_off);
  254. msg_res['msg_id']= msgId; msg_res['type']=2
  255. msg_res = json.dumps(msg_res, ensure_ascii=False)
  256. outStrList= get_infos(taskId, msgId,msg_res,key_str='Waiting stream restoring heartbeat')
  257. send_kafka(producer,kafka_par,msg_res,outStrList,fp_log,line=sys._getframe().f_lineno,logger=logger,thread=thread );
  258. outstr='Waiting stream recovering:%.1f s'%(timeBreak1-timeBreak0)
  259. writeELK_log(msg=outstr,fp=fp_log,line=sys._getframe().f_lineno,logger=logger)
  260. writeELK_log(msg=outstr_channel,fp=fp_log,line=sys._getframe().f_lineno,logger=logger)
  261. time_kafka0 = time_kafka1
  262. #break###断流或者到终点
  263. time.sleep(5)
  264. print('Waiting stream for ',e)
  265. def lauch_process(gpuid,inSource,outSource,taskId,msgId,modelJson,kafka_par,channelIndex='LC001'):
  266. if outSource=='NO':
  267. streamName='off-%s-%s'%(taskId,msgId)
  268. else:
  269. streamName='live-%s-%s'%(taskId,msgId)
  270. dataPar ={
  271. 'imgData':'',
  272. 'imgName':'testW',
  273. 'streamName':streamName,
  274. 'taskId':taskId,
  275. 'msgId':msgId,
  276. 'channelIndex':channelIndex,
  277. 'device':str(gpuid),
  278. 'modelJson':modelJson,
  279. 'kafka_par':kafka_par,
  280. }
  281. #dataPar['inSource'] = 'http://images.5gai.taauav.com/video/8bc32984dd893930dabb2856eb92b4d1.mp4';dataPar['outSource'] = None
  282. dataPar['inSource'] = inSource;dataPar['outSource'] = outSource
  283. process_uid=''.join(random.sample(string.ascii_letters + string.digits, 16));dataPar['process_uid']=process_uid
  284. parent_conn, child_conn = multiprocessing.Pipe();dataPar['callback']=child_conn
  285. gpuProcess=Process(target=onlineModelProcess,name='process:%s'%( process_uid ),args=(dataPar,))
  286. gpuProcess.start()
  287. #print(dir(gpuProcess))
  288. #child_return = parent_conn.recv()
  289. #timestr2=time.strftime("%Y-%m-%d %H:%M:%S ", time.localtime())
  290. #print(timestr2,'-'*20,'progress:%s ,msgId:%s , taskId:%s return:'%(process_uid,msgId,taskId),child_return)
  291. return gpuProcess
  292. msg_dict_offline = {
  293. "biz_id":"hehuzhang",
  294. "mod_id":"ai",
  295. "msg_id":'bb'+''.join(random.sample(string.ascii_letters ,30) ) ,
  296. "offering_id":"http://vod.play.t-aaron.com/customerTrans/c49a2c620795d124f2ae4b10197b8d0e/303b7a58-17f3ef4494e-0004-f90c-f2c-7ec68.mp4",
  297. "offering_type":"mp4",
  298. "results_base_dir": "XJRW202203171535"+str(random.randint(10,99)),
  299. 'outSource':'NO'
  300. }
  301. taskStatus={}
  302. taskStatus['onLine'] = Queue(100)
  303. taskStatus['offLine']= Queue(100)
  304. taskStatus['pidInfos']= {}
  305. def get_msg_from_kafka(par):
  306. thread='master:readingKafka'
  307. outStrList={}
  308. fp_log = par['fp_log']
  309. logger=par['logger']
  310. consumer = KafkaConsumer(bootstrap_servers=par['server'],client_id='AI_server',group_id=par['group_id'],auto_offset_reset='latest')
  311. consumer.subscribe( par['topic'][0:2])
  312. outstr='reading kafka process starts'
  313. writeELK_log(msg=outstr,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  314. kafka_par ={ 'server':par['server'],'topic':par['topic'][2] }
  315. producer = KafkaProducer(
  316. bootstrap_servers=par['server'],#tencent yun
  317. value_serializer=lambda v: v.encode('utf-8'),
  318. metadata_max_age_ms=120000)
  319. for ii,msg in enumerate(consumer):
  320. ##读取消息
  321. try:
  322. taskInfos = eval(msg.value.decode('utf-8') )
  323. except:
  324. outstr='%s msg format error,value:%s,offset:%d partition:%s topic:%s'%('#'*20,msg.value,msg.offset,msg.topic,msg.topic)
  325. continue
  326. if msg.topic == par['topic'][0]: ##
  327. taskInfos['inSource']= taskInfos['pull_channel'];
  328. taskInfos['outSource']= get_push_address(taskInfos['push_channel']) ;
  329. taskStatus['onLine'].put( taskInfos )
  330. save_message(par['kafka'],taskInfos)
  331. ###发送状态信息waiting
  332. msg = create_status_msg(msg_dict_on,taskInfos,sts='waiting')
  333. outStrList=get_infos(taskInfos['results_base_dir'], taskInfos['msg_id'],msg,key_str='read msgs from kafka online task and response to kafka')
  334. send_kafka(producer,kafka_par,msg,outStrList,fp_log,line=sys._getframe().f_lineno,logger=logger,thread=thread);
  335. else:
  336. try:
  337. taskInfos['inSource']= taskInfos['offering_id'];
  338. taskInfos['outSource']= 'NO'
  339. taskStatus['offLine'].put( taskInfos )
  340. save_message(par['kafka'],taskInfos)
  341. ###发送状态信息waiting
  342. msg = create_status_msg(msg_dict_off,taskInfos,sts='waiting')
  343. outStrList=get_infos(taskInfos['results_base_dir'], taskInfos['msg_id'],msg,key_str='read msgs from kafka offline task and response to kafka')
  344. send_kafka(producer,kafka_par,msg,outStrList,fp_log ,line=sys._getframe().f_lineno,logger=logger,thread=thread );
  345. except Exception as e:
  346. print('######msg Error######',msg,e)
  347. def detector(par):
  348. ####初始化信息列表
  349. kafka_par ={ 'server':par['server'],'topic':par['topic'][2] }
  350. producer = KafkaProducer(
  351. bootstrap_servers=par['server'],#tencent yun
  352. value_serializer=lambda v: v.encode('utf-8'),
  353. metadata_max_age_ms=120000)
  354. time_interval=par['logPrintInterval']
  355. logname='detector.log';thread='master:detector'
  356. fp_log=create_logFile(logdir=par['logDir'],name=logname)
  357. ##准备日志函数所需参数
  358. logger=par['logDir'].replace('/','.')+'.'+logname
  359. #wrtiteLog(fp_log,'########### detector process starts ######\n');
  360. outstr='detector process starts';sys._getframe().f_lineno
  361. writeELK_log(msg=outstr,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  362. ###开启kafka consumer 进程##
  363. parIn=copy.deepcopy(par);parIn['fp_log']=fp_log ;parIn['logger']=logger
  364. HeartProcess=Process(target=get_msg_from_kafka,name='process-consumer-kafka',args=(parIn,))
  365. HeartProcess.start()
  366. timeSleep=1
  367. time0=time.time()
  368. time0_kafQuery=time.time()
  369. time0_taskQuery=time.time()
  370. time0_sleep=time.time()
  371. outStrList={}
  372. while True:###每隔timeSleep秒,轮询一次
  373. time0_taskQuery,printFlag = check_time_interval(time0_taskQuery,time_interval)
  374. outstr_task= ' task queue onLine cnt:%d offLine:%d'%(taskStatus['onLine'].qsize(), taskStatus['offLine'].qsize())
  375. if (taskStatus['onLine'].qsize()>0) or (taskStatus['offLine'].qsize()>0):
  376. #outstr_task=wrtiteLog(fp_log,outstr_task);print( outstr_task);
  377. writeELK_log(msg=outstr_task,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  378. ##2-更新显卡信息
  379. gpuStatus = getGPUInfos()
  380. ##3-优先考虑在线任务
  381. if not taskStatus['onLine'].empty():
  382. ###3.1-先判断有没有空闲显卡:
  383. cuda = get_available_gpu(gpuStatus)
  384. ###获取在线任务信息,并执行,lauch process
  385. taskInfos = taskStatus['onLine'].get()
  386. outstr='start to process onLine taskId:%s msgId:%s'%( taskInfos['results_base_dir'],taskInfos['msg_id'] )
  387. #outstr=wrtiteLog(fp_log,outstr);print( outstr);
  388. writeELK_log(msg=outstr,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  389. if cuda: ###3.1.1 -有空余显卡
  390. #lauch process
  391. msg= copy.deepcopy(msg_dict_on);
  392. gpuProcess=lauch_process(cuda,taskInfos['inSource'],taskInfos['outSource'],taskInfos['results_base_dir'],taskInfos['msg_id'],par['modelJson'],kafka_par,taskInfos['channel_code'])
  393. taskStatus['pidInfos'][gpuProcess.pid] = {'gpuProcess':gpuProcess,'type':'onLine','taskInfos':taskInfos}
  394. else:###3.1.2-没有显卡
  395. ##判断有没有显卡上面都是离线进程的
  396. cuda_pid = get_potential_gpu(gpuStatus,taskStatus['pidInfos'])
  397. if cuda_pid:#3.1.2.1 - ##如果有可以杀死的进程
  398. cuda = cuda_pid['cuda']
  399. pids = cuda_pid['pids']
  400. ##kill 离线进程,并更新离线任务表
  401. cnt_off_0 = taskStatus['offLine'].qsize()
  402. for pid in pids:
  403. ##kill 离线进程
  404. taskStatus['pidInfos'][pid]['gpuProcess'].kill()
  405. ##更新离线任务表
  406. taskStatus['offLine'].put( taskStatus['pidInfos'][pid]['taskInfos'] )
  407. taskInfos_off=taskStatus['pidInfos'][pid]['taskInfos']
  408. ##发送离线数据,说明状态变成waiting
  409. msg= msg_dict_off;
  410. msg=update_json(taskInfos_off,msg,offkeys=["msg_id","biz_id" ,"mod_id"] )
  411. msg['results'][0]['original_url']=taskInfos_off['inSource']
  412. msg['results'][0]['sign_url']=get_boradcast_address(taskInfos_off['outSource'])
  413. msg['status']='waiting'
  414. msg = json.dumps(msg, ensure_ascii=False)
  415. outStrList=get_infos(taskInfos_off['results_base_dir'], taskInfos_off['msg_id'],msg,key_str='start online task after kill offline tasks')
  416. send_kafka(producer,kafka_par,msg,outStrList,fp_log ,line=sys._getframe().f_lineno,logger=logger,thread=thread );
  417. cnt_off_1 = taskStatus['offLine'].qsize()
  418. outstr='before killing process, offtask cnt:%d ,after killing, offtask cnt:%d '%(cnt_off_0,cnt_off_1)
  419. #outstr=wrtiteLog(fp_log,outstr);print( outstr);
  420. writeELK_log(msg=outstr,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  421. gpuProcess=lauch_process(cuda,taskInfos['inSource'],taskInfos['outSource'],taskInfos['results_base_dir'],taskInfos['msg_id'],par['modelJson'],kafka_par,taskInfos['channel_code'])
  422. ###更新pidinfos,update pidInfos
  423. taskStatus['pidInfos'][gpuProcess.pid] = {'gpuProcess':gpuProcess,'type':'onLine','taskInfos':taskInfos}
  424. else:
  425. outstr='No available GPUs for onLine task'
  426. #outstr=wrtiteLog(fp_log,outstr);print(outstr);
  427. writeELK_log(msg=outstr,fp=fp_log,level='ERROR',thread=thread,line=sys._getframe().f_lineno,logger=logger)
  428. ##4-更新显卡信息
  429. gpuStatus = getGPUInfos()
  430. ##5-考虑离线任务
  431. if not taskStatus['offLine'].empty():
  432. cudaArrange= arrange_offlineProcess(gpuStatus,taskStatus['pidInfos'],modelMemory=1500)
  433. outstr='IN OFF LINE TASKS available cudas:%s'%(cudaArrange)
  434. #outstr=wrtiteLog(fp_log,outstr);print( outstr);
  435. writeELK_log(msg=outstr,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  436. for cuda in cudaArrange:
  437. if not taskStatus['offLine'].empty():
  438. taskInfos = taskStatus['offLine'].get()
  439. outstr='start to process offLine taskId:%s msgId:%s'%( taskInfos['results_base_dir'],taskInfos['msg_id'] )
  440. taskInfos['channel_code']='LC999'###离线消息没有这个参数
  441. #outstr=wrtiteLog(fp_log,outstr);print( outstr);
  442. writeELK_log(msg=outstr,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  443. gpuProcess=lauch_process(cuda,taskInfos['inSource'],taskInfos['outSource'],taskInfos['results_base_dir'],taskInfos['msg_id'],par['modelJson'],kafka_par,taskInfos['channel_code'])
  444. taskStatus['pidInfos'][gpuProcess.pid] = {'gpuProcess':gpuProcess,'type':'offLine','taskInfos':taskInfos}
  445. if get_whether_gpuProcess():
  446. time0_sleep,printFlag = check_time_interval(time0_sleep,time_interval)
  447. if printFlag:
  448. outstr= '*'*20 +'sleep '+'*'*20;
  449. #outstr=wrtiteLog(fp_log,outstr);print( outstr);
  450. writeELK_log(msg=outstr,fp=fp_log,thread=thread,line=sys._getframe().f_lineno,logger=logger)
  451. time.sleep(timeSleep)
  452. print('########Program End#####')
  453. if __name__ == '__main__':
  454. par={};
  455. ###topic0--在线,topic1--离线
  456. #par['server']='212.129.223.66:9092';par['topic']=('thsw','thsw2','testReturn');par['group_id']='test';
  457. #101.132.127.1:19092
  458. '''
  459. par['server']='101.132.127.1:19092 ';par['topic']=('alg-online-tasks','alg-offline-tasks','alg-task-results');par['group_id']='test';
  460. par['kafka']='mintors/kafka'
  461. par['modelJson']='conf/model.json'
  462. '''
  463. masterFile="conf/master.json"
  464. assert os.path.exists(masterFile)
  465. with open(masterFile,'r') as fp:
  466. data=json.load(fp)
  467. par=data['par']
  468. print(par)
  469. detector(par)