dataflow_mq.py 69 KB

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