dataflow_mq.py 69 KB

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