main.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. return
  168. }
  169. //计算释放,发送udp
  170. if !compute() {
  171. if len(config.Cnum) <= 0 {
  172. return
  173. }
  174. tmpIid := config.Cnum[0]
  175. go func() {
  176. DeleteNode.Reset(time.Minute * 50)
  177. <-DeleteNode.C
  178. config.Cnum = config.Cnum[1:]
  179. }()
  180. cluster.ModifyInstanceAutoReleaseTime(tmpIid, 1)
  181. log.Println("一小时后释放实例", tmpIid)
  182. go func() {
  183. udpclient.WriteUdp([]byte("一小时后释放实例"), mu.OP_DELETE_DOWNLOADERCODES, &net.UDPAddr{
  184. IP: net.ParseIP(tmpIid),
  185. Port: qu.IntAll(config.Sysconfig["broadcast_port"]),
  186. })
  187. }()
  188. return
  189. }
  190. if len(config.Cnum) >= qu.IntAll(config.Sysconfig["pernum"]) {
  191. log.Println("实例申请上限,当前实例:", config.Cnum)
  192. return
  193. }
  194. //if taskNum > 1 {
  195. cluster.DescribeInstances() //查询多台实例的详细信息
  196. ocrescs := mongodb.Find("ocr_ecs", bson.M{}, nil, bson.M{"AutoReleaseTime": 1}, false, -1, -1)
  197. if ocrescs != nil || len(*ocrescs) > 0 {
  198. for _, v := range (*ocrescs) {
  199. if qu.ObjToString(v["AutoReleaseTime"]) != "" {
  200. utc, err := time.ParseInLocation("2006-01-02T15:04Z", qu.ObjToString(v["AutoReleaseTime"]), time.Local)
  201. if err != nil {
  202. log.Println("解析时间异常", err)
  203. continue
  204. }
  205. if utc.Before(nowday) {
  206. log.Println("删除过时实例", mongodb.Del("ocr_ecs", bson.M{"_id": v["_id"].(bson.ObjectId)}))
  207. }
  208. }
  209. }
  210. }
  211. log.Println("申请实例")
  212. now := time.Now()
  213. hours := time.Date(now.Year(), now.Month(), now.Day(), 20, 0, 0, 0, now.Location()).Sub(now).Hours()
  214. cluster.RunInstances("ocr_task_arr", "8", "false", 1, int(math.Round(hours)))
  215. log.Println("实例申请成功")
  216. DynamicTask() //动态任务
  217. log.Println("申请实例结束")
  218. //}
  219. })
  220. c.Start()
  221. log.Println("Http listening port: ", qu.ObjToString(config.Sysconfig["http_port"]))
  222. if err := http.ListenAndServe(":"+qu.ObjToString(config.Sysconfig["http_port"]), mux); err != nil {
  223. fmt.Println("start http server faild:", err)
  224. }
  225. }
  226. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  227. defer qu.Catch()
  228. switch act {
  229. case mu.OP_TYPE_DATA: //保存服务
  230. go udpclient.WriteUdp([]byte("数据接收成功:"+string(data)), mu.OP_NOOP, ra)
  231. tmp := make(map[string]interface{})
  232. err := json.Unmarshal(data, &tmp)
  233. if err != nil {
  234. go udpclient.WriteUdp([]byte("数据接收成功:"+string(data)+",data解析失败,"+err.Error()), mu.OP_NOOP, ra)
  235. return
  236. }
  237. tmp["start"] = tmp[qu.ObjToString(config.SidField)]
  238. tmp["import_time"] = time.Now().Unix()
  239. bytes, _ := json.Marshal(tmp)
  240. b := mongodb.Save("ocr_task", string(bytes))
  241. mongodb.Save("ocr_task_bak", string(bytes))
  242. log.Println("保存id:", b)
  243. case mu.OP_NOOP: //其他节点回应消息打印
  244. log.Println("节点接收成功", string(data), ra.String())
  245. case mu.OP_GET_DOWNLOADERCODE: //分发任务
  246. if `{"permission":"get_ocr_task"}` != string(data) {
  247. log.Println("没有权限:", string(data), ra)
  248. go udpclient.WriteUdp([]byte("没有权限"), mu.OP_NOOP, ra)
  249. return
  250. }
  251. sys.Lock()
  252. datas := mongodb.Find("ocr_task", nil, `{"_id":1}`, nil, false, -1, -1)
  253. if len(*datas) == 0 {
  254. go udpclient.WriteUdp([]byte("没有新数据"), mu.OP_TYPE_DATA, ra)
  255. sys.Unlock()
  256. return
  257. }
  258. tmp := (*datas)[0]
  259. ObjectId := tmp["_id"]
  260. sid := qu.ObjToString(tmp[qu.ObjToString(config.SidField)])
  261. eid := qu.ObjToString(tmp[qu.ObjToString(config.EidField)])
  262. rdata := mongodb.FindOneByField(config.MgoC, bson.M{"_id": bson.M{
  263. "$gt": bson.ObjectIdHex(sid),
  264. }}, `{"_id":1,"`+config.MgoFileFiled+`":1}`)
  265. //log.Println(rdata)
  266. if len((*rdata)) == 0 {
  267. go udpclient.WriteUdp([]byte("没有获取到最新数据"), mu.OP_TYPE_DATA, ra)
  268. sys.Unlock()
  269. return
  270. }
  271. newId := (*rdata)["_id"]
  272. if newId.(bson.ObjectId).Hex() >= eid {
  273. go udpclient.WriteUdp([]byte(`{"id":"`+qu.ObjToString(tmp["start"])+`","permission":"ocr_task","is_start":"true"}`), mu.OP_TYPE_DATA, ra) //起始位置
  274. go udpclient.WriteUdp([]byte(`{"id":"`+newId.(bson.ObjectId).Hex()+`","permission":"ocr_task"}`), mu.OP_TYPE_DATA, ra) //分发任务
  275. totmp := make(map[string]string)
  276. totmp["sid"] = qu.ObjToString(tmp[qu.ObjToString("start")])
  277. totmp["eid"] = qu.ObjToString(tmp[qu.ObjToString(config.EidField)])
  278. tobyte, _ := json.Marshal(totmp)
  279. go udpclient.WriteUdp(tobyte, mu.OP_TYPE_DATA, &net.UDPAddr{
  280. IP: net.ParseIP(qu.ObjToString(config.Sysconfig["toudpip"])),
  281. Port: qu.IntAll(config.Sysconfig["toudpport"]),
  282. })
  283. log.Println("ocr_task处理完成,发送下个节点", string(tobyte))
  284. mongodb.Del("ocr_task", bson.M{"_id": ObjectId.(bson.ObjectId)})
  285. sys.Unlock()
  286. return
  287. }
  288. go udpclient.WriteUdp([]byte(`{"id":"`+newId.(bson.ObjectId).Hex()+`","permission":"ocr_task"}`), mu.OP_TYPE_DATA, ra) //分发任务
  289. //log.Println(newId.(bson.ObjectId).Hex())
  290. tmp[config.SidField] = newId.(bson.ObjectId).Hex()
  291. mongodb.Update("ocr_task",
  292. bson.M{"_id": ObjectId.(bson.ObjectId)}, tmp, false, false)
  293. sys.Unlock()
  294. }
  295. }
  296. func queryOcrTask() map[string]int {
  297. data := make(map[string]int)
  298. taskArr := mongodb.Find("ocr_task", bson.M{}, `{_id:1}`, nil, false, -1, -1)
  299. taskNum := len(*taskArr)
  300. if taskNum == 0 {
  301. return data
  302. }
  303. data["taskNum"] = taskNum
  304. sumNum := 0
  305. nowSumNum := 0
  306. for i, v := range *taskArr {
  307. sid := bson.ObjectIdHex(qu.ObjToString(v["start"]))
  308. eid := bson.ObjectIdHex(qu.ObjToString(v[qu.ObjToString(config.EidField)]))
  309. sumNum += mongodb.Count("bidding", bson.M{"_id": bson.M{
  310. "$gte": sid,
  311. "$lte": eid,
  312. }})
  313. if i == 0 {
  314. nowSumNum = sumNum
  315. }
  316. }
  317. data["sumNum"] = sumNum
  318. data["nowSumNum"] = nowSumNum
  319. tmpsid := bson.ObjectIdHex(qu.ObjToString((*taskArr)[0]["start"]))
  320. over := (*taskArr)[0][qu.ObjToString(config.SidField)]
  321. overNum := mongodb.Count("bidding", bson.M{"_id": bson.M{
  322. "$gte": tmpsid,
  323. "$lt": bson.ObjectIdHex(qu.ObjToString(over)),
  324. }})
  325. data["overNum"] = overNum
  326. undoneNum := sumNum - overNum
  327. data["undoneNum"] = undoneNum
  328. nowUnDoneNum := nowSumNum - overNum
  329. data["nowUnDoneNum"] = nowUnDoneNum
  330. return data
  331. }
  332. func DynamicTask() {
  333. time.Sleep(time.Second * 30)
  334. cluster.DescribeInstances() //查询多台实例的详细信息
  335. escObject := mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, false, -1, -1)
  336. log.Println("实例未部署数量", len(*escObject))
  337. if escObject != nil || len(*escObject) > 0 {
  338. for i, v := range (*escObject) {
  339. if tmpip := qu.ObjToString(v["ip_nw"]); tmpip == "" {
  340. log.Println("没用获取到ip,实例ip异常", tmpip)
  341. DynamicTask()
  342. } else {
  343. if DoCMD(tmpip) {
  344. var tmpstr string
  345. isok2, udpstr := cluster.SshPgrep(tmpip, "pgrep udp2019")
  346. tmpstr += udpstr + ";&nbsp;&nbsp;"
  347. isok3, fil2textstr := cluster.SshPgrep(tmpip, "pgrep file2text")
  348. tmpstr += fil2textstr
  349. if isok2 && isok3 {
  350. (*escObject)[i]["OcrTaskStatus"] = "successful"
  351. mongodb.Update("ocr_ecs", bson.M{"_id": (*escObject)[i]["_id"]}, (*escObject)[i], true, false)
  352. config.Cnum = append(config.Cnum, tmpip)
  353. log.Println((*escObject)[i]["_id"], tmpip, "部署成功")
  354. } else {
  355. log.Println(tmpip, "部署异常,"+tmpstr)
  356. }
  357. } else {
  358. log.Println(tmpip, "部署失败")
  359. }
  360. }
  361. }
  362. } else {
  363. log.Println("动态任务创建失败")
  364. }
  365. }
  366. func DoCMD(ip string) bool {
  367. if ip == "" {
  368. return false
  369. }
  370. return cluster.RunSsh(ip)
  371. }
  372. func reload(ip string) string {
  373. tmp := mongodb.FindOne("ocr_ecs", bson.M{"ip_nw": ip})
  374. if tmp == nil || len(*tmp) <= 0 {
  375. return "ip不存在"
  376. }
  377. for i, v := range config.Cnum {
  378. if v == ip {
  379. config.Cnum = append(config.Cnum[:i], config.Cnum[i+1:]...)
  380. break
  381. }
  382. }
  383. cluster.DeleteInstance(qu.ObjToString((*tmp)["InstanceId"])) //删除要重新部署的实例
  384. now := time.Now()
  385. hours := time.Date(now.Year(), now.Month(), now.Day(), 20, 0, 0, 0, now.Location()).Sub(now).Hours()
  386. cluster.RunInstances("ocr_task_arr", "8", "false", 1, int(math.Round(hours))) //创建新实例
  387. time.Sleep(time.Second * 30)
  388. cluster.DescribeInstances() //查询多台实例的详细信息
  389. escObject := mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, true, -1, -1)
  390. if escObject != nil || len(*escObject) > 0 {
  391. var tmpip string
  392. if tmpip = qu.ObjToString((*escObject)[0]["ip_nw"]); tmpip == "" {
  393. log.Println("没用获取到ip,实例ip异常", tmpip)
  394. time.Sleep(time.Minute)
  395. cluster.DescribeInstances() //查询多台实例的详细信息
  396. escObject = mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, true, -1, -1)
  397. tmpip = qu.ObjToString((*escObject)[0]["ip_nw"])
  398. }
  399. if DoCMD(tmpip) {
  400. var tmpstr string
  401. isok2, udpstr := cluster.SshPgrep(tmpip, "pgrep udp2019")
  402. tmpstr += udpstr + ";&nbsp;&nbsp;"
  403. isok3, fil2textstr := cluster.SshPgrep(tmpip, "pgrep file2text")
  404. tmpstr += fil2textstr
  405. if isok2 && isok3 {
  406. (*escObject)[0]["OcrTaskStatus"] = "successful"
  407. mongodb.Update("ocr_ecs", bson.M{"_id": (*escObject)[0]["_id"]}, (*escObject)[0], true, false)
  408. config.Cnum = append(config.Cnum, tmpip)
  409. log.Println((*escObject)[0]["_id"], tmpip, "部署成功")
  410. return tmpip + "部署成功," + tmpstr
  411. } else {
  412. return tmpip + "部署异常," + tmpstr
  413. }
  414. } else {
  415. return tmpip + "部署失败"
  416. }
  417. }
  418. return "重新部署" + ip + "未知错误,查询多台实例的详细信息,没有查询到新创建实例"
  419. }
  420. func compute() bool {
  421. nowtime := time.Now().Unix()
  422. taskArrase := mongodb.Find("ocr_task", bson.M{}, `{_id:1}`, nil, false, -1, -1)
  423. stmp := (*taskArrase)[0]
  424. etmp := (*taskArrase)[len(*taskArrase)-1]
  425. if stmp != nil && etmp != nil {
  426. stime := qu.Int64All(stmp["import_time"])
  427. if nowtime-stime <= 0 {
  428. return false
  429. }
  430. sid := bson.ObjectIdHex(qu.ObjToString(stmp["start"]))
  431. eid := bson.ObjectIdHex(qu.ObjToString(etmp[qu.ObjToString(config.EidField)]))
  432. sum := mongodb.Count("bidding", bson.M{"_id": bson.M{
  433. "$gte": sid,
  434. "$lt": eid,
  435. }})
  436. gteid := bson.ObjectIdHex(qu.ObjToString(stmp[qu.ObjToString(config.SidField)]))
  437. overNum := mongodb.Count("bidding", bson.M{"_id": bson.M{
  438. "$gte": sid,
  439. "$lt": gteid,
  440. }})
  441. log.Println("overNum:", overNum, ",hs:", int(nowtime-stime), ",sum:", sum)
  442. if overNum == 0{
  443. return false
  444. }
  445. if overNum/int(nowtime-stime)*300 >= sum {
  446. return false
  447. }
  448. return true
  449. }
  450. return false
  451. }