main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. package main
  2. import (
  3. "encoding/json"
  4. "esindex/config"
  5. "esindex/oss"
  6. "fmt"
  7. "github.com/robfig/cron"
  8. "go.uber.org/zap"
  9. "io/ioutil"
  10. util "jygit.jydev.jianyu360.cn/data_processing/common_utils"
  11. "jygit.jydev.jianyu360.cn/data_processing/common_utils/elastic"
  12. "jygit.jydev.jianyu360.cn/data_processing/common_utils/log"
  13. "jygit.jydev.jianyu360.cn/data_processing/common_utils/mongodb"
  14. "jygit.jydev.jianyu360.cn/data_processing/common_utils/mysqldb"
  15. "jygit.jydev.jianyu360.cn/data_processing/common_utils/udp"
  16. "net"
  17. "net/http"
  18. "sync"
  19. "time"
  20. )
  21. var (
  22. MgoB *mongodb.MongodbSim
  23. MgoP *mongodb.MongodbSim
  24. MgoQ *mongodb.MongodbSim
  25. MgoS *mongodb.MongodbSim
  26. Mysql *mysqldb.Mysql
  27. Es, Es2 *elastic.Elastic
  28. PreEs = make(map[string]*elastic.Elastic, 0) //预处理 索引客户端
  29. UdpClient udp.UdpClient
  30. UdpTaskMap = &sync.Map{}
  31. JyUdpAddr *net.UDPAddr
  32. NeUdpAddr *net.UDPAddr
  33. EsBulkSize = 50 // es批量保存大小
  34. updateBiddingPool = make(chan map[string]interface{}, 5000) //更新bingding数据
  35. updateBiddingSp = make(chan bool, 5)
  36. saveEsPool = make(chan map[string]interface{}, 5000) //保存binding数据到es
  37. saveEsSp = make(chan bool, 5)
  38. saveProjectEsPool = make(chan map[string]interface{}, 5000) //保存project数据到es
  39. saveProjectSp = make(chan bool, 5)
  40. saveEsAllPool = make(chan map[string]interface{}, 5000) //存储单机版es,爬虫采集判重使用
  41. saveEsAllSp = make(chan bool, 5)
  42. saveErrBidPool = make(chan map[string]interface{}, 5000)
  43. saveBidSp = make(chan bool, 5)
  44. //detailLength = 50000 // es保存detail长度
  45. fileLength = 200000 // es保存附件文本长度,大于20万 时做一个日志记录
  46. //pscopeLength = 32766 // projectscope长度
  47. specialNames = make(map[string]bool, 0) //存储181 凭安提供的特企,爬虫采购单位
  48. responselock sync.Mutex
  49. BiddingLastNodeResponse int64 //上次节点接受数据时间
  50. ProjectLastNodeResponse int64 //上次节点接受数据时间
  51. )
  52. func init() {
  53. config.InitConf("./common.toml")
  54. InitLog()
  55. InitMysql()
  56. InitMgo()
  57. InitEs()
  58. InitField()
  59. //if config.Conf.Env.OpenPre {
  60. // InitPreProcessField()
  61. // InitPreEsClient()
  62. //}
  63. InitEsBiddingField()
  64. oss.InitOss()
  65. verifyESFields() //检测es 字段类型
  66. JyUdpAddr = &net.UDPAddr{
  67. IP: net.ParseIP(config.Conf.Udp.JyAddr),
  68. Port: util.IntAll(config.Conf.Udp.JyPort),
  69. }
  70. if config.Conf.Udp.NeAddr != "" {
  71. NeUdpAddr = &net.UDPAddr{
  72. IP: net.ParseIP(config.Conf.Udp.NeAddr),
  73. Port: util.IntAll(config.Conf.Udp.NePort),
  74. }
  75. }
  76. BiddingLastNodeResponse = time.Now().Unix()
  77. ProjectLastNodeResponse = time.Now().Unix()
  78. log.Info("init success")
  79. }
  80. func main() {
  81. //正式环境才执行定时任务
  82. if config.Conf.Env.Stype == 0 {
  83. go LastUdpJob() //监听半小时内有无数据
  84. go checkMapJob() //udp 发送邮件
  85. go task_index() //定时同步更新winner_enterprise、buyer_enterprise ES索引;这个功能很少变动,几乎不需要维护
  86. }
  87. go UpdateBidding() //更新bidding表数据
  88. go SaveEsMethod()
  89. go SaveAllEsMethod()
  90. go SaveProjectEs()
  91. go SaveBidErr()
  92. //添加预处理函数
  93. //if config.Conf.Env.OpenPre {
  94. // go SavePreEsMethod()
  95. // go dealPreProcess()
  96. //}
  97. UdpClient = udp.UdpClient{Local: config.Conf.Udp.LocPort, BufSize: 1024}
  98. UdpClient.Listen(processUdpMsg)
  99. log.Info("Udp服务监听", zap.String("port:", config.Conf.Udp.LocPort))
  100. ch := make(chan bool, 1)
  101. <-ch
  102. }
  103. var pool = make(chan bool, 20)
  104. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  105. switch act {
  106. case udp.OP_TYPE_DATA:
  107. var mapInfo map[string]interface{}
  108. err := json.Unmarshal(data, &mapInfo)
  109. log.Info("processUdpMsg", zap.Any("mapInfo:", mapInfo))
  110. if err != nil {
  111. UdpClient.WriteUdp([]byte("err:"+err.Error()), udp.OP_NOOP, ra)
  112. } else if mapInfo != nil {
  113. key, _ := mapInfo["key"].(string)
  114. if key == "" {
  115. key = "udpok"
  116. }
  117. go UdpClient.WriteUdp([]byte(key), udp.OP_NOOP, ra)
  118. //有udp 转发时
  119. if config.Conf.Udp.NeAddr != "" {
  120. go SendUdpMsg(mapInfo, NeUdpAddr)
  121. }
  122. tasktype, _ := mapInfo["stype"].(string)
  123. switch tasktype {
  124. case "index-by-id": //单个索引,更新pici
  125. pool <- true
  126. go func() {
  127. defer func() {
  128. <-pool
  129. }()
  130. biddingTaskById(mapInfo)
  131. }()
  132. case "index_by_id": //单个索引,不更新pici
  133. pool <- true
  134. go func() {
  135. defer func() {
  136. <-pool
  137. }()
  138. biddingTaskById(mapInfo)
  139. }()
  140. case "bidding":
  141. BiddingLastNodeResponse = time.Now().Unix()
  142. pool <- true
  143. go func() {
  144. defer func() {
  145. <-pool
  146. }()
  147. biddingTask(mapInfo)
  148. }()
  149. case "biddingall": //补充存量数据
  150. pool <- true
  151. go func() {
  152. defer func() {
  153. <-pool
  154. }()
  155. biddingAllTask(mapInfo)
  156. }()
  157. case "bidding_all_data": //根据biddingall配置文件,存量迁移数据
  158. pool <- true
  159. go func() {
  160. defer func() {
  161. <-pool
  162. }()
  163. biddingAllDataTask()
  164. }()
  165. case "bidding_history":
  166. pool <- true
  167. go func() {
  168. defer func() {
  169. <-pool
  170. }()
  171. biddingTask(mapInfo)
  172. }()
  173. case "project":
  174. ProjectLastNodeResponse = time.Now().Unix()
  175. pool <- true
  176. go func() {
  177. defer func() {
  178. <-pool
  179. }()
  180. projectTask(data, mapInfo)
  181. }()
  182. case "project_all_data": //存量 projectset 数据
  183. pool <- true
  184. go func() {
  185. defer func() {
  186. <-pool
  187. }()
  188. projectAllData()
  189. }()
  190. case "biddingdata": //es 单机版,采集判重
  191. pool <- true
  192. go func() {
  193. defer func() {
  194. <-pool
  195. }()
  196. biddingDataTask(data, mapInfo)
  197. }()
  198. case "biddingdelbyextracttype": //根据bidding表extracttype=-1,删除es中重复数据
  199. pool <- true
  200. go func() {
  201. defer func() {
  202. <-pool
  203. }()
  204. biddingDelByExtracttype(data, mapInfo)
  205. }()
  206. case "buyer_once": // 采购单位昨天增量数据
  207. pool <- true
  208. go func() {
  209. defer func() {
  210. <-pool
  211. }()
  212. buyerOnce()
  213. }()
  214. case "buyer_all": // 采购单位全量数据
  215. pool <- true
  216. go func() {
  217. defer func() {
  218. <-pool
  219. }()
  220. buyerAll()
  221. }()
  222. case "winner_once": // 中标单位昨天增量数据
  223. pool <- true
  224. go func() {
  225. defer func() {
  226. <-pool
  227. }()
  228. winnerEsTaskOnce()
  229. }()
  230. case "winner_all": // 中标单位存量数据
  231. pool <- true
  232. go func() {
  233. defer func() {
  234. <-pool
  235. }()
  236. winnerEsAll()
  237. }()
  238. case "attachment": // 补充附件采集,对应bidding为bidding_downloadfile_log
  239. pool <- true
  240. go func() {
  241. defer func() {
  242. <-pool
  243. }()
  244. //有单独配置其他操作
  245. if len(config.Conf.Others) > 0 {
  246. if v, ok := config.Conf.Others[tasktype]; ok {
  247. attachmentBiddingTask(mapInfo, v)
  248. }
  249. }
  250. }()
  251. default:
  252. pool <- true
  253. go func() {
  254. defer func() {
  255. <-pool
  256. }()
  257. log.Info("err", zap.Any("mapInfo", mapInfo))
  258. }()
  259. }
  260. }
  261. case udp.OP_NOOP: //下个节点回应
  262. ok := string(data)
  263. if ok != "" {
  264. log.Info("udp re", zap.String("data:", ok))
  265. UdpTaskMap.Delete(ok)
  266. }
  267. }
  268. }
  269. func task_index() {
  270. c := cron.New()
  271. _ = c.AddFunc("0 00 00 * * *", func() { task_winneres() }) //每天凌晨执行一次winner生索引
  272. _ = c.AddFunc("0 00 01 * * *", func() { task_buyeres() }) //每天1点执行一次buyer生索引
  273. c.Start()
  274. }
  275. func task_winneres() {
  276. log.Info("定时任务,winneres")
  277. winnerEsTaskOnce()
  278. }
  279. func task_buyeres() {
  280. log.Info("定时任务,buyeres")
  281. buyerOnce()
  282. }
  283. type UdpNode struct {
  284. data []byte
  285. addr *net.UDPAddr
  286. timestamp int64
  287. retry int
  288. }
  289. // UpdateBidding 更新bidding表数据
  290. func UpdateBidding() {
  291. //arru := make([][]map[string]interface{}, 10)
  292. //indexu := 0
  293. for {
  294. select {
  295. case v := <-updateBiddingPool:
  296. MgoB.UpdateById(config.Conf.DB.MongoB.Coll, v["_id"], map[string]interface{}{"$set": v["set"]})
  297. //arru[indexu] = v
  298. //indexu++
  299. //if indexu == 10 {
  300. // updateBiddingSp <- true
  301. //go func(arru [][]map[string]interface{}) {
  302. // defer func() {
  303. // <-updateBiddingSp
  304. //}()
  305. //MgoB.UpdateBulk(config.Conf.DB.MongoB.Coll, arru...)
  306. //}(arru)
  307. //arru = make([][]map[string]interface{}, 10)
  308. //indexu = 0
  309. //}
  310. //case <-time.After(1000 * time.Millisecond):
  311. // if indexu > 0 {
  312. // updateBiddingSp <- true
  313. // go func(arru [][]map[string]interface{}) {
  314. // defer func() {
  315. // <-updateBiddingSp
  316. // }()
  317. // MgoB.UpdateBulk(config.Conf.DB.MongoB.Coll, arru...)
  318. // }(arru[:indexu])
  319. // arru = make([][]map[string]interface{}, 200)
  320. // indexu = 0
  321. // }
  322. }
  323. }
  324. }
  325. // SaveBidErr 记录错误信息,暂时记录 附件过长的
  326. func SaveBidErr() {
  327. arru := make([]map[string]interface{}, 200)
  328. indexu := 0
  329. for {
  330. select {
  331. case v := <-saveErrBidPool:
  332. arru[indexu] = v
  333. indexu++
  334. if indexu == 200 {
  335. saveBidSp <- true
  336. go func(arru []map[string]interface{}) {
  337. defer func() {
  338. <-saveBidSp
  339. }()
  340. MgoB.SaveBulk("bidding_es_err_record", arru...)
  341. }(arru)
  342. arru = make([]map[string]interface{}, 200)
  343. indexu = 0
  344. }
  345. case <-time.After(1000 * time.Millisecond):
  346. if indexu > 0 {
  347. saveBidSp <- true
  348. go func(arru []map[string]interface{}) {
  349. defer func() {
  350. <-saveBidSp
  351. }()
  352. MgoB.SaveBulk("bidding_es_err_record", arru...)
  353. }(arru[:indexu])
  354. arru = make([]map[string]interface{}, 200)
  355. indexu = 0
  356. }
  357. }
  358. }
  359. }
  360. // SaveEsMethod 保存到es
  361. func SaveEsMethod() {
  362. //arru := make([]map[string]interface{}, EsBulkSize)
  363. //indexu := 0
  364. for {
  365. select {
  366. case v := <-saveEsPool:
  367. id := v["id"]
  368. ids := v["_id"]
  369. Es.Save(config.Conf.DB.Es.IndexB, v)
  370. if config.Conf.DB.Es.Addr2 != "" {
  371. v["id"] = id
  372. v["_id"] = ids
  373. Es2.Save(config.Conf.DB.Es.Indexb2, v)
  374. }
  375. //arru[indexu] = v
  376. //indexu++
  377. //if indexu == EsBulkSize {
  378. // saveEsSp <- true
  379. //go func(arru []map[string]interface{}) {
  380. // defer func() {
  381. //<-saveEsSp
  382. //}()
  383. //if config.Conf.DB.Es.IndexTmp != "" {
  384. // if config.Conf.DB.Es.Addr2 != "" {
  385. // Es2.BulkSave(config.Conf.DB.Es.IndexTmp, arru) // 新集群
  386. // }
  387. // Es.BulkSave(config.Conf.DB.Es.IndexTmp, arru) //老集群
  388. //}
  389. //}(arru)
  390. //arru = make([]map[string]interface{}, EsBulkSize)
  391. //indexu = 0
  392. //}
  393. //case <-time.After(1000 * time.Millisecond):
  394. // if indexu > 0 {
  395. // saveEsSp <- true
  396. // go func(arru []map[string]interface{}) {
  397. // defer func() {
  398. // <-saveEsSp
  399. // }()
  400. // Es.BulkSave(config.Conf.DB.Es.IndexB, arru)
  401. //if config.Conf.DB.Es.IndexTmp != "" {
  402. // if config.Conf.DB.Es.Addr2 != "" {
  403. // Es2.BulkSave(config.Conf.DB.Es.IndexTmp, arru) // 新集群
  404. // }
  405. // Es.BulkSave(config.Conf.DB.Es.IndexTmp, arru)
  406. //}
  407. // if config.Conf.DB.Es.Addr2 != "" {
  408. // Es2.BulkSave(config.Conf.DB.Es.Indexb2, arru)
  409. // }
  410. // }(arru[:indexu])
  411. // arru = make([]map[string]interface{}, EsBulkSize)
  412. // indexu = 0
  413. //}
  414. }
  415. }
  416. }
  417. // SaveAllEsMethod 保存爬虫采集临时数据,保存在华为云上
  418. func SaveAllEsMethod() {
  419. arru := make([]map[string]interface{}, EsBulkSize)
  420. indexu := 0
  421. for {
  422. select {
  423. case v := <-saveEsAllPool:
  424. arru[indexu] = v
  425. indexu++
  426. if indexu == EsBulkSize {
  427. saveEsAllSp <- true
  428. go func(arru []map[string]interface{}) {
  429. defer func() {
  430. <-saveEsAllSp
  431. }()
  432. if config.Conf.DB.Es.Addr2 != "" {
  433. Es2.BulkSave("biddingall", arru)
  434. }
  435. }(arru)
  436. arru = make([]map[string]interface{}, EsBulkSize)
  437. indexu = 0
  438. }
  439. case <-time.After(1000 * time.Millisecond):
  440. if indexu > 0 {
  441. saveEsAllSp <- true
  442. go func(arru []map[string]interface{}) {
  443. defer func() {
  444. <-saveEsAllSp
  445. }()
  446. if config.Conf.DB.Es.Addr2 != "" {
  447. Es2.BulkSave("biddingall", arru)
  448. }
  449. }(arru[:indexu])
  450. arru = make([]map[string]interface{}, EsBulkSize)
  451. indexu = 0
  452. }
  453. }
  454. }
  455. }
  456. func SaveProjectEs() {
  457. arru := make([]map[string]interface{}, EsBulkSize)
  458. indexu := 0
  459. for {
  460. select {
  461. case v := <-saveProjectEsPool:
  462. arru[indexu] = v
  463. indexu++
  464. if indexu == EsBulkSize {
  465. saveProjectSp <- true
  466. go func(arru []map[string]interface{}) {
  467. defer func() {
  468. <-saveProjectSp
  469. }()
  470. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  471. }(arru)
  472. arru = make([]map[string]interface{}, EsBulkSize)
  473. indexu = 0
  474. }
  475. case <-time.After(1000 * time.Millisecond):
  476. if indexu > 0 {
  477. saveProjectSp <- true
  478. go func(arru []map[string]interface{}) {
  479. defer func() {
  480. <-saveProjectSp
  481. }()
  482. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  483. }(arru[:indexu])
  484. arru = make([]map[string]interface{}, EsBulkSize)
  485. indexu = 0
  486. }
  487. }
  488. }
  489. }
  490. func checkMapJob() {
  491. if config.Conf.Mail.Send {
  492. log.Info("checkMapJob", zap.String("to:", config.Conf.Mail.To))
  493. for {
  494. UdpTaskMap.Range(func(k, v interface{}) bool {
  495. now := time.Now().Unix()
  496. node, _ := v.(*UdpNode)
  497. if now-node.timestamp > 120 {
  498. node.retry++
  499. if node.retry > 5 {
  500. UdpTaskMap.Delete(k)
  501. res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", config.Conf.Mail.Api, config.Conf.Mail.To, "field-sync-send-fail", k.(string)))
  502. if err == nil {
  503. defer res.Body.Close()
  504. read, err := ioutil.ReadAll(res.Body)
  505. log.Info("send mail ...", zap.String("r:", string(read)), zap.Any("err:", err))
  506. }
  507. } else {
  508. log.Info("udp重发", zap.Any("k:", k))
  509. UdpClient.WriteUdp(node.data, udp.OP_TYPE_DATA, node.addr)
  510. }
  511. } else if now-node.timestamp > 10 {
  512. log.Info("udp任务超时中..", zap.Any("k:", k))
  513. }
  514. return true
  515. })
  516. time.Sleep(60 * time.Second)
  517. }
  518. }
  519. }
  520. func task() {
  521. sess := MgoB.GetMgoConn()
  522. defer MgoB.DestoryMongoConn(sess)
  523. ch := make(chan bool, 10)
  524. wg := &sync.WaitGroup{}
  525. query := sess.DB("qfw").C("result_replace_repair_log").Find(nil).Iter()
  526. count := 0
  527. for tmp := make(map[string]interface{}); query.Next(tmp); count++ {
  528. if count%1000 == 0 {
  529. util.Debug("current ---", count)
  530. }
  531. ch <- true
  532. wg.Add(1)
  533. go func(tmp map[string]interface{}) {
  534. defer func() {
  535. <-ch
  536. wg.Done()
  537. }()
  538. if id := util.ObjToString(tmp["replace_id"]); mongodb.IsObjectIdHex(id) {
  539. biddingTaskById(map[string]interface{}{"infoid": id, "stype": "bidding"})
  540. }
  541. }(tmp)
  542. tmp = make(map[string]interface{})
  543. }
  544. wg.Wait()
  545. util.Debug("over ---", count)
  546. }
  547. // LastUdpJob 处理UDP 没有接受数据
  548. func LastUdpJob() {
  549. for {
  550. responselock.Lock()
  551. if time.Now().Unix()-BiddingLastNodeResponse >= 1800 {
  552. BiddingLastNodeResponse = time.Now().Unix() //重置时间
  553. sendErrMailApi("索引程序异常", fmt.Sprintf("半小时左右 无bidding据进入 ...相关人员检查..."))
  554. }
  555. if time.Now().Unix()-ProjectLastNodeResponse >= 1800 {
  556. ProjectLastNodeResponse = time.Now().Unix() //重置时间
  557. sendErrMailApi("索引程序异常", fmt.Sprintf("半小时左右 无project数据进入 ...相关人员检查..."))
  558. }
  559. responselock.Unlock()
  560. time.Sleep(300 * time.Second)
  561. }
  562. }
  563. // sendErrMailApi 发送邮件
  564. func sendErrMailApi(title, body string) {
  565. var tomail, api string
  566. if config.Conf.Mail.Send {
  567. tomail = config.Conf.Mail.To
  568. api = config.Conf.Mail.Api
  569. }
  570. log.Info("sendErrMailApi", zap.Any(tomail, api))
  571. res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", api, tomail, title, body))
  572. if err == nil {
  573. defer res.Body.Close()
  574. read, err := ioutil.ReadAll(res.Body)
  575. if err != nil {
  576. log.Info("邮件发送成功", zap.String("read", string(read)))
  577. }
  578. } else {
  579. log.Info("sendErrMailApi", zap.String("邮件发送失败", err.Error()))
  580. }
  581. }