main.go 16 KB

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