main.go 14 KB

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