task.go 50 KB

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