task.go 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755
  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. //一级分类成功,但是二级没有分类成功,并且原值里有subtype
  798. if _, ok := SMap.Map["toptype"]; ok {
  799. if _, ok2 := SMap.Map["subtype"]; !ok2 {
  800. if _, ok3 := tmp["subtype"]; ok3 {
  801. SMap.Map["subtype"] = ""
  802. }
  803. }
  804. }
  805. }
  806. }
  807. //2.针对用户行业分类,单独处理数据
  808. if mapInfo["stype"] == "yonghuhangye" || strings.TrimSpace(tt.S_name) == "用户行业分类" {
  809. subs := SMap.Map["subscope_dy"]
  810. delete(SMap.Map, "topscope_dy")
  811. var tops []string
  812. if subscopes, ok := subs.([]string); ok {
  813. for _, sub := range subscopes {
  814. top := strings.Split(sub, "_")[0]
  815. tops = append(tops, top)
  816. }
  817. SMap.Map["topscope_dy"] = u.RemoveDuplicateString(tops)
  818. }
  819. }
  820. //追加时处理,//更新字段 I_fieldUpdate 0:覆盖 1:追加
  821. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 {
  822. //封装追加信息
  823. if len(SMap.Keys) > 0 {
  824. for _, k := range SMap.Keys {
  825. ksarr := make([]string, 0)
  826. if k != "toptype" && k != "subtype" {
  827. ks, ok := SMap.Map[k].(string)
  828. if ok {
  829. ksarr = append(ksarr, ks)
  830. } else {
  831. ksarr = append(ksarr, SMap.Map[k].([]string)...)
  832. }
  833. }
  834. ksmap[k] = map[string][]string{
  835. "$each": ksarr,
  836. }
  837. }
  838. }
  839. } else { //非多分类
  840. res = SMap.Map
  841. if tt.I_tasktype == 1 { //附件任务
  842. if tmp["projectinfo"] != nil {
  843. res["projectinfo"] = tmp["projectinfo"]
  844. }
  845. }
  846. }
  847. }
  848. //if len(res) > 0 || len(ksmap) > 0 {
  849. IS.NewAdd(tt, res)
  850. if tt.S_attr != "" {
  851. //res[tt.S_attr] = 1
  852. res[tt.S_attr] = tt.AttrVal
  853. }
  854. // 添加分类时间
  855. res["classification_time"] = time.Now().Unix()
  856. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 { //I_fieldUpdate 0:覆盖 1:追加
  857. if len(ksmap) > 0 && len(res) > 0 {
  858. update = append(update, map[string]interface{}{
  859. "$set": res,
  860. "$addToSet": ksmap,
  861. })
  862. } else if len(ksmap) > 0 && len(res) == 0 {
  863. update = append(update, map[string]interface{}{
  864. "$addToSet": ksmap,
  865. })
  866. } else if len(ksmap) == 0 && len(res) > 0 {
  867. update = append(update, map[string]interface{}{
  868. "$set": res,
  869. })
  870. }
  871. } else { //非多分类或者多分类的覆盖
  872. //log.Println("更新==", res)
  873. if len(res) > 0 {
  874. update = append(update, map[string]interface{}{
  875. "$set": res,
  876. })
  877. }
  878. }
  879. //更新
  880. lock.Lock()
  881. if len(update) == 2 { //有更新条件和更新内容时才进行更新操作
  882. arr = append(arr, update)
  883. }
  884. if len(arr) >= NN {
  885. //if s_table == "" {
  886. tt.MgoTask.UpdateBulk(tt.S_collection, arr...)
  887. //} else {
  888. // tt.Mgo.UpdateAndSaveBulk(tt.S_collection, arr...)
  889. //}
  890. arr = [][]map[string]interface{}{}
  891. }
  892. lock.Unlock()
  893. //}
  894. }(tmp)
  895. ttid := u.BsonIdToSId(tid)
  896. if ttid > tt.LastId && !budp {
  897. tt.LastId = ttid
  898. }
  899. tmp = make(map[string]interface{})
  900. }
  901. total = sum
  902. //通过ID 查询分类数据才打印日志
  903. if tt.S_querycon == "1" {
  904. log.Println("总数:————", sum)
  905. if timespan {
  906. log.Println("current:————", sum)
  907. }
  908. }
  909. wg.Wait()
  910. lock.Lock()
  911. if len(arr) > 0 {
  912. //if s_table == "" { //没有结果表
  913. tt.MgoTask.UpdateBulk(tt.S_collection, arr...) //在原表上更新
  914. //} else { //有结果表
  915. // tt.Mgo.UpdateAndSaveBulk(tt.S_collection, arr...)
  916. //}
  917. arr = [][]map[string]interface{}{}
  918. }
  919. lock.Unlock()
  920. tt.WcLock.Lock()
  921. if len(tt.WordCount) > 0 {
  922. savem := []map[string]interface{}{}
  923. tn := time.Now().Unix()
  924. for wk, wm := range tt.WordCount {
  925. for ck, cm := range wm {
  926. m1 := map[string]interface{}{
  927. "s_class": wk,
  928. "s_word": ck,
  929. "i_count": cm,
  930. "bz": tn,
  931. }
  932. savem = append(savem, m1)
  933. if len(savem) >= 1000 {
  934. tools.MgoClass.SaveBulk("wordcount", savem...)
  935. savem = []map[string]interface{}{}
  936. }
  937. }
  938. }
  939. if len(savem) > 0 {
  940. tools.MgoClass.SaveBulk("wordcount", savem...)
  941. savem = nil
  942. }
  943. }
  944. tt.WcLock.Unlock()
  945. //更新最后id
  946. if !budp && oid != tt.LastId {
  947. setid := map[string]interface{}{
  948. "$set": map[string]interface{}{
  949. "s_startid": tt.LastId,
  950. },
  951. }
  952. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, setid, false, false)
  953. }
  954. //更新最后时间
  955. if !budp {
  956. nowtime := time.Now().Unix()
  957. settime := map[string]interface{}{
  958. "$set": map[string]interface{}{
  959. "s_starttime": nowtime,
  960. },
  961. }
  962. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, settime, false, false)
  963. }
  964. //InitRule()
  965. if tt.S_querycon == "1" {
  966. log.Println("运行", tt.S_name, "over", oid, " endid:", tt.LastId)
  967. }
  968. //定时任务完成发送udp信号调抽取
  969. if tools.Extract["preNodeId"] == tt.ID { //常规招标定时任务udp调用抽取
  970. if tt.S_idcoll == "" {
  971. nextNodeSid = oid
  972. nextNodeEid = tt.LastId
  973. }
  974. UdpRunExtract(nextNodeSid, nextNodeEid)
  975. }
  976. })
  977. return total
  978. }
  979. // udp合并数据处理的方法
  980. func UdpTaskRunAll(tt *TTask, budp bool, mapInfo map[string]interface{}, stype string) int {
  981. total := 0
  982. tools.Try(func() { //不加这一层defer运行不了!!!
  983. timespan := false
  984. tt.B_Running = true
  985. defer func() {
  986. tt.B_Running = false
  987. }()
  988. //开始识别
  989. pool := make(chan bool, tt.I_thread)
  990. wg := &sync.WaitGroup{}
  991. lock := &sync.Mutex{}
  992. q := map[string]interface{}{}
  993. s_table := tt.S_table //结果表
  994. s_asfield := tt.S_asfield //关联字段
  995. asfields := strings.Split(s_asfield, "==")
  996. qfield := "" //查询表字段
  997. rfield := "" //结果表字段
  998. qtp := "" //查询字段的类型
  999. rtp := "" //结果字段的类型
  1000. rtype := "" //结果字段的真实类型
  1001. if s_table != "" { //有结果表保存到结果表(更新,插入)
  1002. tt.S_collection = s_table
  1003. }
  1004. if len(asfields) == 2 {
  1005. qfield = asfields[0] //查询表字段
  1006. rfield = asfields[1] //结果表字段
  1007. //id处理 object string互转
  1008. qfield, rfield, qtp, rtp = IdTypeConversion(qfield, rfield)
  1009. queryExis := map[string]interface{}{
  1010. rfield: map[string]interface{}{
  1011. "$exists": true,
  1012. },
  1013. }
  1014. onedata, _ := tt.MgoTask.FindOne(tt.S_collection, queryExis)
  1015. rtype = reflect.TypeOf((*onedata)[rfield]).String() //结果表字段真实类型
  1016. }
  1017. //有结果表有关联字段,在结果表上根据关联字段更新;有结果表没有关联字段,在结果表根据_id段更新
  1018. //没有结果表在查询表上更新
  1019. //log.Println("lastid:", tt.LastId, "查询方式:", tt.S_querycon, "时间:", tt.S_starttime, "条件:", tt.S_query, "table:", tt.S_table, "s_timefieldname:", tt.S_timefieldname)
  1020. q = mapInfo["q"].(map[string]interface{})
  1021. //计算起始id和结束id时间宽度,大于半小时的2000数据打印一次个数,小于半小时的每条数据都打印一次个数
  1022. sid := mapInfo["gtid"].(string)
  1023. eid := mapInfo["lteid"].(string)
  1024. stime, _ := strconv.ParseInt(sid[:8], 16, 64)
  1025. etime, _ := strconv.ParseInt(eid[:8], 16, 64)
  1026. if etime-stime < 1800 { //时间跨度小于半小时
  1027. timespan = true
  1028. }
  1029. udpsess := tt.MulMgo.GetMgoConn()
  1030. if udpsess == nil {
  1031. log.Println("连接为空", tt.S_name, mapInfo)
  1032. return
  1033. }
  1034. defer tt.MulMgo.DestoryMongoConn(udpsess)
  1035. udptmp := udpsess.DB(tt.MulMgo.DbName).C(tt.MulColl).Find(&q).Select(tt.Task_QueryFieldMap).Sort("_id").Iter()
  1036. //task
  1037. tasksess := tt.MgoTask.GetMgoConn()
  1038. defer tt.MgoTask.DestoryMongoConn(tasksess)
  1039. log.Println("线程数:", tt.I_thread, "查询语句", q)
  1040. log.Println("task---", tt.S_mgodb, tt.S_coll, tt.S_collection, tt.S_table)
  1041. log.Println("select:", tt.Task_QueryFieldMap)
  1042. extractquery := tasksess.DB(tt.S_mgodb).C(tt.S_coll).Find(&q).Select(tt.Task_QueryFieldMap).Sort("_id").Iter()
  1043. arr := [][]map[string]interface{}{}
  1044. oid := tt.LastId
  1045. if tt.I_wordcount == 1 {
  1046. tt.WordCount = map[string]map[string]int{}
  1047. }
  1048. sum := 0
  1049. //对比两张表数据,减少查询次数
  1050. var compare bson.M
  1051. for tmp := make(map[string]interface{}); extractquery.Next(&tmp); sum++ {
  1052. result := tmp
  1053. //对比
  1054. for {
  1055. if compare == nil {
  1056. compare = make(bson.M)
  1057. if !udptmp.Next(&compare) { //传参表数据赋值给compare
  1058. break
  1059. }
  1060. }
  1061. if compare != nil {
  1062. //对比
  1063. cid := u.BsonIdToSId(compare["_id"]) //传参表id
  1064. tid := u.BsonIdToSId(tmp["_id"]) //抽取表id
  1065. if cid == tid {
  1066. //更新抽取表的数据,再进行分类
  1067. for _, k := range tt.Task_QueryFieldArr {
  1068. v1 := compare[k]
  1069. v2 := tmp[k]
  1070. if v2 == nil && v1 != nil {
  1071. result[k] = v1
  1072. }
  1073. }
  1074. break
  1075. } else {
  1076. if tid > cid { //抽取表id大于传参表id
  1077. compare = nil
  1078. continue
  1079. } else {
  1080. break
  1081. }
  1082. }
  1083. } else {
  1084. break
  1085. }
  1086. }
  1087. tid := tmp["_id"]
  1088. if !timespan && sum%2000 == 0 {
  1089. log.Println("current:", sum, tid)
  1090. }
  1091. pool <- true
  1092. wg.Add(1)
  1093. go func(result map[string]interface{}) {
  1094. defer func() {
  1095. <-pool
  1096. wg.Done()
  1097. }()
  1098. //按顺序识别
  1099. if result != nil {
  1100. tid := result["_id"]
  1101. update := []map[string]interface{}{}
  1102. //如果有关联字段 根据关联字段更新或者保存
  1103. if len(asfields) == 2 {
  1104. //log.Println("qfield====", qfield)
  1105. field := result[qfield]
  1106. if field != nil {
  1107. //log.Println("field===", field, qtp, rtp)
  1108. if qtp == "bson.ObjectId" && rtp == "bson.ObjectId" { //俩字段类型一致
  1109. } else {
  1110. //log.Println(field, " 查询字段", qfield, "查询类型", qtp, "结果字段", rfield, " 结果类型", rtp, "结果真实类型", rtype)
  1111. if rtype == rtp { //转换后与真实类型不同,填写时类型错误
  1112. //将查询字段类型转换为对应的结果字段类型
  1113. if qtp == "bson.ObjectId" && rtp == "string" {
  1114. field = u.BsonIdToSId(result[qfield])
  1115. } else if qtp == "string" && rtp == "bson.ObjectId" {
  1116. field = u.StringTOBsonId(result[qfield].(string))
  1117. }
  1118. }
  1119. }
  1120. update = append(update, map[string]interface{}{ //根据关联字段更新
  1121. rfield: field,
  1122. })
  1123. }
  1124. } else {
  1125. update = append(update, map[string]interface{}{ //更新的条件 根据id更新
  1126. "_id": tid,
  1127. })
  1128. }
  1129. res := map[string]interface{}{}
  1130. ksmap := make(map[string]map[string][]string)
  1131. if util.IntAll(result["infoformat"]) == 2 { //此处增加特例
  1132. res["toptype"] = "拟建"
  1133. res["subtype"] = "拟建"
  1134. } else if util.IntAll(result["infoformat"]) == 3 {
  1135. res["toptype"] = "产权"
  1136. res["subtype"] = "产权"
  1137. } else {
  1138. SMap := &tools.SortMap{}
  1139. if tt.I_tasktype == 2 { //标签任务
  1140. SMap = TagClassificationRun(tt, result)
  1141. } else if tt.I_tasktype == 1 { //附件任务
  1142. SMap = FileClassificationRun(tt, result)
  1143. //res["projectinfo"] = tmp["projectinfo"]
  1144. } else { //常规任务
  1145. SMap = NewClassificationRun(tt, result)
  1146. //一级分类时,符合结果中成交规则时
  1147. if SMap.Map["toptype"] == "招标" && SMap.Map["subtype"] != "单一" {
  1148. if _, ok := tmp["detail"]; ok {
  1149. if u.ChargeDetailResult(util.ObjToString(tmp["detail"])) {
  1150. SMap.Map["toptype"] = "结果"
  1151. resa := ReSub(tt, tmp, "结果")
  1152. subtype := resa.Map["subtype"]
  1153. delete(SMap.Map, "subtype")
  1154. SMap.Map["subtype"] = subtype
  1155. }
  1156. }
  1157. }
  1158. }
  1159. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 { //更新字段 I_fieldUpdate 0:覆盖 1:追加
  1160. //封装追加信息
  1161. if len(SMap.Keys) > 0 {
  1162. for _, k := range SMap.Keys {
  1163. ksarr := make([]string, 0)
  1164. if k != "toptype" && k != "subtype" {
  1165. ks, ok := SMap.Map[k].(string)
  1166. if ok {
  1167. ksarr = append(ksarr, ks)
  1168. } else {
  1169. ksarr = append(ksarr, SMap.Map[k].([]string)...)
  1170. }
  1171. }
  1172. ksmap[k] = map[string][]string{
  1173. "$each": ksarr,
  1174. }
  1175. }
  1176. }
  1177. } else {
  1178. res = SMap.Map
  1179. }
  1180. }
  1181. IS.NewAdd(tt, res)
  1182. if tt.S_attr != "" {
  1183. res[tt.S_attr] = tt.AttrVal
  1184. }
  1185. if tt.I_fieldUpdate == 1 && tt.I_multiclass == 1 { //I_fieldUpdate 0:覆盖 1:追加
  1186. if len(ksmap) > 0 && len(res) > 0 {
  1187. update = append(update, map[string]interface{}{
  1188. "$set": res,
  1189. "$addToSet": ksmap,
  1190. })
  1191. } else if len(ksmap) > 0 && len(res) == 0 {
  1192. update = append(update, map[string]interface{}{
  1193. "$addToSet": ksmap,
  1194. })
  1195. } else if len(ksmap) == 0 && len(res) > 0 {
  1196. update = append(update, map[string]interface{}{
  1197. "$set": res,
  1198. })
  1199. }
  1200. } else {
  1201. if len(res) > 0 {
  1202. update = append(update, map[string]interface{}{
  1203. "$set": res,
  1204. })
  1205. }
  1206. }
  1207. //更新
  1208. lock.Lock()
  1209. if len(update) == 2 { //有更新条件和更新内容时才进行更新操作
  1210. arr = append(arr, update)
  1211. }
  1212. if len(arr) >= NN {
  1213. tt.MgoTask.UpdateBulk(tt.S_collection, arr...)
  1214. arr = [][]map[string]interface{}{}
  1215. }
  1216. lock.Unlock()
  1217. }
  1218. }(result)
  1219. ttid := u.BsonIdToSId(tid)
  1220. if ttid > tt.LastId {
  1221. tt.LastId = ttid
  1222. }
  1223. tmp = make(map[string]interface{})
  1224. }
  1225. total = sum
  1226. if timespan {
  1227. log.Println("current:", sum)
  1228. }
  1229. wg.Wait()
  1230. lock.Lock()
  1231. if len(arr) > 0 {
  1232. //if s_table == "" { //没有结果表
  1233. tt.MgoTask.UpdateBulk(tt.S_collection, arr...) //在原表上更新
  1234. //} else { //有结果表
  1235. // tt.Mgo.UpdateAndSaveBulk(tt.S_collection, arr...)
  1236. //}
  1237. arr = [][]map[string]interface{}{}
  1238. }
  1239. lock.Unlock()
  1240. tt.WcLock.Lock()
  1241. if len(tt.WordCount) > 0 {
  1242. savem := []map[string]interface{}{}
  1243. tn := time.Now().Unix()
  1244. for wk, wm := range tt.WordCount {
  1245. for ck, cm := range wm {
  1246. m1 := map[string]interface{}{
  1247. "s_class": wk,
  1248. "s_word": ck,
  1249. "i_count": cm,
  1250. "bz": tn,
  1251. }
  1252. savem = append(savem, m1)
  1253. if len(savem) >= 1000 {
  1254. tools.MgoClass.SaveBulk("wordcount", savem...)
  1255. savem = []map[string]interface{}{}
  1256. }
  1257. }
  1258. }
  1259. if len(savem) > 0 {
  1260. tools.MgoClass.SaveBulk("wordcount", savem...)
  1261. savem = nil
  1262. }
  1263. }
  1264. tt.WcLock.Unlock()
  1265. //更新最后id
  1266. if !budp && oid != tt.LastId {
  1267. setid := map[string]interface{}{
  1268. "$set": map[string]interface{}{
  1269. "s_startid": tt.LastId,
  1270. },
  1271. }
  1272. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, setid, false, false)
  1273. }
  1274. //更新最后时间
  1275. if !budp {
  1276. nowtime := time.Now().Unix()
  1277. settime := map[string]interface{}{
  1278. "$set": map[string]interface{}{
  1279. "s_starttime": nowtime,
  1280. },
  1281. }
  1282. go tools.MgoClass.Update("rc_task", `{"_id":"`+tt.ID+`"}`, settime, false, false)
  1283. }
  1284. //InitRule()
  1285. log.Println("运行", tt.S_name, "over")
  1286. })
  1287. return total
  1288. }
  1289. func UdpRunExtract(sid, eid string) { //5cb6c508a5cb26b9b70d6536
  1290. by, _ := json.Marshal(map[string]interface{}{
  1291. "gtid": sid,
  1292. "lteid": eid,
  1293. "stype": tools.ExtractStype,
  1294. })
  1295. log.Println("定时任务调下一节点分类:", tools.ExtractPort, string(by))
  1296. addr := &net.UDPAddr{
  1297. IP: net.ParseIP(tools.ExtractAddr),
  1298. Port: tools.ExtractPort,
  1299. }
  1300. //node := &tools.UdpNode{by, addr, time.Now().Unix(), 0}
  1301. //udptaskmap.Store(key, node)
  1302. tools.Udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  1303. }
  1304. func FindId_back(coll string) (gtid, lteid string) {
  1305. sum := 0 //记录数据总量
  1306. data, _ := tools.MgoClass.Find(coll, `{"isused":false}`, `{"_id":1}`, nil, false, -1, -1)
  1307. length := len(*data)
  1308. set := bson.M{
  1309. "$set": bson.M{
  1310. "isused": true,
  1311. "publishtime": time.Now().Unix(),
  1312. },
  1313. }
  1314. for i, d := range *data {
  1315. id := d["_id"]
  1316. count := util.IntAll(d["count"])
  1317. sum += count
  1318. if gtid == "" {
  1319. gtid = d["gtid"].(string)
  1320. }
  1321. if sum >= 5000 || i == length-1 { //总数大于5000或数据取完,取此id段数据
  1322. lteid := d["lteid"].(string)
  1323. go tools.MgoClass.Update(coll, bson.M{"_id": id}, set, false, false)
  1324. return gtid, lteid
  1325. } else { //总数小于5000,删除已使用数据
  1326. go tools.MgoClass.Update(coll, bson.M{"_id": id}, set, false, false)
  1327. }
  1328. }
  1329. return gtid, lteid
  1330. }
  1331. func FindId(coll string) (gtid, lteid string) {
  1332. data, _ := tools.MgoClass.Find(coll, map[string]interface{}{"dataprocess": 0}, `{"_id":1}`, nil, false, -1, -1)
  1333. for _, d := range *data {
  1334. gtid = d["gtid"].(string)
  1335. lteid = d["lteid"].(string)
  1336. set := map[string]interface{}{
  1337. "$set": map[string]interface{}{
  1338. "dataprocess": 2,
  1339. "updatetime": time.Now().Unix(),
  1340. },
  1341. }
  1342. tools.MgoClass.Update(coll, map[string]interface{}{"_id": d["_id"]}, set, false, false)
  1343. break
  1344. }
  1345. return gtid, lteid
  1346. }
  1347. // NewLoadTestTask 测试任务
  1348. func NewLoadTestTask(_id, s_mgourl, s_mgodb, s_coll, i_poolsize, s_startid, s_endid, s_query string) (bs bool, filename string) {
  1349. defer tools.Catch()
  1350. r, t, _ := NewAnalyTask(_id, s_mgourl, s_mgodb, s_coll, tools.IntAllDef(i_poolsize, 5))
  1351. //log.Println(m)
  1352. if r && t != nil {
  1353. filename = time.Now().Format("150405") + ".csv"
  1354. go t.RRunTest(s_startid, s_endid, s_query, filename)
  1355. bs = true
  1356. }
  1357. return
  1358. }
  1359. // NewLoadTask 加载任务
  1360. func NewLoadTask(_id string, res *tools.JSON) {
  1361. defer tools.Catch()
  1362. //初始化任务信息
  1363. InitTaskData(_id)
  1364. //初始化任务mgo配置信息
  1365. bres, tt, msg := NewAnalyTask(_id, "", "", "", 5)
  1366. tt.I_status = 1
  1367. log.Println(tt.S_mgodb, tt.S_name, tt.I_thread)
  1368. res.Msg = msg
  1369. if bres && tt != nil {
  1370. res.Status = true
  1371. NEWTASKPOOL[_id] = tt //存入当前启动任务
  1372. log.Println("加载", tt.S_name, "完成...", tt.S_query)
  1373. go tt.RRun()
  1374. }
  1375. }
  1376. // 处理id的类型转换
  1377. func IdTypeConversion(q, r string) (string, string, string, string) {
  1378. qtp, rtp := "bson.ObjectId", "bson.ObjectId"
  1379. if strings.Contains(q, "ObjectId") || strings.Contains(q, "objectId") {
  1380. q = q[9 : len(q)-1]
  1381. } else if strings.Contains(q, "StringId") || strings.Contains(q, "stringId") {
  1382. q = q[9 : len(q)-1]
  1383. qtp = "string"
  1384. }
  1385. if strings.Contains(r, "ObjectId") || strings.Contains(r, "objectId") {
  1386. r = r[9 : len(r)-1]
  1387. } else if strings.Contains(r, "StringId") || strings.Contains(r, "stringId") {
  1388. r = r[9 : len(r)-1]
  1389. rtp = "string"
  1390. }
  1391. return q, r, qtp, rtp
  1392. }
  1393. // 获取匹配或不匹配的个数
  1394. func GetNum(rule string) (int, bool) {
  1395. num := 1
  1396. isnum := strings.HasSuffix(rule, ")")
  1397. if !isnum { //是数字
  1398. s := []rune(rule)
  1399. last := string(s[len(s)-1:])
  1400. num = tools.IntAll(last)
  1401. }
  1402. return num, isnum
  1403. }
  1404. // 获取规则
  1405. func GetRule(text string, isnum bool) (matchArr []string) {
  1406. if isnum { //最后一个不是数字
  1407. if strings.HasPrefix(text, "(") && strings.HasSuffix(text, ")") {
  1408. text = text[1 : len(text)-1]
  1409. matchArr = strings.Split(text, "|")
  1410. }
  1411. } else if strings.HasPrefix(text, "(") && !isnum {
  1412. text = text[1 : len(text)-2]
  1413. matchArr = strings.Split(text, "|")
  1414. }
  1415. return matchArr
  1416. }
  1417. func (d *DFA) AddWord(keys ...string) {
  1418. d.AddWordAll(true, keys...)
  1419. }
  1420. func (d *DFA) AddWordAll(haskey bool, keys ...string) {
  1421. if d.Link == nil {
  1422. d.Link = make(map[string]interface{})
  1423. }
  1424. for _, key := range keys {
  1425. nowMap := &d.Link
  1426. for i := 0; i < len(key); i++ {
  1427. kc := key[i : i+1]
  1428. if v, ok := (*nowMap)[kc]; ok {
  1429. nowMap, _ = v.(*map[string]interface{})
  1430. } else {
  1431. newMap := map[string]interface{}{}
  1432. newMap["YN"] = "0"
  1433. (*nowMap)[kc] = &newMap
  1434. nowMap = &newMap
  1435. }
  1436. if i == len(key)-1 {
  1437. (*nowMap)["YN"] = "1"
  1438. if haskey {
  1439. (*nowMap)["K"] = key
  1440. }
  1441. }
  1442. }
  1443. }
  1444. }
  1445. func (d *DFA) CheckSensitiveWord(src string, n int) (bool, []string) {
  1446. res := make([]string, 0)
  1447. tmpMap := make(map[string]int)
  1448. for j := 0; j < len(src); j++ {
  1449. nowMap := &d.Link
  1450. for i := j; i < len(src); i++ {
  1451. word := src[i : i+1]
  1452. nowMap, _ = (*nowMap)[word].(*map[string]interface{})
  1453. if nowMap != nil { // 存在,则判断是否为最后一个
  1454. if "1" == util.ObjToString((*nowMap)["YN"]) {
  1455. s := util.ObjToString((*nowMap)["K"])
  1456. tmpMap[s] = 1
  1457. //nowMap = &d.Link //匹配到之后继续匹配后边的内容
  1458. }
  1459. } else {
  1460. //nowMap = &d.Link
  1461. break
  1462. }
  1463. }
  1464. }
  1465. if len(tmpMap) >= n {
  1466. for k, _ := range tmpMap {
  1467. res = append(res, k)
  1468. }
  1469. return true, res
  1470. }
  1471. return false, []string{}
  1472. }
  1473. func (d *DFA) CheckSensitiveWordTest(src string, n int) (bool, []string) {
  1474. res := make([]string, 0)
  1475. tmpMap := make(map[string]int)
  1476. for j := 0; j < len(src); j++ {
  1477. nowMap := &d.Link
  1478. for i := j; i < len(src); i++ {
  1479. word := src[i : i+1]
  1480. nowMap, _ = (*nowMap)[word].(*map[string]interface{})
  1481. if nowMap != nil { // 存在,则判断是否为最后一个
  1482. if "1" == util.ObjToString((*nowMap)["YN"]) {
  1483. s := util.ObjToString((*nowMap)["K"])
  1484. tmpMap[s] = 1
  1485. //nowMap = &d.Link //匹配到之后继续匹配后边的内容
  1486. }
  1487. } else {
  1488. //nowMap = &d.Link
  1489. break
  1490. }
  1491. }
  1492. }
  1493. for k, _ := range tmpMap {
  1494. res = append(res, k)
  1495. }
  1496. return len(tmpMap) >= n, res
  1497. }
  1498. // UpdateTaskInfo 更新任务信息
  1499. func UpdateTaskInfo(flag bool, tid string) bool {
  1500. query := bson.M{
  1501. "_id": u.StringTOBsonId(tid),
  1502. }
  1503. set := bson.M{
  1504. "$set": bson.M{
  1505. "b_updaterule": flag,
  1506. },
  1507. }
  1508. return tools.MgoClass.Update(tools.COLL_TASK, query, set, false, false)
  1509. }
  1510. // o_projectinfo中数据分类定时任务
  1511. func RunTask() {
  1512. if tools.IsStart { //是否开启定时任务
  1513. tt := InitTimeTask() //初始化任务
  1514. //StartTask(tt)
  1515. //return
  1516. c := cron.New()
  1517. cronstr := "0 */" + fmt.Sprint(tt.I_rate) + " * * * ?" //每TaskTime分钟执行一次
  1518. c.AddFunc(cronstr, func() { StartTask(tt) })
  1519. c.Start()
  1520. }
  1521. }
  1522. // 初始化任务
  1523. func InitTimeTask() *TTask {
  1524. defer util.Catch()
  1525. timeTaskTT := &TTask{}
  1526. InitTaskData(tools.TimeTaskid)
  1527. bres, tt, _ := NewAnalyTask(tools.TimeTaskid, "", "", "", 5)
  1528. if bres && tt != nil {
  1529. timeTaskTT = tt
  1530. logger.Debug("初始化定时任务成功")
  1531. } else {
  1532. logger.Debug("初始化定时任务失败")
  1533. }
  1534. return timeTaskTT
  1535. }
  1536. // StartTask 开始任务
  1537. func StartTask(t *TTask) {
  1538. defer util.Catch()
  1539. logger.Debug("开始执行定时任务")
  1540. query := map[string]interface{}{
  1541. "_id": map[string]interface{}{
  1542. "$gt": u.StringTOBsonId(tools.IdCollSid),
  1543. },
  1544. "dataprocess": 8,
  1545. }
  1546. order := map[string]interface{}{"_id": -1}
  1547. logger.Debug("query:", query)
  1548. list, _ := tools.MgoClass.Find(t.S_idcoll, query, order, nil, false, -1, -1)
  1549. sid := t.S_startid
  1550. eid := ""
  1551. if list != nil && len(*list) > 0 {
  1552. eid = util.ObjToString((*list)[0]["lteid"])
  1553. if eid <= sid {
  1554. logger.Debug("id err. sid:", sid, " eid:", eid)
  1555. return
  1556. }
  1557. t.S_startid = eid //更新任务中数据的起始id
  1558. tools.IdCollSid = u.BsonIdToSId((*list)[0]["_id"]) //更新id表起始id
  1559. //更新任务表中起始id
  1560. setid := map[string]interface{}{
  1561. "$set": map[string]interface{}{
  1562. "s_startid": t.S_startid,
  1563. },
  1564. }
  1565. go tools.MgoClass.Update("rc_task", `{"_id":"`+t.ID+`"}`, setid, false, false)
  1566. //查拟建数据
  1567. query := map[string]interface{}{
  1568. "_id": map[string]interface{}{
  1569. "$gt": u.StringTOBsonId(sid),
  1570. "$lte": u.StringTOBsonId(eid),
  1571. },
  1572. "toptype": "拟建",
  1573. }
  1574. sess := t.MgoTask.GetMgoConn()
  1575. defer t.MgoTask.DestoryMongoConn(sess)
  1576. count, _ := sess.DB(t.S_mgodb).C(t.S_coll).Find(&query).Count()
  1577. logger.Debug("count:", count, " query:", query)
  1578. if count == 0 { //此轮任务没有查到数据
  1579. return
  1580. }
  1581. arr := [][]map[string]interface{}{}
  1582. wg := &sync.WaitGroup{}
  1583. lock := &sync.Mutex{}
  1584. pool := make(chan bool, t.I_thread)
  1585. sum := 0
  1586. logger.Debug("select:", t.Task_QueryFieldMap)
  1587. it := sess.DB(t.S_mgodb).C(t.S_coll).Find(&query).Select(t.Task_QueryFieldMap).Iter()
  1588. for tmp := make(map[string]interface{}); it.Next(&tmp); sum++ {
  1589. pool <- true
  1590. wg.Add(1)
  1591. go func(tmp map[string]interface{}) {
  1592. defer func() {
  1593. <-pool
  1594. wg.Done()
  1595. }()
  1596. update := []map[string]interface{}{}
  1597. update = append(update, map[string]interface{}{"_id": tmp["_id"]})
  1598. SMap := &tools.SortMap{}
  1599. SMap = NewClassificationRun(t, tmp)
  1600. if len(SMap.Map) > 0 {
  1601. //一级分类时,符合结果中成交规则时
  1602. if SMap.Map["toptype"] == "招标" && SMap.Map["subtype"] != "单一" {
  1603. if _, ok := tmp["detail"]; ok {
  1604. if u.ChargeDetailResult(util.ObjToString(tmp["detail"])) {
  1605. SMap.Map["toptype"] = "结果"
  1606. resa := ReSub(t, tmp, "结果")
  1607. subtype := resa.Map["subtype"]
  1608. delete(SMap.Map, "subtype")
  1609. SMap.Map["subtype"] = subtype
  1610. }
  1611. }
  1612. }
  1613. update = append(update, map[string]interface{}{"$set": SMap.Map})
  1614. }
  1615. //更新
  1616. lock.Lock()
  1617. if len(update) == 2 { //有更新条件和更新内容时才进行更新操作
  1618. arr = append(arr, update)
  1619. }
  1620. if len(arr) >= NN {
  1621. tmps := arr
  1622. t.MgoTask.UpdateBulk(t.S_coll, tmps...)
  1623. arr = [][]map[string]interface{}{}
  1624. }
  1625. lock.Unlock()
  1626. }(tmp)
  1627. if sum%100 == 0 {
  1628. log.Println("current:", sum)
  1629. }
  1630. tmp = make(map[string]interface{})
  1631. }
  1632. wg.Wait()
  1633. lock.Lock()
  1634. if len(arr) > 0 {
  1635. t.MgoTask.UpdateBulk(t.S_coll, arr...)
  1636. arr = [][]map[string]interface{}{}
  1637. }
  1638. lock.Unlock()
  1639. logger.Debug("定时任务执行完毕 count:", sum)
  1640. UdpRunProjectForecast(sid, eid)
  1641. }
  1642. logger.Debug("Udp通知项目预测执行完毕")
  1643. }
  1644. // udp通知项目预测
  1645. func UdpRunProjectForecast(sid, eid string) {
  1646. by, _ := json.Marshal(map[string]interface{}{
  1647. "gtid": sid,
  1648. "lteid": eid,
  1649. })
  1650. logger.Debug("定时任务通知项目预测:", string(by))
  1651. addr := &net.UDPAddr{
  1652. IP: net.ParseIP(tools.NextNodeAddr),
  1653. Port: tools.NextNodePort,
  1654. }
  1655. tools.Udpclient.WriteUdp(by, mu.OP_TYPE_DATA, addr)
  1656. }
  1657. // SendAi 调用大模型招标分类;map[result:[结果-中标] status:200]
  1658. func SendAi(data map[string]interface{}, url string) (res map[string]interface{}) {
  1659. // 设置 2 秒的超时
  1660. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  1661. defer cancel()
  1662. //url := "http://192.168.3.109:16688"
  1663. jsonData, err := json.Marshal(data)
  1664. if err != nil {
  1665. fmt.Println("JSON marshal error:", err)
  1666. return
  1667. }
  1668. req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
  1669. if err != nil {
  1670. fmt.Println("Request error:", err)
  1671. return
  1672. }
  1673. req.Header.Set("Content-Type", "application/json")
  1674. // 将请求与上下文关联
  1675. req = req.WithContext(ctx)
  1676. client := &http.Client{}
  1677. resp, err := client.Do(req)
  1678. if err != nil {
  1679. // 使用 errors.Is 检查错误是否是超时错误
  1680. if errors.Is(err, context.DeadlineExceeded) {
  1681. fmt.Println("Request timed out")
  1682. return
  1683. }
  1684. fmt.Println("Request error:", err)
  1685. return
  1686. }
  1687. defer resp.Body.Close()
  1688. err = json.NewDecoder(resp.Body).Decode(&res)
  1689. if err != nil {
  1690. fmt.Println("Response decoding error:", err)
  1691. return
  1692. }
  1693. return
  1694. }