dataflow_mq.py 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  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. log("docid %s dochtmlcon too long len %d "%(str(item.get("docid")),html_len))
  612. try:
  613. _dochtmlcon = re.sub("<html>|</html>|<body>|</body>", "", _dochtmlcon)
  614. _soup = BeautifulSoup(_dochtmlcon,"lxml")
  615. _soup = article_limit(_soup,200000)
  616. _dochtmlcon = str(_soup)
  617. except Exception as e:
  618. traceback.print_exc()
  619. ackMsg(conn,message_id,subscription)
  620. return
  621. log("docid %s len %d limit to %d"%(str(item.get("docid")),html_len,len(_dochtmlcon)))
  622. dhtml.setValue(document_tmp_dochtmlcon,_dochtmlcon,True)
  623. _extract = Document_extract({})
  624. _extract.setValue(document_extract2_partitionkey,item.get(document_partitionkey))
  625. _extract.setValue(document_extract2_docid,item.get(document_docid))
  626. all_done = 1
  627. data = {}
  628. for k,v in item.items():
  629. data[k] = v
  630. data["timeout"] = 440
  631. data["doc_id"] = data.get(document_tmp_docid,0)
  632. # if data["docid"]<298986054 and data["docid"]>0:
  633. # log("jump docid %s"%(str(data["docid"])))
  634. # ackMsg(conn,message_id,subscription)
  635. # return
  636. data["content"] = data.get(document_tmp_dochtmlcon,"")
  637. if document_tmp_dochtmlcon in data:
  638. data.pop(document_tmp_dochtmlcon)
  639. data["title"] = data.get(document_tmp_doctitle,"")
  640. data["web_source_no"] = item.get(document_tmp_web_source_no,"")
  641. data["web_source_name"] = item.get(document_tmp_web_source_name,"")
  642. data["original_docchannel"] = item.get(document_tmp_original_docchannel,"")
  643. _fingerprint = getFingerprint(str(data["title"])+str(data["content"]))
  644. if all_done>0:
  645. _time = time.time()
  646. # extract_json = self.getExtract_json_fromDB(_fingerprint)
  647. extract_json = self.getExtract_json_fromRedis(_fingerprint)
  648. log("get json from db takes %.4f"%(time.time()-_time))
  649. # extract_json = None
  650. _docid = int(data["doc_id"])
  651. if extract_json is not None:
  652. log("fingerprint %s exists docid:%s"%(_fingerprint,str(_docid)))
  653. _extract.setValue(document_extract2_extract_json,extract_json,True)
  654. else:
  655. resp = self.request_extract_interface(json=data,headers=self.header)
  656. if (resp.status_code >=200 and resp.status_code<=213):
  657. extract_json = resp.content.decode("utf8")
  658. _extract.setValue(document_extract2_extract_json,extract_json,True)
  659. _time = time.time()
  660. # self.putExtract_json_toDB(_fingerprint,_docid,extract_json)
  661. self.putExtract_json_toRedis(_fingerprint,extract_json)
  662. log("get json to db takes %.4f"%(time.time()-_time))
  663. else:
  664. log("%s--%s"%(str(resp.status_code),resp.content.decode("utf8")))
  665. all_done = -2
  666. # if all_done>0:
  667. # resp = self.request_industry_interface(json=data,headers=self.header)
  668. # if (resp.status_code >=200 and resp.status_code<=213):
  669. # _extract.setValue(document_extract2_industry_json,resp.content.decode("utf8"),True)
  670. # else:
  671. # log("%s--%s"%(str(resp.status_code),resp.content.decode("utf8")))
  672. # all_done = -3
  673. # _to_ack = False
  674. # if all_done>0 and len(_extract.getProperties().get(document_extract2_extract_json,""))<=2:
  675. # all_done = -4
  676. _extract.setValue(document_extract2_industry_json,"{}",True)
  677. try:
  678. if all_done!=1:
  679. sentMsgToDD("要素提取失败:docid:%d with result:%d"%(item.get(document_tmp_docid),all_done))
  680. if extract_times>=10:
  681. #process as succeed
  682. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  683. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  684. dtmp.update_row(self.ots_client)
  685. dhtml.update_row(self.ots_client)
  686. #replace as {}
  687. _extract.setValue(document_extract2_extract_json,"{}",True)
  688. _extract.setValue(document_extract2_industry_json,"{}",True)
  689. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  690. _extract.update_row(self.ots_client)
  691. _to_ack = True
  692. elif extract_times>5:
  693. #transform to the extract_failed queue
  694. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract_failed):
  695. #process as succeed
  696. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  697. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  698. dtmp.update_row(self.ots_client)
  699. dhtml.update_row(self.ots_client)
  700. #replace as {}
  701. _extract.setValue(document_extract2_extract_json,"{}",True)
  702. _extract.setValue(document_extract2_industry_json,"{}",True)
  703. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  704. _extract.update_row(self.ots_client)
  705. _to_ack = True
  706. else:
  707. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract)
  708. #失败保存
  709. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  710. dtmp.setValue(document_tmp_status,60,True)
  711. if not dtmp.exists_row(self.ots_client):
  712. dtmp.update_row(self.ots_client)
  713. dhtml.update_row(self.ots_client)
  714. if send_succeed:
  715. _to_ack = True
  716. else:
  717. #process succeed
  718. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  719. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  720. if _docid==290816703:
  721. dtmp.setValue("test_json",extract_json,True)
  722. dtmp.update_row(self.ots_client)
  723. dhtml.update_row(self.ots_client)
  724. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  725. _extract.update_row(self.ots_client)
  726. _to_ack = True
  727. except Exception:
  728. traceback.print_exc()
  729. if _to_ack:
  730. ackMsg(conn,message_id,subscription)
  731. log("process %s docid:%d %s"%(str(_to_ack),data["doc_id"],str(all_done)))
  732. except requests.ConnectionError as e1:
  733. item["extract_times"] -= 1
  734. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  735. ackMsg(conn,message_id,subscription)
  736. except Exception as e:
  737. traceback.print_exc()
  738. sentMsgToDD("要素提取失败:docid:%d with result:%s"%(item.get(document_tmp_docid),str(e)))
  739. log("process %s docid: failed message_id:%s"%(data["doc_id"],message_id))
  740. if extract_times>=10:
  741. #process as succeed
  742. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  743. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  744. dtmp.update_row(self.ots_client)
  745. dhtml.update_row(self.ots_client)
  746. #replace as {}
  747. _extract.setValue(document_extract2_extract_json,"{}",True)
  748. _extract.setValue(document_extract2_industry_json,"{}",True)
  749. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  750. _extract.update_row(self.ots_client)
  751. ackMsg(conn,message_id,subscription)
  752. elif extract_times>5:
  753. #transform to the extract_failed queue
  754. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract_failed):
  755. #process as succeed
  756. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  757. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  758. dtmp.update_row(self.ots_client)
  759. dhtml.update_row(self.ots_client)
  760. #replace as {}
  761. _extract.setValue(document_extract2_extract_json,"{}",True)
  762. _extract.setValue(document_extract2_industry_json,"{}",True)
  763. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  764. _extract.update_row(self.ots_client)
  765. ackMsg(conn,message_id,subscription)
  766. else:
  767. #transform to the extract queue
  768. #失败保存
  769. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  770. dtmp.setValue(document_tmp_status,60,True)
  771. if not dtmp.exists_row(self.ots_client):
  772. dtmp.update_row(self.ots_client)
  773. dhtml.update_row(self.ots_client)
  774. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  775. ackMsg(conn,message_id,subscription)
  776. def delete_document_extract(self,save_count=70*10000):
  777. conn = self.pool_postgres.getConnector()
  778. try:
  779. cursor = conn.cursor()
  780. sql = " select max(docid),min(docid) from document_extract "
  781. cursor.execute(sql)
  782. rows = cursor.fetchall()
  783. if len(rows)>0:
  784. maxdocid,mindocid = rows[0]
  785. d_mindocid = int(maxdocid)-save_count
  786. if mindocid<d_mindocid:
  787. sql = " delete from document_extract where docid<%d"%d_mindocid
  788. cursor.execute(sql)
  789. conn.commit()
  790. except Exception as e:
  791. traceback.print_exc()
  792. finally:
  793. self.pool_postgres.putConnector(conn)
  794. def start_flow_extract(self):
  795. schedule = BlockingScheduler()
  796. schedule.add_job(self.flow_extract_producer,"cron",second="*/20")
  797. schedule.add_job(self.process_extract_failed,"cron",minute="*/5")
  798. schedule.add_job(self.delete_document_extract,"cron",hour="*/5")
  799. schedule.add_job(self.monitor_listener,"cron",minute="*/5")
  800. schedule.start()
  801. from multiprocessing import RLock
  802. docid_lock = RLock()
  803. conn_mysql = None
  804. def generateRangeDocid(nums):
  805. global conn_mysql
  806. while 1:
  807. try:
  808. with docid_lock:
  809. if conn_mysql is None:
  810. conn_mysql = getConnection_mysql()
  811. cursor = conn_mysql.cursor()
  812. sql = "select serial_value from b2c_serial_no where serial_name='DocumentIdSerial'"
  813. cursor.execute(sql)
  814. rows = cursor.fetchall()
  815. current_docid = rows[0][0]
  816. next_docid = current_docid+1
  817. update_docid = current_docid+nums
  818. sql = " update b2c_serial_no set serial_value=%d where serial_name='DocumentIdSerial'"%(update_docid)
  819. cursor.execute(sql)
  820. conn_mysql.commit()
  821. return next_docid
  822. except Exception as e:
  823. conn_mysql = getConnection_mysql()
  824. # 自定义jsonEncoder
  825. class MyEncoder(json.JSONEncoder):
  826. def default(self, obj):
  827. if isinstance(obj, np.ndarray):
  828. return obj.tolist()
  829. elif isinstance(obj, bytes):
  830. return str(obj, encoding='utf-8')
  831. elif isinstance(obj, (np.float_, np.float16, np.float32,
  832. np.float64,Decimal)):
  833. return float(obj)
  834. elif isinstance(obj,str):
  835. return obj
  836. return json.JSONEncoder.default(self, obj)
  837. class Dataflow_init(Dataflow):
  838. class InitListener():
  839. def __init__(self,conn,*args,**kwargs):
  840. self.conn = conn
  841. self.get_count = 1000
  842. self.count = self.get_count
  843. self.begin_docid = None
  844. self.mq_attachment = "/queue/dataflow_attachment"
  845. self.mq_extract = "/queue/dataflow_extract"
  846. self.pool_mq1 = ConnectorPool(1,4,getConnect_activateMQ)
  847. def on_error(self, headers):
  848. log('received an error %s' % headers.body)
  849. def getRangeDocid(self):
  850. begin_docid = generateRangeDocid(self.get_count)
  851. self.begin_docid = begin_docid
  852. self.count = 0
  853. def getNextDocid(self):
  854. if self.count>=self.get_count:
  855. self.getRangeDocid()
  856. next_docid = self.begin_docid+self.count
  857. self.count += 1
  858. return next_docid
  859. def on_message(self, headers):
  860. next_docid = int(self.getNextDocid())
  861. partitionkey = int(next_docid%500+1)
  862. message_id = headers.headers["message-id"]
  863. body = json.loads(headers.body)
  864. body[document_tmp_partitionkey] = partitionkey
  865. body[document_tmp_docid] = next_docid
  866. if body.get(document_original_docchannel) is None:
  867. body[document_original_docchannel] = body.get(document_docchannel)
  868. page_attachments = body.get(document_tmp_attachment_path,"[]")
  869. _uuid = body.get(document_tmp_uuid,"")
  870. if page_attachments!="[]":
  871. status = random.randint(1,10)
  872. body[document_tmp_status] = status
  873. if send_msg_toacmq(self.pool_mq1,json.dumps(body,cls=MyEncoder),self.mq_attachment):
  874. log("uuid:%s with docid:%s"%(str(_uuid),str(next_docid)))
  875. ackMsg(self.conn,message_id)
  876. else:
  877. log("send_msg_error on init listener")
  878. else:
  879. status = random.randint(11,50)
  880. body[document_tmp_status] = status
  881. if send_msg_toacmq(self.pool_mq1,json.dumps(body,cls=MyEncoder),self.mq_extract):
  882. log("uuid:%s with docid:%s"%(str(_uuid),str(next_docid)))
  883. ackMsg(self.conn,message_id)
  884. else:
  885. log("send_msg_error on init listener")
  886. def __del__(self):
  887. self.conn.disconnect()
  888. del self.pool_mq1
  889. def __init__(self):
  890. Dataflow.__init__(self)
  891. self.mq_init = "/queue/dataflow_init"
  892. self.mq_attachment = "/queue/dataflow_attachment"
  893. self.mq_extract = "/queue/dataflow_extract"
  894. self.pool_oracle = ConnectorPool(10,15,getConnection_oracle)
  895. self.pool_mq = ConnectorPool(10,30,getConnect_activateMQ)
  896. self.ots_capacity = getConnect_ots_capacity()
  897. self.init_comsumer_counts = 2
  898. self.list_init_comsumer = []
  899. for i in range(self.init_comsumer_counts):
  900. listener = self.InitListener(getConnect_activateMQ())
  901. createComsumer(listener,self.mq_init)
  902. self.list_init_comsumer.append(listener)
  903. def monitor_listener(self):
  904. for i in range(len(self.list_init_comsumer)):
  905. if self.list_init_comsumer[i].conn.is_connected():
  906. continue
  907. else:
  908. listener = self.InitListener(getConnect_activateMQ())
  909. createComsumer(listener,self.mq_init)
  910. self.list_init_comsumer[i] = listener
  911. def temp2mq(self,object):
  912. conn_oracle = self.pool_oracle.getConnector()
  913. try:
  914. list_obj = object.select_rows(conn_oracle,type(object),object.table_name,[],limit=1000)
  915. for _obj in list_obj:
  916. ots_dict = _obj.getProperties_ots()
  917. if len(ots_dict.get("dochtmlcon",""))>500000:
  918. _obj.delete_row(conn_oracle)
  919. log("msg too long:%s,%d"%(ots_dict.get("uuid"),len(ots_dict.get("dochtmlcon",""))))
  920. continue
  921. if send_msg_toacmq(self.pool_mq,json.dumps(ots_dict,cls=MyEncoder),self.mq_init):
  922. #删除数据,上线放开
  923. _obj.delete_row(conn_oracle)
  924. else:
  925. log("send_msg_error111:%s,%d"%(ots_dict.get("uuid"),len(ots_dict.get("dochtmlcon",""))))
  926. self.pool_oracle.putConnector(conn_oracle)
  927. except Exception as e:
  928. traceback.print_exc()
  929. self.pool_oracle.decrease()
  930. def ots2mq(self):
  931. try:
  932. bool_query = BoolQuery(must_queries=[RangeQuery("status",1,51)])
  933. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document","document_index",
  934. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(document_docid)]),get_total_count=True,limit=100),
  935. ColumnsToGet(return_type=ColumnReturnType.ALL))
  936. list_data = getRow_ots(rows)
  937. for _data in list_data:
  938. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  939. document_tmp_docid:_data.get(document_tmp_docid),
  940. document_tmp_status:0}
  941. _document = Document(_d)
  942. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  943. _document_html = Document(_data)
  944. _document_html.fix_columns(self.ots_capacity,[document_tmp_dochtmlcon],True)
  945. if page_attachments!="[]":
  946. status = random.randint(1,10)
  947. _data[document_tmp_status] = status
  948. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  949. else:
  950. status = random.randint(11,50)
  951. _data[document_tmp_status] = status
  952. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  953. if send_succeed:
  954. _document.update_row(self.ots_client)
  955. else:
  956. log("send_msg_error2222")
  957. while next_token:
  958. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document","document_index",
  959. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  960. ColumnsToGet(return_type=ColumnReturnType.ALL))
  961. list_data = getRow_ots(rows)
  962. for _data in list_data:
  963. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  964. document_tmp_docid:_data.get(document_tmp_docid),
  965. document_tmp_status:0}
  966. _document = Document(_d)
  967. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  968. _document_html = Document(_data)
  969. _document_html.fix_columns(self.ots_capacity,[document_tmp_dochtmlcon],True)
  970. if page_attachments!="[]":
  971. status = random.randint(1,10)
  972. _data[document_tmp_status] = status
  973. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  974. else:
  975. status = random.randint(11,50)
  976. _data[document_tmp_status] = status
  977. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  978. if send_succeed:
  979. _document.update_row(self.ots_client)
  980. else:
  981. log("send_msg_error2222")
  982. except Exception as e:
  983. traceback.print_exc()
  984. def otstmp2mq(self):
  985. try:
  986. bool_query = BoolQuery(must_queries=[TermQuery("status",0)])
  987. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document_tmp","document_tmp_index",
  988. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(document_docid)]),get_total_count=True,limit=100),
  989. ColumnsToGet(return_type=ColumnReturnType.ALL))
  990. list_data = getRow_ots(rows)
  991. for _data in list_data:
  992. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  993. document_tmp_docid:_data.get(document_tmp_docid),
  994. document_tmp_status:0}
  995. _document = Document_tmp(_d)
  996. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  997. _document_html = Document_html(_data)
  998. _document_html.fix_columns(self.ots_client,[document_tmp_dochtmlcon],True)
  999. if page_attachments!="[]":
  1000. status = random.randint(1,10)
  1001. _data[document_tmp_status] = status
  1002. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  1003. else:
  1004. status = random.randint(11,50)
  1005. _data[document_tmp_status] = status
  1006. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  1007. if send_succeed:
  1008. _document.setValue(document_tmp_status,1,True)
  1009. _document.update_row(self.ots_client)
  1010. else:
  1011. log("send_msg_error2222")
  1012. while next_token:
  1013. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document_tmp","document_tmp_index",
  1014. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1015. ColumnsToGet(return_type=ColumnReturnType.ALL))
  1016. list_data = getRow_ots(rows)
  1017. for _data in list_data:
  1018. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  1019. document_tmp_docid:_data.get(document_tmp_docid),
  1020. document_tmp_status:0}
  1021. _document = Document_tmp(_d)
  1022. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  1023. _document_html = Document_html(_data)
  1024. _document_html.fix_columns(self.ots_client,[document_tmp_dochtmlcon],True)
  1025. if page_attachments!="[]":
  1026. status = random.randint(1,10)
  1027. _data[document_tmp_status] = status
  1028. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  1029. else:
  1030. status = random.randint(11,50)
  1031. _data[document_tmp_status] = status
  1032. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  1033. if send_succeed:
  1034. _document.setValue(document_tmp_status,1,True)
  1035. _document.update_row(self.ots_client)
  1036. else:
  1037. log("send_msg_error2222")
  1038. except Exception as e:
  1039. traceback.print_exc()
  1040. def test_dump_docid(self):
  1041. class TestDumpListener(ActiveMQListener):
  1042. def on_message(self, headers):
  1043. message_id = headers.headers["message-id"]
  1044. body = headers.body
  1045. self._queue.put(headers,True)
  1046. ackMsg(self.conn,message_id)
  1047. _queue = Queue()
  1048. listener1 = TestDumpListener(getConnect_activateMQ(),_queue)
  1049. listener2 = TestDumpListener(getConnect_activateMQ(),_queue)
  1050. createComsumer(listener1,"/queue/dataflow_attachment")
  1051. createComsumer(listener2,"/queue/dataflow_extract")
  1052. time.sleep(10)
  1053. list_item = []
  1054. list_docid = []
  1055. while 1:
  1056. try:
  1057. _item = _queue.get(timeout=2)
  1058. list_item.append(_item)
  1059. except Exception as e:
  1060. break
  1061. for item in list_item:
  1062. _item = json.loads(item.body)
  1063. list_docid.append(_item.get("docid"))
  1064. log(list_docid[:10])
  1065. log("len docid:%d set len:%d"%(len(list_docid),len(set(list_docid))))
  1066. def start_dataflow_init(self):
  1067. # self.test_dump_docid()
  1068. from BaseDataMaintenance.model.oracle.CaiGouYiXiangTemp import CaiGouYiXiangTemp
  1069. from BaseDataMaintenance.model.oracle.PaiMaiChuRangTemp import PaiMaiChuRangTemp
  1070. from BaseDataMaintenance.model.oracle.ZhaoBiaoGongGaoTemp import ZhaoBiaoGongGaoTemp
  1071. from BaseDataMaintenance.model.oracle.ZhaoBiaoYuGaoTemp import ZhaoBiaoYuGaoTemp
  1072. from BaseDataMaintenance.model.oracle.ZhongBiaoXinXiTemp import ZhongBiaoXinXiTemp
  1073. from BaseDataMaintenance.model.oracle.ZiShenJieGuoTemp import ZiShenJieGuoTemp
  1074. from BaseDataMaintenance.model.oracle.ChanQuanJiaoYiTemp import ChanQuanJiaoYiTemp
  1075. from BaseDataMaintenance.model.oracle.GongGaoBianGengTemp import GongGaoBianGeng
  1076. from BaseDataMaintenance.model.oracle.KongZhiJiaTemp import KongZhiJiaTemp
  1077. from BaseDataMaintenance.model.oracle.TuDiKuangChanTemp import TuDiKuangChanTemp
  1078. from BaseDataMaintenance.model.oracle.ZhaoBiaoDaYiTemp import ZhaoBiaoDaYiTemp
  1079. from BaseDataMaintenance.model.oracle.ZhaoBiaoWenJianTemp import ZhaoBiaoWenJianTemp
  1080. schedule = BlockingScheduler()
  1081. schedule.add_job(self.temp2mq,"cron",args=(CaiGouYiXiangTemp({}),),second="*/10")
  1082. schedule.add_job(self.temp2mq,"cron",args=(PaiMaiChuRangTemp({}),),second="*/10")
  1083. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoGongGaoTemp({}),),second="*/10")
  1084. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoYuGaoTemp({}),),second="*/10")
  1085. schedule.add_job(self.temp2mq,"cron",args=(ZhongBiaoXinXiTemp({}),),second="*/10")
  1086. schedule.add_job(self.temp2mq,"cron",args=(ZiShenJieGuoTemp({}),),second="*/10")
  1087. schedule.add_job(self.temp2mq,"cron",args=(ChanQuanJiaoYiTemp({}),),second="*/10")
  1088. schedule.add_job(self.temp2mq,"cron",args=(GongGaoBianGeng({}),),second="*/10")
  1089. schedule.add_job(self.temp2mq,"cron",args=(KongZhiJiaTemp({}),),second="*/10")
  1090. schedule.add_job(self.temp2mq,"cron",args=(TuDiKuangChanTemp({}),),second="*/10")
  1091. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoDaYiTemp({}),),second="*/10")
  1092. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoWenJianTemp({}),),second="*/10")
  1093. schedule.add_job(self.ots2mq,"cron",second="*/10")
  1094. schedule.add_job(self.otstmp2mq,"cron",second="*/10")
  1095. schedule.add_job(self.monitor_listener,"cron",minute="*/1")
  1096. schedule.start()
  1097. def transform_attachment():
  1098. from BaseDataMaintenance.model.ots.attachment import attachment
  1099. from BaseDataMaintenance.model.postgres.attachment import Attachment_postgres
  1100. from BaseDataMaintenance.dataSource.source import getConnection_postgres,getConnect_ots
  1101. from threading import Thread
  1102. from queue import Queue
  1103. task_queue = Queue()
  1104. def comsumer(task_queue,pool_postgres):
  1105. while 1:
  1106. _dict = task_queue.get(True)
  1107. try:
  1108. attach = Attachment_postgres(_dict)
  1109. if not attach.exists(pool_postgres):
  1110. attach.insert_row(pool_postgres)
  1111. except Exception as e:
  1112. traceback.print_exc()
  1113. def start_comsumer(task_queue):
  1114. pool_postgres = ConnectorPool(10,30,getConnection_postgres)
  1115. comsumer_count = 30
  1116. list_thread = []
  1117. for i in range(comsumer_count):
  1118. _t = Thread(target=comsumer,args=(task_queue,pool_postgres))
  1119. list_thread.append(_t)
  1120. for _t in list_thread:
  1121. _t.start()
  1122. ots_client = getConnect_ots()
  1123. _thread = Thread(target=start_comsumer,args=(task_queue,))
  1124. _thread.start()
  1125. bool_query = BoolQuery(must_queries=[
  1126. RangeQuery(attachment_crtime,"2022-05-06"),
  1127. BoolQuery(should_queries=[TermQuery(attachment_status,10),
  1128. TermQuery(attachment_status,ATTACHMENT_TOOLARGE)])
  1129. ])
  1130. rows,next_token,total_count,is_all_succeed = ots_client.search("attachment","attachment_index",
  1131. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(attachment_crtime,sort_order=SortOrder.DESC)]),get_total_count=True,limit=100),
  1132. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1133. list_dict = getRow_ots(rows)
  1134. for _dict in list_dict:
  1135. task_queue.put(_dict,True)
  1136. _count = len(list_dict)
  1137. while next_token:
  1138. rows,next_token,total_count,is_all_succeed = ots_client.search("attachment","attachment_index",
  1139. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1140. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1141. list_dict = getRow_ots(rows)
  1142. for _dict in list_dict:
  1143. task_queue.put(_dict,True)
  1144. _count += len(list_dict)
  1145. print("%d/%d,queue:%d"%(_count,total_count,task_queue.qsize()))
  1146. def del_test_doc():
  1147. ots_client = getConnect_ots()
  1148. bool_query = BoolQuery(must_queries=[RangeQuery("docid",range_to=0)])
  1149. list_data = []
  1150. rows,next_token,total_count,is_all_succeed = ots_client.search("document_tmp","document_tmp_index",
  1151. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort("docid")]),get_total_count=True,limit=100),
  1152. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1153. print(total_count)
  1154. list_row = getRow_ots(rows)
  1155. list_data.extend(list_row)
  1156. while next_token:
  1157. rows,next_token,total_count,is_all_succeed = ots_client.search("document_tmp","document_tmp_index",
  1158. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1159. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1160. list_row = getRow_ots(rows)
  1161. list_data.extend(list_row)
  1162. for _row in list_data:
  1163. _doc = Document_tmp(_row)
  1164. _doc.delete_row(ots_client)
  1165. _html = Document_html(_row)
  1166. if _html.exists_row(ots_client):
  1167. _html.delete_row(ots_client)
  1168. def fixDoc_to_queue_extract():
  1169. pool_mq = ConnectorPool(10,20,getConnect_activateMQ)
  1170. try:
  1171. ots_client = getConnect_ots()
  1172. ots_capacity = getConnect_ots_capacity()
  1173. bool_query = BoolQuery(must_queries=[
  1174. RangeQuery("crtime","2022-05-31"),
  1175. TermQuery("docchannel",114)
  1176. ])
  1177. list_data = []
  1178. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1179. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort("docid")]),get_total_count=True,limit=100),
  1180. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1181. print(total_count)
  1182. list_row = getRow_ots(rows)
  1183. list_data.extend(list_row)
  1184. _count = len(list_row)
  1185. while next_token:
  1186. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1187. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1188. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1189. list_row = getRow_ots(rows)
  1190. list_data.extend(list_row)
  1191. _count = len(list_data)
  1192. print("%d/%d"%(_count,total_count))
  1193. task_queue = Queue()
  1194. for _row in list_data:
  1195. if "all_columns" in _row:
  1196. _row.pop("all_columns")
  1197. _html = Document(_row)
  1198. task_queue.put(_html)
  1199. def _handle(item,result_queue):
  1200. _html = item
  1201. _html.fix_columns(ots_capacity,["dochtmlcon"],True)
  1202. print(_html.getProperties().get(document_tmp_docid))
  1203. send_msg_toacmq(pool_mq,json.dumps(_html.getProperties()),"/queue/dataflow_extract")
  1204. mt = MultiThreadHandler(task_queue,_handle,None,30)
  1205. mt.run()
  1206. except Exception as e:
  1207. traceback.print_exc()
  1208. finally:
  1209. pool_mq.destory()
  1210. def check_data_synchronization():
  1211. # filepath = "C:\\Users\\Administrator\\Desktop\\to_check.log"
  1212. # list_uuid = []
  1213. # _regrex = "delete\s+(?P<tablename>[^\s]+)\s+.*ID='(?P<uuid>.+)'"
  1214. # with open(filepath,"r",encoding="utf8") as f:
  1215. # while 1:
  1216. # _line = f.readline()
  1217. # if not _line:
  1218. # break
  1219. # _match = re.search(_regrex,_line)
  1220. # if _match is not None:
  1221. # _uuid = _match.groupdict().get("uuid")
  1222. # tablename = _match.groupdict.get("tablename")
  1223. # if _uuid is not None:
  1224. # list_uuid.append({"uuid":_uuid,"tablename":tablename})
  1225. # print("total_count:",len(list_uuid))
  1226. import pandas as pd
  1227. from BaseDataMaintenance.common.Utils import load
  1228. task_queue = Queue()
  1229. list_data = []
  1230. df_data = load("uuid.pk")
  1231. # df_data = pd.read_excel("check.xlsx")
  1232. for uuid,tablename in zip(df_data["uuid"],df_data["tablename"]):
  1233. _dict = {"uuid":uuid,
  1234. "tablename":tablename}
  1235. list_data.append(_dict)
  1236. task_queue.put(_dict)
  1237. print("qsize:",task_queue.qsize())
  1238. ots_client = getConnect_ots()
  1239. def _handle(_item,result_queue):
  1240. bool_query = BoolQuery(must_queries=[TermQuery("uuid",_item.get("uuid"))])
  1241. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1242. SearchQuery(bool_query,get_total_count=True),
  1243. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1244. _item["exists"] = total_count
  1245. mt = MultiThreadHandler(task_queue,_handle,None,30)
  1246. mt.run()
  1247. df_data = {"uuid":[],
  1248. "tablename":[],
  1249. "exists":[]}
  1250. for _data in list_data:
  1251. if _data["exists"]==0:
  1252. for k,v in df_data.items():
  1253. v.append(_data.get(k))
  1254. import pandas as pd
  1255. df2 = pd.DataFrame(df_data)
  1256. df2.to_excel("check1.xlsx")
  1257. current_path = os.path.abspath(os.path.dirname(__file__))
  1258. def fixDoc_to_queue_init(filename=""):
  1259. import pandas as pd
  1260. from BaseDataMaintenance.model.oracle.GongGaoTemp import dict_oracle2ots
  1261. if filename=="":
  1262. filename = os.path.join(current_path,"check.xlsx")
  1263. df = pd.read_excel(filename)
  1264. dict_oracle2ots.pop("docchannel")
  1265. row_name = ",".join(list(dict_oracle2ots.keys()))
  1266. conn = getConnection_oracle()
  1267. cursor = conn.cursor()
  1268. _count = 0
  1269. for uuid,tablename,_exists,_toolong in zip(df["uuid"],df["tablename"],df["exists"],df["tolong"]):
  1270. if _exists==0 and _toolong==0:
  1271. _count += 1
  1272. _source = str(tablename).replace("_TEMP","")
  1273. sql = " insert into %s(%s) select %s from %s where id='%s' "%(tablename,row_name,row_name,_source,uuid)
  1274. cursor.execute(sql)
  1275. log("%d:%s"%(_count,sql))
  1276. conn.commit()
  1277. if __name__ == '__main__':
  1278. # di = Dataflow_init()
  1279. # di.start_dataflow_init()
  1280. # transform_attachment()
  1281. # del_test_doc()
  1282. # de = Dataflow_ActivteMQ_extract()
  1283. # de.start_flow_extract()
  1284. # fixDoc_to_queue_extract()
  1285. # check_data_synchronization()
  1286. # fixDoc_to_queue_init(filename="C:\\Users\\Administrator\\Desktop\\flow_init_2023-02-07.xlsx")
  1287. current_date = getCurrent_date(format="%Y-%m-%d")
  1288. last_date = timeAdd(current_date,-30,format="%Y-%m-%d")
  1289. sql = " delete from attachment where crtime<='%s 00:00:00' "%(last_date)
  1290. print(sql)