dataflow_mq.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  1. from BaseDataMaintenance.maintenance.dataflow import *
  2. from BaseDataMaintenance.common.activateMQUtils import *
  3. from BaseDataMaintenance.dataSource.source import getConnect_activateMQ,getConnection_postgres,getConnection_mysql,getConnection_oracle,getConnect_ots_capacity,getConnect_redis_doc
  4. from BaseDataMaintenance.dataSource.setttings import *
  5. from BaseDataMaintenance.model.postgres.attachment import Attachment_postgres
  6. import os
  7. from BaseDataMaintenance.common.ossUtils import *
  8. from BaseDataMaintenance.dataSource.pool import ConnectorPool
  9. from BaseDataMaintenance.model.ots.document import Document
  10. from BaseDataMaintenance.common.Utils import article_limit
  11. from BaseDataMaintenance.common.documentFingerprint import getFingerprint
  12. from BaseDataMaintenance.model.postgres.document_extract import *
  13. import sys
  14. sys.setrecursionlimit(1000000)
  15. class ActiveMQListener():
  16. def __init__(self,conn,_queue,*args,**kwargs):
  17. self.conn = conn
  18. self._queue = _queue
  19. def on_error(self, headers):
  20. log("===============")
  21. log('received an error %s' % str(headers.body))
  22. def on_message(self, headers):
  23. log("====message====")
  24. message_id = headers.headers["message-id"]
  25. body = headers.body
  26. self._queue.put({"frame":headers,"conn":self.conn},True)
  27. def __del__(self):
  28. self.conn.disconnect()
  29. class Dataflow_ActivteMQ_attachment(Dataflow_attachment):
  30. def __init__(self):
  31. Dataflow_attachment.__init__(self)
  32. self.mq_attachment = "/queue/dataflow_attachment"
  33. self.mq_attachment_failed = "/queue/dataflow_attachment_failed"
  34. self.mq_extract = "/queue/dataflow_extract"
  35. self.comsumer_count = 120
  36. self.retry_comsumer_count = 10
  37. self.retry_times = 5
  38. self.list_attachment_comsumer = []
  39. for _i in range(self.comsumer_count):
  40. listener_attachment = ActiveMQListener(getConnect_activateMQ(),self.queue_attachment)
  41. createComsumer(listener_attachment,self.mq_attachment)
  42. self.list_attachment_comsumer.append(listener_attachment)
  43. self.attach_pool = ConnectorPool(10,30,getConnection_postgres)
  44. self.conn_mq = getConnect_activateMQ()
  45. self.pool_mq = ConnectorPool(10,30,getConnect_activateMQ)
  46. def monitor_listener(self):
  47. for i in range(len(self.list_attachment_comsumer)):
  48. if self.list_attachment_comsumer[i].conn.is_connected():
  49. continue
  50. else:
  51. listener = ActiveMQListener(getConnect_activateMQ(),self.queue_attachment)
  52. createComsumer(listener,self.mq_attachment)
  53. self.list_attachment_comsumer[i] = listener
  54. def process_failed_attachment(self):
  55. from BaseDataMaintenance.java.MQInfo import getQueueSize
  56. attachment_size = getQueueSize("dataflow_attachment")
  57. failed_attachment_size = getQueueSize("dataflow_attachment_failed")
  58. if attachment_size<100 and failed_attachment_size>0:
  59. list_comsumer = []
  60. for _i in range(self.retry_comsumer_count):
  61. listener_attachment = ActiveMQListener(getConnect_activateMQ(),self.queue_attachment)
  62. list_comsumer.append(listener_attachment)
  63. createComsumer(listener_attachment,self.mq_attachment_failed)
  64. while 1:
  65. failed_attachment_size = getQueueSize("dataflow_attachment_failed")
  66. if failed_attachment_size==0:
  67. break
  68. time.sleep(10)
  69. for _c in list_comsumer:
  70. _c.conn.disconnect()
  71. def rec_attachments_by_interface(self,list_attach,_dochtmlcon,save=True):
  72. try:
  73. list_html = []
  74. swf_urls = []
  75. _not_failed = True
  76. for _attach in list_attach:
  77. #测试全跑
  78. _filemd5 = _attach.getProperties().get(attachment_filemd5)
  79. if _attach.getProperties().get(attachment_status) in (ATTACHMENT_PROCESSED,ATTACHMENT_TOOLARGE):
  80. log("%s has processed or toolarge"%(_filemd5))
  81. _html = _attach.getProperties().get(attachment_attachmenthtml,"")
  82. if _html is None:
  83. _html = ""
  84. list_html.append({attachment_filemd5:_filemd5,
  85. "html":_html})
  86. else:
  87. #has process_time then jump
  88. if len(str(_attach.getProperties().get(attachment_process_time,"")))>10 and _attach.getProperties().get(attachment_status)!=ATTACHMENT_INIT:
  89. log("%s has process_time jump"%(_filemd5))
  90. _html = _attach.getProperties().get(attachment_attachmenthtml,"")
  91. if _html is None:
  92. _html = ""
  93. list_html.append({attachment_filemd5:_filemd5,
  94. "html":_html})
  95. else:
  96. log("%s requesting interface"%(_filemd5))
  97. _succeed = self.request_attachment_interface(_attach,_dochtmlcon)
  98. if not _succeed:
  99. _not_failed = False
  100. _html = _attach.getProperties().get(attachment_attachmenthtml,"")
  101. if _html is None:
  102. _html = ""
  103. list_html.append({attachment_filemd5:_filemd5,
  104. "html":_html})
  105. if _attach.getProperties().get(attachment_filetype)=="swf":
  106. swf_urls.extend(json.loads(_attach.getProperties().get(attachment_swfUrls,"[]")))
  107. if not _not_failed:
  108. return False,list_html,swf_urls
  109. return True,list_html,swf_urls
  110. except requests.ConnectionError as e1:
  111. raise e1
  112. except Exception as e:
  113. return False,list_html,swf_urls
  114. def attachment_recognize(self,_dict,result_queue):
  115. '''
  116. 识别附件内容
  117. :param _dict: 附件内容
  118. :param result_queue:
  119. :return:
  120. '''
  121. try:
  122. item = _dict.get("item")
  123. list_attach = _dict.get("list_attach")
  124. conn = _dict["conn"]
  125. message_id = _dict.get("message_id")
  126. _retry_times = item.get("retry_times",0)
  127. dhtml = Document_html({"partitionkey":item.get("partitionkey"),
  128. "docid":item.get("docid")})
  129. _dochtmlcon = item.get(document_tmp_dochtmlcon,"")
  130. dhtml.setValue(document_tmp_dochtmlcon,_dochtmlcon,True)
  131. dtmp = Document_tmp(item)
  132. #调用识别接口
  133. _succeed,list_html,swf_urls = self.rec_attachments_by_interface(list_attach,_dochtmlcon,save=True)
  134. _to_ack = False
  135. if not _succeed and _retry_times<self.retry_times:
  136. item[document_tmp_status] = random.randint(*flow_attachment_status_failed_to)
  137. item["retry_times"] = _retry_times+1
  138. #失败次数大于5次就放入失败队列,此队列的数据会在空闲时间重新处理一次
  139. if item["retry_times"]>=self.retry_times:
  140. send_msg_toacmq(self.pool_mq,json.dumps(item,cls=MyEncoder,ensure_ascii=False),self.mq_attachment_failed)
  141. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(item,cls=MyEncoder,ensure_ascii=False),self.mq_attachment)
  142. #失败保存
  143. if _retry_times==0:
  144. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  145. dtmp.setValue(document_tmp_status,0,True)
  146. if not dtmp.exists_row(self.ots_client):
  147. dtmp.update_row(self.ots_client)
  148. dhtml.update_row(self.ots_client)
  149. if send_succeed:
  150. _to_ack = True
  151. else:
  152. try:
  153. log("docid:%d,retry:%d swf_urls:%s list_html:%s"%(dhtml.getProperties().get(document_docid),_retry_times,str(swf_urls),str(len(list_html))))
  154. dhtml.updateSWFImages(swf_urls)
  155. dhtml.updateAttachment(list_html)
  156. dtmp.setValue(document_tmp_attachment_extract_status,1,True)
  157. dtmp.setValue(document_tmp_dochtmlcon,dhtml.getProperties().get(document_tmp_dochtmlcon),True)
  158. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(dtmp.getProperties(),cls=MyEncoder),self.mq_extract)
  159. if send_succeed:
  160. _to_ack = True
  161. except Exception as e:
  162. traceback.print_exc()
  163. if _to_ack:
  164. ackMsg(conn,message_id)
  165. log("document:%d get attachments with result:%s %s retry_times:%d"%(item.get("docid"),str(_succeed),str(_to_ack),_retry_times))
  166. except Exception as e:
  167. if send_msg_toacmq(self.pool_mq,json.dumps(item,cls=MyEncoder,ensure_ascii=False),self.mq_attachment):
  168. ackMsg(conn,message_id)
  169. def request_attachment_interface(self,attach,_dochtmlcon):
  170. filemd5 = attach.getProperties().get(attachment_filemd5)
  171. _status = attach.getProperties().get(attachment_status)
  172. _filetype = attach.getProperties().get(attachment_filetype)
  173. _path = attach.getProperties().get(attachment_path)
  174. _uuid = uuid4()
  175. objectPath = attach.getProperties().get(attachment_path)
  176. docids = attach.getProperties().get(attachment_docids)
  177. if objectPath is None:
  178. relative_path = "%s/%s"%(_uuid.hex[:4],_uuid.hex)
  179. else:
  180. relative_path = objectPath[5:]
  181. localpath = "/FileInfo/%s"%(relative_path)
  182. if not os.path.exists(localpath):
  183. if not os.path.exists(os.path.dirname(localpath)):
  184. os.makedirs(os.path.dirname(localpath))
  185. local_exists = False
  186. else:
  187. local_exists = True
  188. _size = os.path.getsize(localpath)
  189. not_failed_flag = True
  190. try:
  191. d_start_time = time.time()
  192. if not local_exists:
  193. log("md5:%s path:%s not exists,start downloading"%(filemd5,objectPath))
  194. try:
  195. download_succeed = downloadFile(self.bucket,objectPath,localpath)
  196. except Exception as e:
  197. download_succeed = False
  198. else:
  199. log("md5:%s path:%s exists"%(filemd5,objectPath[5:]))
  200. if not (local_exists or download_succeed):
  201. _ots_attach = attachment(attach.getProperties_ots())
  202. _ots_exists = _ots_attach.fix_columns(self.ots_client,[attachment_attachmenthtml,attachment_classification,attachment_attachmentcon,attachment_path,attachment_status,attachment_filetype],True)
  203. log("md5:%s path:%s file not in local or oss,search ots.attachment"%(filemd5,objectPath[5:]))
  204. if _ots_attach.getProperties().get(attachment_attachmenthtml,"")!="" and str(_ots_attach.getProperties().get(attachment_status))!=str(ATTACHMENT_INIT):
  205. attach.setValue(attachment_attachmenthtml,_ots_attach.getProperties().get(attachment_attachmenthtml,""))
  206. attach.setValue(attachment_attachmentcon,_ots_attach.getProperties().get(attachment_attachmentcon,""))
  207. attach.setValue(attachment_status,_ots_attach.getProperties().get(attachment_status,""))
  208. attach.setValue(attachment_filetype,_ots_attach.getProperties().get(attachment_filetype,""))
  209. attach.setValue(attachment_classification,_ots_attach.getProperties().get(attachment_classification,""))
  210. if attach.exists(self.attach_pool):
  211. attach.update_row(self.attach_pool)
  212. else:
  213. attach.insert_row(self.attach_pool)
  214. try:
  215. if os.exists(localpath):
  216. os.remove(localpath)
  217. except Exception as e:
  218. pass
  219. return True
  220. if _ots_exists:
  221. objectPath = attach.getProperties().get(attachment_path)
  222. download_succeed = downloadFile(self.bucket,objectPath,localpath)
  223. if download_succeed:
  224. log("md5:%s path:%s download file from oss succeed"%(filemd5,objectPath[5:]))
  225. else:
  226. log("md5:%s path:%s download file from ots failed=="%(filemd5,objectPath[5:]))
  227. else:
  228. log("md5:%s path:%s not found in ots"%(filemd5,objectPath[5:]))
  229. if local_exists or download_succeed:
  230. _size = os.path.getsize(localpath)
  231. attach.setValue(attachment_size,_size,True)
  232. if _size>ATTACHMENT_LARGESIZE:
  233. attach.setValue(attachment_status, ATTACHMENT_TOOLARGE,True)
  234. log("attachment :%s of path:%s to large"%(filemd5,_path))
  235. _ots_attach = attachment(attach.getProperties_ots())
  236. _ots_attach.update_row(self.ots_client)
  237. #更新postgres
  238. if attach.exists(self.attach_pool):
  239. attach.update_row(self.attach_pool)
  240. else:
  241. attach.insert_row(self.attach_pool)
  242. if local_exists:
  243. upload_status = uploadFileByPath(self.bucket,localpath,objectPath)
  244. os.remove(localpath)
  245. return True
  246. time_download = time.time()-d_start_time
  247. #调用接口处理结果
  248. start_time = time.time()
  249. _filetype = attach.getProperties().get(attachment_filetype)
  250. # _data_base64 = base64.b64encode(open(localpath,"rb").read())
  251. # _success,_html,swf_images = getAttachDealInterface(_data_base64,_filetype)
  252. _success,_html,swf_images,classification = getAttachDealInterface(None,_filetype,path=localpath)
  253. log("process filemd5:%s %s of type:%s with size:%.3fM download:%ds recognize takes %ds,ret_size:%d"%(filemd5,str(_success),_filetype,round(_size/1024/1024,4),time_download,time.time()-start_time,len(_html)))
  254. if _success:
  255. if len(_html)<5:
  256. _html = ""
  257. else:
  258. if len(_html)>1:
  259. _html = "interface return error"
  260. else:
  261. sentMsgToDD("attach interface failed of docid:%s of filemd5:%s of type:%s size:%.3fM with result:%s"%(str(docids),filemd5,_filetype,round(_size/1024/1024,4),str(_html)))
  262. _html = ""
  263. return False
  264. swf_images = eval(swf_images)
  265. if attach.getProperties().get(attachment_filetype)=="swf" and len(swf_images)>0:
  266. swf_urls = json.loads(attach.getProperties().get(attachment_swfUrls,"[]"))
  267. if len(swf_urls)==0:
  268. objectPath = attach.getProperties().get(attachment_path,"")
  269. swf_dir = os.path.join(self.current_path,"swf_images",uuid4().hex)
  270. if not os.path.exists(swf_dir):
  271. os.mkdir(swf_dir)
  272. for _i in range(len(swf_images)):
  273. _base = swf_images[_i]
  274. _base = base64.b64decode(_base)
  275. filename = "swf_page_%d.png"%(_i)
  276. filepath = os.path.join(swf_dir,filename)
  277. with open(filepath,"wb") as f:
  278. f.write(_base)
  279. swf_urls = transformSWF(self.bucket,self.attachment_hub_url,objectPath,None,swf_dir)
  280. if os.path.exists(swf_dir):
  281. os.rmdir(swf_dir)
  282. attach.setValue(attachment_swfUrls,json.dumps(swf_urls,ensure_ascii=False),True)
  283. if re.search("<td",_html) is not None:
  284. attach.setValue(attachment_has_table,1,True)
  285. _file_title = self.getTitleFromHtml(filemd5,_dochtmlcon)
  286. filelink = self.getSourceLinkFromHtml(filemd5,_dochtmlcon)
  287. if _file_title!="":
  288. attach.setValue(attachment_file_title,_file_title,True)
  289. if filelink!="":
  290. attach.setValue(attachment_file_link,filelink,True)
  291. attach.setValue(attachment_attachmenthtml,_html,True)
  292. attach.setValue(attachment_attachmentcon,BeautifulSoup(_html,"lxml").get_text(),True)
  293. attach.setValue(attachment_status,ATTACHMENT_PROCESSED,True)
  294. attach.setValue(attachment_recsize,len(_html),True)
  295. attach.setValue(attachment_process_time,getCurrent_date(format="%Y-%m-%d %H:%M:%S"),True)
  296. attach.setValue(attachment_classification,classification,True)
  297. #更新ots
  298. _ots_attach = attachment(attach.getProperties_ots())
  299. _ots_attach.update_row(self.ots_client) #线上再开放更新
  300. #更新postgres
  301. if attach.exists(self.attach_pool):
  302. attach.update_row(self.attach_pool)
  303. else:
  304. attach.insert_row(self.attach_pool)
  305. if local_exists:
  306. upload_status = uploadFileByPath(self.bucket,localpath,objectPath)
  307. try:
  308. if upload_status and os.exists(localpath):
  309. os.remove(localpath)
  310. except Exception as e:
  311. pass
  312. return True
  313. else:
  314. return True
  315. except requests.ConnectionError as e1:
  316. raise e1
  317. except oss2.exceptions.NotFound as e:
  318. return True
  319. except Exception as e:
  320. traceback.print_exc()
  321. def flow_attachment(self):
  322. self.flow_attachment_producer()
  323. self.flow_attachment_producer_comsumer()
  324. def getAttachPath(self,filemd5,_dochtmlcon):
  325. _soup = BeautifulSoup(_dochtmlcon,"lxml")
  326. _find = _soup.find("a",attrs={"data":filemd5})
  327. filelink = ""
  328. if _find is None:
  329. _find = _soup.find("img",attrs={"data":filemd5})
  330. if _find is not None:
  331. filelink = _find.attrs.get("src","")
  332. else:
  333. filelink = _find.attrs.get("href","")
  334. _path = filelink.split("/file")
  335. if len(_path)>1:
  336. return _path[1]
  337. def getAttachments(self,list_filemd5,_dochtmlcon):
  338. conn = self.attach_pool.getConnector()
  339. #搜索postgres
  340. try:
  341. to_find_md5 = []
  342. for _filemd5 in list_filemd5[:50]:
  343. if _filemd5 is not None:
  344. to_find_md5.append(_filemd5)
  345. conditions = ["filemd5 in ('%s')"%("','".join(to_find_md5))]
  346. list_attachment = Attachment_postgres.select_rows(conn,Attachment_postgres,"attachment",conditions)
  347. log("select localpath database %d/%d"%(len(list_attachment),len(to_find_md5)))
  348. set_md5 = set()
  349. for _attach in list_attachment:
  350. set_md5.add(_attach.getProperties().get(attachment_filemd5))
  351. list_not_in_md5 = []
  352. for _filemd5 in to_find_md5:
  353. if _filemd5 not in set_md5:
  354. list_not_in_md5.append(_filemd5)
  355. _path = self.getAttachPath(_filemd5,_dochtmlcon)
  356. if _path is not None:
  357. if _path[0]=="/":
  358. _path = _path[1:]
  359. _filetype = _path.split(".")[-1]
  360. _attach = {attachment_filemd5:_filemd5,
  361. attachment_filetype:_filetype,
  362. attachment_status:20,
  363. attachment_path:"%s/%s"%(_filemd5[:4],_path),
  364. attachment_crtime:getCurrent_date(format="%Y-%m-%d %H:%M:%S")}
  365. list_attachment.append(Attachment_postgres(_attach))
  366. else:
  367. log("getAttachments search in ots:%s"%(_filemd5))
  368. _attach = {attachment_filemd5:_filemd5}
  369. _attach_ots = attachment(_attach)
  370. _attach_ots.fix_columns(self.ots_client,[attachment_status,attachment_path,attachment_attachmenthtml,attachment_attachmentcon,attachment_filetype,attachment_swfUrls,attachment_process_time],True)
  371. if _attach_ots.getProperties().get(attachment_status) is not None:
  372. log("getAttachments find in ots:%s"%(_filemd5))
  373. list_attachment.append(Attachment_postgres(_attach_ots.getProperties()))
  374. return list_attachment
  375. except Exception as e:
  376. log("attachProcess comsumer error %s"%str(e))
  377. log(str(to_find_md5))
  378. traceback.print_exc()
  379. return []
  380. finally:
  381. self.attach_pool.putConnector(conn)
  382. def flow_attachment_producer(self,columns=[document_tmp_attachment_path,document_tmp_crtime]):
  383. q_size = self.queue_attachment.qsize()
  384. qsize_ocr = self.queue_attachment_ocr.qsize()
  385. qsize_not_ocr = self.queue_attachment_not_ocr.qsize()
  386. log("queue_attachment:%d,queue_attachment_ocr:%d,queue_attachment_not_ocr:%d"%(q_size,qsize_ocr,qsize_not_ocr))
  387. def flow_attachment_producer_comsumer(self):
  388. log("start flow_attachment comsumer")
  389. mt = MultiThreadHandler(self.queue_attachment,self.comsumer_handle,None,10,1,restart=True)
  390. mt.run()
  391. def set_queue(self,_dict):
  392. list_attach = _dict.get("list_attach")
  393. to_ocr = False
  394. for attach in list_attach:
  395. if attach.getProperties().get(attachment_filetype) in ["bmp","jpeg","jpg","png","swf","pdf","tif"]:
  396. to_ocr = True
  397. break
  398. if to_ocr:
  399. self.queue_attachment_ocr.put(_dict,True)
  400. else:
  401. self.queue_attachment_not_ocr.put(_dict,True)
  402. def comsumer_handle(self,_dict,result_queue):
  403. try:
  404. frame = _dict["frame"]
  405. conn = _dict["conn"]
  406. message_id = frame.headers["message-id"]
  407. item = json.loads(frame.body)
  408. page_attachments = json.loads(item.get(document_tmp_attachment_path,"[]"))
  409. _dochtmlcon = item.get(document_tmp_dochtmlcon,"")
  410. if len(page_attachments)==0:
  411. self.set_queue({"item":item,"list_attach":[],"message_id":message_id,"conn":conn})
  412. else:
  413. list_fileMd5 = []
  414. for _atta in page_attachments:
  415. list_fileMd5.append(_atta.get(document_tmp_attachment_path_filemd5))
  416. list_attach = self.getAttachments(list_fileMd5,_dochtmlcon)
  417. self.set_queue({"item":item,"list_attach":list_attach,"message_id":message_id,"conn":conn})
  418. except Exception as e:
  419. traceback.print_exc()
  420. def remove_attachment_postgres(self):
  421. current_date = getCurrent_date(format="%Y-%m-%d")
  422. last_date = timeAdd(current_date,-2,format="%Y-%m-%d")
  423. sql = " delete from attachment where crtime<='%s 00:00:00' "%(last_date)
  424. conn = getConnection_postgres()
  425. cursor = conn.cursor()
  426. cursor.execute(sql)
  427. conn.commit()
  428. conn.close()
  429. def start_flow_attachment(self):
  430. schedule = BlockingScheduler()
  431. schedule.add_job(self.flow_attachment_process,"cron",second="*/20")
  432. schedule.add_job(self.flow_attachment,"cron",second="*/10")
  433. schedule.add_job(self.monitor_attachment_process,"cron",second="*/10")
  434. schedule.add_job(self.remove_attachment_postgres,"cron",hour="6")
  435. schedule.add_job(self.process_failed_attachment,"cron",minute="*/10")
  436. schedule.add_job(self.monitor_listener,"cron",minute="*/1")
  437. schedule.start()
  438. class Dataflow_ActivteMQ_extract(Dataflow_extract):
  439. class ExtractListener():
  440. def __init__(self,conn,_func,*args,**kwargs):
  441. self.conn = conn
  442. self._func = _func
  443. def on_message(self, headers):
  444. try:
  445. log("get message")
  446. message_id = headers.headers["message-id"]
  447. body = headers.body
  448. log("get message %s crtime:%s"%(message_id,json.loads(body).get("crtime","")))
  449. self._func(_dict={"frame":headers,"conn":self.conn},result_queue=None)
  450. except Exception as e:
  451. traceback.print_exc()
  452. pass
  453. def on_error(self, headers):
  454. log('received an error %s' % str(headers.body))
  455. def __del__(self):
  456. self.conn.disconnect()
  457. def __init__(self):
  458. Dataflow_extract.__init__(self)
  459. self.industy_url = "http://127.0.0.1:15000/industry_extract"
  460. self.extract_interfaces = [["http://127.0.0.1:15030/content_extract",20],
  461. ["http://192.168.0.115:15030/content_extract",10]
  462. ]
  463. self.mq_extract = "/queue/dataflow_extract"
  464. self.mq_extract_failed = "/queue/dataflow_extract_failed"
  465. self.whole_weight = 0
  466. for _url,weight in self.extract_interfaces:
  467. self.whole_weight+= weight
  468. current_weight = 0
  469. for _i in range(len(self.extract_interfaces)):
  470. current_weight += self.extract_interfaces[_i][1]
  471. self.extract_interfaces[_i][1] = current_weight/self.whole_weight
  472. self.comsumer_count = 40
  473. self.pool_postgres = ConnectorPool(10,self.comsumer_count,getConnection_postgres)
  474. self.pool_redis_doc = ConnectorPool(10,self.comsumer_count,getConnect_redis_doc)
  475. self.conn_mq = getConnect_activateMQ()
  476. self.pool_mq = ConnectorPool(10,30,getConnect_activateMQ)
  477. self.block_url = RLock()
  478. self.url_count = 0
  479. self.list_extract_comsumer = []
  480. for _i in range(self.comsumer_count):
  481. listener_extract = self.ExtractListener(getConnect_activateMQ(),self.comsumer_handle)
  482. createComsumer(listener_extract,self.mq_extract)
  483. self.list_extract_comsumer.append(listener_extract)
  484. def monitor_listener(self):
  485. for i in range(len(self.list_extract_comsumer)):
  486. if self.list_extract_comsumer[i].conn.is_connected():
  487. continue
  488. else:
  489. listener = self.ExtractListener(getConnect_activateMQ(),self.comsumer_handle)
  490. createComsumer(listener,self.mq_extract)
  491. self.list_extract_comsumer[i] = listener
  492. def getExtract_url(self):
  493. _url_num = 0
  494. with self.block_url:
  495. self.url_count += 1
  496. self.url_count %= self.whole_weight
  497. _url_num = self.url_count
  498. # _r = random.random()
  499. _r = _url_num/self.whole_weight
  500. for _i in range(len(self.extract_interfaces)):
  501. if _r<=self.extract_interfaces[_i][1]:
  502. return self.extract_interfaces[_i][0]
  503. def request_extract_interface(self,json,headers):
  504. # _i = random.randint(0,len(self.extract_interfaces)-1)
  505. # _i = 0
  506. # _url = self.extract_interfaces[_i]
  507. _url = self.getExtract_url()
  508. log("extract_url:%s"%(str(_url)))
  509. resp = requests.post(_url,json=json,headers=headers,timeout=10*60)
  510. return resp
  511. def request_industry_interface(self,json,headers):
  512. resp = requests.post(self.industy_url,json=json,headers=headers)
  513. return resp
  514. def flow_extract_producer(self,columns=[document_tmp_page_time,document_tmp_doctitle,document_tmp_docchannel,document_tmp_status,document_tmp_original_docchannel,document_tmp_web_source_no]):
  515. q_size = self.queue_extract.qsize()
  516. log("queue extract size:%d"%(q_size))
  517. def process_extract_failed(self):
  518. def _handle(_dict,result_queue):
  519. frame = _dict.get("frame")
  520. message_id = frame.headers["message-id"]
  521. subscription = frame.headers.setdefault('subscription', None)
  522. conn = _dict.get("conn")
  523. body = frame.body
  524. if body is not None:
  525. item = json.loads(body)
  526. item["extract_times"] = 10
  527. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  528. ackMsg(conn,message_id,subscription)
  529. from BaseDataMaintenance.java.MQInfo import getQueueSize
  530. extract_failed_size = getQueueSize("dataflow_extract_failed")
  531. extract_size = getQueueSize("dataflow_extract")
  532. log("extract_failed_size %s extract_size %s"%(str(extract_failed_size),str(extract_size)))
  533. if extract_failed_size>0 and extract_size<100:
  534. failed_listener = self.ExtractListener(getConnect_activateMQ(),_handle)
  535. createComsumer(failed_listener,self.mq_extract_failed)
  536. while 1:
  537. extract_failed_size = getQueueSize("dataflow_extract_failed")
  538. if extract_failed_size==0:
  539. break
  540. time.sleep(10)
  541. failed_listener.conn.disconnect()
  542. def flow_extract(self,):
  543. self.comsumer()
  544. def comsumer(self):
  545. mt = MultiThreadHandler(self.queue_extract,self.comsumer_handle,None,20,1,True)
  546. mt.run()
  547. def getExtract_json_fromDB(self,_fingerprint):
  548. conn = self.pool_postgres.getConnector()
  549. try:
  550. list_extract = Document_extract_postgres.select_rows(conn,Document_extract_postgres,"document_extract",[" fingerprint='%s'"%_fingerprint])
  551. if len(list_extract)>0:
  552. _extract = list_extract[0]
  553. return _extract.getProperties().get(document_extract_extract_json)
  554. except Exception as e:
  555. traceback.print_exc()
  556. finally:
  557. self.pool_postgres.putConnector(conn)
  558. return None
  559. def putExtract_json_toDB(self,fingerprint,docid,extract_json):
  560. _de = Document_extract_postgres({document_extract_fingerprint:fingerprint,
  561. document_extract_docid:docid,
  562. document_extract_extract_json:extract_json})
  563. _de.insert_row(self.pool_postgres,1)
  564. def getExtract_json_fromRedis(self,_fingerprint):
  565. db = self.pool_redis_doc.getConnector()
  566. try:
  567. _extract_json = db.get(_fingerprint)
  568. return _extract_json
  569. except Exception as e:
  570. log("getExtract_json_fromRedis error %s"%(str(e)))
  571. finally:
  572. try:
  573. if db.connection.check_health():
  574. self.pool_redis_doc.putConnector(db)
  575. except Exception as e:
  576. pass
  577. return None
  578. def putExtract_json_toRedis(self,fingerprint,extract_json):
  579. db = self.pool_redis_doc.getConnector()
  580. try:
  581. _extract_json = db.set(str(fingerprint),extract_json)
  582. db.expire(fingerprint,3600*2)
  583. return _extract_json
  584. except Exception as e:
  585. log("putExtract_json_toRedis error%s"%(str(e)))
  586. traceback.print_exc()
  587. finally:
  588. try:
  589. if db.connection.check_health():
  590. self.pool_redis_doc.putConnector(db)
  591. except Exception as e:
  592. pass
  593. def comsumer_handle(self,_dict,result_queue):
  594. try:
  595. log("start handle")
  596. frame = _dict["frame"]
  597. conn = _dict["conn"]
  598. message_id = frame.headers["message-id"]
  599. subscription = frame.headers.setdefault('subscription', None)
  600. item = json.loads(frame.body)
  601. dtmp = Document_tmp(item)
  602. dhtml = Document_html({"partitionkey":item.get("partitionkey"),
  603. "docid":item.get("docid")})
  604. extract_times = item.get("extract_times",0)+1
  605. item["extract_times"] = extract_times
  606. _dochtmlcon = item.get(document_tmp_dochtmlcon,"")
  607. html_len = len(_dochtmlcon)
  608. if html_len>200000:
  609. # if int(item.get("docid"))==238431011:
  610. # save(item,"238431011.pk")
  611. try:
  612. _dochtmlcon = re.sub("<html>|</html>|<body>|</body>", "", _dochtmlcon)
  613. _soup = BeautifulSoup(_dochtmlcon,"lxml")
  614. _soup = article_limit(_soup,200000)
  615. _dochtmlcon = str(_soup)
  616. except Exception as e:
  617. traceback.print_exc()
  618. ackMsg(conn,message_id,subscription)
  619. return
  620. log("docid %s len %d limit to %d"%(str(item.get("docid")),html_len,len(_dochtmlcon)))
  621. dhtml.setValue(document_tmp_dochtmlcon,_dochtmlcon,True)
  622. _extract = Document_extract({})
  623. _extract.setValue(document_extract2_partitionkey,item.get(document_partitionkey))
  624. _extract.setValue(document_extract2_docid,item.get(document_docid))
  625. all_done = 1
  626. data = {}
  627. for k,v in item.items():
  628. data[k] = v
  629. data["timeout"] = 440
  630. data["doc_id"] = data.get(document_tmp_docid,0)
  631. # if data["docid"]<298986054 and data["docid"]>0:
  632. # log("jump docid %s"%(str(data["docid"])))
  633. # ackMsg(conn,message_id,subscription)
  634. # return
  635. data["content"] = data.get(document_tmp_dochtmlcon,"")
  636. if document_tmp_dochtmlcon in data:
  637. data.pop(document_tmp_dochtmlcon)
  638. data["title"] = data.get(document_tmp_doctitle,"")
  639. data["web_source_no"] = item.get(document_tmp_web_source_no,"")
  640. data["web_source_name"] = item.get(document_tmp_web_source_name,"")
  641. data["original_docchannel"] = item.get(document_tmp_original_docchannel,"")
  642. _fingerprint = getFingerprint(str(data["title"])+str(data["content"]))
  643. if all_done>0:
  644. _time = time.time()
  645. # extract_json = self.getExtract_json_fromDB(_fingerprint)
  646. extract_json = self.getExtract_json_fromRedis(_fingerprint)
  647. log("get json from db takes %.4f"%(time.time()-_time))
  648. # extract_json = None
  649. _docid = int(data["doc_id"])
  650. if extract_json is not None:
  651. log("fingerprint %s exists docid:%s"%(_fingerprint,str(_docid)))
  652. _extract.setValue(document_extract2_extract_json,extract_json,True)
  653. else:
  654. resp = self.request_extract_interface(json=data,headers=self.header)
  655. if (resp.status_code >=200 and resp.status_code<=213):
  656. extract_json = resp.content.decode("utf8")
  657. _extract.setValue(document_extract2_extract_json,extract_json,True)
  658. _time = time.time()
  659. # self.putExtract_json_toDB(_fingerprint,_docid,extract_json)
  660. self.putExtract_json_toRedis(_fingerprint,extract_json)
  661. log("get json to db takes %.4f"%(time.time()-_time))
  662. else:
  663. log("%s--%s"%(str(resp.status_code),resp.content.decode("utf8")))
  664. all_done = -2
  665. # if all_done>0:
  666. # resp = self.request_industry_interface(json=data,headers=self.header)
  667. # if (resp.status_code >=200 and resp.status_code<=213):
  668. # _extract.setValue(document_extract2_industry_json,resp.content.decode("utf8"),True)
  669. # else:
  670. # log("%s--%s"%(str(resp.status_code),resp.content.decode("utf8")))
  671. # all_done = -3
  672. # _to_ack = False
  673. # if all_done>0 and len(_extract.getProperties().get(document_extract2_extract_json,""))<=2:
  674. # all_done = -4
  675. _extract.setValue(document_extract2_industry_json,"{}",True)
  676. try:
  677. if all_done!=1:
  678. sentMsgToDD("要素提取失败:docid:%d with result:%d"%(item.get(document_tmp_docid),all_done))
  679. if extract_times>=10:
  680. #process as succeed
  681. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  682. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  683. dtmp.update_row(self.ots_client)
  684. dhtml.update_row(self.ots_client)
  685. #replace as {}
  686. _extract.setValue(document_extract2_extract_json,"{}",True)
  687. _extract.setValue(document_extract2_industry_json,"{}",True)
  688. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  689. _extract.update_row(self.ots_client)
  690. _to_ack = True
  691. elif extract_times>5:
  692. #transform to the extract_failed queue
  693. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract_failed):
  694. #process as succeed
  695. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  696. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  697. dtmp.update_row(self.ots_client)
  698. dhtml.update_row(self.ots_client)
  699. #replace as {}
  700. _extract.setValue(document_extract2_extract_json,"{}",True)
  701. _extract.setValue(document_extract2_industry_json,"{}",True)
  702. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  703. _extract.update_row(self.ots_client)
  704. _to_ack = True
  705. else:
  706. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract)
  707. #失败保存
  708. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  709. dtmp.setValue(document_tmp_status,60,True)
  710. if not dtmp.exists_row(self.ots_client):
  711. dtmp.update_row(self.ots_client)
  712. dhtml.update_row(self.ots_client)
  713. if send_succeed:
  714. _to_ack = True
  715. else:
  716. #process succeed
  717. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  718. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  719. if _docid==290816703:
  720. dtmp.setValue("test_json",extract_json,True)
  721. dtmp.update_row(self.ots_client)
  722. dhtml.update_row(self.ots_client)
  723. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  724. _extract.update_row(self.ots_client)
  725. _to_ack = True
  726. except Exception:
  727. traceback.print_exc()
  728. if _to_ack:
  729. ackMsg(conn,message_id,subscription)
  730. log("process %s docid:%d %s"%(str(_to_ack),data["doc_id"],str(all_done)))
  731. except requests.ConnectionError as e1:
  732. item["extract_times"] -= 1
  733. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  734. ackMsg(conn,message_id,subscription)
  735. except Exception as e:
  736. traceback.print_exc()
  737. sentMsgToDD("要素提取失败:docid:%d with result:%s"%(item.get(document_tmp_docid),str(e)))
  738. log("process %s docid: failed message_id:%s"%(data["doc_id"],message_id))
  739. if extract_times>=10:
  740. #process as succeed
  741. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  742. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  743. dtmp.update_row(self.ots_client)
  744. dhtml.update_row(self.ots_client)
  745. #replace as {}
  746. _extract.setValue(document_extract2_extract_json,"{}",True)
  747. _extract.setValue(document_extract2_industry_json,"{}",True)
  748. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  749. _extract.update_row(self.ots_client)
  750. ackMsg(conn,message_id,subscription)
  751. elif extract_times>5:
  752. #transform to the extract_failed queue
  753. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract_failed):
  754. #process as succeed
  755. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  756. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  757. dtmp.update_row(self.ots_client)
  758. dhtml.update_row(self.ots_client)
  759. #replace as {}
  760. _extract.setValue(document_extract2_extract_json,"{}",True)
  761. _extract.setValue(document_extract2_industry_json,"{}",True)
  762. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  763. _extract.update_row(self.ots_client)
  764. ackMsg(conn,message_id,subscription)
  765. else:
  766. #transform to the extract queue
  767. #失败保存
  768. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  769. dtmp.setValue(document_tmp_status,60,True)
  770. if not dtmp.exists_row(self.ots_client):
  771. dtmp.update_row(self.ots_client)
  772. dhtml.update_row(self.ots_client)
  773. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  774. ackMsg(conn,message_id,subscription)
  775. def delete_document_extract(self,save_count=70*10000):
  776. conn = self.pool_postgres.getConnector()
  777. try:
  778. cursor = conn.cursor()
  779. sql = " select max(docid),min(docid) from document_extract "
  780. cursor.execute(sql)
  781. rows = cursor.fetchall()
  782. if len(rows)>0:
  783. maxdocid,mindocid = rows[0]
  784. d_mindocid = int(maxdocid)-save_count
  785. if mindocid<d_mindocid:
  786. sql = " delete from document_extract where docid<%d"%d_mindocid
  787. cursor.execute(sql)
  788. conn.commit()
  789. except Exception as e:
  790. traceback.print_exc()
  791. finally:
  792. self.pool_postgres.putConnector(conn)
  793. def start_flow_extract(self):
  794. schedule = BlockingScheduler()
  795. schedule.add_job(self.flow_extract_producer,"cron",second="*/20")
  796. schedule.add_job(self.process_extract_failed,"cron",minute="*/5")
  797. schedule.add_job(self.delete_document_extract,"cron",hour="*/5")
  798. schedule.add_job(self.monitor_listener,"cron",minute="*/5")
  799. schedule.start()
  800. from multiprocessing import RLock
  801. docid_lock = RLock()
  802. conn_mysql = None
  803. def generateRangeDocid(nums):
  804. global conn_mysql
  805. while 1:
  806. try:
  807. with docid_lock:
  808. if conn_mysql is None:
  809. conn_mysql = getConnection_mysql()
  810. cursor = conn_mysql.cursor()
  811. sql = "select serial_value from b2c_serial_no where serial_name='DocumentIdSerial'"
  812. cursor.execute(sql)
  813. rows = cursor.fetchall()
  814. current_docid = rows[0][0]
  815. next_docid = current_docid+1
  816. update_docid = current_docid+nums
  817. sql = " update b2c_serial_no set serial_value=%d where serial_name='DocumentIdSerial'"%(update_docid)
  818. cursor.execute(sql)
  819. conn_mysql.commit()
  820. return next_docid
  821. except Exception as e:
  822. conn_mysql = getConnection_mysql()
  823. # 自定义jsonEncoder
  824. class MyEncoder(json.JSONEncoder):
  825. def default(self, obj):
  826. if isinstance(obj, np.ndarray):
  827. return obj.tolist()
  828. elif isinstance(obj, bytes):
  829. return str(obj, encoding='utf-8')
  830. elif isinstance(obj, (np.float_, np.float16, np.float32,
  831. np.float64,Decimal)):
  832. return float(obj)
  833. elif isinstance(obj,str):
  834. return obj
  835. return json.JSONEncoder.default(self, obj)
  836. class Dataflow_init(Dataflow):
  837. class InitListener():
  838. def __init__(self,conn,*args,**kwargs):
  839. self.conn = conn
  840. self.get_count = 1000
  841. self.count = self.get_count
  842. self.begin_docid = None
  843. self.mq_attachment = "/queue/dataflow_attachment"
  844. self.mq_extract = "/queue/dataflow_extract"
  845. self.pool_mq1 = ConnectorPool(1,4,getConnect_activateMQ)
  846. def on_error(self, headers):
  847. log('received an error %s' % headers.body)
  848. def getRangeDocid(self):
  849. begin_docid = generateRangeDocid(self.get_count)
  850. self.begin_docid = begin_docid
  851. self.count = 0
  852. def getNextDocid(self):
  853. if self.count>=self.get_count:
  854. self.getRangeDocid()
  855. next_docid = self.begin_docid+self.count
  856. self.count += 1
  857. return next_docid
  858. def on_message(self, headers):
  859. next_docid = int(self.getNextDocid())
  860. partitionkey = int(next_docid%500+1)
  861. message_id = headers.headers["message-id"]
  862. body = json.loads(headers.body)
  863. body[document_tmp_partitionkey] = partitionkey
  864. body[document_tmp_docid] = next_docid
  865. if body.get(document_original_docchannel) is None:
  866. body[document_original_docchannel] = body.get(document_docchannel)
  867. page_attachments = body.get(document_tmp_attachment_path,"[]")
  868. _uuid = body.get(document_tmp_uuid,"")
  869. if page_attachments!="[]":
  870. status = random.randint(1,10)
  871. body[document_tmp_status] = status
  872. if send_msg_toacmq(self.pool_mq1,json.dumps(body,cls=MyEncoder),self.mq_attachment):
  873. log("uuid:%s with docid:%s"%(str(_uuid),str(next_docid)))
  874. ackMsg(self.conn,message_id)
  875. else:
  876. log("send_msg_error on init listener")
  877. else:
  878. status = random.randint(11,50)
  879. body[document_tmp_status] = status
  880. if send_msg_toacmq(self.pool_mq1,json.dumps(body,cls=MyEncoder),self.mq_extract):
  881. log("uuid:%s with docid:%s"%(str(_uuid),str(next_docid)))
  882. ackMsg(self.conn,message_id)
  883. else:
  884. log("send_msg_error on init listener")
  885. def __del__(self):
  886. self.conn.disconnect()
  887. del self.pool_mq1
  888. def __init__(self):
  889. Dataflow.__init__(self)
  890. self.mq_init = "/queue/dataflow_init"
  891. self.mq_attachment = "/queue/dataflow_attachment"
  892. self.mq_extract = "/queue/dataflow_extract"
  893. self.pool_oracle = ConnectorPool(10,15,getConnection_oracle)
  894. self.pool_mq = ConnectorPool(10,30,getConnect_activateMQ)
  895. self.ots_capacity = getConnect_ots_capacity()
  896. self.init_comsumer_counts = 2
  897. self.list_init_comsumer = []
  898. for i in range(self.init_comsumer_counts):
  899. listener = self.InitListener(getConnect_activateMQ())
  900. createComsumer(listener,self.mq_init)
  901. self.list_init_comsumer.append(listener)
  902. def monitor_listener(self):
  903. for i in range(len(self.list_init_comsumer)):
  904. if self.list_init_comsumer[i].conn.is_connected():
  905. continue
  906. else:
  907. listener = self.InitListener(getConnect_activateMQ())
  908. createComsumer(listener,self.mq_init)
  909. self.list_init_comsumer[i] = listener
  910. def temp2mq(self,object):
  911. conn_oracle = self.pool_oracle.getConnector()
  912. try:
  913. list_obj = object.select_rows(conn_oracle,type(object),object.table_name,[],limit=1000)
  914. for _obj in list_obj:
  915. ots_dict = _obj.getProperties_ots()
  916. if len(ots_dict.get("dochtmlcon",""))>500000:
  917. _obj.delete_row(conn_oracle)
  918. log("msg too long:%s,%d"%(ots_dict.get("uuid"),len(ots_dict.get("dochtmlcon",""))))
  919. continue
  920. if send_msg_toacmq(self.pool_mq,json.dumps(ots_dict,cls=MyEncoder),self.mq_init):
  921. #删除数据,上线放开
  922. _obj.delete_row(conn_oracle)
  923. else:
  924. log("send_msg_error111:%s,%d"%(ots_dict.get("uuid"),len(ots_dict.get("dochtmlcon",""))))
  925. self.pool_oracle.putConnector(conn_oracle)
  926. except Exception as e:
  927. traceback.print_exc()
  928. self.pool_oracle.decrease()
  929. def ots2mq(self):
  930. try:
  931. bool_query = BoolQuery(must_queries=[RangeQuery("status",1,51)])
  932. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document","document_index",
  933. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(document_docid)]),get_total_count=True,limit=100),
  934. ColumnsToGet(return_type=ColumnReturnType.ALL))
  935. list_data = getRow_ots(rows)
  936. for _data in list_data:
  937. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  938. document_tmp_docid:_data.get(document_tmp_docid),
  939. document_tmp_status:0}
  940. _document = Document(_d)
  941. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  942. _document_html = Document(_data)
  943. _document_html.fix_columns(self.ots_capacity,[document_tmp_dochtmlcon],True)
  944. if page_attachments!="[]":
  945. status = random.randint(1,10)
  946. _data[document_tmp_status] = status
  947. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  948. else:
  949. status = random.randint(11,50)
  950. _data[document_tmp_status] = status
  951. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  952. if send_succeed:
  953. _document.update_row(self.ots_client)
  954. else:
  955. log("send_msg_error2222")
  956. while next_token:
  957. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document","document_index",
  958. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  959. ColumnsToGet(return_type=ColumnReturnType.ALL))
  960. list_data = getRow_ots(rows)
  961. for _data in list_data:
  962. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  963. document_tmp_docid:_data.get(document_tmp_docid),
  964. document_tmp_status:0}
  965. _document = Document(_d)
  966. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  967. _document_html = Document(_data)
  968. _document_html.fix_columns(self.ots_capacity,[document_tmp_dochtmlcon],True)
  969. if page_attachments!="[]":
  970. status = random.randint(1,10)
  971. _data[document_tmp_status] = status
  972. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  973. else:
  974. status = random.randint(11,50)
  975. _data[document_tmp_status] = status
  976. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  977. if send_succeed:
  978. _document.update_row(self.ots_client)
  979. else:
  980. log("send_msg_error2222")
  981. except Exception as e:
  982. traceback.print_exc()
  983. def otstmp2mq(self):
  984. try:
  985. bool_query = BoolQuery(must_queries=[TermQuery("status",0)])
  986. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document_tmp","document_tmp_index",
  987. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(document_docid)]),get_total_count=True,limit=100),
  988. ColumnsToGet(return_type=ColumnReturnType.ALL))
  989. list_data = getRow_ots(rows)
  990. for _data in list_data:
  991. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  992. document_tmp_docid:_data.get(document_tmp_docid),
  993. document_tmp_status:0}
  994. _document = Document_tmp(_d)
  995. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  996. _document_html = Document_html(_data)
  997. _document_html.fix_columns(self.ots_client,[document_tmp_dochtmlcon],True)
  998. if page_attachments!="[]":
  999. status = random.randint(1,10)
  1000. _data[document_tmp_status] = status
  1001. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  1002. else:
  1003. status = random.randint(11,50)
  1004. _data[document_tmp_status] = status
  1005. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  1006. if send_succeed:
  1007. _document.setValue(document_tmp_status,1,True)
  1008. _document.update_row(self.ots_client)
  1009. else:
  1010. log("send_msg_error2222")
  1011. while next_token:
  1012. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document_tmp","document_tmp_index",
  1013. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1014. ColumnsToGet(return_type=ColumnReturnType.ALL))
  1015. list_data = getRow_ots(rows)
  1016. for _data in list_data:
  1017. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  1018. document_tmp_docid:_data.get(document_tmp_docid),
  1019. document_tmp_status:0}
  1020. _document = Document_tmp(_d)
  1021. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  1022. _document_html = Document_html(_data)
  1023. _document_html.fix_columns(self.ots_client,[document_tmp_dochtmlcon],True)
  1024. if page_attachments!="[]":
  1025. status = random.randint(1,10)
  1026. _data[document_tmp_status] = status
  1027. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  1028. else:
  1029. status = random.randint(11,50)
  1030. _data[document_tmp_status] = status
  1031. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  1032. if send_succeed:
  1033. _document.setValue(document_tmp_status,1,True)
  1034. _document.update_row(self.ots_client)
  1035. else:
  1036. log("send_msg_error2222")
  1037. except Exception as e:
  1038. traceback.print_exc()
  1039. def test_dump_docid(self):
  1040. class TestDumpListener(ActiveMQListener):
  1041. def on_message(self, headers):
  1042. message_id = headers.headers["message-id"]
  1043. body = headers.body
  1044. self._queue.put(headers,True)
  1045. ackMsg(self.conn,message_id)
  1046. _queue = Queue()
  1047. listener1 = TestDumpListener(getConnect_activateMQ(),_queue)
  1048. listener2 = TestDumpListener(getConnect_activateMQ(),_queue)
  1049. createComsumer(listener1,"/queue/dataflow_attachment")
  1050. createComsumer(listener2,"/queue/dataflow_extract")
  1051. time.sleep(10)
  1052. list_item = []
  1053. list_docid = []
  1054. while 1:
  1055. try:
  1056. _item = _queue.get(timeout=2)
  1057. list_item.append(_item)
  1058. except Exception as e:
  1059. break
  1060. for item in list_item:
  1061. _item = json.loads(item.body)
  1062. list_docid.append(_item.get("docid"))
  1063. log(list_docid[:10])
  1064. log("len docid:%d set len:%d"%(len(list_docid),len(set(list_docid))))
  1065. def start_dataflow_init(self):
  1066. # self.test_dump_docid()
  1067. from BaseDataMaintenance.model.oracle.CaiGouYiXiangTemp import CaiGouYiXiangTemp
  1068. from BaseDataMaintenance.model.oracle.PaiMaiChuRangTemp import PaiMaiChuRangTemp
  1069. from BaseDataMaintenance.model.oracle.ZhaoBiaoGongGaoTemp import ZhaoBiaoGongGaoTemp
  1070. from BaseDataMaintenance.model.oracle.ZhaoBiaoYuGaoTemp import ZhaoBiaoYuGaoTemp
  1071. from BaseDataMaintenance.model.oracle.ZhongBiaoXinXiTemp import ZhongBiaoXinXiTemp
  1072. from BaseDataMaintenance.model.oracle.ZiShenJieGuoTemp import ZiShenJieGuoTemp
  1073. from BaseDataMaintenance.model.oracle.ChanQuanJiaoYiTemp import ChanQuanJiaoYiTemp
  1074. from BaseDataMaintenance.model.oracle.GongGaoBianGengTemp import GongGaoBianGeng
  1075. from BaseDataMaintenance.model.oracle.KongZhiJiaTemp import KongZhiJiaTemp
  1076. from BaseDataMaintenance.model.oracle.TuDiKuangChanTemp import TuDiKuangChanTemp
  1077. from BaseDataMaintenance.model.oracle.ZhaoBiaoDaYiTemp import ZhaoBiaoDaYiTemp
  1078. from BaseDataMaintenance.model.oracle.ZhaoBiaoWenJianTemp import ZhaoBiaoWenJianTemp
  1079. schedule = BlockingScheduler()
  1080. schedule.add_job(self.temp2mq,"cron",args=(CaiGouYiXiangTemp({}),),second="*/10")
  1081. schedule.add_job(self.temp2mq,"cron",args=(PaiMaiChuRangTemp({}),),second="*/10")
  1082. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoGongGaoTemp({}),),second="*/10")
  1083. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoYuGaoTemp({}),),second="*/10")
  1084. schedule.add_job(self.temp2mq,"cron",args=(ZhongBiaoXinXiTemp({}),),second="*/10")
  1085. schedule.add_job(self.temp2mq,"cron",args=(ZiShenJieGuoTemp({}),),second="*/10")
  1086. schedule.add_job(self.temp2mq,"cron",args=(ChanQuanJiaoYiTemp({}),),second="*/10")
  1087. schedule.add_job(self.temp2mq,"cron",args=(GongGaoBianGeng({}),),second="*/10")
  1088. schedule.add_job(self.temp2mq,"cron",args=(KongZhiJiaTemp({}),),second="*/10")
  1089. schedule.add_job(self.temp2mq,"cron",args=(TuDiKuangChanTemp({}),),second="*/10")
  1090. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoDaYiTemp({}),),second="*/10")
  1091. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoWenJianTemp({}),),second="*/10")
  1092. schedule.add_job(self.ots2mq,"cron",second="*/10")
  1093. schedule.add_job(self.otstmp2mq,"cron",second="*/10")
  1094. schedule.add_job(self.monitor_listener,"cron",minute="*/1")
  1095. schedule.start()
  1096. def transform_attachment():
  1097. from BaseDataMaintenance.model.ots.attachment import attachment
  1098. from BaseDataMaintenance.model.postgres.attachment import Attachment_postgres
  1099. from BaseDataMaintenance.dataSource.source import getConnection_postgres,getConnect_ots
  1100. from threading import Thread
  1101. from queue import Queue
  1102. task_queue = Queue()
  1103. def comsumer(task_queue,pool_postgres):
  1104. while 1:
  1105. _dict = task_queue.get(True)
  1106. try:
  1107. attach = Attachment_postgres(_dict)
  1108. if not attach.exists(pool_postgres):
  1109. attach.insert_row(pool_postgres)
  1110. except Exception as e:
  1111. traceback.print_exc()
  1112. def start_comsumer(task_queue):
  1113. pool_postgres = ConnectorPool(10,30,getConnection_postgres)
  1114. comsumer_count = 30
  1115. list_thread = []
  1116. for i in range(comsumer_count):
  1117. _t = Thread(target=comsumer,args=(task_queue,pool_postgres))
  1118. list_thread.append(_t)
  1119. for _t in list_thread:
  1120. _t.start()
  1121. ots_client = getConnect_ots()
  1122. _thread = Thread(target=start_comsumer,args=(task_queue,))
  1123. _thread.start()
  1124. bool_query = BoolQuery(must_queries=[
  1125. RangeQuery(attachment_crtime,"2022-05-06"),
  1126. BoolQuery(should_queries=[TermQuery(attachment_status,10),
  1127. TermQuery(attachment_status,ATTACHMENT_TOOLARGE)])
  1128. ])
  1129. rows,next_token,total_count,is_all_succeed = ots_client.search("attachment","attachment_index",
  1130. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(attachment_crtime,sort_order=SortOrder.DESC)]),get_total_count=True,limit=100),
  1131. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1132. list_dict = getRow_ots(rows)
  1133. for _dict in list_dict:
  1134. task_queue.put(_dict,True)
  1135. _count = len(list_dict)
  1136. while next_token:
  1137. rows,next_token,total_count,is_all_succeed = ots_client.search("attachment","attachment_index",
  1138. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1139. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1140. list_dict = getRow_ots(rows)
  1141. for _dict in list_dict:
  1142. task_queue.put(_dict,True)
  1143. _count += len(list_dict)
  1144. print("%d/%d,queue:%d"%(_count,total_count,task_queue.qsize()))
  1145. def del_test_doc():
  1146. ots_client = getConnect_ots()
  1147. bool_query = BoolQuery(must_queries=[RangeQuery("docid",range_to=0)])
  1148. list_data = []
  1149. rows,next_token,total_count,is_all_succeed = ots_client.search("document_tmp","document_tmp_index",
  1150. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort("docid")]),get_total_count=True,limit=100),
  1151. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1152. print(total_count)
  1153. list_row = getRow_ots(rows)
  1154. list_data.extend(list_row)
  1155. while next_token:
  1156. rows,next_token,total_count,is_all_succeed = ots_client.search("document_tmp","document_tmp_index",
  1157. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1158. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1159. list_row = getRow_ots(rows)
  1160. list_data.extend(list_row)
  1161. for _row in list_data:
  1162. _doc = Document_tmp(_row)
  1163. _doc.delete_row(ots_client)
  1164. _html = Document_html(_row)
  1165. if _html.exists_row(ots_client):
  1166. _html.delete_row(ots_client)
  1167. def fixDoc_to_queue_extract():
  1168. pool_mq = ConnectorPool(10,20,getConnect_activateMQ)
  1169. try:
  1170. ots_client = getConnect_ots()
  1171. ots_capacity = getConnect_ots_capacity()
  1172. bool_query = BoolQuery(must_queries=[
  1173. RangeQuery("crtime","2022-05-31"),
  1174. TermQuery("docchannel",114)
  1175. ])
  1176. list_data = []
  1177. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1178. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort("docid")]),get_total_count=True,limit=100),
  1179. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1180. print(total_count)
  1181. list_row = getRow_ots(rows)
  1182. list_data.extend(list_row)
  1183. _count = len(list_row)
  1184. while next_token:
  1185. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1186. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1187. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1188. list_row = getRow_ots(rows)
  1189. list_data.extend(list_row)
  1190. _count = len(list_data)
  1191. print("%d/%d"%(_count,total_count))
  1192. task_queue = Queue()
  1193. for _row in list_data:
  1194. if "all_columns" in _row:
  1195. _row.pop("all_columns")
  1196. _html = Document(_row)
  1197. task_queue.put(_html)
  1198. def _handle(item,result_queue):
  1199. _html = item
  1200. _html.fix_columns(ots_capacity,["dochtmlcon"],True)
  1201. print(_html.getProperties().get(document_tmp_docid))
  1202. send_msg_toacmq(pool_mq,json.dumps(_html.getProperties()),"/queue/dataflow_extract")
  1203. mt = MultiThreadHandler(task_queue,_handle,None,30)
  1204. mt.run()
  1205. except Exception as e:
  1206. traceback.print_exc()
  1207. finally:
  1208. pool_mq.destory()
  1209. def check_data_synchronization():
  1210. # filepath = "C:\\Users\\Administrator\\Desktop\\to_check.log"
  1211. # list_uuid = []
  1212. # _regrex = "delete\s+(?P<tablename>[^\s]+)\s+.*ID='(?P<uuid>.+)'"
  1213. # with open(filepath,"r",encoding="utf8") as f:
  1214. # while 1:
  1215. # _line = f.readline()
  1216. # if not _line:
  1217. # break
  1218. # _match = re.search(_regrex,_line)
  1219. # if _match is not None:
  1220. # _uuid = _match.groupdict().get("uuid")
  1221. # tablename = _match.groupdict.get("tablename")
  1222. # if _uuid is not None:
  1223. # list_uuid.append({"uuid":_uuid,"tablename":tablename})
  1224. # print("total_count:",len(list_uuid))
  1225. import pandas as pd
  1226. from BaseDataMaintenance.common.Utils import load
  1227. task_queue = Queue()
  1228. list_data = []
  1229. df_data = load("uuid.pk")
  1230. # df_data = pd.read_excel("check.xlsx")
  1231. for uuid,tablename in zip(df_data["uuid"],df_data["tablename"]):
  1232. _dict = {"uuid":uuid,
  1233. "tablename":tablename}
  1234. list_data.append(_dict)
  1235. task_queue.put(_dict)
  1236. print("qsize:",task_queue.qsize())
  1237. ots_client = getConnect_ots()
  1238. def _handle(_item,result_queue):
  1239. bool_query = BoolQuery(must_queries=[TermQuery("uuid",_item.get("uuid"))])
  1240. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1241. SearchQuery(bool_query,get_total_count=True),
  1242. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1243. _item["exists"] = total_count
  1244. mt = MultiThreadHandler(task_queue,_handle,None,30)
  1245. mt.run()
  1246. df_data = {"uuid":[],
  1247. "tablename":[],
  1248. "exists":[]}
  1249. for _data in list_data:
  1250. if _data["exists"]==0:
  1251. for k,v in df_data.items():
  1252. v.append(_data.get(k))
  1253. import pandas as pd
  1254. df2 = pd.DataFrame(df_data)
  1255. df2.to_excel("check1.xlsx")
  1256. current_path = os.path.abspath(os.path.dirname(__file__))
  1257. def fixDoc_to_queue_init(filename=""):
  1258. import pandas as pd
  1259. from BaseDataMaintenance.model.oracle.GongGaoTemp import dict_oracle2ots
  1260. if filename=="":
  1261. filename = os.path.join(current_path,"check.xlsx")
  1262. df = pd.read_excel(filename)
  1263. dict_oracle2ots.pop("docchannel")
  1264. row_name = ",".join(list(dict_oracle2ots.keys()))
  1265. conn = getConnection_oracle()
  1266. cursor = conn.cursor()
  1267. _count = 0
  1268. for uuid,tablename,_exists,_toolong in zip(df["uuid"],df["tablename"],df["exists"],df["tolong"]):
  1269. if _exists==0 and _toolong==0:
  1270. _count += 1
  1271. _source = str(tablename).replace("_TEMP","")
  1272. sql = " insert into %s(%s) select %s from %s where id='%s' "%(tablename,row_name,row_name,_source,uuid)
  1273. cursor.execute(sql)
  1274. log("%d:%s"%(_count,sql))
  1275. conn.commit()
  1276. if __name__ == '__main__':
  1277. # di = Dataflow_init()
  1278. # di.start_dataflow_init()
  1279. # transform_attachment()
  1280. # del_test_doc()
  1281. # de = Dataflow_ActivteMQ_extract()
  1282. # de.start_flow_extract()
  1283. # fixDoc_to_queue_extract()
  1284. # check_data_synchronization()
  1285. # fixDoc_to_queue_init(filename="C:\\Users\\Administrator\\Desktop\\flow_init_2023-02-07.xlsx")
  1286. current_date = getCurrent_date(format="%Y-%m-%d")
  1287. last_date = timeAdd(current_date,-30,format="%Y-%m-%d")
  1288. sql = " delete from attachment where crtime<='%s 00:00:00' "%(last_date)
  1289. print(sql)