main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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 "winner_once": // 中标单位昨天增量数据
  215. pool <- true
  216. go func() {
  217. defer func() {
  218. <-pool
  219. }()
  220. winnerEsTaskOnce()
  221. }()
  222. case "winner_all": // 中标单位存量数据
  223. pool <- true
  224. go func() {
  225. defer func() {
  226. <-pool
  227. }()
  228. winnerEsAll()
  229. }()
  230. case "attachment": // 补充附件采集,对应bidding为bidding_downloadfile_log
  231. pool <- true
  232. go func() {
  233. defer func() {
  234. <-pool
  235. }()
  236. //有单独配置其他操作
  237. if len(config.Conf.Others) > 0 {
  238. if v, ok := config.Conf.Others[tasktype]; ok {
  239. attachmentBiddingTask(mapInfo, v)
  240. }
  241. }
  242. }()
  243. default:
  244. pool <- true
  245. go func() {
  246. defer func() {
  247. <-pool
  248. }()
  249. log.Info("err", zap.Any("mapInfo", mapInfo))
  250. }()
  251. }
  252. }
  253. case udp.OP_NOOP: //下个节点回应
  254. ok := string(data)
  255. if ok != "" {
  256. log.Info("udp re", zap.String("data:", ok))
  257. UdpTaskMap.Delete(ok)
  258. }
  259. }
  260. }
  261. func task_index() {
  262. c := cron.New()
  263. _ = c.AddFunc("0 0 0 * * ?", func() { task_winneres() }) //每天凌晨执行一次winner生索引
  264. _ = c.AddFunc("0 0 1 * * ?", func() { task_buyeres() }) //每天1点执行一次buyer生索引
  265. c.Start()
  266. }
  267. func task_winneres() {
  268. log.Info("定时任务,winneres")
  269. winnerEsTaskOnce()
  270. }
  271. func task_buyeres() {
  272. log.Info("定时任务,buyeres")
  273. buyerOnce()
  274. }
  275. type UdpNode struct {
  276. data []byte
  277. addr *net.UDPAddr
  278. timestamp int64
  279. retry int
  280. }
  281. //UpdateBidding 更新bidding表数据
  282. func UpdateBidding() {
  283. arru := make([][]map[string]interface{}, 200)
  284. indexu := 0
  285. for {
  286. select {
  287. case v := <-updateBiddingPool:
  288. arru[indexu] = v
  289. indexu++
  290. if indexu == 200 {
  291. updateBiddingSp <- true
  292. go func(arru [][]map[string]interface{}) {
  293. defer func() {
  294. <-updateBiddingSp
  295. }()
  296. MgoB.UpdateBulk(config.Conf.DB.MongoB.Coll, arru...)
  297. }(arru)
  298. arru = make([][]map[string]interface{}, 200)
  299. indexu = 0
  300. }
  301. case <-time.After(1000 * time.Millisecond):
  302. if indexu > 0 {
  303. updateBiddingSp <- true
  304. go func(arru [][]map[string]interface{}) {
  305. defer func() {
  306. <-updateBiddingSp
  307. }()
  308. MgoB.UpdateBulk(config.Conf.DB.MongoB.Coll, arru...)
  309. }(arru[:indexu])
  310. arru = make([][]map[string]interface{}, 200)
  311. indexu = 0
  312. }
  313. }
  314. }
  315. }
  316. //SaveBidErr 记录错误信息,暂时记录 附件过长的
  317. func SaveBidErr() {
  318. arru := make([]map[string]interface{}, 200)
  319. indexu := 0
  320. for {
  321. select {
  322. case v := <-saveErrBidPool:
  323. arru[indexu] = v
  324. indexu++
  325. if indexu == 200 {
  326. saveBidSp <- true
  327. go func(arru []map[string]interface{}) {
  328. defer func() {
  329. <-saveBidSp
  330. }()
  331. MgoB.SaveBulk("bidding_es_err_record", arru...)
  332. }(arru)
  333. arru = make([]map[string]interface{}, 200)
  334. indexu = 0
  335. }
  336. case <-time.After(1000 * time.Millisecond):
  337. if indexu > 0 {
  338. saveBidSp <- true
  339. go func(arru []map[string]interface{}) {
  340. defer func() {
  341. <-saveBidSp
  342. }()
  343. MgoB.SaveBulk("bidding_es_err_record", arru...)
  344. }(arru[:indexu])
  345. arru = make([]map[string]interface{}, 200)
  346. indexu = 0
  347. }
  348. }
  349. }
  350. }
  351. //SaveEsMethod 保存到es
  352. func SaveEsMethod() {
  353. arru := make([]map[string]interface{}, EsBulkSize)
  354. indexu := 0
  355. for {
  356. select {
  357. case v := <-saveEsPool:
  358. arru[indexu] = v
  359. indexu++
  360. if indexu == EsBulkSize {
  361. saveEsSp <- true
  362. go func(arru []map[string]interface{}) {
  363. defer func() {
  364. <-saveEsSp
  365. }()
  366. Es.BulkSave(config.Conf.DB.Es.IndexB, arru)
  367. //if config.Conf.DB.Es.IndexTmp != "" {
  368. // if config.Conf.DB.Es.Addr2 != "" {
  369. // Es2.BulkSave(config.Conf.DB.Es.IndexTmp, arru) // 新集群
  370. // }
  371. // Es.BulkSave(config.Conf.DB.Es.IndexTmp, arru) //老集群
  372. //}
  373. if config.Conf.DB.Es.Addr2 != "" {
  374. Es2.BulkSave(config.Conf.DB.Es.Indexb2, arru)
  375. }
  376. }(arru)
  377. arru = make([]map[string]interface{}, EsBulkSize)
  378. indexu = 0
  379. }
  380. case <-time.After(1000 * time.Millisecond):
  381. if indexu > 0 {
  382. saveEsSp <- true
  383. go func(arru []map[string]interface{}) {
  384. defer func() {
  385. <-saveEsSp
  386. }()
  387. Es.BulkSave(config.Conf.DB.Es.IndexB, arru)
  388. //if config.Conf.DB.Es.IndexTmp != "" {
  389. // if config.Conf.DB.Es.Addr2 != "" {
  390. // Es2.BulkSave(config.Conf.DB.Es.IndexTmp, arru) // 新集群
  391. // }
  392. // Es.BulkSave(config.Conf.DB.Es.IndexTmp, arru)
  393. //}
  394. if config.Conf.DB.Es.Addr2 != "" {
  395. Es2.BulkSave(config.Conf.DB.Es.Indexb2, arru)
  396. }
  397. }(arru[:indexu])
  398. arru = make([]map[string]interface{}, EsBulkSize)
  399. indexu = 0
  400. }
  401. }
  402. }
  403. }
  404. //SaveAllEsMethod 保存爬虫采集临时数据,保存在华为云上
  405. func SaveAllEsMethod() {
  406. arru := make([]map[string]interface{}, EsBulkSize)
  407. indexu := 0
  408. for {
  409. select {
  410. case v := <-saveEsAllPool:
  411. arru[indexu] = v
  412. indexu++
  413. if indexu == EsBulkSize {
  414. saveEsAllSp <- true
  415. go func(arru []map[string]interface{}) {
  416. defer func() {
  417. <-saveEsAllSp
  418. }()
  419. if config.Conf.DB.Es.Addr2 != "" {
  420. Es2.BulkSave("biddingall", arru)
  421. }
  422. }(arru)
  423. arru = make([]map[string]interface{}, EsBulkSize)
  424. indexu = 0
  425. }
  426. case <-time.After(1000 * time.Millisecond):
  427. if indexu > 0 {
  428. saveEsAllSp <- true
  429. go func(arru []map[string]interface{}) {
  430. defer func() {
  431. <-saveEsAllSp
  432. }()
  433. if config.Conf.DB.Es.Addr2 != "" {
  434. Es2.BulkSave("biddingall", arru)
  435. }
  436. }(arru[:indexu])
  437. arru = make([]map[string]interface{}, EsBulkSize)
  438. indexu = 0
  439. }
  440. }
  441. }
  442. }
  443. func SaveProjectEs() {
  444. arru := make([]map[string]interface{}, EsBulkSize)
  445. indexu := 0
  446. for {
  447. select {
  448. case v := <-saveProjectEsPool:
  449. arru[indexu] = v
  450. indexu++
  451. if indexu == EsBulkSize {
  452. saveProjectSp <- true
  453. go func(arru []map[string]interface{}) {
  454. defer func() {
  455. <-saveProjectSp
  456. }()
  457. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  458. }(arru)
  459. arru = make([]map[string]interface{}, EsBulkSize)
  460. indexu = 0
  461. }
  462. case <-time.After(1000 * time.Millisecond):
  463. if indexu > 0 {
  464. saveProjectSp <- true
  465. go func(arru []map[string]interface{}) {
  466. defer func() {
  467. <-saveProjectSp
  468. }()
  469. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  470. }(arru[:indexu])
  471. arru = make([]map[string]interface{}, EsBulkSize)
  472. indexu = 0
  473. }
  474. }
  475. }
  476. }
  477. func checkMapJob() {
  478. if config.Conf.Mail.Send {
  479. log.Info("checkMapJob", zap.String("to:", config.Conf.Mail.To))
  480. for {
  481. UdpTaskMap.Range(func(k, v interface{}) bool {
  482. now := time.Now().Unix()
  483. node, _ := v.(*UdpNode)
  484. if now-node.timestamp > 120 {
  485. node.retry++
  486. if node.retry > 5 {
  487. UdpTaskMap.Delete(k)
  488. 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)))
  489. if err == nil {
  490. defer res.Body.Close()
  491. read, err := ioutil.ReadAll(res.Body)
  492. log.Info("send mail ...", zap.String("r:", string(read)), zap.Any("err:", err))
  493. }
  494. } else {
  495. log.Info("udp重发", zap.Any("k:", k))
  496. UdpClient.WriteUdp(node.data, udp.OP_TYPE_DATA, node.addr)
  497. }
  498. } else if now-node.timestamp > 10 {
  499. log.Info("udp任务超时中..", zap.Any("k:", k))
  500. }
  501. return true
  502. })
  503. time.Sleep(60 * time.Second)
  504. }
  505. }
  506. }
  507. func task() {
  508. sess := MgoB.GetMgoConn()
  509. defer MgoB.DestoryMongoConn(sess)
  510. ch := make(chan bool, 10)
  511. wg := &sync.WaitGroup{}
  512. query := sess.DB("qfw").C("result_replace_repair_log").Find(nil).Iter()
  513. count := 0
  514. for tmp := make(map[string]interface{}); query.Next(tmp); count++ {
  515. if count%1000 == 0 {
  516. util.Debug("current ---", count)
  517. }
  518. ch <- true
  519. wg.Add(1)
  520. go func(tmp map[string]interface{}) {
  521. defer func() {
  522. <-ch
  523. wg.Done()
  524. }()
  525. if id := util.ObjToString(tmp["replace_id"]); mongodb.IsObjectIdHex(id) {
  526. biddingTaskById(map[string]interface{}{"infoid": id, "stype": "bidding"})
  527. }
  528. }(tmp)
  529. tmp = make(map[string]interface{})
  530. }
  531. wg.Wait()
  532. util.Debug("over ---", count)
  533. }
  534. //LastUdpJob 处理UDP 没有接受数据
  535. func LastUdpJob() {
  536. for {
  537. responselock.Lock()
  538. if time.Now().Unix()-BiddingLastNodeResponse >= 1800 {
  539. BiddingLastNodeResponse = time.Now().Unix() //重置时间
  540. sendErrMailApi("索引程序异常", fmt.Sprintf("半小时左右 无bidding据进入 ...相关人员检查..."))
  541. }
  542. if time.Now().Unix()-ProjectLastNodeResponse >= 1800 {
  543. ProjectLastNodeResponse = time.Now().Unix() //重置时间
  544. sendErrMailApi("索引程序异常", fmt.Sprintf("半小时左右 无project数据进入 ...相关人员检查..."))
  545. }
  546. responselock.Unlock()
  547. time.Sleep(300 * time.Second)
  548. }
  549. }
  550. //sendErrMailApi 发送邮件
  551. func sendErrMailApi(title, body string) {
  552. var tomail, api string
  553. if config.Conf.Mail.Send {
  554. tomail = config.Conf.Mail.To
  555. api = config.Conf.Mail.Api
  556. }
  557. log.Info("sendErrMailApi", zap.Any(tomail, api))
  558. res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", api, tomail, title, body))
  559. if err == nil {
  560. defer res.Body.Close()
  561. read, err := ioutil.ReadAll(res.Body)
  562. if err != nil {
  563. log.Info("邮件发送成功", zap.String("read", string(read)))
  564. }
  565. } else {
  566. log.Info("sendErrMailApi", zap.String("邮件发送失败", err.Error()))
  567. }
  568. }