dataflow_mq.py 62 KB

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