main.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. package main
  2. import (
  3. "cluster"
  4. "config"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/cron"
  8. "gopkg.in/mgo.v2/bson"
  9. "html/template"
  10. "log"
  11. "math"
  12. mu "mfw/util"
  13. "net"
  14. "net/http"
  15. qu "qfw/util"
  16. "qfw/util/mongodb"
  17. "regexp"
  18. "strings"
  19. "sync"
  20. "time"
  21. )
  22. var udpclient mu.UdpClient //udp对象
  23. var sys sync.RWMutex
  24. var DeleteNode = time.NewTimer(time.Minute * 50)
  25. func main() {
  26. udpclient = mu.UdpClient{Local: config.Sysconfig["udpip"].(string) + ":" + config.Sysconfig["udpport"].(string), BufSize: 1024}
  27. udpclient.Listen(processUdpMsg)
  28. log.Printf("Udp listening port: %s:%s\n", config.Sysconfig["udpip"], config.Sysconfig["udpport"])
  29. if config.Sysconfig["broadcast"].(bool) { //重启的话通知分布式节点
  30. ips := qu.ObjToString(config.Sysconfig["broadcast_ips"])
  31. ipsArr := strings.Split(ips, ";")
  32. for _, v := range ipsArr {
  33. udpclient.WriteUdp([]byte{}, mu.OP_TYPE_DATA, &net.UDPAddr{
  34. IP: net.ParseIP(v),
  35. Port: qu.IntAll(config.Sysconfig["broadcast_port"]),
  36. })
  37. }
  38. }
  39. mux := http.NewServeMux()
  40. mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
  41. http.Redirect(writer, request, "/login", http.StatusFound)
  42. })
  43. mux.HandleFunc("/favicon.ico", func(writer http.ResponseWriter, request *http.Request) {
  44. writer.WriteHeader(http.StatusOK)
  45. })
  46. mux.HandleFunc("/login", func(writer http.ResponseWriter, request *http.Request) {
  47. tp, err := template.ParseFiles("src/web/login.html")
  48. if err != nil {
  49. log.Println(err)
  50. writer.Write([]byte( "页面找不到了~"))
  51. return
  52. }
  53. if request.Method == "GET" {
  54. tp.Execute(writer, "")
  55. return
  56. }
  57. if request.Method == "POST" {
  58. err := request.ParseForm()
  59. if err != nil {
  60. http.Error(writer, err.Error(), http.StatusBadRequest)
  61. return
  62. }
  63. email := request.Form.Get("username")
  64. pwd := request.Form.Get("pwd")
  65. if email == "ocr_task" && pwd == "ocr_task_pwd" {
  66. http.SetCookie(writer, &http.Cookie{Name: "username", Value: qu.GetMd5String("email")})
  67. http.Redirect(writer, request, "/query", http.StatusFound)
  68. } else {
  69. writer.WriteHeader(http.StatusUnauthorized)
  70. tp.Execute(writer, "密码错误")
  71. }
  72. return
  73. }
  74. })
  75. res := http.FileServer(http.Dir("src/res"))
  76. mux.Handle("/res/", http.StripPrefix("/res/", res))
  77. mux.HandleFunc("/query", func(writer http.ResponseWriter, request *http.Request) {
  78. tplogin, err := template.ParseFiles("src/web/login.html")
  79. if err != nil {
  80. log.Println(err)
  81. writer.Write([]byte( "页面找不到了~"))
  82. return
  83. }
  84. cookie, _ := request.Cookie("username")
  85. if cookie == nil {
  86. http.RedirectHandler("/login", http.StatusUnauthorized)
  87. tplogin.Execute(writer, "请先登录")
  88. return
  89. }
  90. if cookie.Value != "0c83f57c786a0b4a39efab23731c7ebc" {
  91. http.RedirectHandler("/login", http.StatusUnauthorized)
  92. tplogin.Execute(writer, "密钥错误")
  93. return
  94. }
  95. tp, err := template.ParseFiles("src/web/index.html", "src/public/header.html")
  96. if err != nil {
  97. log.Println(err)
  98. writer.Write([]byte( "页面找不到了~"))
  99. return
  100. }
  101. task := queryOcrTask()
  102. tp.Execute(writer, task)
  103. })
  104. mux.HandleFunc("/reload", func(writer http.ResponseWriter, request *http.Request) {
  105. tplogin, err := template.ParseFiles("src/web/login.html")
  106. if err != nil {
  107. log.Println(err)
  108. writer.Write([]byte( "页面找不到了~"))
  109. return
  110. }
  111. cookie, _ := request.Cookie("username")
  112. if cookie == nil {
  113. http.RedirectHandler("/login", http.StatusUnauthorized)
  114. tplogin.Execute(writer, "请先登录")
  115. return
  116. }
  117. tpReload, err := template.ParseFiles("src/web/reload.html")
  118. if err != nil {
  119. log.Println(err)
  120. writer.Write([]byte( "页面找不到了~"))
  121. return
  122. }
  123. if request.Method == "POST" {
  124. err = request.ParseForm()
  125. if err != nil {
  126. tpReload.Execute(writer, err)
  127. return
  128. }
  129. data := request.PostForm["ips"]
  130. if len(data) <= 0 {
  131. tpReload.Execute(writer, "参数无效")
  132. return
  133. }
  134. var tmpstr string
  135. for _, v := range data {
  136. if !regexp.MustCompile("((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}").MatchString(v) {
  137. tmpstr += v + "ip格式不正确</br>"
  138. continue
  139. }
  140. result := reload(v)
  141. tmpstr += v + "---->" + result + "</br>"
  142. log.Println(v, "重新部署完成", )
  143. }
  144. tpReload.Execute(writer, template.HTML(
  145. "</br><span style=\"color: red\">"+tmpstr+" 重新部署结束</span></br>"+
  146. "</br>"+
  147. "<form action=\"/reload\" method=\"post\">"+
  148. "<input id=\"ips1\" name=\"ips\" placeholder=\"请输入实例ip\" required/></br>"+
  149. "<input type=\"submit\" value=\"提交\" />"+
  150. "</form>"))
  151. return
  152. }
  153. tpReload.Execute(writer, template.HTML("<form action=\"/reload\" method=\"post\">"+
  154. "<input id=\"ips1\" name=\"ips\" placeholder=\"请输入实例ip\" required/></br>"+
  155. "<input type=\"submit\" value=\"提交\" />"+
  156. "</form>"))
  157. })
  158. c := cron.New()
  159. spec := qu.ObjToString(config.Sysconfig["cornstr"])
  160. c.AddFunc(spec, func() {
  161. d := time.Now()
  162. nowday := time.Date(d.Year(), d.Month(), d.Day(), 0, 0, 0, 0, d.Location())
  163. taskArr := mongodb.Find("ocr_task", bson.M{}, `{_id:1}`, nil, false, -1, -1)
  164. taskNum := len(*taskArr)
  165. log.Println("当前任务数量:", taskNum)
  166. //if taskNum <= 0 {
  167. //计算释放,发送udp
  168. if !compute() {
  169. if len(config.Cnum) <= 0 {
  170. log.Println("当前实例为空,无需释放",config.Cnum,)
  171. return
  172. }
  173. tmpIid := config.Cnum[0]
  174. go func(tmpIid string) {
  175. DeleteNode.Reset(time.Minute * 50)
  176. <-DeleteNode.C
  177. config.Cnum = config.Cnum[1:]
  178. mongodb.Del("ocr_ecs", bson.M{"ip_nw": tmpIid})
  179. udpclient.WriteUdp([]byte("一小时后释放实例"), mu.OP_DELETE_DOWNLOADERCODES, &net.UDPAddr{
  180. IP: net.ParseIP(tmpIid),
  181. Port: qu.IntAll(config.Sysconfig["broadcast_port"]),
  182. })
  183. }(tmpIid)
  184. cluster.ModifyInstanceAutoReleaseTime(tmpIid, 1)
  185. log.Println("一小时后释放实例", tmpIid)
  186. return
  187. }
  188. //}
  189. if len(config.Cnum) >= qu.IntAll(config.Sysconfig["pernum"]) {
  190. log.Println("实例申请上限,当前实例:", config.Cnum)
  191. return
  192. }
  193. //if taskNum > 1 {
  194. cluster.DescribeInstances() //查询多台实例的详细信息
  195. ocrescs := mongodb.Find("ocr_ecs", bson.M{}, nil, bson.M{"AutoReleaseTime": 1}, false, -1, -1)
  196. if ocrescs != nil || len(*ocrescs) > 0 {
  197. for _, v := range (*ocrescs) {
  198. if qu.ObjToString(v["AutoReleaseTime"]) != "" {
  199. utc, err := time.ParseInLocation("2006-01-02T15:04Z", qu.ObjToString(v["AutoReleaseTime"]), time.Local)
  200. if err != nil {
  201. log.Println("解析时间异常", err)
  202. continue
  203. }
  204. if utc.Before(nowday) {
  205. log.Println("删除过时实例", mongodb.Del("ocr_ecs", bson.M{"_id": v["_id"].(bson.ObjectId)}))
  206. }
  207. }
  208. }
  209. }
  210. log.Println("申请实例")
  211. now := time.Now()
  212. hours := time.Date(now.Year(), now.Month(), now.Day(), 20, 0, 0, 0, now.Location()).Sub(now).Hours()
  213. cluster.RunInstances("ocr_task_arr", "8", "false", 1, int(math.Round(hours)))
  214. log.Println("实例申请成功")
  215. DynamicTask() //动态任务
  216. log.Println("申请实例结束")
  217. //}
  218. })
  219. c.Start()
  220. log.Println("Http listening port: ", qu.ObjToString(config.Sysconfig["http_port"]))
  221. if err := http.ListenAndServe(":"+qu.ObjToString(config.Sysconfig["http_port"]), mux); err != nil {
  222. fmt.Println("start http server faild:", err)
  223. }
  224. }
  225. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  226. defer qu.Catch()
  227. switch act {
  228. case mu.OP_TYPE_DATA: //保存服务
  229. go udpclient.WriteUdp([]byte("数据接收成功:"+string(data)), mu.OP_NOOP, ra)
  230. tmp := make(map[string]interface{})
  231. err := json.Unmarshal(data, &tmp)
  232. if err != nil {
  233. go udpclient.WriteUdp([]byte("数据接收成功:"+string(data)+",data解析失败,"+err.Error()), mu.OP_NOOP, ra)
  234. return
  235. }
  236. tmp["start"] = tmp[qu.ObjToString(config.SidField)]
  237. tmp["import_time"] = time.Now().Unix()
  238. bytes, _ := json.Marshal(tmp)
  239. b := mongodb.Save("ocr_task", string(bytes))
  240. mongodb.Save("ocr_task_bak", string(bytes))
  241. log.Println("保存id:", b)
  242. case mu.OP_NOOP: //其他节点回应消息打印
  243. log.Println("节点接收成功", string(data), ra.String())
  244. case mu.OP_GET_DOWNLOADERCODE: //分发任务
  245. if `{"permission":"get_ocr_task"}` != string(data) {
  246. log.Println("没有权限:", string(data), ra)
  247. go udpclient.WriteUdp([]byte("没有权限"), mu.OP_NOOP, ra)
  248. return
  249. }
  250. sys.Lock()
  251. datas := mongodb.Find("ocr_task", nil, `{"_id":1}`, nil, false, -1, -1)
  252. if len(*datas) == 0 {
  253. go udpclient.WriteUdp([]byte("没有新数据"), mu.OP_TYPE_DATA, ra)
  254. sys.Unlock()
  255. return
  256. }
  257. tmp := (*datas)[0]
  258. ObjectId := tmp["_id"]
  259. sid := qu.ObjToString(tmp[qu.ObjToString(config.SidField)])
  260. eid := qu.ObjToString(tmp[qu.ObjToString(config.EidField)])
  261. rdata := mongodb.FindOneByField(config.MgoC, bson.M{"_id": bson.M{
  262. "$gt": bson.ObjectIdHex(sid),
  263. }}, `{"_id":1,"`+config.MgoFileFiled+`":1}`)
  264. //log.Println(rdata)
  265. if len((*rdata)) == 0 {
  266. go udpclient.WriteUdp([]byte("没有获取到最新数据"), mu.OP_TYPE_DATA, ra)
  267. sys.Unlock()
  268. return
  269. }
  270. newId := (*rdata)["_id"]
  271. if newId.(bson.ObjectId).Hex() >= eid {
  272. go udpclient.WriteUdp([]byte(`{"id":"`+qu.ObjToString(tmp["start"])+`","permission":"ocr_task","is_start":"true"}`), mu.OP_TYPE_DATA, ra) //起始位置
  273. go udpclient.WriteUdp([]byte(`{"id":"`+newId.(bson.ObjectId).Hex()+`","permission":"ocr_task"}`), mu.OP_TYPE_DATA, ra) //分发任务
  274. totmp := make(map[string]string)
  275. totmp["sid"] = qu.ObjToString(tmp[qu.ObjToString("start")])
  276. totmp["eid"] = qu.ObjToString(tmp[qu.ObjToString(config.EidField)])
  277. tobyte, _ := json.Marshal(totmp)
  278. go udpclient.WriteUdp(tobyte, mu.OP_TYPE_DATA, &net.UDPAddr{
  279. IP: net.ParseIP(qu.ObjToString(config.Sysconfig["toudpip"])),
  280. Port: qu.IntAll(config.Sysconfig["toudpport"]),
  281. })
  282. log.Println("ocr_task处理完成,发送下个节点", string(tobyte))
  283. mongodb.Del("ocr_task", bson.M{"_id": ObjectId.(bson.ObjectId)})
  284. sys.Unlock()
  285. return
  286. }
  287. go udpclient.WriteUdp([]byte(`{"id":"`+newId.(bson.ObjectId).Hex()+`","permission":"ocr_task"}`), mu.OP_TYPE_DATA, ra) //分发任务
  288. //log.Println(newId.(bson.ObjectId).Hex())
  289. tmp[config.SidField] = newId.(bson.ObjectId).Hex()
  290. mongodb.Update("ocr_task",
  291. bson.M{"_id": ObjectId.(bson.ObjectId)}, tmp, false, false)
  292. sys.Unlock()
  293. }
  294. }
  295. func queryOcrTask() map[string]int {
  296. data := make(map[string]int)
  297. taskArr := mongodb.Find("ocr_task", bson.M{}, `{_id:1}`, nil, false, -1, -1)
  298. taskNum := len(*taskArr)
  299. if taskNum == 0 {
  300. return data
  301. }
  302. data["taskNum"] = taskNum
  303. sumNum := 0
  304. nowSumNum := 0
  305. for i, v := range *taskArr {
  306. sid := bson.ObjectIdHex(qu.ObjToString(v["start"]))
  307. eid := bson.ObjectIdHex(qu.ObjToString(v[qu.ObjToString(config.EidField)]))
  308. sumNum += mongodb.Count("bidding", bson.M{"_id": bson.M{
  309. "$gte": sid,
  310. "$lte": eid,
  311. }})
  312. if i == 0 {
  313. nowSumNum = sumNum
  314. }
  315. }
  316. data["sumNum"] = sumNum
  317. data["nowSumNum"] = nowSumNum
  318. tmpsid := bson.ObjectIdHex(qu.ObjToString((*taskArr)[0]["start"]))
  319. over := (*taskArr)[0][qu.ObjToString(config.SidField)]
  320. overNum := mongodb.Count("bidding", bson.M{"_id": bson.M{
  321. "$gte": tmpsid,
  322. "$lt": bson.ObjectIdHex(qu.ObjToString(over)),
  323. }})
  324. data["overNum"] = overNum
  325. undoneNum := sumNum - overNum
  326. data["undoneNum"] = undoneNum
  327. nowUnDoneNum := nowSumNum - overNum
  328. data["nowUnDoneNum"] = nowUnDoneNum
  329. return data
  330. }
  331. func DynamicTask() {
  332. time.Sleep(time.Second * 30)
  333. cluster.DescribeInstances() //查询多台实例的详细信息
  334. escObject := mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, false, -1, -1)
  335. log.Println("实例未部署数量", len(*escObject))
  336. if escObject != nil || len(*escObject) > 0 {
  337. for i, v := range (*escObject) {
  338. if tmpip := qu.ObjToString(v["ip_nw"]); tmpip == "" {
  339. log.Println("没用获取到ip,实例ip异常", tmpip)
  340. DynamicTask()
  341. } else {
  342. if DoCMD(tmpip) {
  343. var tmpstr string
  344. isok2, udpstr := cluster.SshPgrep(tmpip, "pgrep udp2019")
  345. tmpstr += udpstr + ";&nbsp;&nbsp;"
  346. isok3, fil2textstr := cluster.SshPgrep(tmpip, "pgrep file2text")
  347. tmpstr += fil2textstr
  348. if isok2 && isok3 {
  349. (*escObject)[i]["OcrTaskStatus"] = "successful"
  350. mongodb.Update("ocr_ecs", bson.M{"_id": (*escObject)[i]["_id"]}, (*escObject)[i], true, false)
  351. config.Cnum = append(config.Cnum, tmpip)
  352. log.Println((*escObject)[i]["_id"], tmpip, "部署成功")
  353. } else {
  354. log.Println(tmpip, "部署异常,"+tmpstr)
  355. }
  356. } else {
  357. log.Println(tmpip, "部署失败")
  358. }
  359. }
  360. }
  361. } else {
  362. log.Println("动态任务创建失败")
  363. }
  364. }
  365. func DoCMD(ip string) bool {
  366. if ip == "" {
  367. return false
  368. }
  369. return cluster.RunSsh(ip)
  370. }
  371. func reload(ip string) string {
  372. tmp := mongodb.FindOne("ocr_ecs", bson.M{"ip_nw": ip})
  373. if tmp == nil || len(*tmp) <= 0 {
  374. return "ip不存在"
  375. }
  376. for i, v := range config.Cnum {
  377. if v == ip {
  378. config.Cnum = append(config.Cnum[:i], config.Cnum[i+1:]...)
  379. break
  380. }
  381. }
  382. cluster.DeleteInstance(qu.ObjToString((*tmp)["InstanceId"])) //删除要重新部署的实例
  383. now := time.Now()
  384. hours := time.Date(now.Year(), now.Month(), now.Day(), 20, 0, 0, 0, now.Location()).Sub(now).Hours()
  385. cluster.RunInstances("ocr_task_arr", "8", "false", 1, int(math.Round(hours))) //创建新实例
  386. time.Sleep(time.Second * 30)
  387. cluster.DescribeInstances() //查询多台实例的详细信息
  388. escObject := mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, true, -1, -1)
  389. if escObject != nil || len(*escObject) > 0 {
  390. var tmpip string
  391. if tmpip = qu.ObjToString((*escObject)[0]["ip_nw"]); tmpip == "" {
  392. log.Println("没用获取到ip,实例ip异常", tmpip)
  393. time.Sleep(time.Minute)
  394. cluster.DescribeInstances() //查询多台实例的详细信息
  395. escObject = mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, true, -1, -1)
  396. tmpip = qu.ObjToString((*escObject)[0]["ip_nw"])
  397. }
  398. if DoCMD(tmpip) {
  399. var tmpstr string
  400. isok2, udpstr := cluster.SshPgrep(tmpip, "pgrep udp2019")
  401. tmpstr += udpstr + ";&nbsp;&nbsp;"
  402. isok3, fil2textstr := cluster.SshPgrep(tmpip, "pgrep file2text")
  403. tmpstr += fil2textstr
  404. if isok2 && isok3 {
  405. (*escObject)[0]["OcrTaskStatus"] = "successful"
  406. mongodb.Update("ocr_ecs", bson.M{"_id": (*escObject)[0]["_id"]}, (*escObject)[0], true, false)
  407. config.Cnum = append(config.Cnum, tmpip)
  408. log.Println((*escObject)[0]["_id"], tmpip, "部署成功")
  409. return tmpip + "部署成功," + tmpstr
  410. } else {
  411. return tmpip + "部署异常," + tmpstr
  412. }
  413. } else {
  414. return tmpip + "部署失败"
  415. }
  416. }
  417. return "重新部署" + ip + "未知错误,查询多台实例的详细信息,没有查询到新创建实例"
  418. }
  419. func compute() bool {
  420. nowtime := time.Now().Unix()
  421. taskArrase := mongodb.Find("ocr_task", bson.M{}, `{_id:1}`, nil, false, -1, -1)
  422. if taskArrase == nil || len(*taskArrase) == 0{
  423. return false
  424. }
  425. stmp := (*taskArrase)[0]
  426. etmp := (*taskArrase)[len(*taskArrase)-1]
  427. if stmp != nil && etmp != nil {
  428. stime := qu.Int64All(stmp["import_time"])
  429. if nowtime-stime <= 0 {
  430. return false
  431. }
  432. sid := bson.ObjectIdHex(qu.ObjToString(stmp["start"]))
  433. eid := bson.ObjectIdHex(qu.ObjToString(etmp[qu.ObjToString(config.EidField)]))
  434. sum := mongodb.Count("bidding", bson.M{"_id": bson.M{
  435. "$gte": sid,
  436. "$lt": eid,
  437. }})
  438. gteid := bson.ObjectIdHex(qu.ObjToString(stmp[qu.ObjToString(config.SidField)]))
  439. overNum := mongodb.Count("bidding", bson.M{"_id": bson.M{
  440. "$gte": sid,
  441. "$lt": gteid,
  442. }})
  443. log.Println("overNum:", overNum, ",hs:", int(nowtime-stime), ",sum:", sum)
  444. if overNum == 0 {
  445. return false
  446. }
  447. if overNum/int(nowtime-stime)*qu.IntAll(config.Sysconfig["corntime_consuming"]) >= sum {
  448. return false
  449. }
  450. return true
  451. }
  452. return false
  453. }