dataflow_mq.py 68 KB

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