main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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, Es1, 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. func SaveAllEsMethod() {
  405. arru := make([]map[string]interface{}, EsBulkSize)
  406. indexu := 0
  407. for {
  408. select {
  409. case v := <-saveEsAllPool:
  410. arru[indexu] = v
  411. indexu++
  412. if indexu == EsBulkSize {
  413. saveEsAllSp <- true
  414. go func(arru []map[string]interface{}) {
  415. defer func() {
  416. <-saveEsAllSp
  417. }()
  418. Es1.BulkSave("biddingall", arru)
  419. }(arru)
  420. arru = make([]map[string]interface{}, EsBulkSize)
  421. indexu = 0
  422. }
  423. case <-time.After(1000 * time.Millisecond):
  424. if indexu > 0 {
  425. saveEsAllSp <- true
  426. go func(arru []map[string]interface{}) {
  427. defer func() {
  428. <-saveEsAllSp
  429. }()
  430. Es1.BulkSave("biddingall", arru)
  431. }(arru[:indexu])
  432. arru = make([]map[string]interface{}, EsBulkSize)
  433. indexu = 0
  434. }
  435. }
  436. }
  437. }
  438. func SaveProjectEs() {
  439. arru := make([]map[string]interface{}, EsBulkSize)
  440. indexu := 0
  441. for {
  442. select {
  443. case v := <-saveProjectEsPool:
  444. arru[indexu] = v
  445. indexu++
  446. if indexu == EsBulkSize {
  447. saveProjectSp <- true
  448. go func(arru []map[string]interface{}) {
  449. defer func() {
  450. <-saveProjectSp
  451. }()
  452. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  453. }(arru)
  454. arru = make([]map[string]interface{}, EsBulkSize)
  455. indexu = 0
  456. }
  457. case <-time.After(1000 * time.Millisecond):
  458. if indexu > 0 {
  459. saveProjectSp <- true
  460. go func(arru []map[string]interface{}) {
  461. defer func() {
  462. <-saveProjectSp
  463. }()
  464. Es.BulkSave(config.Conf.DB.Es.IndexP, arru)
  465. }(arru[:indexu])
  466. arru = make([]map[string]interface{}, EsBulkSize)
  467. indexu = 0
  468. }
  469. }
  470. }
  471. }
  472. func checkMapJob() {
  473. if config.Conf.Mail.Send {
  474. log.Info("checkMapJob", zap.String("to:", config.Conf.Mail.To))
  475. for {
  476. UdpTaskMap.Range(func(k, v interface{}) bool {
  477. now := time.Now().Unix()
  478. node, _ := v.(*UdpNode)
  479. if now-node.timestamp > 120 {
  480. node.retry++
  481. if node.retry > 5 {
  482. UdpTaskMap.Delete(k)
  483. 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)))
  484. if err == nil {
  485. defer res.Body.Close()
  486. read, err := ioutil.ReadAll(res.Body)
  487. log.Info("send mail ...", zap.String("r:", string(read)), zap.Any("err:", err))
  488. }
  489. } else {
  490. log.Info("udp重发", zap.Any("k:", k))
  491. UdpClient.WriteUdp(node.data, udp.OP_TYPE_DATA, node.addr)
  492. }
  493. } else if now-node.timestamp > 10 {
  494. log.Info("udp任务超时中..", zap.Any("k:", k))
  495. }
  496. return true
  497. })
  498. time.Sleep(60 * time.Second)
  499. }
  500. }
  501. }
  502. func task() {
  503. sess := MgoB.GetMgoConn()
  504. defer MgoB.DestoryMongoConn(sess)
  505. ch := make(chan bool, 10)
  506. wg := &sync.WaitGroup{}
  507. query := sess.DB("qfw").C("result_replace_repair_log").Find(nil).Iter()
  508. count := 0
  509. for tmp := make(map[string]interface{}); query.Next(tmp); count++ {
  510. if count%1000 == 0 {
  511. util.Debug("current ---", count)
  512. }
  513. ch <- true
  514. wg.Add(1)
  515. go func(tmp map[string]interface{}) {
  516. defer func() {
  517. <-ch
  518. wg.Done()
  519. }()
  520. if id := util.ObjToString(tmp["replace_id"]); mongodb.IsObjectIdHex(id) {
  521. biddingTaskById(map[string]interface{}{"infoid": id, "stype": "bidding"})
  522. }
  523. }(tmp)
  524. tmp = make(map[string]interface{})
  525. }
  526. wg.Wait()
  527. util.Debug("over ---", count)
  528. }
  529. //LastUdpJob 处理UDP 没有接受数据
  530. func LastUdpJob() {
  531. for {
  532. responselock.Lock()
  533. if time.Now().Unix()-BiddingLastNodeResponse >= 1800 {
  534. BiddingLastNodeResponse = time.Now().Unix() //重置时间
  535. sendErrMailApi("索引程序异常", fmt.Sprintf("半小时左右 无bidding据进入 ...相关人员检查..."))
  536. }
  537. if time.Now().Unix()-ProjectLastNodeResponse >= 1800 {
  538. ProjectLastNodeResponse = time.Now().Unix() //重置时间
  539. sendErrMailApi("索引程序异常", fmt.Sprintf("半小时左右 无project数据进入 ...相关人员检查..."))
  540. }
  541. responselock.Unlock()
  542. time.Sleep(300 * time.Second)
  543. }
  544. }
  545. //sendErrMailApi 发送邮件
  546. func sendErrMailApi(title, body string) {
  547. var tomail, api string
  548. if config.Conf.Mail.Send {
  549. tomail = config.Conf.Mail.To
  550. api = config.Conf.Mail.Api
  551. }
  552. log.Info("sendErrMailApi", zap.Any(tomail, api))
  553. res, err := http.Get(fmt.Sprintf("%s?to=%s&title=%s&body=%s", api, tomail, title, body))
  554. if err == nil {
  555. defer res.Body.Close()
  556. read, err := ioutil.ReadAll(res.Body)
  557. if err != nil {
  558. log.Info("邮件发送成功", zap.String("read", string(read)))
  559. }
  560. } else {
  561. log.Info("sendErrMailApi", zap.String("邮件发送失败", err.Error()))
  562. }
  563. }