task.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747
  1. package task
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/csv"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "log"
  10. mu "mfw/util"
  11. "net"
  12. "net/http"
  13. "os"
  14. "qfw/util"
  15. "reflect"
  16. "regexp"
  17. "strconv"
  18. "strings"
  19. "sync"
  20. "time"
  21. "tools"
  22. u "util"
  23. "github.com/cron"
  24. "github.com/donnie4w/go-logger/logger"
  25. "go.mongodb.org/mongo-driver/bson"
  26. "go.mongodb.org/mongo-driver/bson/primitive"
  27. )
  28. func init() {
  29. REG, _ = regexp.Compile(`\(.*?\)\d*`)
  30. REG1, _ = regexp.Compile(`\(.*?\)`)
  31. //log.Println(REG.FindAllString("(平台|软件|电子商务|多媒体|通讯设备)1(建设|采购|开发)2", -1))
  32. //加载所有任务
  33. StartMonitor()
  34. if tools.NoAutoRun == 0 {
  35. rtask, b := tools.MgoClass.Find(tools.COLL_TASK, `{"i_status":1}`, nil, `{"_id":1}`, false, 0, 50)
  36. if b && rtask != nil && *rtask != nil {
  37. for _, t := range *rtask {
  38. _id := u.BsonIdToSId(t["_id"])
  39. res := tools.JSON{}
  40. //LoadTask(_id, &res)
  41. NewLoadTask(_id, &res)
  42. }
  43. }
  44. }
  45. }
  46. // var UdpSess *tools.MongodbSim
  47. var REG *regexp.Regexp
  48. var REG1 *regexp.Regexp
  49. var TaskLock = sync.Mutex{}
  50. var NEWTASKPOOL = map[string]*TTask{} //存储当前任务
  51. var TaskMap = map[string]*TTask{}
  52. var HangyeUdps = make(chan map[string]interface{}, 100) //初始化行业分类udp任务池
  53. type Rule struct {
  54. Reg []interface{} //规则
  55. DetailReg []interface{} //detail正则,目前只针对title、channel的二级招标分类中的中标规则
  56. NotReg []interface{} //排除规则
  57. Rid string
  58. Class *Class
  59. Rule_PreRule string
  60. S_name string
  61. S_code string
  62. S_pid string
  63. //Reg []*RuleDFA
  64. }
  65. type Class struct {
  66. Cid string
  67. TTask *TTask
  68. Rule []*Rule
  69. Class_PreRule string
  70. S_name string
  71. S_fields string
  72. S_code string
  73. S_default string
  74. S_pid string
  75. S_savefield string
  76. }
  77. type TTask struct {
  78. Class []*Class //任务中类集合
  79. ID string //任务id
  80. S_name string //任务名称
  81. I_rate int //任务执行频率
  82. S_class string //任务中类id
  83. S_mgourl string //任务mgo addr
  84. S_mgodb string //任务mgo db
  85. S_collection string //查询、存储表
  86. I_poolsize int //任务连接池个数
  87. S_startid string //任务起始id
  88. I_status int //控制任务状态属性
  89. S_attr string //标识属性key值
  90. AttrVal int //标识属性val值
  91. S_coll string //查询、存储表
  92. LastId string //上次定时任务的结束id
  93. Lock sync.Mutex
  94. S_query string //任务查询条件
  95. FlagQuit chan bool //任务结束控制
  96. B_Running bool //任务是否执行
  97. MgoTask *u.MongodbSim //任务查询表mgo
  98. I_multiclass int //是否支持多分类
  99. I_savetype int //1 名称 2 值
  100. I_thread int //线程数
  101. I_wordcount int //词频统计
  102. WordCount map[string]map[string]int //词频统计集合
  103. WcLock sync.Mutex
  104. Task_PreRule string //任务前置过滤
  105. S_table string //结果表
  106. S_querycon string //查询方式 1是id查询 0是时间查询
  107. S_starttime int64 //起始时间
  108. S_timefieldname string //各表所查时间字段名称
  109. S_asfield string //查询表与结果表关联字段
  110. I_fieldUpdate int //分类中的保存字段信息 0:覆盖 1:更新
  111. MulMgo *u.MongodbSim //联合查询的mgo配置信息
  112. MulColl string //联合查询的表名
  113. I_tasktype int //任务类型 0:常规任务 1:附件任务:2
  114. S_idcoll string //正式环境查询数据id段
  115. B_UpdateRule bool //是否更新任务下的规则
  116. S_classField string //分类字段
  117. Task_QueryFieldArr []string //用于合并数据
  118. Task_QueryFieldMap map[string]interface{} //用于仅查询字段
  119. Dbtype string //用于区分连得是哪个库,使用不同的用户密码
  120. }
  121. type RuleDFA struct {
  122. Match []DFA //包含的敏感词
  123. MatchNum []int //包含敏感词匹配个数
  124. MisMatch DFA //不包含的敏感词
  125. MisMatchNum int //不包含敏感词匹配个数
  126. }
  127. type DFA struct {
  128. Link map[string]interface{}
  129. }
  130. // 初始化任务
  131. func InitTaskData(_id string) {
  132. defer tools.Catch()
  133. taskData, _ := tools.MgoClass.FindById(tools.COLL_TASK, _id, nil)
  134. task := &TTask{}
  135. task.MgoTask = &u.MongodbSim{}
  136. s_querycon := "1"
  137. s_table := ""
  138. s_timefieldname := ""
  139. s_starttime := int64(0)
  140. s_asfield := ""
  141. if b_updaterule, ok := (*taskData)["b_updaterule"].(bool); ok {
  142. task.B_UpdateRule = b_updaterule //更新任务下的规则
  143. }
  144. if (*taskData)["s_querycon"] != nil { //
  145. s_querycon = util.ObjToString((*taskData)["s_querycon"])
  146. }
  147. if (*taskData)["s_starttime"] != nil {
  148. s_starttime = (*taskData)["s_starttime"].(int64)
  149. }
  150. if (*taskData)["s_table"] != nil {
  151. s_table = util.ObjToString((*taskData)["s_table"])
  152. }
  153. if (*taskData)["s_timefieldname"] != nil {
  154. s_timefieldname = util.ObjToString((*taskData)["s_timefieldname"])
  155. }
  156. if (*taskData)["s_asfield"] != nil {
  157. s_asfield = util.ObjToString((*taskData)["s_asfield"])
  158. }
  159. //task.Class
  160. task.ID = u.BsonIdToSId((*taskData)["_id"])
  161. task.S_name = util.ObjToString((*taskData)["s_name"])
  162. task.S_class = util.ObjToString((*taskData)["s_class"])
  163. task.S_mgourl = util.ObjToString((*taskData)["s_mgourl"])
  164. task.S_mgodb = util.ObjToString((*taskData)["s_mgodb"])
  165. task.S_coll = util.ObjToString((*taskData)["s_coll"])
  166. task.I_poolsize = util.IntAll((*taskData)["i_poolsize"])
  167. task.Task_PreRule = util.ObjToString((*taskData)["s_task_prerule"])
  168. task.I_multiclass = util.IntAllDef((*taskData)["i_multiclass"], 0)
  169. task.I_wordcount = util.IntAllDef((*taskData)["i_wordcount"], 0)
  170. task.I_savetype = util.IntAllDef((*taskData)["i_savetype"], 1)
  171. task.I_thread = util.IntAllDef((*taskData)["i_thread"], 1)
  172. task.S_query = util.ObjToString((*taskData)["s_query"])
  173. task.S_startid = util.ObjToString((*taskData)["s_startid"])
  174. task.S_attr = util.ObjToString((*taskData)["s_attr"])
  175. task.I_rate = util.IntAllDef((*taskData)["i_rate"], 10)
  176. task.I_tasktype = util.IntAllDef((*taskData)["i_tasktype"], 0)
  177. task.I_status = util.IntAll((*taskData)["i_status"])
  178. task.S_idcoll = util.ObjToString((*taskData)["s_idcoll"])
  179. task.S_querycon = s_querycon
  180. task.S_starttime = s_starttime
  181. task.S_table = s_table
  182. task.S_timefieldname = s_timefieldname
  183. task.S_asfield = s_asfield
  184. task.I_fieldUpdate = util.IntAllDef((*taskData)["i_fieldUpdate"], 0)
  185. task.S_classField = util.ObjToString((*taskData)["s_classfield"])
  186. task.Dbtype = util.ObjToString((*taskData)["s_dbtype"])
  187. flagAttrVal := 1
  188. attrs := strings.Split(task.S_attr, "__")
  189. if len(attrs) == 2 {
  190. flagAttrVal = util.IntAll(attrs[1])
  191. task.S_attr = attrs[0]
  192. }
  193. task.AttrVal = flagAttrVal
  194. //联表查询初始化mgo,线上只有行业分类用到;跑历史招标、行业分类的时候也用到两边查询
  195. for _, v := range tools.Config {
  196. if m, ok := v.(map[string]interface{}); ok {
  197. if m["taskid"] == task.ID {
  198. if m["mgoaddr"] != nil && m["db"] != nil && m["coll"] != nil {
  199. dbtype := util.ObjToString(m["dbtype"])
  200. addr, _ := m["mgoaddr"].(string)
  201. db, _ := m["db"].(string)
  202. coll, _ := m["coll"].(string)
  203. task.MulMgo = &u.MongodbSim{}
  204. task.MulMgo.MongodbAddr = addr
  205. task.MulMgo.Size = 3
  206. task.MulMgo.DbName = db
  207. if dbtype != "" {
  208. task.MulMgo.UserName = tools.DbInfo[dbtype][0]
  209. task.MulMgo.Password = tools.DbInfo[dbtype][1]
  210. }
  211. task.MulMgo.InitPool()
  212. task.MulColl = coll
  213. }
  214. }
  215. }
  216. }
  217. //初始化查询字段信息
  218. if task.Task_QueryFieldMap == nil {
  219. task.Task_QueryFieldMap = make(map[string]interface{})
  220. }
  221. //Task_QueryFieldMap加入关联字段
  222. for _, v := range strings.Split(s_asfield, "==") {
  223. if v != "" {
  224. task.Task_QueryFieldMap[v] = 1
  225. }
  226. }
  227. //Task_QueryFieldMap加入分类字段
  228. //Task_QueryFieldArr加入分类字段
  229. for _, f := range strings.Split(task.S_classField, ",") {
  230. task.Task_QueryFieldMap[f] = 1
  231. task.Task_QueryFieldArr = append(task.Task_QueryFieldArr, f)
  232. }
  233. //初始化任务下所有的分类和规则
  234. InitClassAndRuleData(_id, task)
  235. }
  236. // InitClassAndRuleData 初始化任务下所有的分类和规则
  237. func InitClassAndRuleData(_id string, task *TTask) {
  238. defer tools.Catch()
  239. classIdStr := task.S_class
  240. if classIdStr != "" {
  241. classIdArr := strings.Split(classIdStr, ",")
  242. classArr := make([]*Class, 0)
  243. for _, classid := range classIdArr {
  244. classData, _ := tools.MgoClass.FindById(tools.COLL_CLASS, classid, nil)
  245. if classData != nil {
  246. //初始化Class
  247. class := &Class{
  248. //Rule: CidRuleMap[classid],
  249. Cid: classid,
  250. Class_PreRule: util.ObjToString((*classData)["s_class_prerule"]),
  251. S_name: util.ObjToString((*classData)["s_name"]),
  252. S_fields: util.ObjToString((*classData)["s_fields"]),
  253. S_code: util.ObjToString((*classData)["s_code"]),
  254. S_default: util.ObjToString((*classData)["s_default"]),
  255. S_pid: util.ObjToString((*classData)["s_pid"]),
  256. S_savefield: util.ObjToString((*classData)["s_savefield"]),
  257. }
  258. //根据classid查找对应的rule
  259. ruleList, _ := tools.MgoClass.Find(tools.COLL_RULE, `{"s_classid":"`+classid+`"}`, `{"i_order":1}`, nil, false, -1, -1)
  260. if ruleList != nil && len(*ruleList) > 0 {
  261. for _, v := range *ruleList {
  262. _id := u.BsonIdToSId(v["_id"])
  263. //rule
  264. s_rule, _ := v["s_rule"].(primitive.A)
  265. i_rule := DealRules(s_rule)
  266. //detailrule
  267. s_detailrule, _ := v["s_detailrule"].(primitive.A)
  268. i_detailrule := DealRules(s_detailrule)
  269. //notrule
  270. s_notrule, _ := v["s_notrule"].(primitive.A)
  271. i_notrule := DealRules(s_notrule)
  272. rule := &Rule{
  273. Rid: _id,
  274. Reg: i_rule,
  275. DetailReg: i_detailrule,
  276. NotReg: i_notrule,
  277. Rule_PreRule: util.ObjToString(v["s_rule_prerule"]),
  278. S_name: util.ObjToString(v["s_name"]),
  279. S_code: util.ObjToString(v["s_code"]),
  280. S_pid: util.ObjToString(v["s_pid"]),
  281. }
  282. class.Rule = append(class.Rule, rule)
  283. }
  284. }
  285. classArr = append(classArr, class)
  286. }
  287. }
  288. task.Class = classArr
  289. TaskMap[_id] = task
  290. }
  291. }
  292. func DealRules(rules []interface{}) (i_rule []interface{}) {
  293. for _, r := range tools.ObjArrToStringArr(rules) {
  294. if strings.HasPrefix(r, "'") && strings.HasSuffix(r, "'") { //正则
  295. rs := []rune(r)
  296. ru := string(rs[1 : len(rs)-1])
  297. rureg, err := regexp.Compile(ru)
  298. if err != nil {
  299. log.Println("error---rule:", r)
  300. continue
  301. }
  302. i_rule = append(i_rule, []interface{}{rureg}...)
  303. } else { //规则,加入到敏感词匹配
  304. matchnum := 0
  305. mismatchnum := 0
  306. isnum1 := false
  307. isnum2 := false
  308. numArr := make([]int, 0)
  309. ruleDFA := &RuleDFA{
  310. Match: []DFA{},
  311. MisMatch: DFA{},
  312. }
  313. tmpArr := strings.Split(r, "^")
  314. matchTmp := tmpArr[0]
  315. ruleTextArr := REG.FindAllString(matchTmp, -1)
  316. for _, match := range ruleTextArr {
  317. matchnum, isnum1 = GetNum(match)
  318. numArr = append(numArr, matchnum)
  319. matchArr := GetRule(match, isnum1)
  320. tmpDFA := DFA{
  321. Link: make(map[string]interface{}),
  322. }
  323. tmpDFA.AddWord(matchArr...)
  324. ruleDFA.Match = append(ruleDFA.Match, tmpDFA)
  325. }
  326. if len(tmpArr) == 2 {
  327. mismatch := tmpArr[1]
  328. mismatchnum, isnum2 = GetNum(mismatch)
  329. mismatchArr := GetRule(mismatch, isnum2)
  330. ruleDFA.MisMatch.AddWord(mismatchArr...)
  331. }
  332. ruleDFA.MatchNum = numArr
  333. ruleDFA.MisMatchNum = mismatchnum
  334. i_rule = append(i_rule, []interface{}{ruleDFA}...)
  335. }
  336. }
  337. return
  338. }
  339. // 更新任务状态
  340. func (tt *TTask) Sstatus() int {
  341. if tt.I_status == 0 && tt.B_Running {
  342. return 1
  343. } else if tt.I_status == 0 && !tt.B_Running {
  344. return 0
  345. } else if tt.I_status == 1 && tt.B_Running {
  346. return 2
  347. } else if tt.I_status == 1 && !tt.B_Running {
  348. return 3
  349. }
  350. return -1
  351. }
  352. // 停止任务
  353. func (tt *TTask) SStop() bool {
  354. tt.Lock.Lock()
  355. defer tt.Lock.Unlock()
  356. if tt.I_status == 1 {
  357. tt.I_status = 0
  358. tt.FlagQuit <- true
  359. log.Println("开始停止...")
  360. }
  361. return true
  362. }
  363. var NN = 400
  364. // 存放测试的数据
  365. var TEST = &TestList{
  366. Count: map[string][]int{},
  367. }
  368. type TestList struct {
  369. Lock sync.Mutex
  370. Count map[string][]int
  371. }
  372. func (tl *TestList) Get(id string) []int {
  373. tl.Lock.Lock()
  374. defer tl.Lock.Unlock()
  375. return tl.Count[id]
  376. }
  377. func (tl *TestList) Put(id string, val ...int) {
  378. defer tools.Catch()
  379. tl.Lock.Lock()
  380. defer tl.Lock.Unlock()
  381. if len(val) == 3 {
  382. tl.Count[id] = val
  383. } else {
  384. tval := tl.Count[id]
  385. tl.Count[id][2] = val[0]
  386. if tval[1] <= val[0] {
  387. tl.Count[id][0] = 1
  388. }
  389. }
  390. }
  391. func (tl *TestList) Del(id string) {
  392. tl.Lock.Lock()
  393. defer tl.Lock.Unlock()
  394. delete(tl.Count, id)
  395. os.Remove("csv/" + id)
  396. }
  397. // 任务测试
  398. func (tt *TTask) RRunTest(s_startid, s_endid, s_query, filename string) {
  399. defer tools.Catch()
  400. defer func() {
  401. go func() {
  402. time.AfterFunc(10*time.Minute, func() {
  403. TEST.Del(filename)
  404. })
  405. }()
  406. }()
  407. //开始识别
  408. sess := tt.MgoTask.GetMgoConn()
  409. defer tt.MgoTask.DestoryMongoConn(sess)
  410. q := map[string]interface{}{}
  411. if s_query != "" {
  412. json.Unmarshal([]byte(strings.Replace(s_query, "'", "\"", -1)), &q)
  413. }
  414. if s_startid != "" {
  415. q["_id"] = map[string]interface{}{
  416. "$gte": u.StringTOBsonId(s_startid),
  417. }
  418. }
  419. if s_endid != "" {
  420. if q["_id"] != nil {
  421. q["_id"].(map[string]interface{})["$lte"] = u.StringTOBsonId(s_endid)
  422. } else {
  423. q["_id"] = map[string]interface{}{
  424. "$lte": u.StringTOBsonId(s_endid),
  425. }
  426. }
  427. }
  428. count := tt.MgoTask.Count(tt.S_coll, &q)
  429. if count == 0 {
  430. return
  431. }
  432. TEST.Put(filename, 0, count, 0)
  433. query := sess.DB(tt.S_mgodb).C(tt.S_coll).Find(&q).Iter()
  434. arr := [][]string{}
  435. i := 0
  436. for tmp := make(map[string]interface{}); query.Next(&tmp); i = i + 1 {
  437. if i > 2000 { //数据跑至2000停止
  438. break
  439. }
  440. //按顺序识别
  441. tid := tmp["_id"]
  442. res := make([]string, 3)
  443. res[0] = u.BsonIdToSId(tid)
  444. res[1] = util.ObjToString(tmp["title"])
  445. if util.IntAll(tmp["infoformat"]) == 2 { //此处增加特例
  446. res = append(res, "拟建", "拟建")
  447. } else if util.IntAll(tmp["infoformat"]) == 3 {
  448. res = append(res, "产权", "产权")
  449. } else {
  450. SMap := NewClassificationRun(tt, tmp)
  451. for _, k := range SMap.Keys {
  452. res = append(res, util.ObjToString((SMap.Map[k].([]string))[0]))
  453. }
  454. }
  455. arr = append(arr, res)
  456. TEST.Put(filename, i+1)
  457. tmp = make(map[string]interface{})
  458. }
  459. if len(arr) > 0 {
  460. if !Exist("csv") {
  461. os.Mkdir("csv", 777)
  462. }
  463. f, _ := os.Create("csv/" + filename)
  464. w := csv.NewWriter(f)
  465. for _, str := range arr {
  466. w.Write(str)
  467. }
  468. w.Flush()
  469. f.Close()
  470. }
  471. log.Println("运行RUNTEST-OVER")
  472. }
  473. func Exist(filename string) bool {
  474. _, err := os.Stat(filename)
  475. return err == nil || os.IsExist(err)
  476. }
  477. func (tt *TTask) RRun() {
  478. first := make(chan bool, 1)
  479. if tt.I_status == 1 {
  480. first <- true
  481. }
  482. OVER:
  483. for tt.I_status == 1 {
  484. tt.B_Running = false
  485. select {
  486. case <-tt.FlagQuit: //结果任务控制
  487. log.Println("退出,RUN", tt.S_name)
  488. tt = nil
  489. break OVER
  490. case <-first: //第一次执行控制
  491. if tools.ControlTaskRun { //任务流程控制,现有模式用不到,默认false
  492. tools.AllTaskFinish = false
  493. }
  494. log.Println("第一次执行任务:", tt.S_name)
  495. newtaskrun(tt)
  496. case <-time.Tick(time.Duration(tt.I_rate) * time.Second): //任务定时控制
  497. //执行定时任务前,检查任务是否更新了rule
  498. if tt.B_UpdateRule {
  499. InitClassAndRuleData(tt.ID, tt) //重新加载任务的rule
  500. tt.B_UpdateRule = false
  501. UpdateTaskInfo(false, tt.ID)
  502. }
  503. //上一轮任务执行完毕再走下一轮(上一轮任务执行完毕的标志是业主分类执行完)
  504. //util.Debug("ControlTaskRun---", tools.ControlTaskRun, "AllTaskFinish---", tools.AllTaskFinish)
  505. if !tools.ControlTaskRun || tt.S_querycon == "0" { //线下环境不控制定时任务;或者线上通过时间定时执行
  506. newtaskrun(tt)
  507. } else if tools.ControlTaskRun && tools.AllTaskFinish { //线上控制
  508. tools.AllTaskFinish = false
  509. newtaskrun(tt)
  510. } else {
  511. log.Println("上轮任务暂未完成")
  512. }
  513. }
  514. }
  515. }
  516. func newtaskrun(tt *TTask) {
  517. NewTaskRunAll(tt, false, nil)
  518. }
  519. // NewTaskRunAll 常规任务和udp非合并数据处理方法
  520. func NewTaskRunAll(tt *TTask, budp bool, mapInfo map[string]interface{}) int {
  521. total := 0
  522. tools.Try(func() { //不加这一层defer运行不了!!!
  523. timespan := false //时间间隔(控制数据条数打印)
  524. tt.B_Running = true
  525. defer func() {
  526. //业主分类执行完修改AllTaskFinish状态;控制流程的任务id(整个分类流程业主分类结尾,以此为标记)
  527. if tt.ID == tools.ControlLastTaskId {
  528. tools.AllTaskFinish = true
  529. }
  530. tt.B_Running = false
  531. }()
  532. //开始识别
  533. pool := make(chan bool, tt.I_thread)
  534. wg := &sync.WaitGroup{}
  535. lock := &sync.Mutex{}
  536. q := make(map[string]interface{})
  537. nextNodeSid, nextNodeEid := "", ""
  538. oid := tt.LastId //上次定时任务的结束id
  539. s_table := tt.S_table //结果表
  540. s_asfield := tt.S_asfield //关联字段
  541. asfields := strings.Split(s_asfield, "==")
  542. qfield := "" //查询表字段
  543. rfield := "" //结果表字段
  544. qtp := "" //查询字段的类型
  545. rtp := "" //结果字段的类型
  546. rtype := "" //结果字段的真实类型
  547. if s_table != "" { //有结果表保存到结果表(更新,插入)
  548. tt.S_collection = s_table
  549. }
  550. if len(asfields) == 2 {
  551. qfield = asfields[0] //查询表字段
  552. rfield = asfields[1] //结果表字段
  553. //id处理 object string互转
  554. qfield, rfield, qtp, rtp = IdTypeConversion(qfield, rfield)
  555. queryExis := map[string]interface{}{
  556. rfield: map[string]interface{}{
  557. "$exists": true,
  558. },
  559. }
  560. onedata, _ := tt.MgoTask.FindOne(tt.S_collection, queryExis)
  561. rtype = reflect.TypeOf((*onedata)[rfield]).String() //结果表字段真实类型
  562. }
  563. //有结果表有关联字段,在结果表上根据关联字段更新;有结果表没有关联字段,在结果表根据_id段更新
  564. //没有结果表在查询表上更新
  565. //log.Println("lastid:", tt.LastId, "查询方式:", tt.S_querycon, "时间:", tt.S_starttime, "条件:", tt.S_query, "table:", tt.S_table, "s_timefieldname:", tt.S_timefieldname)
  566. sort := ""
  567. if !budp { //非udp查询条件
  568. sort = "_id"
  569. if tt.S_query != "" { //有查询条件
  570. json.Unmarshal([]byte(strings.Replace(tt.S_query, "'", "\"", -1)), &q)
  571. }
  572. idcoll := tt.S_idcoll
  573. if idcoll != "" { //idcoll中查询id区间,bidding_processing_ids
  574. nextNodeSid, nextNodeEid = FindId(idcoll) //查询id段
  575. if nextNodeSid != "" && nextNodeEid != "" && nextNodeSid <= nextNodeEid {
  576. q["_id"] = bson.M{
  577. "$gt": u.StringTOBsonId(nextNodeSid),
  578. "$lte": u.StringTOBsonId(nextNodeEid),
  579. }
  580. } else {
  581. log.Println("定时任务", tt.S_name, "查询", tt.S_idcoll, "时间段出错", nextNodeSid, nextNodeEid)
  582. tools.AllTaskFinish = true //为查询到数据视为此轮任务完成
  583. return
  584. }
  585. stime, _ := strconv.ParseInt(nextNodeSid[:8], 16, 64) //取id前8位转成时间戳
  586. etime, _ := strconv.ParseInt(nextNodeEid[:8], 16, 64) //
  587. if etime-stime < 1800 { //时间跨度小于半小时
  588. timespan = true
  589. }
  590. } else {
  591. if q["_id"] != nil {
  592. if _id, ok := q["_id"].(string); ok {
  593. q["_id"] = u.StringTOBsonId(_id)
  594. } else if _ids, ok := q["_id"].(map[string]interface{}); ok {
  595. for k, v := range _ids {
  596. if id, bk := v.(string); bk {
  597. _ids[k] = u.StringTOBsonId(id)
  598. }
  599. }
  600. }
  601. }
  602. if tt.S_querycon == "1" { //id查询
  603. if tt.S_query != "" {
  604. //页面上配置了查询条件,直接使用,不再单独查询上次任务结束ID
  605. if tt.LastId != "" && q["_id"] == nil {
  606. q["_id"] = map[string]interface{}{
  607. "$gt": u.StringTOBsonId(tt.LastId),
  608. }
  609. }
  610. } else {
  611. //临时修改查询id区间段
  612. comeintime := time.Now().Unix() - 5*60
  613. query := map[string]interface{}{
  614. "comeintime": map[string]interface{}{
  615. "$gt": comeintime,
  616. },
  617. }
  618. qId := tt.MgoTask.GetMgoConn()
  619. defer tt.MgoTask.DestoryMongoConn(qId)
  620. tmpData := qId.DB(tt.S_mgodb).C(tt.S_coll).Find(&query).Limit(1).Sort("-_id").Iter()
  621. eId := ""
  622. for tmp := make(map[string]interface{}); tmpData.Next(tmp); {
  623. eId = u.BsonIdToSId(tmp["_id"])
  624. }
  625. if tt.LastId != "" && q["_id"] == nil {
  626. sid := tt.LastId
  627. q["_id"] = map[string]interface{}{
  628. "$gt": u.StringTOBsonId(sid),
  629. }
  630. if eId != "" {
  631. q["_id"] = map[string]interface{}{
  632. "$gt": u.StringTOBsonId(sid),
  633. "$lte": u.StringTOBsonId(eId),
  634. }
  635. }
  636. }
  637. //按id查询,为了保证有新数据入库,每次休息2分钟
  638. time.Sleep(time.Second * 60)
  639. //测试环境q的赋值执行下述代码
  640. //if tt.LastId != "" && q["_id"] == nil {
  641. // q["_id"] = map[string]interface{}{
  642. // "$gt": u.StringTOBsonId(tt.LastId),
  643. // }
  644. //}
  645. }
  646. } else { //时间查询
  647. name := tt.S_timefieldname
  648. q[name] = map[string]interface{}{
  649. "$gt": tt.S_starttime,
  650. }
  651. }
  652. }
  653. } else { //udp查询条件
  654. sort = "-_id"
  655. if tt.S_query != "" { //有查询条件
  656. json.Unmarshal([]byte(strings.Replace(tt.S_query, "'", "\"", -1)), &q)
  657. }
  658. tmpq := mapInfo["q"].(map[string]interface{})
  659. for k, v := range tmpq {
  660. q[k] = v
  661. }
  662. sid := mapInfo["gtid"].(string)
  663. eid := mapInfo["lteid"].(string)
  664. stime, _ := strconv.ParseInt(sid[:8], 16, 64)
  665. etime, _ := strconv.ParseInt(eid[:8], 16, 64)
  666. if etime-stime < 1800 { //时间跨度小于半小时
  667. timespan = true
  668. }
  669. }
  670. //task
  671. tasksess := tt.MgoTask.GetMgoConn()
  672. defer tt.MgoTask.DestoryMongoConn(tasksess)
  673. //通过ID 查询数据时,才打印日志
  674. if tt.S_querycon == "1" {
  675. log.Println("运行", tt.S_name, "start")
  676. log.Println("线程数:", tt.I_thread, "查询语句", q)
  677. log.Println("查询---", tt.S_mgodb, tt.S_coll, tt.S_collection, tt.S_table)
  678. log.Println("select:", tt.Task_QueryFieldMap, tt.Task_QueryFieldArr)
  679. }
  680. extractquery := tasksess.DB(tt.S_mgodb).C(tt.S_coll).Find(q).Select(tt.Task_QueryFieldMap).Sort(sort).Iter()
  681. arr := [][]map[string]interface{}{}
  682. if tt.I_wordcount == 1 {
  683. tt.WordCount = map[string]map[string]int{}
  684. }
  685. sum := 0
  686. for tmp := make(map[string]interface{}); extractquery.Next(&tmp); sum++ {
  687. tid := tmp["_id"]
  688. if !timespan && sum%2000 == 0 {
  689. log.Println("current:", sum, tt.S_name)
  690. }
  691. pool <- true
  692. wg.Add(1)
  693. go func(tmp map[string]interface{}) {
  694. defer func() {
  695. <-pool
  696. wg.Done()
  697. }()
  698. //按顺序识别
  699. tid := tmp["_id"]
  700. update := []map[string]interface{}{}
  701. //如果有关联字段 根据关联字段更新或者保存
  702. if len(asfields) == 2 {
  703. //log.Println("qfield====", qfield)
  704. field := tmp[qfield]
  705. if field != nil {
  706. //log.Println("field===", field, qtp, rtp)
  707. if qtp == "bson.ObjectId" && rtp == "bson.ObjectId" { //俩字段类型一致
  708. } else {
  709. //log.Println(field, " 查询字段", qfield, "查询类型", qtp, "结果字段", rfield, " 结果类型", rtp, "结果真实类型", rtype)
  710. if rtype == rtp { //转换后与真实类型不同,填写时类型错误
  711. //将查询字段类型转换为对应的结果字段类型
  712. if qtp == "bson.ObjectId" && rtp == "string" {
  713. field = u.BsonIdToSId(tmp[qfield])
  714. } else if qtp == "string" && rtp == "bson.ObjectId" {
  715. field = u.StringTOBsonId(tmp[qfield].(string))
  716. }
  717. }
  718. }
  719. update = append(update, map[string]interface{}{ //根据关联字段更新
  720. rfield: field,
  721. })
  722. }
  723. } else {
  724. update = append(update, map[string]interface{}{ //更新的条件 根据id更新
  725. "_id": tid,
  726. })
  727. }
  728. res := map[string]interface{}{}
  729. ksmap := make(map[string]map[string][]string)
  730. if util.IntAll(tmp["infoformat"]) == 2 { //此处增加特例
  731. res["toptype"] = "拟建"
  732. res["subtype"] = "拟建"
  733. } else if util.IntAll(tmp["infoformat"]) == 3 {
  734. res["toptype"] = "产权"
  735. res["subtype"] = "产权"
  736. } else {
  737. SMap := &tools.SortMap{}
  738. if tt.I_tasktype == 2 { //标签任务
  739. SMap = TagClassificationRun(tt, tmp)
  740. } else if tt.I_tasktype == 1 { //附件任务
  741. SMap = FileClassificationRun(tt, tmp)
  742. //res["projectinfo"] = tmp["projectinfo"]
  743. } else { //常规任务
  744. SMap = NewClassificationRun(tt, tmp)
  745. //1.针对招标分类的特殊处理
  746. if tt.ID == "57982b4436b82b073c000001" && tt.S_name == "招标分类" {
  747. //1.一级分类时,符合结果中成交规则时
  748. //todo 如果没有打上分类,调用ai 模型分类
  749. if _, ok := SMap.Map["toptype"]; !ok {
  750. if util.ObjToString(tools.Config["aiurl"]) != "" {
  751. now := time.Now()
  752. data := map[string]interface{}{
  753. "title": tmp["title"],
  754. "detail": tmp["detail"],
  755. }
  756. reqData := map[string]interface{}{
  757. "texts": []interface{}{data},
  758. }
  759. rai := SendAi(reqData, util.ObjToString(tools.Config["aiurl"]))
  760. log.Println("ai 分类时长", time.Since(now).Seconds())
  761. if len(rai) > 0 {
  762. resa := rai["result"]
  763. if dataa, ok := resa.([]interface{}); ok {
  764. da := dataa[0]
  765. if len(util.ObjToString(da)) > 0 {
  766. cs := strings.Split(util.ObjToString(da), "-")
  767. SMap.Map["toptype"] = cs[0]
  768. SMap.Map["subtype"] = cs[1]
  769. }
  770. }
  771. }
  772. }
  773. }
  774. if SMap.Map["toptype"] == "招标" && SMap.Map["subtype"] != "单一" {
  775. if _, ok := tmp["detail"]; ok {
  776. if u.ChargeDetailResult(util.ObjToString(tmp["detail"])) {
  777. SMap.Map["toptype"] = "结果"
  778. resa := ReSub(tt, tmp, "结果")
  779. subtype := resa.Map["subtype"]
  780. delete(SMap.Map, "subtype")
  781. SMap.Map["subtype"] = subtype
  782. }
  783. }
  784. }
  785. //2.一级分类是预告,但是标题含有招标计划,同时含有 预公告|预公示,变为 采购意向
  786. if SMap.Map["toptype"] == "预告" {
  787. if u.DealYuce(tmp["title"].(string)) {
  788. SMap.Map["toptype"] = "采购意向"
  789. SMap.Map["subtype"] = "采购意向"
  790. }
  791. }
  792. //3.针对 项目登记 相关数据处理,符合条件的归类为‘采购意向’
  793. if u.IsPurchasingIntent(tmp) {
  794. SMap.Map["toptype"] = "采购意向"
  795. SMap.Map["subtype"] = "采购意向"
  796. }
  797. }
  798. }
  799. //2.针对用户行业分类,单独处理数据
  800. if mapInfo["stype"] == "yonghuhangye" || strings.TrimSpace(tt.S_name) == "用户行业分类" {
  801. subs := SMap.Map["subscope_dy"]
  802. delete(SMap.Map, "topscope_dy")
  803. var tops []string
  804. if subscopes, ok := subs.([]string); ok {
  805. for _, sub := range subscopes {
  806. top := strings.Split(sub, "_")[0]
  807. tops = append(tops, top)
  808. }
  809. SMap.Map["topscope_dy"] = u.RemoveDuplicateString(tops)
  810. }
  811. }
  812. //追加时处理,//更新字段 I_fieldUpdate 0:覆盖 1:追加
  813. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 {
  814. //封装追加信息
  815. if len(SMap.Keys) > 0 {
  816. for _, k := range SMap.Keys {
  817. ksarr := make([]string, 0)
  818. if k != "toptype" && k != "subtype" {
  819. ks, ok := SMap.Map[k].(string)
  820. if ok {
  821. ksarr = append(ksarr, ks)
  822. } else {
  823. ksarr = append(ksarr, SMap.Map[k].([]string)...)
  824. }
  825. }
  826. ksmap[k] = map[string][]string{
  827. "$each": ksarr,
  828. }
  829. }
  830. }
  831. } else { //非多分类
  832. res = SMap.Map
  833. if tt.I_tasktype == 1 { //附件任务
  834. if tmp["projectinfo"] != nil {
  835. res["projectinfo"] = tmp["projectinfo"]
  836. }
  837. }
  838. }
  839. }
  840. //if len(res) > 0 || len(ksmap) > 0 {
  841. IS.NewAdd(tt, res)
  842. if tt.S_attr != "" {
  843. //res[tt.S_attr] = 1
  844. res[tt.S_attr] = tt.AttrVal
  845. }
  846. // 添加分类时间
  847. res["classification_time"] = time.Now().Unix()
  848. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 { //I_fieldUpdate 0:覆盖 1:追加
  849. if len(ksmap) > 0 && len(res) > 0 {
  850. update = append(update, map[string]interface{}{
  851. "$set": res,
  852. "$addToSet": ksmap,
  853. })
  854. } else if len(ksmap) > 0 && len(res) == 0 {
  855. update = append(update, map[string]interface{}{
  856. "$addToSet": ksmap,
  857. })
  858. } else if len(ksmap) == 0 && len(res) > 0 {
  859. update = append(update, map[string]interface{}{
  860. "$set": res,
  861. })
  862. }
  863. } else { //非多分类或者多分类的覆盖
  864. //log.Println("更新==", res)
  865. if len(res) > 0 {
  866. update = append(update, map[string]interface{}{
  867. "$set": res,
  868. })
  869. }
  870. }
  871. //更新
  872. lock.Lock()
  873. if len(update) == 2 { //有更新条件和更新内容时才进行更新操作
  874. arr = append(arr, update)
  875. }
  876. if len(arr) >= NN {
  877. //if s_table == "" {
  878. tt.MgoTask.UpdateBulk(tt.S_collection, arr...)
  879. //} else {
  880. // tt.Mgo.UpdateAndSaveBulk(tt.S_collection, arr...)
  881. //}
  882. arr = [][]map[string]interface{}{}
  883. }
  884. lock.Unlock()
  885. //}
  886. }(tmp)
  887. ttid := u.BsonIdToSId(tid)
  888. if ttid > tt.LastId && !budp {
  889. tt.LastId = ttid
  890. }
  891. tmp = make(map[string]interface{})
  892. }
  893. total = sum
  894. //通过ID 查询分类数据才打印日志
  895. if tt.S_querycon == "1" {
  896. log.Println("总数:————", sum)
  897. if timespan {
  898. log.Println("current:————", sum)
  899. }
  900. }
  901. wg.Wait()
  902. lock.Lock()
  903. if len(arr) > 0 {
  904. //if s_table == "" { //没有结果表
  905. tt.MgoTask.UpdateBulk(tt.S_collection, arr...) //在原表上更新
  906. //} else { //有结果表
  907. // tt.Mgo.UpdateAndSaveBulk(tt.S_collection, arr...)
  908. //}
  909. arr = [][]map[string]interface{}{}
  910. }
  911. lock.Unlock()
  912. tt.WcLock.Lock()
  913. if len(tt.WordCount) > 0 {
  914. savem := []map[string]interface{}{}
  915. tn := time.Now().Unix()
  916. for wk, wm := range tt.WordCount {
  917. for ck, cm := range wm {
  918. m1 := map[string]interface{}{
  919. "s_class": wk,
  920. "s_word": ck,
  921. "i_count": cm,
  922. "bz": tn,
  923. }
  924. savem = append(savem, m1)
  925. if len(savem) >= 1000 {
  926. tools.MgoClass.SaveBulk("wordcount", savem...)
  927. savem = []map[string]interface{}{}
  928. }
  929. }
  930. }
  931. if len(savem) > 0 {
  932. tools.MgoClass.SaveBulk("wordcount", savem...)
  933. savem = nil
  934. }
  935. }
  936. tt.WcLock.Unlock()
  937. //更新最后id
  938. if !budp && oid != tt.LastId {
  939. setid := map[string]interface{}{
  940. "$set": map[string]interface{}{
  941. "s_startid": tt.LastId,
  942. },
  943. }
  944. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, setid, false, false)
  945. }
  946. //更新最后时间
  947. if !budp {
  948. nowtime := time.Now().Unix()
  949. settime := map[string]interface{}{
  950. "$set": map[string]interface{}{
  951. "s_starttime": nowtime,
  952. },
  953. }
  954. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, settime, false, false)
  955. }
  956. //InitRule()
  957. if tt.S_querycon == "1" {
  958. log.Println("运行", tt.S_name, "over", oid, " endid:", tt.LastId)
  959. }
  960. //定时任务完成发送udp信号调抽取
  961. if tools.Extract["preNodeId"] == tt.ID { //常规招标定时任务udp调用抽取
  962. if tt.S_idcoll == "" {
  963. nextNodeSid = oid
  964. nextNodeEid = tt.LastId
  965. }
  966. UdpRunExtract(nextNodeSid, nextNodeEid)
  967. }
  968. })
  969. return total
  970. }
  971. // udp合并数据处理的方法
  972. func UdpTaskRunAll(tt *TTask, budp bool, mapInfo map[string]interface{}, stype string) int {
  973. total := 0
  974. tools.Try(func() { //不加这一层defer运行不了!!!
  975. timespan := false
  976. tt.B_Running = true
  977. defer func() {
  978. tt.B_Running = false
  979. }()
  980. //开始识别
  981. pool := make(chan bool, tt.I_thread)
  982. wg := &sync.WaitGroup{}
  983. lock := &sync.Mutex{}
  984. q := map[string]interface{}{}
  985. s_table := tt.S_table //结果表
  986. s_asfield := tt.S_asfield //关联字段
  987. asfields := strings.Split(s_asfield, "==")
  988. qfield := "" //查询表字段
  989. rfield := "" //结果表字段
  990. qtp := "" //查询字段的类型
  991. rtp := "" //结果字段的类型
  992. rtype := "" //结果字段的真实类型
  993. if s_table != "" { //有结果表保存到结果表(更新,插入)
  994. tt.S_collection = s_table
  995. }
  996. if len(asfields) == 2 {
  997. qfield = asfields[0] //查询表字段
  998. rfield = asfields[1] //结果表字段
  999. //id处理 object string互转
  1000. qfield, rfield, qtp, rtp = IdTypeConversion(qfield, rfield)
  1001. queryExis := map[string]interface{}{
  1002. rfield: map[string]interface{}{
  1003. "$exists": true,
  1004. },
  1005. }
  1006. onedata, _ := tt.MgoTask.FindOne(tt.S_collection, queryExis)
  1007. rtype = reflect.TypeOf((*onedata)[rfield]).String() //结果表字段真实类型
  1008. }
  1009. //有结果表有关联字段,在结果表上根据关联字段更新;有结果表没有关联字段,在结果表根据_id段更新
  1010. //没有结果表在查询表上更新
  1011. //log.Println("lastid:", tt.LastId, "查询方式:", tt.S_querycon, "时间:", tt.S_starttime, "条件:", tt.S_query, "table:", tt.S_table, "s_timefieldname:", tt.S_timefieldname)
  1012. q = mapInfo["q"].(map[string]interface{})
  1013. //计算起始id和结束id时间宽度,大于半小时的2000数据打印一次个数,小于半小时的每条数据都打印一次个数
  1014. sid := mapInfo["gtid"].(string)
  1015. eid := mapInfo["lteid"].(string)
  1016. stime, _ := strconv.ParseInt(sid[:8], 16, 64)
  1017. etime, _ := strconv.ParseInt(eid[:8], 16, 64)
  1018. if etime-stime < 1800 { //时间跨度小于半小时
  1019. timespan = true
  1020. }
  1021. udpsess := tt.MulMgo.GetMgoConn()
  1022. if udpsess == nil {
  1023. log.Println("连接为空", tt.S_name, mapInfo)
  1024. return
  1025. }
  1026. defer tt.MulMgo.DestoryMongoConn(udpsess)
  1027. udptmp := udpsess.DB(tt.MulMgo.DbName).C(tt.MulColl).Find(&q).Select(tt.Task_QueryFieldMap).Sort("_id").Iter()
  1028. //task
  1029. tasksess := tt.MgoTask.GetMgoConn()
  1030. defer tt.MgoTask.DestoryMongoConn(tasksess)
  1031. log.Println("线程数:", tt.I_thread, "查询语句", q)
  1032. log.Println("task---", tt.S_mgodb, tt.S_coll, tt.S_collection, tt.S_table)
  1033. log.Println("select:", tt.Task_QueryFieldMap)
  1034. extractquery := tasksess.DB(tt.S_mgodb).C(tt.S_coll).Find(&q).Select(tt.Task_QueryFieldMap).Sort("_id").Iter()
  1035. arr := [][]map[string]interface{}{}
  1036. oid := tt.LastId
  1037. if tt.I_wordcount == 1 {
  1038. tt.WordCount = map[string]map[string]int{}
  1039. }
  1040. sum := 0
  1041. //对比两张表数据,减少查询次数
  1042. var compare bson.M
  1043. for tmp := make(map[string]interface{}); extractquery.Next(&tmp); sum++ {
  1044. result := tmp
  1045. //对比
  1046. for {
  1047. if compare == nil {
  1048. compare = make(bson.M)
  1049. if !udptmp.Next(&compare) { //传参表数据赋值给compare
  1050. break
  1051. }
  1052. }
  1053. if compare != nil {
  1054. //对比
  1055. cid := u.BsonIdToSId(compare["_id"]) //传参表id
  1056. tid := u.BsonIdToSId(tmp["_id"]) //抽取表id
  1057. if cid == tid {
  1058. //更新抽取表的数据,再进行分类
  1059. for _, k := range tt.Task_QueryFieldArr {
  1060. v1 := compare[k]
  1061. v2 := tmp[k]
  1062. if v2 == nil && v1 != nil {
  1063. result[k] = v1
  1064. }
  1065. }
  1066. break
  1067. } else {
  1068. if tid > cid { //抽取表id大于传参表id
  1069. compare = nil
  1070. continue
  1071. } else {
  1072. break
  1073. }
  1074. }
  1075. } else {
  1076. break
  1077. }
  1078. }
  1079. tid := tmp["_id"]
  1080. if !timespan && sum%2000 == 0 {
  1081. log.Println("current:", sum, tid)
  1082. }
  1083. pool <- true
  1084. wg.Add(1)
  1085. go func(result map[string]interface{}) {
  1086. defer func() {
  1087. <-pool
  1088. wg.Done()
  1089. }()
  1090. //按顺序识别
  1091. if result != nil {
  1092. tid := result["_id"]
  1093. update := []map[string]interface{}{}
  1094. //如果有关联字段 根据关联字段更新或者保存
  1095. if len(asfields) == 2 {
  1096. //log.Println("qfield====", qfield)
  1097. field := result[qfield]
  1098. if field != nil {
  1099. //log.Println("field===", field, qtp, rtp)
  1100. if qtp == "bson.ObjectId" && rtp == "bson.ObjectId" { //俩字段类型一致
  1101. } else {
  1102. //log.Println(field, " 查询字段", qfield, "查询类型", qtp, "结果字段", rfield, " 结果类型", rtp, "结果真实类型", rtype)
  1103. if rtype == rtp { //转换后与真实类型不同,填写时类型错误
  1104. //将查询字段类型转换为对应的结果字段类型
  1105. if qtp == "bson.ObjectId" && rtp == "string" {
  1106. field = u.BsonIdToSId(result[qfield])
  1107. } else if qtp == "string" && rtp == "bson.ObjectId" {
  1108. field = u.StringTOBsonId(result[qfield].(string))
  1109. }
  1110. }
  1111. }
  1112. update = append(update, map[string]interface{}{ //根据关联字段更新
  1113. rfield: field,
  1114. })
  1115. }
  1116. } else {
  1117. update = append(update, map[string]interface{}{ //更新的条件 根据id更新
  1118. "_id": tid,
  1119. })
  1120. }
  1121. res := map[string]interface{}{}
  1122. ksmap := make(map[string]map[string][]string)
  1123. if util.IntAll(result["infoformat"]) == 2 { //此处增加特例
  1124. res["toptype"] = "拟建"
  1125. res["subtype"] = "拟建"
  1126. } else if util.IntAll(result["infoformat"]) == 3 {
  1127. res["toptype"] = "产权"
  1128. res["subtype"] = "产权"
  1129. } else {
  1130. SMap := &tools.SortMap{}
  1131. if tt.I_tasktype == 2 { //标签任务
  1132. SMap = TagClassificationRun(tt, result)
  1133. } else if tt.I_tasktype == 1 { //附件任务
  1134. SMap = FileClassificationRun(tt, result)
  1135. //res["projectinfo"] = tmp["projectinfo"]
  1136. } else { //常规任务
  1137. SMap = NewClassificationRun(tt, result)
  1138. //一级分类时,符合结果中成交规则时
  1139. if SMap.Map["toptype"] == "招标" && SMap.Map["subtype"] != "单一" {
  1140. if _, ok := tmp["detail"]; ok {
  1141. if u.ChargeDetailResult(util.ObjToString(tmp["detail"])) {
  1142. SMap.Map["toptype"] = "结果"
  1143. resa := ReSub(tt, tmp, "结果")
  1144. subtype := resa.Map["subtype"]
  1145. delete(SMap.Map, "subtype")
  1146. SMap.Map["subtype"] = subtype
  1147. }
  1148. }
  1149. }
  1150. }
  1151. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 { //更新字段 I_fieldUpdate 0:覆盖 1:追加
  1152. //封装追加信息
  1153. if len(SMap.Keys) > 0 {
  1154. for _, k := range SMap.Keys {
  1155. ksarr := make([]string, 0)
  1156. if k != "toptype" && k != "subtype" {
  1157. ks, ok := SMap.Map[k].(string)
  1158. if ok {
  1159. ksarr = append(ksarr, ks)
  1160. } else {
  1161. ksarr = append(ksarr, SMap.Map[k].([]string)...)
  1162. }
  1163. }
  1164. ksmap[k] = map[string][]string{
  1165. "$each": ksarr,
  1166. }
  1167. }
  1168. }
  1169. } else {
  1170. res = SMap.Map
  1171. }
  1172. }
  1173. IS.NewAdd(tt, res)
  1174. if tt.S_attr != "" {
  1175. res[tt.S_attr] = tt.AttrVal
  1176. }
  1177. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 { //I_fieldUpdate 0:覆盖 1:追加
  1178. if len(ksmap) > 0 && len(res) > 0 {
  1179. update = append(update, map[string]interface{}{
  1180. "$set": res,
  1181. "$addToSet": ksmap,
  1182. })
  1183. } else if len(ksmap) > 0 && len(res) == 0 {
  1184. update = append(update, map[string]interface{}{
  1185. "$addToSet": ksmap,
  1186. })
  1187. } else if len(ksmap) == 0 && len(res) > 0 {
  1188. update = append(update, map[string]interface{}{
  1189. "$set": res,
  1190. })
  1191. }
  1192. } else {
  1193. if len(res) > 0 {
  1194. update = append(update, map[string]interface{}{
  1195. "$set": res,
  1196. })
  1197. }
  1198. }
  1199. //更新
  1200. lock.Lock()
  1201. if len(update) == 2 { //有更新条件和更新内容时才进行更新操作
  1202. arr = append(arr, update)
  1203. }
  1204. if len(arr) >= NN {
  1205. tt.MgoTask.UpdateBulk(tt.S_collection, arr...)
  1206. arr = [][]map[string]interface{}{}
  1207. }
  1208. lock.Unlock()
  1209. }
  1210. }(result)
  1211. ttid := u.BsonIdToSId(tid)
  1212. if ttid > tt.LastId {
  1213. tt.LastId = ttid
  1214. }
  1215. tmp = make(map[string]interface{})
  1216. }
  1217. total = sum
  1218. if timespan {
  1219. log.Println("current:", sum)
  1220. }
  1221. wg.Wait()
  1222. lock.Lock()
  1223. if len(arr) > 0 {
  1224. //if s_table == "" { //没有结果表
  1225. tt.MgoTask.UpdateBulk(tt.S_collection, arr...) //在原表上更新
  1226. //} else { //有结果表
  1227. // tt.Mgo.UpdateAndSaveBulk(tt.S_collection, arr...)
  1228. //}
  1229. arr = [][]map[string]interface{}{}
  1230. }
  1231. lock.Unlock()
  1232. tt.WcLock.Lock()
  1233. if len(tt.WordCount) > 0 {
  1234. savem := []map[string]interface{}{}
  1235. tn := time.Now().Unix()
  1236. for wk, wm := range tt.WordCount {
  1237. for ck, cm := range wm {
  1238. m1 := map[string]interface{}{
  1239. "s_class": wk,
  1240. "s_word": ck,
  1241. "i_count": cm,
  1242. "bz": tn,
  1243. }
  1244. savem = append(savem, m1)
  1245. if len(savem) >= 1000 {
  1246. tools.MgoClass.SaveBulk("wordcount", savem...)
  1247. savem = []map[string]interface{}{}
  1248. }
  1249. }
  1250. }
  1251. if len(savem) > 0 {
  1252. tools.MgoClass.SaveBulk("wordcount", savem...)
  1253. savem = nil
  1254. }
  1255. }
  1256. tt.WcLock.Unlock()
  1257. //更新最后id
  1258. if !budp && oid != tt.LastId {
  1259. setid := map[string]interface{}{
  1260. "$set": map[string]interface{}{
  1261. "s_startid": tt.LastId,
  1262. },
  1263. }
  1264. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, setid, false, false)
  1265. }
  1266. //更新最后时间
  1267. if !budp {
  1268. nowtime := time.Now().Unix()
  1269. settime := map[string]interface{}{
  1270. "$set": map[string]interface{}{
  1271. "s_starttime": nowtime,
  1272. },
  1273. }
  1274. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, settime, false, false)
  1275. }
  1276. //InitRule()
  1277. log.Println("运行", tt.S_name, "over")
  1278. })
  1279. return total
  1280. }
  1281. func UdpRunExtract(sid, eid string) { //5cb6c508a5cb26b9b70d6536
  1282. by, _ := json.Marshal(map[string]interface{}{
  1283. "gtid": sid,
  1284. "lteid": eid,
  1285. "stype": tools.ExtractStype,
  1286. })
  1287. log.Println("定时任务调下一节点分类:", tools.ExtractPort, string(by))
  1288. addr := &net.UDPAddr{
  1289. IP: net.ParseIP(tools.ExtractAddr),
  1290. Port: tools.ExtractPort,
  1291. }
  1292. //node := &tools.UdpNode{by, addr, time.Now().Unix(), 0}
  1293. //udptaskmap.Store(key, node)
  1294. tools.Udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  1295. }
  1296. func FindId_back(coll string) (gtid, lteid string) {
  1297. sum := 0 //记录数据总量
  1298. data, _ := tools.MgoClass.Find(coll, `{"isused":false}`, `{"_id":1}`, nil, false, -1, -1)
  1299. length := len(*data)
  1300. set := bson.M{
  1301. "$set": bson.M{
  1302. "isused": true,
  1303. "publishtime": time.Now().Unix(),
  1304. },
  1305. }
  1306. for i, d := range *data {
  1307. id := d["_id"]
  1308. count := util.IntAll(d["count"])
  1309. sum += count
  1310. if gtid == "" {
  1311. gtid = d["gtid"].(string)
  1312. }
  1313. if sum >= 5000 || i == length-1 { //总数大于5000或数据取完,取此id段数据
  1314. lteid := d["lteid"].(string)
  1315. go tools.MgoClass.Update(coll, bson.M{"_id": id}, set, false, false)
  1316. return gtid, lteid
  1317. } else { //总数小于5000,删除已使用数据
  1318. go tools.MgoClass.Update(coll, bson.M{"_id": id}, set, false, false)
  1319. }
  1320. }
  1321. return gtid, lteid
  1322. }
  1323. func FindId(coll string) (gtid, lteid string) {
  1324. data, _ := tools.MgoClass.Find(coll, map[string]interface{}{"dataprocess": 0}, `{"_id":1}`, nil, false, -1, -1)
  1325. for _, d := range *data {
  1326. gtid = d["gtid"].(string)
  1327. lteid = d["lteid"].(string)
  1328. set := map[string]interface{}{
  1329. "$set": map[string]interface{}{
  1330. "dataprocess": 2,
  1331. "updatetime": time.Now().Unix(),
  1332. },
  1333. }
  1334. tools.MgoClass.Update(coll, map[string]interface{}{"_id": d["_id"]}, set, false, false)
  1335. break
  1336. }
  1337. return gtid, lteid
  1338. }
  1339. // NewLoadTestTask 测试任务
  1340. func NewLoadTestTask(_id, s_mgourl, s_mgodb, s_coll, i_poolsize, s_startid, s_endid, s_query string) (bs bool, filename string) {
  1341. defer tools.Catch()
  1342. r, t, _ := NewAnalyTask(_id, s_mgourl, s_mgodb, s_coll, tools.IntAllDef(i_poolsize, 5))
  1343. //log.Println(m)
  1344. if r && t != nil {
  1345. filename = time.Now().Format("150405") + ".csv"
  1346. go t.RRunTest(s_startid, s_endid, s_query, filename)
  1347. bs = true
  1348. }
  1349. return
  1350. }
  1351. // NewLoadTask 加载任务
  1352. func NewLoadTask(_id string, res *tools.JSON) {
  1353. defer tools.Catch()
  1354. //初始化任务信息
  1355. InitTaskData(_id)
  1356. //初始化任务mgo配置信息
  1357. bres, tt, msg := NewAnalyTask(_id, "", "", "", 5)
  1358. tt.I_status = 1
  1359. log.Println(tt.S_mgodb, tt.S_name, tt.I_thread)
  1360. res.Msg = msg
  1361. if bres && tt != nil {
  1362. res.Status = true
  1363. NEWTASKPOOL[_id] = tt //存入当前启动任务
  1364. log.Println("加载", tt.S_name, "完成...", tt.S_query)
  1365. go tt.RRun()
  1366. }
  1367. }
  1368. // 处理id的类型转换
  1369. func IdTypeConversion(q, r string) (string, string, string, string) {
  1370. qtp, rtp := "bson.ObjectId", "bson.ObjectId"
  1371. if strings.Contains(q, "ObjectId") || strings.Contains(q, "objectId") {
  1372. q = q[9 : len(q)-1]
  1373. } else if strings.Contains(q, "StringId") || strings.Contains(q, "stringId") {
  1374. q = q[9 : len(q)-1]
  1375. qtp = "string"
  1376. }
  1377. if strings.Contains(r, "ObjectId") || strings.Contains(r, "objectId") {
  1378. r = r[9 : len(r)-1]
  1379. } else if strings.Contains(r, "StringId") || strings.Contains(r, "stringId") {
  1380. r = r[9 : len(r)-1]
  1381. rtp = "string"
  1382. }
  1383. return q, r, qtp, rtp
  1384. }
  1385. // 获取匹配或不匹配的个数
  1386. func GetNum(rule string) (int, bool) {
  1387. num := 1
  1388. isnum := strings.HasSuffix(rule, ")")
  1389. if !isnum { //是数字
  1390. s := []rune(rule)
  1391. last := string(s[len(s)-1:])
  1392. num = tools.IntAll(last)
  1393. }
  1394. return num, isnum
  1395. }
  1396. // 获取规则
  1397. func GetRule(text string, isnum bool) (matchArr []string) {
  1398. if isnum { //最后一个不是数字
  1399. if strings.HasPrefix(text, "(") && strings.HasSuffix(text, ")") {
  1400. text = text[1 : len(text)-1]
  1401. matchArr = strings.Split(text, "|")
  1402. }
  1403. } else if strings.HasPrefix(text, "(") && !isnum {
  1404. text = text[1 : len(text)-2]
  1405. matchArr = strings.Split(text, "|")
  1406. }
  1407. return matchArr
  1408. }
  1409. func (d *DFA) AddWord(keys ...string) {
  1410. d.AddWordAll(true, keys...)
  1411. }
  1412. func (d *DFA) AddWordAll(haskey bool, keys ...string) {
  1413. if d.Link == nil {
  1414. d.Link = make(map[string]interface{})
  1415. }
  1416. for _, key := range keys {
  1417. nowMap := &d.Link
  1418. for i := 0; i < len(key); i++ {
  1419. kc := key[i : i+1]
  1420. if v, ok := (*nowMap)[kc]; ok {
  1421. nowMap, _ = v.(*map[string]interface{})
  1422. } else {
  1423. newMap := map[string]interface{}{}
  1424. newMap["YN"] = "0"
  1425. (*nowMap)[kc] = &newMap
  1426. nowMap = &newMap
  1427. }
  1428. if i == len(key)-1 {
  1429. (*nowMap)["YN"] = "1"
  1430. if haskey {
  1431. (*nowMap)["K"] = key
  1432. }
  1433. }
  1434. }
  1435. }
  1436. }
  1437. func (d *DFA) CheckSensitiveWord(src string, n int) (bool, []string) {
  1438. res := make([]string, 0)
  1439. tmpMap := make(map[string]int)
  1440. for j := 0; j < len(src); j++ {
  1441. nowMap := &d.Link
  1442. for i := j; i < len(src); i++ {
  1443. word := src[i : i+1]
  1444. nowMap, _ = (*nowMap)[word].(*map[string]interface{})
  1445. if nowMap != nil { // 存在,则判断是否为最后一个
  1446. if "1" == util.ObjToString((*nowMap)["YN"]) {
  1447. s := util.ObjToString((*nowMap)["K"])
  1448. tmpMap[s] = 1
  1449. //nowMap = &d.Link //匹配到之后继续匹配后边的内容
  1450. }
  1451. } else {
  1452. //nowMap = &d.Link
  1453. break
  1454. }
  1455. }
  1456. }
  1457. if len(tmpMap) >= n {
  1458. for k, _ := range tmpMap {
  1459. res = append(res, k)
  1460. }
  1461. return true, res
  1462. }
  1463. return false, []string{}
  1464. }
  1465. func (d *DFA) CheckSensitiveWordTest(src string, n int) (bool, []string) {
  1466. res := make([]string, 0)
  1467. tmpMap := make(map[string]int)
  1468. for j := 0; j < len(src); j++ {
  1469. nowMap := &d.Link
  1470. for i := j; i < len(src); i++ {
  1471. word := src[i : i+1]
  1472. nowMap, _ = (*nowMap)[word].(*map[string]interface{})
  1473. if nowMap != nil { // 存在,则判断是否为最后一个
  1474. if "1" == util.ObjToString((*nowMap)["YN"]) {
  1475. s := util.ObjToString((*nowMap)["K"])
  1476. tmpMap[s] = 1
  1477. //nowMap = &d.Link //匹配到之后继续匹配后边的内容
  1478. }
  1479. } else {
  1480. //nowMap = &d.Link
  1481. break
  1482. }
  1483. }
  1484. }
  1485. for k, _ := range tmpMap {
  1486. res = append(res, k)
  1487. }
  1488. return len(tmpMap) >= n, res
  1489. }
  1490. // UpdateTaskInfo 更新任务信息
  1491. func UpdateTaskInfo(flag bool, tid string) bool {
  1492. query := bson.M{
  1493. "_id": u.StringTOBsonId(tid),
  1494. }
  1495. set := bson.M{
  1496. "$set": bson.M{
  1497. "b_updaterule": flag,
  1498. },
  1499. }
  1500. return tools.MgoClass.Update(tools.COLL_TASK, query, set, false, false)
  1501. }
  1502. // o_projectinfo中数据分类定时任务
  1503. func RunTask() {
  1504. if tools.IsStart { //是否开启定时任务
  1505. tt := InitTimeTask() //初始化任务
  1506. //StartTask(tt)
  1507. //return
  1508. c := cron.New()
  1509. cronstr := "0 */" + fmt.Sprint(tt.I_rate) + " * * * ?" //每TaskTime分钟执行一次
  1510. c.AddFunc(cronstr, func() { StartTask(tt) })
  1511. c.Start()
  1512. }
  1513. }
  1514. // 初始化任务
  1515. func InitTimeTask() *TTask {
  1516. defer util.Catch()
  1517. timeTaskTT := &TTask{}
  1518. InitTaskData(tools.TimeTaskid)
  1519. bres, tt, _ := NewAnalyTask(tools.TimeTaskid, "", "", "", 5)
  1520. if bres && tt != nil {
  1521. timeTaskTT = tt
  1522. logger.Debug("初始化定时任务成功")
  1523. } else {
  1524. logger.Debug("初始化定时任务失败")
  1525. }
  1526. return timeTaskTT
  1527. }
  1528. // StartTask 开始任务
  1529. func StartTask(t *TTask) {
  1530. defer util.Catch()
  1531. logger.Debug("开始执行定时任务")
  1532. query := map[string]interface{}{
  1533. "_id": map[string]interface{}{
  1534. "$gt": u.StringTOBsonId(tools.IdCollSid),
  1535. },
  1536. "dataprocess": 8,
  1537. }
  1538. order := map[string]interface{}{"_id": -1}
  1539. logger.Debug("query:", query)
  1540. list, _ := tools.MgoClass.Find(t.S_idcoll, query, order, nil, false, -1, -1)
  1541. sid := t.S_startid
  1542. eid := ""
  1543. if list != nil && len(*list) > 0 {
  1544. eid = util.ObjToString((*list)[0]["lteid"])
  1545. if eid <= sid {
  1546. logger.Debug("id err. sid:", sid, " eid:", eid)
  1547. return
  1548. }
  1549. t.S_startid = eid //更新任务中数据的起始id
  1550. tools.IdCollSid = u.BsonIdToSId((*list)[0]["_id"]) //更新id表起始id
  1551. //更新任务表中起始id
  1552. setid := map[string]interface{}{
  1553. "$set": map[string]interface{}{
  1554. "s_startid": t.S_startid,
  1555. },
  1556. }
  1557. go tools.MgoClass.Update("rc_task", `{"_id":"`+t.ID+`"}`, setid, false, false)
  1558. //查拟建数据
  1559. query := map[string]interface{}{
  1560. "_id": map[string]interface{}{
  1561. "$gt": u.StringTOBsonId(sid),
  1562. "$lte": u.StringTOBsonId(eid),
  1563. },
  1564. "toptype": "拟建",
  1565. }
  1566. sess := t.MgoTask.GetMgoConn()
  1567. defer t.MgoTask.DestoryMongoConn(sess)
  1568. count, _ := sess.DB(t.S_mgodb).C(t.S_coll).Find(&query).Count()
  1569. logger.Debug("count:", count, " query:", query)
  1570. if count == 0 { //此轮任务没有查到数据
  1571. return
  1572. }
  1573. arr := [][]map[string]interface{}{}
  1574. wg := &sync.WaitGroup{}
  1575. lock := &sync.Mutex{}
  1576. pool := make(chan bool, t.I_thread)
  1577. sum := 0
  1578. logger.Debug("select:", t.Task_QueryFieldMap)
  1579. it := sess.DB(t.S_mgodb).C(t.S_coll).Find(&query).Select(t.Task_QueryFieldMap).Iter()
  1580. for tmp := make(map[string]interface{}); it.Next(&tmp); sum++ {
  1581. pool <- true
  1582. wg.Add(1)
  1583. go func(tmp map[string]interface{}) {
  1584. defer func() {
  1585. <-pool
  1586. wg.Done()
  1587. }()
  1588. update := []map[string]interface{}{}
  1589. update = append(update, map[string]interface{}{"_id": tmp["_id"]})
  1590. SMap := &tools.SortMap{}
  1591. SMap = NewClassificationRun(t, tmp)
  1592. if len(SMap.Map) > 0 {
  1593. //一级分类时,符合结果中成交规则时
  1594. if SMap.Map["toptype"] == "招标" && SMap.Map["subtype"] != "单一" {
  1595. if _, ok := tmp["detail"]; ok {
  1596. if u.ChargeDetailResult(util.ObjToString(tmp["detail"])) {
  1597. SMap.Map["toptype"] = "结果"
  1598. resa := ReSub(t, tmp, "结果")
  1599. subtype := resa.Map["subtype"]
  1600. delete(SMap.Map, "subtype")
  1601. SMap.Map["subtype"] = subtype
  1602. }
  1603. }
  1604. }
  1605. update = append(update, map[string]interface{}{"$set": SMap.Map})
  1606. }
  1607. //更新
  1608. lock.Lock()
  1609. if len(update) == 2 { //有更新条件和更新内容时才进行更新操作
  1610. arr = append(arr, update)
  1611. }
  1612. if len(arr) >= NN {
  1613. tmps := arr
  1614. t.MgoTask.UpdateBulk(t.S_coll, tmps...)
  1615. arr = [][]map[string]interface{}{}
  1616. }
  1617. lock.Unlock()
  1618. }(tmp)
  1619. if sum%100 == 0 {
  1620. log.Println("current:", sum)
  1621. }
  1622. tmp = make(map[string]interface{})
  1623. }
  1624. wg.Wait()
  1625. lock.Lock()
  1626. if len(arr) > 0 {
  1627. t.MgoTask.UpdateBulk(t.S_coll, arr...)
  1628. arr = [][]map[string]interface{}{}
  1629. }
  1630. lock.Unlock()
  1631. logger.Debug("定时任务执行完毕 count:", sum)
  1632. UdpRunProjectForecast(sid, eid)
  1633. }
  1634. logger.Debug("Udp通知项目预测执行完毕")
  1635. }
  1636. // udp通知项目预测
  1637. func UdpRunProjectForecast(sid, eid string) {
  1638. by, _ := json.Marshal(map[string]interface{}{
  1639. "gtid": sid,
  1640. "lteid": eid,
  1641. })
  1642. logger.Debug("定时任务通知项目预测:", string(by))
  1643. addr := &net.UDPAddr{
  1644. IP: net.ParseIP(tools.NextNodeAddr),
  1645. Port: tools.NextNodePort,
  1646. }
  1647. tools.Udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  1648. }
  1649. // SendAi 调用大模型招标分类;map[result:[结果-中标] status:200]
  1650. func SendAi(data map[string]interface{}, url string) (res map[string]interface{}) {
  1651. // 设置 2 秒的超时
  1652. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  1653. defer cancel()
  1654. //url := "http://192.168.3.109:16688"
  1655. jsonData, err := json.Marshal(data)
  1656. if err != nil {
  1657. fmt.Println("JSON marshal error:", err)
  1658. return
  1659. }
  1660. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
  1661. if err != nil {
  1662. fmt.Println("Request error:", err)
  1663. return
  1664. }
  1665. req.Header.Set("Content-Type", "application/json")
  1666. // 将请求与上下文关联
  1667. req = req.WithContext(ctx)
  1668. client := &http.Client{}
  1669. resp, err := client.Do(req)
  1670. if err != nil {
  1671. // 使用 errors.Is 检查错误是否是超时错误
  1672. if errors.Is(err, context.DeadlineExceeded) {
  1673. fmt.Println("Request timed out")
  1674. return
  1675. }
  1676. fmt.Println("Request error:", err)
  1677. return
  1678. }
  1679. defer resp.Body.Close()
  1680. err = json.NewDecoder(resp.Body).Decode(&res)
  1681. if err != nil {
  1682. fmt.Println("Response decoding error:", err)
  1683. return
  1684. }
  1685. return
  1686. }