dataflow_mq.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542
  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:].replace("//","/")
  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))
  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))
  225. else:
  226. log("md5:%s path:%s download file from ots failed=="%(filemd5,objectPath))
  227. else:
  228. log("md5:%s path:%s not found in ots"%(filemd5,objectPath))
  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. log("getAttachments search in ots:%s"%(_filemd5))
  357. _attach = {attachment_filemd5:_filemd5}
  358. _attach_ots = attachment(_attach)
  359. if _attach_ots.fix_columns(self.ots_client,[attachment_status,attachment_path,attachment_attachmenthtml,attachment_attachmentcon,attachment_filetype,attachment_swfUrls,attachment_process_time],True):
  360. if _attach_ots.getProperties().get(attachment_status) is not None:
  361. log("getAttachments find in ots:%s"%(_filemd5))
  362. list_attachment.append(Attachment_postgres(_attach_ots.getProperties()))
  363. else:
  364. if _path[0]=="/":
  365. _path = _path[1:]
  366. _filetype = _path.split(".")[-1]
  367. _attach = {attachment_filemd5:_filemd5,
  368. attachment_filetype:_filetype,
  369. attachment_status:20,
  370. attachment_path:"%s/%s"%(_filemd5[:4],_path),
  371. attachment_crtime:getCurrent_date(format="%Y-%m-%d %H:%M:%S")}
  372. list_attachment.append(Attachment_postgres(_attach))
  373. return list_attachment
  374. except Exception as e:
  375. log("attachProcess comsumer error %s"%str(e))
  376. log(str(to_find_md5))
  377. traceback.print_exc()
  378. return []
  379. finally:
  380. self.attach_pool.putConnector(conn)
  381. def flow_attachment_producer(self,columns=[document_tmp_attachment_path,document_tmp_crtime]):
  382. q_size = self.queue_attachment.qsize()
  383. qsize_ocr = self.queue_attachment_ocr.qsize()
  384. qsize_not_ocr = self.queue_attachment_not_ocr.qsize()
  385. log("queue_attachment:%d,queue_attachment_ocr:%d,queue_attachment_not_ocr:%d"%(q_size,qsize_ocr,qsize_not_ocr))
  386. def flow_attachment_producer_comsumer(self):
  387. log("start flow_attachment comsumer")
  388. mt = MultiThreadHandler(self.queue_attachment,self.comsumer_handle,None,10,1,restart=True)
  389. mt.run()
  390. def set_queue(self,_dict):
  391. list_attach = _dict.get("list_attach")
  392. to_ocr = False
  393. for attach in list_attach:
  394. if attach.getProperties().get(attachment_filetype) in ["bmp","jpeg","jpg","png","swf","pdf","tif"]:
  395. to_ocr = True
  396. break
  397. if to_ocr:
  398. self.queue_attachment_ocr.put(_dict,True)
  399. else:
  400. self.queue_attachment_not_ocr.put(_dict,True)
  401. def comsumer_handle(self,_dict,result_queue):
  402. try:
  403. frame = _dict["frame"]
  404. conn = _dict["conn"]
  405. message_id = frame.headers["message-id"]
  406. item = json.loads(frame.body)
  407. page_attachments = json.loads(item.get(document_tmp_attachment_path,"[]"))
  408. _dochtmlcon = item.get(document_tmp_dochtmlcon,"")
  409. if len(page_attachments)==0:
  410. self.set_queue({"item":item,"list_attach":[],"message_id":message_id,"conn":conn})
  411. else:
  412. list_fileMd5 = []
  413. for _atta in page_attachments:
  414. list_fileMd5.append(_atta.get(document_tmp_attachment_path_filemd5))
  415. list_attach = self.getAttachments(list_fileMd5,_dochtmlcon)
  416. self.set_queue({"item":item,"list_attach":list_attach,"message_id":message_id,"conn":conn})
  417. except Exception as e:
  418. traceback.print_exc()
  419. def remove_attachment_postgres(self):
  420. current_date = getCurrent_date(format="%Y-%m-%d")
  421. last_date = timeAdd(current_date,-2,format="%Y-%m-%d")
  422. sql = " delete from attachment where crtime<='%s 00:00:00' "%(last_date)
  423. conn = getConnection_postgres()
  424. cursor = conn.cursor()
  425. cursor.execute(sql)
  426. conn.commit()
  427. conn.close()
  428. def start_flow_attachment(self):
  429. schedule = BlockingScheduler()
  430. schedule.add_job(self.flow_attachment_process,"cron",second="*/20")
  431. schedule.add_job(self.flow_attachment,"cron",second="*/10")
  432. schedule.add_job(self.monitor_attachment_process,"cron",second="*/10")
  433. schedule.add_job(self.remove_attachment_postgres,"cron",hour="6")
  434. schedule.add_job(self.process_failed_attachment,"cron",minute="*/10")
  435. schedule.add_job(self.monitor_listener,"cron",minute="*/1")
  436. schedule.start()
  437. class Dataflow_ActivteMQ_extract(Dataflow_extract):
  438. class ExtractListener():
  439. def __init__(self,conn,_func,*args,**kwargs):
  440. self.conn = conn
  441. self._func = _func
  442. def on_message(self, headers):
  443. try:
  444. log("get message")
  445. message_id = headers.headers["message-id"]
  446. body = headers.body
  447. log("get message %s crtime:%s"%(message_id,json.loads(body).get("crtime","")))
  448. self._func(_dict={"frame":headers,"conn":self.conn},result_queue=None)
  449. except Exception as e:
  450. traceback.print_exc()
  451. pass
  452. def on_error(self, headers):
  453. log('received an error %s' % str(headers.body))
  454. def __del__(self):
  455. self.conn.disconnect()
  456. def __init__(self):
  457. Dataflow_extract.__init__(self)
  458. self.industy_url = "http://127.0.0.1:15000/industry_extract"
  459. self.extract_interfaces = [["http://127.0.0.1:15030/content_extract",20],
  460. ["http://192.168.0.115:15030/content_extract",10]
  461. ]
  462. self.mq_extract = "/queue/dataflow_extract"
  463. self.mq_extract_failed = "/queue/dataflow_extract_failed"
  464. self.whole_weight = 0
  465. for _url,weight in self.extract_interfaces:
  466. self.whole_weight+= weight
  467. current_weight = 0
  468. for _i in range(len(self.extract_interfaces)):
  469. current_weight += self.extract_interfaces[_i][1]
  470. self.extract_interfaces[_i][1] = current_weight/self.whole_weight
  471. self.comsumer_count = 40
  472. self.pool_postgres = ConnectorPool(10,self.comsumer_count,getConnection_postgres)
  473. self.pool_redis_doc = ConnectorPool(10,self.comsumer_count,getConnect_redis_doc)
  474. self.conn_mq = getConnect_activateMQ()
  475. self.pool_mq = ConnectorPool(10,30,getConnect_activateMQ)
  476. self.block_url = RLock()
  477. self.url_count = 0
  478. self.list_extract_comsumer = []
  479. for _i in range(self.comsumer_count):
  480. listener_extract = self.ExtractListener(getConnect_activateMQ(),self.comsumer_handle)
  481. createComsumer(listener_extract,self.mq_extract)
  482. self.list_extract_comsumer.append(listener_extract)
  483. def monitor_listener(self):
  484. for i in range(len(self.list_extract_comsumer)):
  485. if self.list_extract_comsumer[i].conn.is_connected():
  486. continue
  487. else:
  488. listener = self.ExtractListener(getConnect_activateMQ(),self.comsumer_handle)
  489. createComsumer(listener,self.mq_extract)
  490. self.list_extract_comsumer[i] = listener
  491. def getExtract_url(self):
  492. _url_num = 0
  493. with self.block_url:
  494. self.url_count += 1
  495. self.url_count %= self.whole_weight
  496. _url_num = self.url_count
  497. # _r = random.random()
  498. _r = _url_num/self.whole_weight
  499. for _i in range(len(self.extract_interfaces)):
  500. if _r<=self.extract_interfaces[_i][1]:
  501. return self.extract_interfaces[_i][0]
  502. def request_extract_interface(self,json,headers):
  503. # _i = random.randint(0,len(self.extract_interfaces)-1)
  504. # _i = 0
  505. # _url = self.extract_interfaces[_i]
  506. _url = self.getExtract_url()
  507. log("extract_url:%s"%(str(_url)))
  508. resp = requests.post(_url,json=json,headers=headers,timeout=10*60)
  509. return resp
  510. def request_industry_interface(self,json,headers):
  511. resp = requests.post(self.industy_url,json=json,headers=headers)
  512. return resp
  513. 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]):
  514. q_size = self.queue_extract.qsize()
  515. log("queue extract size:%d"%(q_size))
  516. def process_extract_failed(self):
  517. def _handle(_dict,result_queue):
  518. frame = _dict.get("frame")
  519. message_id = frame.headers["message-id"]
  520. subscription = frame.headers.setdefault('subscription', None)
  521. conn = _dict.get("conn")
  522. body = frame.body
  523. if body is not None:
  524. item = json.loads(body)
  525. item["extract_times"] = 10
  526. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  527. ackMsg(conn,message_id,subscription)
  528. from BaseDataMaintenance.java.MQInfo import getQueueSize
  529. extract_failed_size = getQueueSize("dataflow_extract_failed")
  530. extract_size = getQueueSize("dataflow_extract")
  531. log("extract_failed_size %s extract_size %s"%(str(extract_failed_size),str(extract_size)))
  532. if extract_failed_size>0 and extract_size<100:
  533. failed_listener = self.ExtractListener(getConnect_activateMQ(),_handle)
  534. createComsumer(failed_listener,self.mq_extract_failed)
  535. while 1:
  536. extract_failed_size = getQueueSize("dataflow_extract_failed")
  537. if extract_failed_size==0:
  538. break
  539. time.sleep(10)
  540. failed_listener.conn.disconnect()
  541. def flow_extract(self,):
  542. self.comsumer()
  543. def comsumer(self):
  544. mt = MultiThreadHandler(self.queue_extract,self.comsumer_handle,None,20,1,True)
  545. mt.run()
  546. def getExtract_json_fromDB(self,_fingerprint):
  547. conn = self.pool_postgres.getConnector()
  548. try:
  549. list_extract = Document_extract_postgres.select_rows(conn,Document_extract_postgres,"document_extract",[" fingerprint='%s'"%_fingerprint])
  550. if len(list_extract)>0:
  551. _extract = list_extract[0]
  552. return _extract.getProperties().get(document_extract_extract_json)
  553. except Exception as e:
  554. traceback.print_exc()
  555. finally:
  556. self.pool_postgres.putConnector(conn)
  557. return None
  558. def putExtract_json_toDB(self,fingerprint,docid,extract_json):
  559. _de = Document_extract_postgres({document_extract_fingerprint:fingerprint,
  560. document_extract_docid:docid,
  561. document_extract_extract_json:extract_json})
  562. _de.insert_row(self.pool_postgres,1)
  563. def getExtract_json_fromRedis(self,_fingerprint):
  564. db = self.pool_redis_doc.getConnector()
  565. try:
  566. _extract_json = db.get(_fingerprint)
  567. return _extract_json
  568. except Exception as e:
  569. log("getExtract_json_fromRedis error %s"%(str(e)))
  570. finally:
  571. try:
  572. if db.connection.check_health():
  573. self.pool_redis_doc.putConnector(db)
  574. except Exception as e:
  575. pass
  576. return None
  577. def putExtract_json_toRedis(self,fingerprint,extract_json):
  578. db = self.pool_redis_doc.getConnector()
  579. try:
  580. _extract_json = db.set(str(fingerprint),extract_json)
  581. db.expire(fingerprint,3600*2)
  582. return _extract_json
  583. except Exception as e:
  584. log("putExtract_json_toRedis error%s"%(str(e)))
  585. traceback.print_exc()
  586. finally:
  587. try:
  588. if db.connection.check_health():
  589. self.pool_redis_doc.putConnector(db)
  590. except Exception as e:
  591. pass
  592. def comsumer_handle(self,_dict,result_queue):
  593. try:
  594. log("start handle")
  595. frame = _dict["frame"]
  596. conn = _dict["conn"]
  597. message_id = frame.headers["message-id"]
  598. subscription = frame.headers.setdefault('subscription', None)
  599. item = json.loads(frame.body)
  600. dtmp = Document_tmp(item)
  601. dhtml = Document_html({"partitionkey":item.get("partitionkey"),
  602. "docid":item.get("docid")})
  603. extract_times = item.get("extract_times",0)+1
  604. item["extract_times"] = extract_times
  605. _dochtmlcon = item.get(document_tmp_dochtmlcon,"")
  606. html_len = len(_dochtmlcon)
  607. if html_len>50000:
  608. if int(item.get("docid"))==329546490:
  609. save(item,"329546490.pk")
  610. log("docid %s dochtmlcon too long len %d "%(str(item.get("docid")),html_len))
  611. try:
  612. _dochtmlcon = re.sub("<html>|</html>|<body>|</body>", "", _dochtmlcon)
  613. _soup = BeautifulSoup(_dochtmlcon,"lxml")
  614. if len(_dochtmlcon)>200000:
  615. _find = _soup.find("div",attrs={"class":"richTextFetch"})
  616. if _find is not None:
  617. _find.decompose()
  618. else:
  619. _soup = article_limit(_soup,50000)
  620. _dochtmlcon = str(_soup)
  621. except Exception as e:
  622. traceback.print_exc()
  623. ackMsg(conn,message_id,subscription)
  624. return
  625. log("docid %s len %d limit to %d"%(str(item.get("docid")),html_len,len(_dochtmlcon)))
  626. dhtml.setValue(document_tmp_dochtmlcon,_dochtmlcon,True)
  627. _extract = Document_extract({})
  628. _extract.setValue(document_extract2_partitionkey,item.get(document_partitionkey))
  629. _extract.setValue(document_extract2_docid,item.get(document_docid))
  630. all_done = 1
  631. data = {}
  632. for k,v in item.items():
  633. data[k] = v
  634. data["timeout"] = 440
  635. data["doc_id"] = data.get(document_tmp_docid,0)
  636. # if data["docid"]<298986054 and data["docid"]>0:
  637. # log("jump docid %s"%(str(data["docid"])))
  638. # ackMsg(conn,message_id,subscription)
  639. # return
  640. data["content"] = data.get(document_tmp_dochtmlcon,"")
  641. if document_tmp_dochtmlcon in data:
  642. data.pop(document_tmp_dochtmlcon)
  643. data["title"] = data.get(document_tmp_doctitle,"")
  644. data["web_source_no"] = item.get(document_tmp_web_source_no,"")
  645. data["web_source_name"] = item.get(document_tmp_web_source_name,"")
  646. data["original_docchannel"] = item.get(document_tmp_original_docchannel,"")
  647. _fingerprint = getFingerprint(str(data["title"])+str(data["content"]))
  648. if all_done>0:
  649. _time = time.time()
  650. # extract_json = self.getExtract_json_fromDB(_fingerprint)
  651. extract_json = self.getExtract_json_fromRedis(_fingerprint)
  652. log("get json from db takes %.4f"%(time.time()-_time))
  653. # extract_json = None
  654. _docid = int(data["doc_id"])
  655. if extract_json is not None:
  656. log("fingerprint %s exists docid:%s"%(_fingerprint,str(_docid)))
  657. _extract.setValue(document_extract2_extract_json,extract_json,True)
  658. else:
  659. resp = self.request_extract_interface(json=data,headers=self.header)
  660. if (resp.status_code >=200 and resp.status_code<=213):
  661. extract_json = resp.content.decode("utf8")
  662. _extract.setValue(document_extract2_extract_json,extract_json,True)
  663. _time = time.time()
  664. # self.putExtract_json_toDB(_fingerprint,_docid,extract_json)
  665. self.putExtract_json_toRedis(_fingerprint,extract_json)
  666. log("get json to db takes %.4f"%(time.time()-_time))
  667. else:
  668. log("%s--%s"%(str(resp.status_code),resp.content.decode("utf8")))
  669. all_done = -2
  670. # if all_done>0:
  671. # resp = self.request_industry_interface(json=data,headers=self.header)
  672. # if (resp.status_code >=200 and resp.status_code<=213):
  673. # _extract.setValue(document_extract2_industry_json,resp.content.decode("utf8"),True)
  674. # else:
  675. # log("%s--%s"%(str(resp.status_code),resp.content.decode("utf8")))
  676. # all_done = -3
  677. # _to_ack = False
  678. # if all_done>0 and len(_extract.getProperties().get(document_extract2_extract_json,""))<=2:
  679. # all_done = -4
  680. _extract.setValue(document_extract2_industry_json,"{}",True)
  681. try:
  682. if all_done!=1:
  683. sentMsgToDD("要素提取失败:docid:%d with result:%d"%(item.get(document_tmp_docid),all_done))
  684. if extract_times>=10:
  685. #process as succeed
  686. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  687. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  688. dtmp.update_row(self.ots_client)
  689. dhtml.update_row(self.ots_client)
  690. #replace as {}
  691. _extract.setValue(document_extract2_extract_json,"{}",True)
  692. _extract.setValue(document_extract2_industry_json,"{}",True)
  693. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  694. _extract.update_row(self.ots_client)
  695. _to_ack = True
  696. elif extract_times>5:
  697. #transform to the extract_failed queue
  698. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract_failed):
  699. #process as succeed
  700. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  701. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  702. dtmp.update_row(self.ots_client)
  703. dhtml.update_row(self.ots_client)
  704. #replace as {}
  705. _extract.setValue(document_extract2_extract_json,"{}",True)
  706. _extract.setValue(document_extract2_industry_json,"{}",True)
  707. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  708. _extract.update_row(self.ots_client)
  709. _to_ack = True
  710. else:
  711. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract)
  712. #失败保存
  713. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  714. dtmp.setValue(document_tmp_status,60,True)
  715. if not dtmp.exists_row(self.ots_client):
  716. dtmp.update_row(self.ots_client)
  717. dhtml.update_row(self.ots_client)
  718. if send_succeed:
  719. _to_ack = True
  720. else:
  721. #process succeed
  722. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  723. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  724. if _docid==290816703:
  725. dtmp.setValue("test_json",extract_json,True)
  726. dtmp.update_row(self.ots_client)
  727. dhtml.update_row(self.ots_client)
  728. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  729. _extract.update_row(self.ots_client)
  730. _to_ack = True
  731. except Exception:
  732. traceback.print_exc()
  733. if _to_ack:
  734. ackMsg(conn,message_id,subscription)
  735. log("process %s docid:%d %s"%(str(_to_ack),data["doc_id"],str(all_done)))
  736. except requests.ConnectionError as e1:
  737. item["extract_times"] -= 1
  738. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  739. ackMsg(conn,message_id,subscription)
  740. except Exception as e:
  741. traceback.print_exc()
  742. sentMsgToDD("要素提取失败:docid:%d with result:%s"%(item.get(document_tmp_docid),str(e)))
  743. log("process %s docid: failed message_id:%s"%(data["doc_id"],message_id))
  744. if extract_times>=10:
  745. #process as succeed
  746. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  747. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  748. dtmp.update_row(self.ots_client)
  749. dhtml.update_row(self.ots_client)
  750. #replace as {}
  751. _extract.setValue(document_extract2_extract_json,"{}",True)
  752. _extract.setValue(document_extract2_industry_json,"{}",True)
  753. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  754. _extract.update_row(self.ots_client)
  755. ackMsg(conn,message_id,subscription)
  756. elif extract_times>5:
  757. #transform to the extract_failed queue
  758. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract_failed):
  759. #process as succeed
  760. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  761. dtmp.setValue(document_tmp_status,random.randint(*flow_extract_status_succeed_to),True)
  762. dtmp.update_row(self.ots_client)
  763. dhtml.update_row(self.ots_client)
  764. #replace as {}
  765. _extract.setValue(document_extract2_extract_json,"{}",True)
  766. _extract.setValue(document_extract2_industry_json,"{}",True)
  767. _extract.setValue(document_extract2_status,random.randint(1,50),True)
  768. _extract.update_row(self.ots_client)
  769. ackMsg(conn,message_id,subscription)
  770. else:
  771. #transform to the extract queue
  772. #失败保存
  773. dtmp.setValue(document_tmp_dochtmlcon,"",False)
  774. dtmp.setValue(document_tmp_status,60,True)
  775. if not dtmp.exists_row(self.ots_client):
  776. dtmp.update_row(self.ots_client)
  777. dhtml.update_row(self.ots_client)
  778. if send_msg_toacmq(self.pool_mq,json.dumps(item,ensure_ascii=False),self.mq_extract):
  779. ackMsg(conn,message_id,subscription)
  780. def delete_document_extract(self,save_count=70*10000):
  781. conn = self.pool_postgres.getConnector()
  782. try:
  783. cursor = conn.cursor()
  784. sql = " select max(docid),min(docid) from document_extract "
  785. cursor.execute(sql)
  786. rows = cursor.fetchall()
  787. if len(rows)>0:
  788. maxdocid,mindocid = rows[0]
  789. d_mindocid = int(maxdocid)-save_count
  790. if mindocid<d_mindocid:
  791. sql = " delete from document_extract where docid<%d"%d_mindocid
  792. cursor.execute(sql)
  793. conn.commit()
  794. except Exception as e:
  795. traceback.print_exc()
  796. finally:
  797. self.pool_postgres.putConnector(conn)
  798. def start_flow_extract(self):
  799. schedule = BlockingScheduler()
  800. schedule.add_job(self.flow_extract_producer,"cron",second="*/20")
  801. schedule.add_job(self.process_extract_failed,"cron",minute="*/5")
  802. schedule.add_job(self.delete_document_extract,"cron",hour="*/5")
  803. schedule.add_job(self.monitor_listener,"cron",minute="*/5")
  804. schedule.start()
  805. from multiprocessing import RLock
  806. docid_lock = RLock()
  807. conn_mysql = None
  808. def generateRangeDocid(nums):
  809. global conn_mysql
  810. while 1:
  811. try:
  812. with docid_lock:
  813. if conn_mysql is None:
  814. conn_mysql = getConnection_mysql()
  815. cursor = conn_mysql.cursor()
  816. sql = "select serial_value from b2c_serial_no where serial_name='DocumentIdSerial'"
  817. cursor.execute(sql)
  818. rows = cursor.fetchall()
  819. current_docid = rows[0][0]
  820. next_docid = current_docid+1
  821. update_docid = current_docid+nums
  822. sql = " update b2c_serial_no set serial_value=%d where serial_name='DocumentIdSerial'"%(update_docid)
  823. cursor.execute(sql)
  824. conn_mysql.commit()
  825. return next_docid
  826. except Exception as e:
  827. conn_mysql = getConnection_mysql()
  828. # 自定义jsonEncoder
  829. class MyEncoder(json.JSONEncoder):
  830. def default(self, obj):
  831. if isinstance(obj, np.ndarray):
  832. return obj.tolist()
  833. elif isinstance(obj, bytes):
  834. return str(obj, encoding='utf-8')
  835. elif isinstance(obj, (np.float_, np.float16, np.float32,
  836. np.float64,Decimal)):
  837. return float(obj)
  838. elif isinstance(obj,str):
  839. return obj
  840. return json.JSONEncoder.default(self, obj)
  841. class Dataflow_init(Dataflow):
  842. class InitListener():
  843. def __init__(self,conn,*args,**kwargs):
  844. self.conn = conn
  845. self.get_count = 1000
  846. self.count = self.get_count
  847. self.begin_docid = None
  848. self.mq_attachment = "/queue/dataflow_attachment"
  849. self.mq_extract = "/queue/dataflow_extract"
  850. self.pool_mq1 = ConnectorPool(1,4,getConnect_activateMQ)
  851. def on_error(self, headers):
  852. log('received an error %s' % headers.body)
  853. def getRangeDocid(self):
  854. begin_docid = generateRangeDocid(self.get_count)
  855. self.begin_docid = begin_docid
  856. self.count = 0
  857. def getNextDocid(self):
  858. if self.count>=self.get_count:
  859. self.getRangeDocid()
  860. next_docid = self.begin_docid+self.count
  861. self.count += 1
  862. return next_docid
  863. def on_message(self, headers):
  864. next_docid = int(self.getNextDocid())
  865. partitionkey = int(next_docid%500+1)
  866. message_id = headers.headers["message-id"]
  867. body = json.loads(headers.body)
  868. body[document_tmp_partitionkey] = partitionkey
  869. body[document_tmp_docid] = next_docid
  870. if body.get(document_original_docchannel) is None:
  871. body[document_original_docchannel] = body.get(document_docchannel)
  872. page_attachments = body.get(document_tmp_attachment_path,"[]")
  873. _uuid = body.get(document_tmp_uuid,"")
  874. if page_attachments!="[]":
  875. status = random.randint(1,10)
  876. body[document_tmp_status] = status
  877. if send_msg_toacmq(self.pool_mq1,json.dumps(body,cls=MyEncoder),self.mq_attachment):
  878. log("uuid:%s with docid:%s"%(str(_uuid),str(next_docid)))
  879. ackMsg(self.conn,message_id)
  880. else:
  881. log("send_msg_error on init listener")
  882. else:
  883. status = random.randint(11,50)
  884. body[document_tmp_status] = status
  885. if send_msg_toacmq(self.pool_mq1,json.dumps(body,cls=MyEncoder),self.mq_extract):
  886. log("uuid:%s with docid:%s"%(str(_uuid),str(next_docid)))
  887. ackMsg(self.conn,message_id)
  888. else:
  889. log("send_msg_error on init listener")
  890. def __del__(self):
  891. self.conn.disconnect()
  892. del self.pool_mq1
  893. def __init__(self):
  894. Dataflow.__init__(self)
  895. self.mq_init = "/queue/dataflow_init"
  896. self.mq_attachment = "/queue/dataflow_attachment"
  897. self.mq_extract = "/queue/dataflow_extract"
  898. self.pool_oracle = ConnectorPool(10,15,getConnection_oracle)
  899. self.pool_mq = ConnectorPool(10,30,getConnect_activateMQ)
  900. self.ots_capacity = getConnect_ots_capacity()
  901. self.init_comsumer_counts = 2
  902. self.list_init_comsumer = []
  903. for i in range(self.init_comsumer_counts):
  904. listener = self.InitListener(getConnect_activateMQ())
  905. createComsumer(listener,self.mq_init)
  906. self.list_init_comsumer.append(listener)
  907. def monitor_listener(self):
  908. for i in range(len(self.list_init_comsumer)):
  909. if self.list_init_comsumer[i].conn.is_connected():
  910. continue
  911. else:
  912. listener = self.InitListener(getConnect_activateMQ())
  913. createComsumer(listener,self.mq_init)
  914. self.list_init_comsumer[i] = listener
  915. def temp2mq(self,object):
  916. conn_oracle = self.pool_oracle.getConnector()
  917. try:
  918. list_obj = object.select_rows(conn_oracle,type(object),object.table_name,[],limit=1000)
  919. for _obj in list_obj:
  920. ots_dict = _obj.getProperties_ots()
  921. if len(ots_dict.get("dochtmlcon",""))>500000:
  922. _obj.delete_row(conn_oracle)
  923. log("msg too long:%s,%d"%(ots_dict.get("uuid"),len(ots_dict.get("dochtmlcon",""))))
  924. continue
  925. if send_msg_toacmq(self.pool_mq,json.dumps(ots_dict,cls=MyEncoder),self.mq_init):
  926. #删除数据,上线放开
  927. _obj.delete_row(conn_oracle)
  928. else:
  929. log("send_msg_error111:%s,%d"%(ots_dict.get("uuid"),len(ots_dict.get("dochtmlcon",""))))
  930. self.pool_oracle.putConnector(conn_oracle)
  931. except Exception as e:
  932. traceback.print_exc()
  933. self.pool_oracle.decrease()
  934. def ots2mq(self):
  935. try:
  936. bool_query = BoolQuery(must_queries=[RangeQuery("status",1,51)])
  937. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document","document_index",
  938. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(document_docid)]),get_total_count=True,limit=100),
  939. ColumnsToGet(return_type=ColumnReturnType.ALL))
  940. list_data = getRow_ots(rows)
  941. for _data in list_data:
  942. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  943. document_tmp_docid:_data.get(document_tmp_docid),
  944. document_tmp_status:0}
  945. _document = Document(_d)
  946. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  947. _document_html = Document(_data)
  948. _document_html.fix_columns(self.ots_capacity,[document_tmp_dochtmlcon],True)
  949. if page_attachments!="[]":
  950. status = random.randint(1,10)
  951. _data[document_tmp_status] = status
  952. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  953. else:
  954. status = random.randint(11,50)
  955. _data[document_tmp_status] = status
  956. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  957. if send_succeed:
  958. _document.update_row(self.ots_client)
  959. else:
  960. log("send_msg_error2222")
  961. while next_token:
  962. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document","document_index",
  963. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  964. ColumnsToGet(return_type=ColumnReturnType.ALL))
  965. list_data = getRow_ots(rows)
  966. for _data in list_data:
  967. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  968. document_tmp_docid:_data.get(document_tmp_docid),
  969. document_tmp_status:0}
  970. _document = Document(_d)
  971. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  972. _document_html = Document(_data)
  973. _document_html.fix_columns(self.ots_capacity,[document_tmp_dochtmlcon],True)
  974. if page_attachments!="[]":
  975. status = random.randint(1,10)
  976. _data[document_tmp_status] = status
  977. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  978. else:
  979. status = random.randint(11,50)
  980. _data[document_tmp_status] = status
  981. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  982. if send_succeed:
  983. _document.update_row(self.ots_client)
  984. else:
  985. log("send_msg_error2222")
  986. except Exception as e:
  987. traceback.print_exc()
  988. def otstmp2mq(self):
  989. try:
  990. bool_query = BoolQuery(must_queries=[TermQuery("status",0)])
  991. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document_tmp","document_tmp_index",
  992. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(document_docid)]),get_total_count=True,limit=100),
  993. ColumnsToGet(return_type=ColumnReturnType.ALL))
  994. list_data = getRow_ots(rows)
  995. for _data in list_data:
  996. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  997. document_tmp_docid:_data.get(document_tmp_docid),
  998. document_tmp_status:0}
  999. _document = Document_tmp(_d)
  1000. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  1001. _document_html = Document_html(_data)
  1002. _document_html.fix_columns(self.ots_client,[document_tmp_dochtmlcon],True)
  1003. if page_attachments!="[]":
  1004. status = random.randint(1,10)
  1005. _data[document_tmp_status] = status
  1006. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  1007. else:
  1008. status = random.randint(11,50)
  1009. _data[document_tmp_status] = status
  1010. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  1011. if send_succeed:
  1012. _document.setValue(document_tmp_status,1,True)
  1013. _document.update_row(self.ots_client)
  1014. else:
  1015. log("send_msg_error2222")
  1016. while next_token:
  1017. rows,next_token,total_count,is_all_succeed = self.ots_client.search("document_tmp","document_tmp_index",
  1018. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1019. ColumnsToGet(return_type=ColumnReturnType.ALL))
  1020. list_data = getRow_ots(rows)
  1021. for _data in list_data:
  1022. _d = {document_tmp_partitionkey:_data.get(document_tmp_partitionkey),
  1023. document_tmp_docid:_data.get(document_tmp_docid),
  1024. document_tmp_status:0}
  1025. _document = Document_tmp(_d)
  1026. page_attachments = _data.get(document_tmp_attachment_path,"[]")
  1027. _document_html = Document_html(_data)
  1028. _document_html.fix_columns(self.ots_client,[document_tmp_dochtmlcon],True)
  1029. if page_attachments!="[]":
  1030. status = random.randint(1,10)
  1031. _data[document_tmp_status] = status
  1032. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_attachment)
  1033. else:
  1034. status = random.randint(11,50)
  1035. _data[document_tmp_status] = status
  1036. send_succeed = send_msg_toacmq(self.pool_mq,json.dumps(_document_html.getProperties(),cls=MyEncoder),self.mq_extract)
  1037. if send_succeed:
  1038. _document.setValue(document_tmp_status,1,True)
  1039. _document.update_row(self.ots_client)
  1040. else:
  1041. log("send_msg_error2222")
  1042. except Exception as e:
  1043. traceback.print_exc()
  1044. def test_dump_docid(self):
  1045. class TestDumpListener(ActiveMQListener):
  1046. def on_message(self, headers):
  1047. message_id = headers.headers["message-id"]
  1048. body = headers.body
  1049. self._queue.put(headers,True)
  1050. ackMsg(self.conn,message_id)
  1051. _queue = Queue()
  1052. listener1 = TestDumpListener(getConnect_activateMQ(),_queue)
  1053. listener2 = TestDumpListener(getConnect_activateMQ(),_queue)
  1054. createComsumer(listener1,"/queue/dataflow_attachment")
  1055. createComsumer(listener2,"/queue/dataflow_extract")
  1056. time.sleep(10)
  1057. list_item = []
  1058. list_docid = []
  1059. while 1:
  1060. try:
  1061. _item = _queue.get(timeout=2)
  1062. list_item.append(_item)
  1063. except Exception as e:
  1064. break
  1065. for item in list_item:
  1066. _item = json.loads(item.body)
  1067. list_docid.append(_item.get("docid"))
  1068. log(list_docid[:10])
  1069. log("len docid:%d set len:%d"%(len(list_docid),len(set(list_docid))))
  1070. def start_dataflow_init(self):
  1071. # self.test_dump_docid()
  1072. from BaseDataMaintenance.model.oracle.CaiGouYiXiangTemp import CaiGouYiXiangTemp
  1073. from BaseDataMaintenance.model.oracle.PaiMaiChuRangTemp import PaiMaiChuRangTemp
  1074. from BaseDataMaintenance.model.oracle.ZhaoBiaoGongGaoTemp import ZhaoBiaoGongGaoTemp
  1075. from BaseDataMaintenance.model.oracle.ZhaoBiaoYuGaoTemp import ZhaoBiaoYuGaoTemp
  1076. from BaseDataMaintenance.model.oracle.ZhongBiaoXinXiTemp import ZhongBiaoXinXiTemp
  1077. from BaseDataMaintenance.model.oracle.ZiShenJieGuoTemp import ZiShenJieGuoTemp
  1078. from BaseDataMaintenance.model.oracle.ChanQuanJiaoYiTemp import ChanQuanJiaoYiTemp
  1079. from BaseDataMaintenance.model.oracle.GongGaoBianGengTemp import GongGaoBianGeng
  1080. from BaseDataMaintenance.model.oracle.KongZhiJiaTemp import KongZhiJiaTemp
  1081. from BaseDataMaintenance.model.oracle.TuDiKuangChanTemp import TuDiKuangChanTemp
  1082. from BaseDataMaintenance.model.oracle.ZhaoBiaoDaYiTemp import ZhaoBiaoDaYiTemp
  1083. from BaseDataMaintenance.model.oracle.ZhaoBiaoWenJianTemp import ZhaoBiaoWenJianTemp
  1084. schedule = BlockingScheduler()
  1085. schedule.add_job(self.temp2mq,"cron",args=(CaiGouYiXiangTemp({}),),second="*/10")
  1086. schedule.add_job(self.temp2mq,"cron",args=(PaiMaiChuRangTemp({}),),second="*/10")
  1087. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoGongGaoTemp({}),),second="*/10")
  1088. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoYuGaoTemp({}),),second="*/10")
  1089. schedule.add_job(self.temp2mq,"cron",args=(ZhongBiaoXinXiTemp({}),),second="*/10")
  1090. schedule.add_job(self.temp2mq,"cron",args=(ZiShenJieGuoTemp({}),),second="*/10")
  1091. schedule.add_job(self.temp2mq,"cron",args=(ChanQuanJiaoYiTemp({}),),second="*/10")
  1092. schedule.add_job(self.temp2mq,"cron",args=(GongGaoBianGeng({}),),second="*/10")
  1093. schedule.add_job(self.temp2mq,"cron",args=(KongZhiJiaTemp({}),),second="*/10")
  1094. schedule.add_job(self.temp2mq,"cron",args=(TuDiKuangChanTemp({}),),second="*/10")
  1095. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoDaYiTemp({}),),second="*/10")
  1096. schedule.add_job(self.temp2mq,"cron",args=(ZhaoBiaoWenJianTemp({}),),second="*/10")
  1097. schedule.add_job(self.ots2mq,"cron",second="*/10")
  1098. schedule.add_job(self.otstmp2mq,"cron",second="*/10")
  1099. schedule.add_job(self.monitor_listener,"cron",minute="*/1")
  1100. schedule.start()
  1101. def transform_attachment():
  1102. from BaseDataMaintenance.model.ots.attachment import attachment
  1103. from BaseDataMaintenance.model.postgres.attachment import Attachment_postgres
  1104. from BaseDataMaintenance.dataSource.source import getConnection_postgres,getConnect_ots
  1105. from threading import Thread
  1106. from queue import Queue
  1107. task_queue = Queue()
  1108. def comsumer(task_queue,pool_postgres):
  1109. while 1:
  1110. _dict = task_queue.get(True)
  1111. try:
  1112. attach = Attachment_postgres(_dict)
  1113. if not attach.exists(pool_postgres):
  1114. attach.insert_row(pool_postgres)
  1115. except Exception as e:
  1116. traceback.print_exc()
  1117. def start_comsumer(task_queue):
  1118. pool_postgres = ConnectorPool(10,30,getConnection_postgres)
  1119. comsumer_count = 30
  1120. list_thread = []
  1121. for i in range(comsumer_count):
  1122. _t = Thread(target=comsumer,args=(task_queue,pool_postgres))
  1123. list_thread.append(_t)
  1124. for _t in list_thread:
  1125. _t.start()
  1126. ots_client = getConnect_ots()
  1127. _thread = Thread(target=start_comsumer,args=(task_queue,))
  1128. _thread.start()
  1129. bool_query = BoolQuery(must_queries=[
  1130. RangeQuery(attachment_crtime,"2022-05-06"),
  1131. BoolQuery(should_queries=[TermQuery(attachment_status,10),
  1132. TermQuery(attachment_status,ATTACHMENT_TOOLARGE)])
  1133. ])
  1134. rows,next_token,total_count,is_all_succeed = ots_client.search("attachment","attachment_index",
  1135. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort(attachment_crtime,sort_order=SortOrder.DESC)]),get_total_count=True,limit=100),
  1136. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1137. list_dict = getRow_ots(rows)
  1138. for _dict in list_dict:
  1139. task_queue.put(_dict,True)
  1140. _count = len(list_dict)
  1141. while next_token:
  1142. rows,next_token,total_count,is_all_succeed = ots_client.search("attachment","attachment_index",
  1143. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1144. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1145. list_dict = getRow_ots(rows)
  1146. for _dict in list_dict:
  1147. task_queue.put(_dict,True)
  1148. _count += len(list_dict)
  1149. print("%d/%d,queue:%d"%(_count,total_count,task_queue.qsize()))
  1150. def del_test_doc():
  1151. ots_client = getConnect_ots()
  1152. bool_query = BoolQuery(must_queries=[RangeQuery("docid",range_to=0)])
  1153. list_data = []
  1154. rows,next_token,total_count,is_all_succeed = ots_client.search("document_tmp","document_tmp_index",
  1155. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort("docid")]),get_total_count=True,limit=100),
  1156. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1157. print(total_count)
  1158. list_row = getRow_ots(rows)
  1159. list_data.extend(list_row)
  1160. while next_token:
  1161. rows,next_token,total_count,is_all_succeed = ots_client.search("document_tmp","document_tmp_index",
  1162. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1163. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1164. list_row = getRow_ots(rows)
  1165. list_data.extend(list_row)
  1166. for _row in list_data:
  1167. _doc = Document_tmp(_row)
  1168. _doc.delete_row(ots_client)
  1169. _html = Document_html(_row)
  1170. if _html.exists_row(ots_client):
  1171. _html.delete_row(ots_client)
  1172. def fixDoc_to_queue_extract():
  1173. pool_mq = ConnectorPool(10,20,getConnect_activateMQ)
  1174. try:
  1175. ots_client = getConnect_ots()
  1176. ots_capacity = getConnect_ots_capacity()
  1177. bool_query = BoolQuery(must_queries=[
  1178. RangeQuery("crtime","2022-05-31"),
  1179. TermQuery("docchannel",114)
  1180. ])
  1181. list_data = []
  1182. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1183. SearchQuery(bool_query,sort=Sort(sorters=[FieldSort("docid")]),get_total_count=True,limit=100),
  1184. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1185. print(total_count)
  1186. list_row = getRow_ots(rows)
  1187. list_data.extend(list_row)
  1188. _count = len(list_row)
  1189. while next_token:
  1190. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1191. SearchQuery(bool_query,next_token=next_token,get_total_count=True,limit=100),
  1192. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.ALL))
  1193. list_row = getRow_ots(rows)
  1194. list_data.extend(list_row)
  1195. _count = len(list_data)
  1196. print("%d/%d"%(_count,total_count))
  1197. task_queue = Queue()
  1198. for _row in list_data:
  1199. if "all_columns" in _row:
  1200. _row.pop("all_columns")
  1201. _html = Document(_row)
  1202. task_queue.put(_html)
  1203. def _handle(item,result_queue):
  1204. _html = item
  1205. _html.fix_columns(ots_capacity,["dochtmlcon"],True)
  1206. print(_html.getProperties().get(document_tmp_docid))
  1207. send_msg_toacmq(pool_mq,json.dumps(_html.getProperties()),"/queue/dataflow_extract")
  1208. mt = MultiThreadHandler(task_queue,_handle,None,30)
  1209. mt.run()
  1210. except Exception as e:
  1211. traceback.print_exc()
  1212. finally:
  1213. pool_mq.destory()
  1214. def check_data_synchronization():
  1215. # filepath = "C:\\Users\\Administrator\\Desktop\\to_check.log"
  1216. # list_uuid = []
  1217. # _regrex = "delete\s+(?P<tablename>[^\s]+)\s+.*ID='(?P<uuid>.+)'"
  1218. # with open(filepath,"r",encoding="utf8") as f:
  1219. # while 1:
  1220. # _line = f.readline()
  1221. # if not _line:
  1222. # break
  1223. # _match = re.search(_regrex,_line)
  1224. # if _match is not None:
  1225. # _uuid = _match.groupdict().get("uuid")
  1226. # tablename = _match.groupdict.get("tablename")
  1227. # if _uuid is not None:
  1228. # list_uuid.append({"uuid":_uuid,"tablename":tablename})
  1229. # print("total_count:",len(list_uuid))
  1230. import pandas as pd
  1231. from BaseDataMaintenance.common.Utils import load
  1232. task_queue = Queue()
  1233. list_data = []
  1234. df_data = load("uuid.pk")
  1235. # df_data = pd.read_excel("check.xlsx")
  1236. for uuid,tablename in zip(df_data["uuid"],df_data["tablename"]):
  1237. _dict = {"uuid":uuid,
  1238. "tablename":tablename}
  1239. list_data.append(_dict)
  1240. task_queue.put(_dict)
  1241. print("qsize:",task_queue.qsize())
  1242. ots_client = getConnect_ots()
  1243. def _handle(_item,result_queue):
  1244. bool_query = BoolQuery(must_queries=[TermQuery("uuid",_item.get("uuid"))])
  1245. rows,next_token,total_count,is_all_succeed = ots_client.search("document","document_index",
  1246. SearchQuery(bool_query,get_total_count=True),
  1247. columns_to_get=ColumnsToGet(return_type=ColumnReturnType.NONE))
  1248. _item["exists"] = total_count
  1249. mt = MultiThreadHandler(task_queue,_handle,None,30)
  1250. mt.run()
  1251. df_data = {"uuid":[],
  1252. "tablename":[],
  1253. "exists":[]}
  1254. for _data in list_data:
  1255. if _data["exists"]==0:
  1256. for k,v in df_data.items():
  1257. v.append(_data.get(k))
  1258. import pandas as pd
  1259. df2 = pd.DataFrame(df_data)
  1260. df2.to_excel("check1.xlsx")
  1261. current_path = os.path.abspath(os.path.dirname(__file__))
  1262. def fixDoc_to_queue_init(filename=""):
  1263. import pandas as pd
  1264. from BaseDataMaintenance.model.oracle.GongGaoTemp import dict_oracle2ots
  1265. if filename=="":
  1266. filename = os.path.join(current_path,"check.xlsx")
  1267. df = pd.read_excel(filename)
  1268. if "docchannel" in dict_oracle2ots:
  1269. dict_oracle2ots.pop("docchannel")
  1270. row_name = ",".join(list(dict_oracle2ots.keys()))
  1271. conn = getConnection_oracle()
  1272. cursor = conn.cursor()
  1273. _count = 0
  1274. for uuid,tablename,_exists,_toolong in zip(df["uuid"],df["tablename"],df["exists"],df["tolong"]):
  1275. if _exists==0 and _toolong==0:
  1276. _count += 1
  1277. _source = str(tablename).replace("_TEMP","")
  1278. sql = " insert into %s(%s) select %s from %s where id='%s' "%(tablename,row_name,row_name,_source,uuid)
  1279. cursor.execute(sql)
  1280. log("%d:%s"%(_count,sql))
  1281. conn.commit()
  1282. conn.close()
  1283. if __name__ == '__main__':
  1284. # di = Dataflow_init()
  1285. # di.start_dataflow_init()
  1286. # transform_attachment()
  1287. # del_test_doc()
  1288. # de = Dataflow_ActivteMQ_extract()
  1289. # de.start_flow_extract()
  1290. # fixDoc_to_queue_extract()
  1291. # check_data_synchronization()
  1292. # fixDoc_to_queue_init(filename="C:\\Users\\Administrator\\Desktop\\flow_init_2023-02-07.xlsx")
  1293. current_date = getCurrent_date(format="%Y-%m-%d")
  1294. last_date = timeAdd(current_date,-30,format="%Y-%m-%d")
  1295. sql = " delete from attachment where crtime<='%s 00:00:00' "%(last_date)
  1296. print(sql)