main.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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 mainT() {
  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 main() {
  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. time.Sleep(30 * time.Second)
  289. //更新Ocr的标记
  290. updateOcrFileData(mapInfo["lteid"].(string))
  291. //任务完成,开始发送广播通知下面节点
  292. if n >= repeateN && mapInfo["stop"] == nil {
  293. log.Println("判重任务完成发送udp")
  294. for _, to := range nextNode {
  295. sid, _ := mapInfo["gtid"].(string)
  296. eid, _ := mapInfo["lteid"].(string)
  297. key := sid + "-" + eid + "-" + util.ObjToString(to["stype"])
  298. by, _ := json.Marshal(map[string]interface{}{
  299. "gtid": sid,
  300. "lteid": eid,
  301. "stype": util.ObjToString(to["stype"]),
  302. "key": key,
  303. })
  304. addr := &net.UDPAddr{
  305. IP: net.ParseIP(to["addr"].(string)),
  306. Port: util.IntAll(to["port"]),
  307. }
  308. node := &udpNode{by, addr, time.Now().Unix(), 0}
  309. udptaskmap.Store(key, node)
  310. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  311. }
  312. }
  313. }
  314. func updateOcrFileData(cur_lteid string) {
  315. //更新ocr 分类表-判重的状态
  316. log.Println("开始更新Ocr表-标记",cur_lteid)
  317. task_sess := task_mgo.GetMgoConn()
  318. defer task_mgo.DestoryMongoConn(task_sess)
  319. q_task:=map[string]interface{}{}
  320. it_last := task_sess.DB(task_mgo.DbName).C(task_collName).Find(&q_task).Sort("-_id").Iter()
  321. isUpdateOcr:=false
  322. updateOcrFile:=[][]map[string]interface{}{}
  323. for tmp := make(map[string]interface{}); it_last.Next(&tmp); {
  324. cur_id := BsonTOStringId(tmp["_id"])
  325. lteid:=util.ObjToString(tmp["lteid"])
  326. if (lteid==cur_lteid) { //需要更新
  327. log.Println("找到该lteid数据",cur_lteid,cur_id)
  328. isUpdateOcr = true
  329. updateOcrFile = append(updateOcrFile, []map[string]interface{}{//重复数据打标签
  330. map[string]interface{}{
  331. "_id": tmp["_id"],
  332. },
  333. map[string]interface{}{
  334. "$set": map[string]interface{}{
  335. "is_repeat_status": 1,
  336. "is_repeat_time" : util.Int64All(time.Now().Unix()),
  337. },
  338. },
  339. })
  340. tmp = make(map[string]interface{})
  341. break
  342. }else {
  343. tmp = make(map[string]interface{})
  344. }
  345. }
  346. if !isUpdateOcr {
  347. log.Println("出现异常问题,查询不到ocr的lteid",cur_lteid)
  348. }else {
  349. if len(updateOcrFile) > 0 {
  350. task_mgo.UpSertBulk(task_collName, updateOcrFile...)
  351. }
  352. }
  353. }
  354. //历史判重
  355. func historyTaskDay() {
  356. defer util.Catch()
  357. for {
  358. start:=time.Now().Unix()
  359. if gtid=="" {
  360. log.Println("请传gtid,否则无法运行")
  361. os.Exit(0)
  362. return
  363. }
  364. if lteid!="" {
  365. //先进行数据迁移
  366. log.Println("开启一次迁移任务",gtid,lteid)
  367. moveHistoryData(gtid,lteid)
  368. gtid = lteid //替换数据
  369. }
  370. //查询表最后一个id
  371. task_sess := task_mgo.GetMgoConn()
  372. defer task_mgo.DestoryMongoConn(task_sess)
  373. q:=map[string]interface{}{}
  374. between_time := time.Now().Unix() - (86400 * timingPubScope)//两年周期
  375. it_last := task_sess.DB(task_mgo.DbName).C(task_collName).Find(&q).Sort("-_id").Iter()
  376. isRepeatStatus:=false
  377. for tmp := make(map[string]interface{}); it_last.Next(&tmp); {
  378. is_repeat_status:=util.IntAll(tmp["is_repeat_status"])
  379. if is_repeat_status == 1 {
  380. lteid = util.ObjToString(tmp["lteid"])
  381. log.Println("查询的最后一个已标记的任务lteid:",lteid)
  382. isRepeatStatus = true
  383. tmp = make(map[string]interface{})
  384. break
  385. }else {
  386. tmp = make(map[string]interface{})
  387. }
  388. }
  389. if !isRepeatStatus {
  390. log.Println("查询不到有标记的lteid数据")
  391. log.Println("睡眠5分钟 gtid:",gtid,"lteid:",lteid)
  392. time.Sleep(5 * time.Minute)
  393. continue
  394. }
  395. log.Println("查询完毕-找到有标记的lteid-先睡眠5分钟",gtid,lteid)
  396. time.Sleep(5 * time.Minute)
  397. sess := mgo.GetMgoConn()//连接器
  398. defer mgo.DestoryMongoConn(sess)
  399. //开始判重
  400. q = map[string]interface{}{
  401. "_id": map[string]interface{}{
  402. "$gt": StringTOBsonId(gtid),
  403. "$lte": StringTOBsonId(lteid),
  404. },
  405. }
  406. log.Println("历史判重查询条件:",q,"时间:", between_time)
  407. it := sess.DB(mgo.DbName).C(extract).Find(&q).Sort("publishtime").Iter()
  408. num,oknum,outnum, deterTime:= int64(0),int64(0),int64(0),int64(0) //计数
  409. pendAllArr:=[][]map[string]interface{}{}//待处理数组
  410. dayArr := []map[string]interface{}{}
  411. for tmp := make(map[string]interface{}); it.Next(&tmp); num++ {
  412. if num%10000 == 0 {
  413. log.Println("正序遍历:", num)
  414. }
  415. //取-符合-发布时间X年内的数据
  416. if util.IntAll(tmp["dataging"]) == 1 {
  417. pubtime := util.Int64All(tmp["publishtime"])
  418. if pubtime > 0 && pubtime >= between_time {
  419. oknum++
  420. if deterTime==0 {
  421. log.Println("找到第一条符合条件的数据")
  422. deterTime = util.Int64All(tmp["publishtime"])
  423. dayArr = append(dayArr,tmp)
  424. }else {
  425. if pubtime-deterTime >timingSpanDay*86400 {
  426. //新数组重新构建,当前组数据加到全部组数据
  427. pendAllArr = append(pendAllArr,dayArr)
  428. dayArr = []map[string]interface{}{}
  429. deterTime = util.Int64All(tmp["publishtime"])
  430. dayArr = append(dayArr,tmp)
  431. }else {
  432. dayArr = append(dayArr,tmp)
  433. }
  434. }
  435. }else {
  436. outnum++
  437. //不在两年内的也清标记
  438. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  439. map[string]interface{}{
  440. "_id": tmp["_id"],
  441. },
  442. map[string]interface{}{
  443. "$set": map[string]interface{}{
  444. "dataging": 0,
  445. "history_updatetime":util.Int64All(time.Now().Unix()),
  446. },
  447. },
  448. }
  449. }
  450. }
  451. tmp = make(map[string]interface{})
  452. }
  453. if len(dayArr)>0 {
  454. pendAllArr = append(pendAllArr,dayArr)
  455. dayArr = []map[string]interface{}{}
  456. }
  457. log.Println("查询数量:",num,"符合条件:",oknum,"未在两年内:",outnum)
  458. if len(pendAllArr) <= 0 {
  459. log.Println("没找到dataging==1的数据")
  460. }
  461. //测试分组数量是否正确
  462. testNum:=0
  463. for k,v:=range pendAllArr {
  464. log.Println("第",k,"组--","数量:",len(v))
  465. testNum = testNum+len(v)
  466. }
  467. log.Println("本地构建分组完成:",len(pendAllArr),"组","测试-总计数量:",testNum)
  468. n, repeateN := 0, 0
  469. log.Println("线程数:",threadNum)
  470. pool := make(chan bool, threadNum)
  471. wg := &sync.WaitGroup{}
  472. for k,v:=range pendAllArr { //每组结束更新一波数据
  473. pool <- true
  474. wg.Add(1)
  475. go func(k int, v []map[string]interface{}) {
  476. defer func() {
  477. <-pool
  478. wg.Done()
  479. }()
  480. //相关ids 跨表
  481. groupOtherExtract := [][]map[string]interface{}{}
  482. //构建当前组的数据池
  483. log.Println("构建第", k, "组---(数据池)")
  484. //当前组的第一个发布时间
  485. first_pt := util.Int64All(v[len(v)-1]["publishtime"])
  486. curTM := TimedTaskDatamap(dupdays+int(timingSpanDay)+1, first_pt+86400, int(k))
  487. log.Println("开始遍历判重第", k, "组 共计数量:", len(v))
  488. n = n + len(v)
  489. log.Println("统计目前总数量:", n, "重复数量:", repeateN)
  490. for _, tmp := range v {
  491. info := NewInfo(tmp)
  492. b, source, reason := curTM.check(info)
  493. if b { //有重复,生成更新语句,更新抽取和更新招标
  494. repeateN++
  495. //重复数据打标签
  496. repeat_ids:=source.repeat_ids
  497. repeat_ids = append(repeat_ids,info.id)
  498. source.repeat_ids = repeat_ids
  499. updatelock.Lock()
  500. //替换数据池-更新
  501. DM.replacePoolData(source)
  502. //更新数据源
  503. //判断是否在当前段落
  504. if judgeIsCurIds(gtid,lteid,source.id) {
  505. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  506. map[string]interface{}{
  507. "_id": StringTOBsonId(source.id),
  508. },
  509. map[string]interface{}{
  510. "$set": map[string]interface{}{
  511. "repeat_ids": repeat_ids,
  512. },
  513. },
  514. }
  515. }else {
  516. groupOtherExtract = append(groupOtherExtract, []map[string]interface{}{//重复数据打标签
  517. map[string]interface{}{
  518. "_id": StringTOBsonId(source.id),
  519. },
  520. map[string]interface{}{
  521. "$set": map[string]interface{}{
  522. "repeat_ids": repeat_ids,
  523. },
  524. },
  525. })
  526. }
  527. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  528. map[string]interface{}{
  529. "_id": tmp["_id"],
  530. },
  531. map[string]interface{}{
  532. "$set": map[string]interface{}{
  533. "repeat": 1,
  534. "repeat_reason": reason,
  535. "repeat_id": source.id,
  536. "dataging": 0,
  537. "history_updatetime":util.Int64All(time.Now().Unix()),
  538. },
  539. },
  540. }
  541. if len(groupOtherExtract) >= 500 {
  542. mgo.UpSertBulk(extract_back, groupOtherExtract...)
  543. groupOtherExtract = [][]map[string]interface{}{}
  544. }
  545. updatelock.Unlock()
  546. } else {
  547. Update.updatePool <- []map[string]interface{}{//重复数据打标签
  548. map[string]interface{}{
  549. "_id": tmp["_id"],
  550. },
  551. map[string]interface{}{
  552. "$set": map[string]interface{}{
  553. "dataging": 0, //符合条件的都为dataging==0
  554. "history_updatetime":util.Int64All(time.Now().Unix()),
  555. },
  556. },
  557. }
  558. }
  559. }
  560. //每组数据结束-更新数据
  561. updatelock.Lock()
  562. if len(groupOtherExtract) > 0 {
  563. mgo.UpSertBulk(extract_back, groupOtherExtract...)
  564. }
  565. updatelock.Unlock()
  566. }(k, v)
  567. }
  568. wg.Wait()
  569. log.Println("this timeTask over.", n, "repeateN:", repeateN,gtid,lteid)
  570. time.Sleep(30 * time.Second)
  571. //任务完成,开始发送广播通知下面节点 发udp 去升索引待定 + 合并
  572. if n >= repeateN && gtid!=lteid{
  573. for _, to := range nextNode {
  574. next_sid := util.BsonIdToSId(gtid)
  575. next_eid := util.BsonIdToSId(lteid)
  576. key := next_sid + "-" + next_eid + "-" + util.ObjToString(to["stype"])
  577. by, _ := json.Marshal(map[string]interface{}{
  578. "gtid": next_sid,
  579. "lteid": next_eid,
  580. "stype": util.ObjToString(to["stype"]),
  581. "key": key,
  582. })
  583. addr := &net.UDPAddr{
  584. IP: net.ParseIP(to["addr"].(string)),
  585. Port: util.IntAll(to["port"]),
  586. }
  587. node := &udpNode{by, addr, time.Now().Unix(), 0}
  588. udptaskmap.Store(key, node)
  589. udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  590. }
  591. }
  592. end:=time.Now().Unix()
  593. log.Println(gtid,lteid)
  594. if end-start<60*5 {
  595. log.Println("睡眠.............")
  596. time.Sleep(5 * time.Minute)
  597. }
  598. log.Println("继续下一段的历史判重")
  599. }
  600. }
  601. //判断是否在当前id段落
  602. func judgeIsCurIds (gtid string,lteid string,curid string) bool {
  603. gt_time, _ := strconv.ParseInt(gtid[:8], 16, 64)
  604. lte_time, _ := strconv.ParseInt(lteid[:8], 16, 64)
  605. cur_time, _ := strconv.ParseInt(curid[:8], 16, 64)
  606. if cur_time>=gt_time&&cur_time<=lte_time {
  607. return true
  608. }
  609. return false
  610. }
  611. //迁移上一段数据
  612. func moveHistoryData(startid string,endid string) {
  613. sess := mgo.GetMgoConn()
  614. defer mgo.DestoryMongoConn(sess)
  615. year, month, day := time.Now().Date()
  616. q := map[string]interface{}{
  617. "_id": map[string]interface{}{
  618. "$gt": StringTOBsonId(startid),
  619. "$lte": StringTOBsonId(endid),
  620. },
  621. }
  622. log.Println(q)
  623. it := sess.DB(mgo.DbName).C(extract).Find(&q).Iter()
  624. index := 0
  625. for tmp := make(map[string]interface{}); it.Next(&tmp); index++ {
  626. mgo.Save(extract_back, tmp)
  627. tmp = map[string]interface{}{}
  628. if index%1000 == 0 {
  629. log.Println("index", index)
  630. }
  631. }
  632. log.Println("save to", extract_back, " ok index", index)
  633. qv := map[string]interface{}{
  634. "comeintime": map[string]interface{}{
  635. "$lt": time.Date(year, month, day, 0, 0, 0, 0, time.Local).Add(-time.Duration(dupdays+1) * 24 * time.Hour*2).Unix(),
  636. },
  637. }
  638. delnum := mgo.Delete(extract, qv)
  639. log.Println("remove from ", extract, delnum)
  640. }
  641. func moveTimeoutData() {
  642. log.Println("部署迁移定时任务")
  643. c := cron.New()
  644. c.AddFunc("0 0 0 * * ?", func() { moveOnceTimeOut() })
  645. c.Start()
  646. }
  647. func moveOnceTimeOut() {
  648. log.Println("执行一次迁移超时数据")
  649. sess := mgo.GetMgoConn()
  650. defer mgo.DestoryMongoConn(sess)
  651. now:=time.Now()
  652. move_time := time.Date(now.Year()-2, now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
  653. task_id := util.BsonIdToSId(bson.NewObjectIdWithTime(move_time))
  654. q := map[string]interface{}{
  655. "_id": map[string]interface{}{
  656. "$lt": StringTOBsonId(task_id),
  657. },
  658. }
  659. it := sess.DB(mgo.DbName).C("result_20200714").Find(&q).Iter()
  660. index := 0
  661. for tmp := make(map[string]interface{}); it.Next(&tmp); index++ {
  662. if index%10000 == 0 {
  663. log.Println("index", index)
  664. }
  665. del_id:=BsonTOStringId(tmp["_id"])
  666. mgo.Save("result_20200713", tmp)
  667. mgo.DeleteById("result_20200714",del_id)
  668. tmp = map[string]interface{}{}
  669. }
  670. log.Println("save and delete", " ok index", index)
  671. }