main.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. package main
  2. /**
  3. 招标信息判重
  4. **/
  5. import (
  6. "encoding/json"
  7. "flag"
  8. "fmt"
  9. "github.com/cron"
  10. "gopkg.in/mgo.v2/bson"
  11. "log"
  12. mu "mfw/util"
  13. "net"
  14. "os"
  15. "qfw/util"
  16. "regexp"
  17. "strconv"
  18. "sync"
  19. "time"
  20. )
  21. var (
  22. Sysconfig map[string]interface{} //配置文件
  23. mconf map[string]interface{} //mongodb配置信息
  24. mgo *MongodbSim //mongodb操作对象
  25. task_mgo *MongodbSim //mongodb操作对象
  26. task_collName string
  27. extract string
  28. extract_back string
  29. udpclient mu.UdpClient //udp对象
  30. nextNode []map[string]interface{} //下节点数组
  31. dupdays = 7 //初始化判重范围
  32. DM *datamap //
  33. Update *updateInfo
  34. //正则筛选相关
  35. FilterRegTitle = regexp.MustCompile("^_$")
  36. FilterRegTitle_0 = regexp.MustCompile("^_$")
  37. FilterRegTitle_1 = regexp.MustCompile("^_$")
  38. FilterRegTitle_2 = regexp.MustCompile("^_$")
  39. isMerger bool //是否合并
  40. threadNum int //线程数量
  41. SiteMap map[string]map[string]interface{} //站点map
  42. LowHeavy bool //低质量数据判重
  43. TimingTask bool //是否定时任务
  44. timingSpanDay int64 //时间跨度
  45. timingPubScope int64 //发布时间周期
  46. gtid,lastid,gtept,ltept string //命令输入
  47. lteid string //历史增量属性
  48. IsFull bool //是否全量
  49. updatelock sync.Mutex //锁4
  50. userName,passWord string //mongo -用户密码
  51. )
  52. func init() {
  53. flag.StringVar(&lastid, "id", "", "增量加载的lastid") //增量
  54. flag.StringVar(&gtid, "gtid", "", "历史增量的起始id") //历史
  55. flag.StringVar(&gtept, "gtept", "", "全量gte发布时间")//全量区间pt
  56. flag.StringVar(&ltept, "ltept", "", "全量lte发布时间") //全量区间pt
  57. flag.Parse()
  58. util.ReadConfig(&Sysconfig)
  59. userName = util.ObjToString(Sysconfig["userName"])
  60. passWord = util.ObjToString(Sysconfig["passWord"])
  61. log.Println("集群用户密码:",userName,passWord)
  62. task_mconf := Sysconfig["task_mongodb"].(map[string]interface{})
  63. task_mgo = &MongodbSim{
  64. MongodbAddr: task_mconf["task_addrName"].(string),
  65. DbName: task_mconf["task_dbName"].(string),
  66. Size: util.IntAllDef(task_mconf["task_pool"], 10),
  67. UserName: userName,
  68. Password: passWord,
  69. }
  70. task_mgo.InitPool()
  71. task_collName = task_mconf["task_collName"].(string)
  72. nextNode = util.ObjArrToMapArr(Sysconfig["nextNode"].([]interface{}))
  73. mconf = Sysconfig["mongodb"].(map[string]interface{})
  74. mgo = &MongodbSim{
  75. MongodbAddr: mconf["addr"].(string),
  76. DbName: mconf["db"].(string),
  77. Size: util.IntAllDef(mconf["pool"], 10),
  78. }
  79. mgo.InitPool()
  80. extract = mconf["extract"].(string)
  81. extract_back = mconf["extract_back"].(string)
  82. dupdays = util.IntAllDef(Sysconfig["dupdays"], 3)
  83. //加载数据
  84. DM = NewDatamap(dupdays, lastid)
  85. //更新池
  86. Update = newUpdatePool()
  87. go Update.updateData()
  88. FilterRegTitle = regexp.MustCompile(util.ObjToString(Sysconfig["specialwords"]))
  89. FilterRegTitle_0 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_0"]))
  90. FilterRegTitle_1 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_1"]))
  91. FilterRegTitle_2 = regexp.MustCompile(util.ObjToString(Sysconfig["specialtitle_2"]))
  92. isMerger = Sysconfig["isMerger"].(bool)
  93. threadNum = util.IntAllDef(Sysconfig["threads"], 1)
  94. LowHeavy = Sysconfig["lowHeavy"].(bool)
  95. TimingTask = Sysconfig["timingTask"].(bool)
  96. timingSpanDay = util.Int64All(Sysconfig["timingSpanDay"])
  97. timingPubScope = util.Int64All(Sysconfig["timingPubScope"])
  98. //站点配置
  99. site := mconf["site"].(map[string]interface{})
  100. SiteMap = make(map[string]map[string]interface{}, 0)
  101. start := int(time.Now().Unix())
  102. sess_site := mgo.GetMgoConn()
  103. defer mgo.DestoryMongoConn(sess_site)
  104. res_site := sess_site.DB(site["dbname"].(string)).C(site["coll"].(string)).Find(map[string]interface{}{}).Sort("_id").Iter()
  105. for site_dict := make(map[string]interface{}); res_site.Next(&site_dict); {
  106. data_map := map[string]interface{}{
  107. "area": util.ObjToString(site_dict["area"]),
  108. "city": util.ObjToString(site_dict["city"]),
  109. "district": util.ObjToString(site_dict["district"]),
  110. "sitetype": util.ObjToString(site_dict["sitetype"]),
  111. "level": util.ObjToString(site_dict["level"]),
  112. "weight": util.ObjToString(site_dict["weight"]),
  113. }
  114. SiteMap[util.ObjToString(site_dict["site"])] = data_map
  115. }
  116. log.Printf("new站点加载用时:%d秒,%d个\n", int(time.Now().Unix())-start, len(SiteMap))
  117. }
  118. func main() {
  119. go checkMapJob()
  120. updport := Sysconfig["udpport"].(string)
  121. udpclient = mu.UdpClient{Local: updport, BufSize: 1024}
  122. udpclient.Listen(processUdpMsg)
  123. log.Println("Udp服务监听", updport)
  124. if TimingTask {
  125. log.Println("正常历史部署")
  126. go historyTaskDay()
  127. }else {
  128. if gtept!=""&&ltept!="" {
  129. log.Println("全量判重-准备开始")
  130. IsFull = true //全量判重
  131. sid := "1fffffffffffffffffffffff"
  132. eid := "9fffffffffffffffffffffff"
  133. mapinfo := map[string]interface{}{}
  134. if sid == "" || eid == "" {
  135. log.Println("sid,eid参数不能为空")
  136. os.Exit(0)
  137. }
  138. mapinfo["gtid"] = sid
  139. mapinfo["lteid"] = eid
  140. mapinfo["stop"] = "true"
  141. task([]byte{}, mapinfo)
  142. time.Sleep(99999 * time.Hour)
  143. }else {
  144. //正常增量
  145. log.Println("正常增量部署")
  146. }
  147. }
  148. time.Sleep(99999 * time.Hour)
  149. }
  150. //测试组人员使用
  151. func mainT() {
  152. if TimingTask {
  153. go historyTaskDay()
  154. time.Sleep(99999 * time.Hour)
  155. } else {
  156. IsFull = true //全量判重
  157. sid := "1fffffffffffffffffffffff"
  158. eid := "9fffffffffffffffffffffff"
  159. mapinfo := map[string]interface{}{}
  160. if sid == "" || eid == "" {
  161. log.Println("sid,eid参数不能为空")
  162. os.Exit(0)
  163. }
  164. mapinfo["gtid"] = sid
  165. mapinfo["lteid"] = eid
  166. mapinfo["stop"] = "true"
  167. log.Println("测试:全量判重-准备开始")
  168. task([]byte{}, mapinfo)
  169. time.Sleep(99999 * time.Hour)
  170. }
  171. }
  172. //upd接收
  173. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  174. fmt.Println("接受的段数据")
  175. switch act {
  176. case mu.OP_TYPE_DATA: //上个节点的数据
  177. //从表中开始处理
  178. var mapInfo map[string]interface{}
  179. err := json.Unmarshal(data, &mapInfo)
  180. log.Println("err:", err, "mapInfo:", mapInfo)
  181. if err != nil {
  182. udpclient.WriteUdp([]byte("err:"+err.Error()), mu.OP_NOOP, ra)
  183. } else if mapInfo != nil {
  184. go task(data, mapInfo)
  185. key, _ := mapInfo["key"].(string)
  186. if key == "" {
  187. key = "udpok"
  188. }
  189. udpclient.WriteUdp([]byte(key), mu.OP_NOOP, ra)
  190. }
  191. case mu.OP_NOOP: //下个节点回应
  192. ok := string(data)
  193. if ok != "" {
  194. log.Println("ok:", ok)
  195. udptaskmap.Delete(ok)
  196. }
  197. }
  198. }
  199. //开始判重程序
  200. func task(data []byte, mapInfo map[string]interface{}) {
  201. log.Println("开始数据判重")
  202. defer util.Catch()
  203. //区间id
  204. q := map[string]interface{}{
  205. "_id": map[string]interface{}{
  206. "$gt": StringTOBsonId(mapInfo["gtid"].(string)),
  207. "$lte": StringTOBsonId(mapInfo["lteid"].(string)),
  208. },
  209. }
  210. //全量
  211. if IsFull && gtept!="" && ltept!=""{
  212. log.Println("执行全量分段模式")
  213. log.Println(gtept,"---",ltept)
  214. q = map[string]interface{}{
  215. "publishtime": map[string]interface{}{
  216. "$gte": util.Int64All(gtept),
  217. "$lte": util.Int64All(ltept),
  218. },
  219. }
  220. }
  221. log.Println("查询条件:",mgo.DbName, extract, q)
  222. sess := mgo.GetMgoConn()
  223. defer mgo.DestoryMongoConn(sess)
  224. it := sess.DB(mgo.DbName).C(extract).Find(&q).Sort("publishtime").Iter()
  225. pool := make(chan bool, threadNum)
  226. wg := &sync.WaitGroup{}
  227. n, repeateN := 0, 0
  228. for tmp := make(map[string]interface{}); it.Next(&tmp); n++ {
  229. if n%1000 == 0 {
  230. log.Println("current:", n, tmp["_id"],tmp["publishtime"], "repeateN:", repeateN)
  231. }
  232. if util.IntAll(tmp["repeat"]) == 1 {
  233. repeateN++
  234. tmp = make(map[string]interface{})
  235. continue
  236. }
  237. if util.IntAll(tmp["dataging"]) == 1 && !IsFull{
  238. tmp = make(map[string]interface{})
  239. continue
  240. }
  241. pool <- true
  242. wg.Add(1)
  243. go func(tmp map[string]interface{}) {
  244. defer func() {
  245. <-pool
  246. wg.Done()
  247. }()
  248. info := NewInfo(tmp)
  249. //正常判重
  250. b, source, reason := DM.check(info)
  251. if b {
  252. repeateN++
  253. var updateID = map[string]interface{}{} //记录更新判重的
  254. updateID["_id"] = StringTOBsonId(info.id)
  255. repeat_ids:=source.repeat_ids
  256. repeat_ids = append(repeat_ids,info.id)
  257. source.repeat_ids = repeat_ids
  258. //替换数据池-更新
  259. DM.replacePoolData(source)
  260. Update.updatePool <- []map[string]interface{}{//原始数据打标签
  261. map[string]interface{}{
  262. "_id": StringTOBsonId(source.id),
  263. },
  264. map[string]interface{}{
  265. "$set": map[string]interface{}{
  266. "repeat_ids": repeat_ids,
  267. },
  268. },
  269. }
  270. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  271. updateID,
  272. map[string]interface{}{
  273. "$set": map[string]interface{}{
  274. "repeat": 1,
  275. "repeat_reason": reason,
  276. "repeat_id": source.id,
  277. "dataging": 0,
  278. },
  279. },
  280. }
  281. }
  282. }(tmp)
  283. tmp = make(map[string]interface{})
  284. }
  285. wg.Wait()
  286. log.Println("this task over.", n, "repeateN:", repeateN, mapInfo["stop"])
  287. log.Println("当前数据池的数量:",DM.currentTotalCount())
  288. //睡眠时间 增+
  289. time.Sleep(30 * time.Second)
  290. //更新Ocr的标记
  291. updateOcrFileData(mapInfo["lteid"].(string))
  292. //任务完成,开始发送广播通知下面节点
  293. if n >= repeateN && mapInfo["stop"] == nil {
  294. log.Println("判重任务完成发送udp")
  295. for _, to := range nextNode {
  296. sid, _ := mapInfo["gtid"].(string)
  297. eid, _ := mapInfo["lteid"].(string)
  298. key := sid + "-" + eid + "-" + util.ObjToString(to["stype"])
  299. by, _ := json.Marshal(map[string]interface{}{
  300. "gtid": sid,
  301. "lteid": eid,
  302. "stype": util.ObjToString(to["stype"]),
  303. "key": key,
  304. })
  305. addr := &net.UDPAddr{
  306. IP: net.ParseIP(to["addr"].(string)),
  307. Port: util.IntAll(to["port"]),
  308. }
  309. node := &udpNode{by, addr, time.Now().Unix(), 0}
  310. udptaskmap.Store(key, node)
  311. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  312. }
  313. }
  314. }
  315. func updateOcrFileData(cur_lteid string) {
  316. //更新ocr 分类表-判重的状态
  317. log.Println("开始更新Ocr表-标记",cur_lteid)
  318. task_sess := task_mgo.GetMgoConn()
  319. defer task_mgo.DestoryMongoConn(task_sess)
  320. q_task:=map[string]interface{}{}
  321. it_last := task_sess.DB(task_mgo.DbName).C(task_collName).Find(&q_task).Sort("-_id").Iter()
  322. isUpdateOcr:=false
  323. updateOcrFile:=[][]map[string]interface{}{}
  324. for tmp := make(map[string]interface{}); it_last.Next(&tmp); {
  325. cur_id := BsonTOStringId(tmp["_id"])
  326. lteid:=util.ObjToString(tmp["lteid"])
  327. if (lteid==cur_lteid) { //需要更新
  328. log.Println("找到该lteid数据",cur_lteid,cur_id)
  329. isUpdateOcr = true
  330. updateOcrFile = append(updateOcrFile, []map[string]interface{}{//重复数据打标签
  331. map[string]interface{}{
  332. "_id": tmp["_id"],
  333. },
  334. map[string]interface{}{
  335. "$set": map[string]interface{}{
  336. "is_repeat_status": 1,
  337. "is_repeat_time" : util.Int64All(time.Now().Unix()),
  338. },
  339. },
  340. })
  341. tmp = make(map[string]interface{})
  342. break
  343. }else {
  344. tmp = make(map[string]interface{})
  345. }
  346. }
  347. if !isUpdateOcr {
  348. log.Println("出现异常问题,查询不到ocr的lteid",cur_lteid)
  349. }else {
  350. if len(updateOcrFile) > 0 {
  351. task_mgo.UpSertBulk(task_collName, updateOcrFile...)
  352. }
  353. }
  354. }
  355. //历史判重
  356. func historyTaskDay() {
  357. defer util.Catch()
  358. for {
  359. start:=time.Now().Unix()
  360. if gtid=="" {
  361. log.Println("请传gtid,否则无法运行")
  362. os.Exit(0)
  363. return
  364. }
  365. if lteid!="" {
  366. //先进行数据迁移
  367. log.Println("开启一次迁移任务",gtid,lteid)
  368. moveHistoryData(gtid,lteid)
  369. gtid = lteid //替换数据
  370. }
  371. //查询表最后一个id
  372. task_sess := task_mgo.GetMgoConn()
  373. defer task_mgo.DestoryMongoConn(task_sess)
  374. q:=map[string]interface{}{}
  375. between_time := time.Now().Unix() - (86400 * timingPubScope)//两年周期
  376. it_last := task_sess.DB(task_mgo.DbName).C(task_collName).Find(&q).Sort("-_id").Iter()
  377. isRepeatStatus:=false
  378. for tmp := make(map[string]interface{}); it_last.Next(&tmp); {
  379. is_repeat_status:=util.IntAll(tmp["is_repeat_status"])
  380. if is_repeat_status == 1 {
  381. lteid = util.ObjToString(tmp["lteid"])
  382. log.Println("查询的最后一个已标记的任务lteid:",lteid)
  383. isRepeatStatus = true
  384. tmp = make(map[string]interface{})
  385. break
  386. }else {
  387. tmp = make(map[string]interface{})
  388. }
  389. }
  390. if !isRepeatStatus {
  391. log.Println("查询不到有标记的lteid数据")
  392. log.Println("睡眠5分钟 gtid:",gtid,"lteid:",lteid)
  393. time.Sleep(5 * time.Minute)
  394. continue
  395. }
  396. log.Println("查询完毕-找到有标记的lteid-先睡眠5分钟",gtid,lteid)
  397. time.Sleep(5 * time.Minute)
  398. sess := mgo.GetMgoConn()//连接器
  399. defer mgo.DestoryMongoConn(sess)
  400. //开始判重
  401. q = map[string]interface{}{
  402. "_id": map[string]interface{}{
  403. "$gt": StringTOBsonId(gtid),
  404. "$lte": StringTOBsonId(lteid),
  405. },
  406. }
  407. log.Println("历史判重查询条件:",q,"时间:", between_time)
  408. it := sess.DB(mgo.DbName).C(extract).Find(&q).Sort("publishtime").Iter()
  409. num,oknum,outnum, deterTime:= int64(0),int64(0),int64(0),int64(0) //计数
  410. pendAllArr:=[][]map[string]interface{}{}//待处理数组
  411. dayArr := []map[string]interface{}{}
  412. for tmp := make(map[string]interface{}); it.Next(&tmp); num++ {
  413. if num%10000 == 0 {
  414. log.Println("正序遍历:", num)
  415. }
  416. //取-符合-发布时间X年内的数据
  417. if util.IntAll(tmp["dataging"]) == 1 {
  418. pubtime := util.Int64All(tmp["publishtime"])
  419. if pubtime > 0 && pubtime >= between_time {
  420. oknum++
  421. if deterTime==0 {
  422. log.Println("找到第一条符合条件的数据")
  423. deterTime = util.Int64All(tmp["publishtime"])
  424. dayArr = append(dayArr,tmp)
  425. }else {
  426. if pubtime-deterTime >timingSpanDay*86400 {
  427. //新数组重新构建,当前组数据加到全部组数据
  428. pendAllArr = append(pendAllArr,dayArr)
  429. dayArr = []map[string]interface{}{}
  430. deterTime = util.Int64All(tmp["publishtime"])
  431. dayArr = append(dayArr,tmp)
  432. }else {
  433. dayArr = append(dayArr,tmp)
  434. }
  435. }
  436. }else {
  437. outnum++
  438. //不在两年内的也清标记
  439. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  440. map[string]interface{}{
  441. "_id": tmp["_id"],
  442. },
  443. map[string]interface{}{
  444. "$set": map[string]interface{}{
  445. "dataging": 0,
  446. "history_updatetime":util.Int64All(time.Now().Unix()),
  447. },
  448. },
  449. }
  450. }
  451. }
  452. tmp = make(map[string]interface{})
  453. }
  454. if len(dayArr)>0 {
  455. pendAllArr = append(pendAllArr,dayArr)
  456. dayArr = []map[string]interface{}{}
  457. }
  458. log.Println("查询数量:",num,"符合条件:",oknum,"未在两年内:",outnum)
  459. if len(pendAllArr) <= 0 {
  460. log.Println("没找到dataging==1的数据")
  461. }
  462. //测试分组数量是否正确
  463. testNum:=0
  464. for k,v:=range pendAllArr {
  465. log.Println("第",k,"组--","数量:",len(v))
  466. testNum = testNum+len(v)
  467. }
  468. log.Println("本地构建分组完成:",len(pendAllArr),"组","测试-总计数量:",testNum)
  469. n, repeateN := 0, 0
  470. log.Println("线程数:",threadNum)
  471. pool := make(chan bool, threadNum)
  472. wg := &sync.WaitGroup{}
  473. for k,v:=range pendAllArr { //每组结束更新一波数据
  474. pool <- true
  475. wg.Add(1)
  476. go func(k int, v []map[string]interface{}) {
  477. defer func() {
  478. <-pool
  479. wg.Done()
  480. }()
  481. //相关ids 跨表
  482. groupOtherExtract := [][]map[string]interface{}{}
  483. //构建当前组的数据池
  484. log.Println("构建第", k, "组---(数据池)")
  485. //当前组的第一个发布时间
  486. first_pt := util.Int64All(v[len(v)-1]["publishtime"])
  487. curTM := TimedTaskDatamap(dupdays+int(timingSpanDay)+1, first_pt+86400, int(k))
  488. log.Println("开始遍历判重第", k, "组 共计数量:", len(v))
  489. n = n + len(v)
  490. log.Println("统计目前总数量:", n, "重复数量:", repeateN)
  491. for _, tmp := range v {
  492. info := NewInfo(tmp)
  493. b, source, reason := curTM.check(info)
  494. if b { //有重复,生成更新语句,更新抽取和更新招标
  495. repeateN++
  496. //重复数据打标签
  497. repeat_ids:=source.repeat_ids
  498. repeat_ids = append(repeat_ids,info.id)
  499. source.repeat_ids = repeat_ids
  500. updatelock.Lock()
  501. //替换数据池-更新
  502. DM.replacePoolData(source)
  503. //更新数据源
  504. //判断是否在当前段落
  505. if judgeIsCurIds(gtid,lteid,source.id) {
  506. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  507. map[string]interface{}{
  508. "_id": StringTOBsonId(source.id),
  509. },
  510. map[string]interface{}{
  511. "$set": map[string]interface{}{
  512. "repeat_ids": repeat_ids,
  513. },
  514. },
  515. }
  516. }else {
  517. groupOtherExtract = append(groupOtherExtract, []map[string]interface{}{//重复数据打标签
  518. map[string]interface{}{
  519. "_id": StringTOBsonId(source.id),
  520. },
  521. map[string]interface{}{
  522. "$set": map[string]interface{}{
  523. "repeat_ids": repeat_ids,
  524. },
  525. },
  526. })
  527. }
  528. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  529. map[string]interface{}{
  530. "_id": tmp["_id"],
  531. },
  532. map[string]interface{}{
  533. "$set": map[string]interface{}{
  534. "repeat": 1,
  535. "repeat_reason": reason,
  536. "repeat_id": source.id,
  537. "dataging": 0,
  538. "history_updatetime":util.Int64All(time.Now().Unix()),
  539. },
  540. },
  541. }
  542. if len(groupOtherExtract) >= 500 {
  543. mgo.UpSertBulk(extract_back, groupOtherExtract...)
  544. groupOtherExtract = [][]map[string]interface{}{}
  545. }
  546. updatelock.Unlock()
  547. } else {
  548. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  549. map[string]interface{}{
  550. "_id": tmp["_id"],
  551. },
  552. map[string]interface{}{
  553. "$set": map[string]interface{}{
  554. "dataging": 0, //符合条件的都为dataging==0
  555. "history_updatetime":util.Int64All(time.Now().Unix()),
  556. },
  557. },
  558. }
  559. }
  560. }
  561. //每组数据结束-更新数据
  562. updatelock.Lock()
  563. if len(groupOtherExtract) > 0 {
  564. mgo.UpSertBulk(extract_back, groupOtherExtract...)
  565. }
  566. updatelock.Unlock()
  567. }(k, v)
  568. }
  569. wg.Wait()
  570. log.Println("this timeTask over.", n, "repeateN:", repeateN,gtid,lteid)
  571. time.Sleep(30 * time.Second)
  572. //任务完成,开始发送广播通知下面节点 发udp 去升索引待定 + 合并
  573. if n >= repeateN && gtid!=lteid{
  574. for _, to := range nextNode {
  575. next_sid := util.BsonIdToSId(gtid)
  576. next_eid := util.BsonIdToSId(lteid)
  577. key := next_sid + "-" + next_eid + "-" + util.ObjToString(to["stype"])
  578. by, _ := json.Marshal(map[string]interface{}{
  579. "gtid": next_sid,
  580. "lteid": next_eid,
  581. "stype": util.ObjToString(to["stype"]),
  582. "key": key,
  583. })
  584. addr := &net.UDPAddr{
  585. IP: net.ParseIP(to["addr"].(string)),
  586. Port: util.IntAll(to["port"]),
  587. }
  588. node := &udpNode{by, addr, time.Now().Unix(), 0}
  589. udptaskmap.Store(key, node)
  590. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  591. }
  592. }
  593. end:=time.Now().Unix()
  594. log.Println(gtid,lteid)
  595. if end-start<60*5 {
  596. log.Println("睡眠.............")
  597. time.Sleep(5 * time.Minute)
  598. }
  599. log.Println("继续下一段的历史判重")
  600. }
  601. }
  602. //判断是否在当前id段落
  603. func judgeIsCurIds (gtid string,lteid string,curid string) bool {
  604. gt_time, _ := strconv.ParseInt(gtid[:8], 16, 64)
  605. lte_time, _ := strconv.ParseInt(lteid[:8], 16, 64)
  606. cur_time, _ := strconv.ParseInt(curid[:8], 16, 64)
  607. if cur_time>=gt_time&&cur_time<=lte_time {
  608. return true
  609. }
  610. return false
  611. }
  612. //迁移上一段数据
  613. func moveHistoryData(startid string,endid string) {
  614. sess := mgo.GetMgoConn()
  615. defer mgo.DestoryMongoConn(sess)
  616. year, month, day := time.Now().Date()
  617. q := map[string]interface{}{
  618. "_id": map[string]interface{}{
  619. "$gt": StringTOBsonId(startid),
  620. "$lte": StringTOBsonId(endid),
  621. },
  622. }
  623. log.Println(q)
  624. it := sess.DB(mgo.DbName).C(extract).Find(&q).Iter()
  625. index := 0
  626. for tmp := make(map[string]interface{}); it.Next(&tmp); index++ {
  627. mgo.Save(extract_back, tmp)
  628. tmp = map[string]interface{}{}
  629. if index%1000 == 0 {
  630. log.Println("index", index)
  631. }
  632. }
  633. log.Println("save to", extract_back, " ok index", index)
  634. qv := map[string]interface{}{
  635. "comeintime": map[string]interface{}{
  636. "$lt": time.Date(year, month, day, 0, 0, 0, 0, time.Local).Add(-time.Duration(dupdays+1) * 24 * time.Hour*2).Unix(),
  637. },
  638. }
  639. delnum := mgo.Delete(extract, qv)
  640. log.Println("remove from ", extract, delnum)
  641. }
  642. func moveTimeoutData() {
  643. log.Println("部署迁移定时任务")
  644. c := cron.New()
  645. c.AddFunc("0 0 0 * * ?", func() { moveOnceTimeOut() })
  646. c.Start()
  647. }
  648. func moveOnceTimeOut() {
  649. log.Println("执行一次迁移超时数据")
  650. sess := mgo.GetMgoConn()
  651. defer mgo.DestoryMongoConn(sess)
  652. now:=time.Now()
  653. move_time := time.Date(now.Year()-2, now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
  654. task_id := util.BsonIdToSId(bson.NewObjectIdWithTime(move_time))
  655. q := map[string]interface{}{
  656. "_id": map[string]interface{}{
  657. "$lt": StringTOBsonId(task_id),
  658. },
  659. }
  660. it := sess.DB(mgo.DbName).C("result_20200714").Find(&q).Iter()
  661. index := 0
  662. for tmp := make(map[string]interface{}); it.Next(&tmp); index++ {
  663. if index%10000 == 0 {
  664. log.Println("index", index)
  665. }
  666. del_id:=BsonTOStringId(tmp["_id"])
  667. mgo.Save("result_20200713", tmp)
  668. mgo.DeleteById("result_20200714",del_id)
  669. tmp = map[string]interface{}{}
  670. }
  671. log.Println("save and delete", " ok index", index)
  672. }