main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. package main
  2. import (
  3. "cluster"
  4. "config"
  5. "corntask"
  6. "encoding/json"
  7. "fmt"
  8. "github.com/cron"
  9. "gopkg.in/mgo.v2/bson"
  10. "html/template"
  11. "info"
  12. "log"
  13. "math"
  14. mu "mfw/util"
  15. "net"
  16. "net/http"
  17. qu "qfw/util"
  18. "qfw/util/mongodb"
  19. "regexp"
  20. "strings"
  21. "time"
  22. )
  23. var DeleteNode = time.NewTimer(time.Minute * 50)
  24. func main() {
  25. config.Udpclient.Listen(processUdpMsg)
  26. log.Printf("Udp listening port: %s:%s\n", config.Sysconfig["udpip"], config.Sysconfig["udpport"])
  27. if config.Sysconfig["broadcast"].(bool) { //重启的话通知分布式节点
  28. ips := qu.ObjToString(config.Sysconfig["broadcast_ips"])
  29. ipsArr := strings.Split(ips, ";")
  30. for _, v := range ipsArr {
  31. log.Println("通知udp来取数据1:",v,config.Sysconfig["broadcast_port"],config.Udpclient.WriteUdp([]byte{}, mu.OP_TYPE_DATA, &net.UDPAddr{
  32. IP: net.ParseIP(v),
  33. Port: qu.IntAll(config.Sysconfig["broadcast_port"]),
  34. }))
  35. }
  36. }
  37. for _,v:= range config.CID{
  38. log.Println("通知udp来取数据2:",v,config.Sysconfig["broadcast_port"],config.Udpclient.WriteUdp([]byte{}, mu.OP_TYPE_DATA, &net.UDPAddr{
  39. IP: net.ParseIP(v),
  40. Port: qu.IntAll(config.Sysconfig["broadcast_port"]),
  41. }))
  42. }
  43. mux := http.NewServeMux()
  44. mux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
  45. http.Redirect(writer, request, "/login", http.StatusFound)
  46. })
  47. mux.HandleFunc("/favicon.ico", func(writer http.ResponseWriter, request *http.Request) {
  48. writer.WriteHeader(http.StatusOK)
  49. })
  50. mux.HandleFunc("/login", func(writer http.ResponseWriter, request *http.Request) {
  51. tp, err := template.ParseFiles("src/web/login.html")
  52. if err != nil {
  53. log.Println(err)
  54. writer.Write([]byte( "页面找不到了~"))
  55. return
  56. }
  57. if request.Method == "GET" {
  58. tp.Execute(writer, "")
  59. return
  60. }
  61. if request.Method == "POST" {
  62. err := request.ParseForm()
  63. if err != nil {
  64. http.Error(writer, err.Error(), http.StatusBadRequest)
  65. return
  66. }
  67. email := request.Form.Get("username")
  68. pwd := request.Form.Get("pwd")
  69. if email == "ocr_task" && pwd == "ocr_task_pwd" {
  70. http.SetCookie(writer, &http.Cookie{Name: "username", Value: qu.GetMd5String("email")})
  71. http.Redirect(writer, request, "/query", http.StatusFound)
  72. } else {
  73. writer.WriteHeader(http.StatusUnauthorized)
  74. tp.Execute(writer, "密码错误")
  75. }
  76. return
  77. }
  78. })
  79. res := http.FileServer(http.Dir("src/res"))
  80. mux.Handle("/res/", http.StripPrefix("/res/", res))
  81. mux.HandleFunc("/query", func(writer http.ResponseWriter, request *http.Request) {
  82. tplogin, err := template.ParseFiles("src/web/login.html")
  83. if err != nil {
  84. log.Println(err)
  85. writer.Write([]byte( "页面找不到了~"))
  86. return
  87. }
  88. cookie, _ := request.Cookie("username")
  89. if cookie == nil {
  90. http.RedirectHandler("/login", http.StatusUnauthorized)
  91. tplogin.Execute(writer, "请先登录")
  92. return
  93. }
  94. if cookie.Value != "0c83f57c786a0b4a39efab23731c7ebc" {
  95. http.RedirectHandler("/login", http.StatusUnauthorized)
  96. tplogin.Execute(writer, "密钥错误")
  97. return
  98. }
  99. tp, err := template.ParseFiles("src/web/index.html", "src/public/header.html")
  100. if err != nil {
  101. log.Println(err)
  102. writer.Write([]byte( "页面找不到了~"))
  103. return
  104. }
  105. task := info.QueryInfo()
  106. tp.Execute(writer, task)
  107. })
  108. mux.HandleFunc("/reload", func(writer http.ResponseWriter, request *http.Request) {
  109. tplogin, err := template.ParseFiles("src/web/login.html")
  110. if err != nil {
  111. log.Println(err)
  112. writer.Write([]byte( "页面找不到了~"))
  113. return
  114. }
  115. cookie, _ := request.Cookie("username")
  116. if cookie == nil {
  117. http.RedirectHandler("/login", http.StatusUnauthorized)
  118. tplogin.Execute(writer, "请先登录")
  119. return
  120. }
  121. tpReload, err := template.ParseFiles("src/web/reload.html")
  122. if err != nil {
  123. log.Println(err)
  124. writer.Write([]byte( "页面找不到了~"))
  125. return
  126. }
  127. if request.Method == "POST" {
  128. err = request.ParseForm()
  129. if err != nil {
  130. tpReload.Execute(writer, err)
  131. return
  132. }
  133. data := request.PostForm["ips"]
  134. if len(data) <= 0 {
  135. tpReload.Execute(writer, "参数无效")
  136. return
  137. }
  138. var tmpstr string
  139. for _, v := range data {
  140. 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) {
  141. tmpstr += v + "ip格式不正确</br>"
  142. continue
  143. }
  144. result := reload(v)
  145. tmpstr += v + "---->" + result + "</br>"
  146. log.Println(v, "重新部署完成", )
  147. }
  148. tpReload.Execute(writer, template.HTML(
  149. "</br><span style=\"color: red\">"+tmpstr+" 重新部署结束</span></br>"+
  150. "</br>"+
  151. "<form action=\"/reload\" method=\"post\">"+
  152. "<input id=\"ips1\" name=\"ips\" placeholder=\"请输入实例ip\" required/></br>"+
  153. "<input type=\"submit\" value=\"提交\" />"+
  154. "</form>"))
  155. return
  156. }
  157. tpReload.Execute(writer, template.HTML("<form action=\"/reload\" method=\"post\">"+
  158. "<input id=\"ips1\" name=\"ips\" placeholder=\"请输入实例ip\" required/></br>"+
  159. "<input type=\"submit\" value=\"提交\" />"+
  160. "</form>"))
  161. })
  162. c := cron.New()
  163. spec := qu.ObjToString(config.Sysconfig["cornstr"])
  164. c.AddFunc(spec, corntask.Auto)
  165. c.Start()
  166. log.Println("Http listening port: ", qu.ObjToString(config.Sysconfig["http_port"]))
  167. if err := http.ListenAndServe(":"+qu.ObjToString(config.Sysconfig["http_port"]), mux); err != nil {
  168. fmt.Println("start http server faild:", err)
  169. }
  170. }
  171. func processUdpMsg(act byte, data []byte, ra *net.UDPAddr) {
  172. defer qu.Catch()
  173. switch act {
  174. case mu.OP_TYPE_DATA: //保存服务
  175. go config.Udpclient.WriteUdp([]byte("数据接收成功:"+string(data)), mu.OP_NOOP, ra)
  176. tmp := make(map[string]interface{})
  177. err := json.Unmarshal(data, &tmp)
  178. if err != nil {
  179. go config.Udpclient.WriteUdp([]byte("数据接收成功:"+string(data)+",data解析失败,"+err.Error()), mu.OP_NOOP, ra)
  180. return
  181. }
  182. tmp["start"] = tmp[qu.ObjToString(config.SidField)]
  183. tmp["import_time"] = time.Now().Unix()
  184. bytes, _ := json.Marshal(tmp)
  185. b := mongodb.Save("ocr_task", string(bytes))
  186. mongodb.Save("ocr_task_bak", string(bytes))
  187. log.Println("保存id:", b)
  188. case mu.OP_NOOP: //其他节点回应消息打印
  189. log.Println("节点接收成功", string(data), ra.String())
  190. case mu.OP_GET_DOWNLOADERCODE: //分发任务
  191. if `{"permission":"get_ocr_task"}` != string(data) {
  192. log.Println("没有权限:", string(data), ra)
  193. go config.Udpclient.WriteUdp([]byte("没有权限"), mu.OP_NOOP, ra)
  194. return
  195. }
  196. config.Sys.Lock()
  197. datas := mongodb.Find("ocr_task", nil, `{"_id":1}`, nil, false, -1, -1)
  198. if len(*datas) == 0 {
  199. go config.Udpclient.WriteUdp([]byte("没有新数据"), mu.OP_TYPE_DATA, ra)
  200. config.Sys.Unlock()
  201. return
  202. }
  203. tmp := (*datas)[0]
  204. ObjectId := tmp["_id"]
  205. sid := qu.ObjToString(tmp[qu.ObjToString(config.SidField)])
  206. eid := qu.ObjToString(tmp[qu.ObjToString(config.EidField)])
  207. rdata := mongodb.FindOneByField(config.MgoC, bson.M{"_id": bson.M{
  208. "$gt": bson.ObjectIdHex(sid),
  209. }}, `{"_id":1,"`+config.MgoFileFiled+`":1}`)
  210. //log.Println(rdata)
  211. if len((*rdata)) == 0 {
  212. go config.Udpclient.WriteUdp([]byte("没有获取到最新数据"), mu.OP_TYPE_DATA, ra)
  213. config.Sys.Unlock()
  214. return
  215. }
  216. newId := (*rdata)["_id"]
  217. if newId.(bson.ObjectId).Hex() >= eid {
  218. go config.Udpclient.WriteUdp([]byte(`{"id":"`+qu.ObjToString(tmp["start"])+`","permission":"ocr_task","is_start":"true"}`), mu.OP_TYPE_DATA, ra) //起始位置
  219. go config.Udpclient.WriteUdp([]byte(`{"id":"`+newId.(bson.ObjectId).Hex()+`","permission":"ocr_task"}`), mu.OP_TYPE_DATA, ra) //分发任务
  220. totmp := make(map[string]string)
  221. totmp["sid"] = qu.ObjToString(tmp[qu.ObjToString("start")])
  222. totmp["eid"] = qu.ObjToString(tmp[qu.ObjToString(config.EidField)])
  223. tobyte, _ := json.Marshal(totmp)
  224. go config.Udpclient.WriteUdp(tobyte, mu.OP_TYPE_DATA, &net.UDPAddr{
  225. IP: net.ParseIP(qu.ObjToString(config.Sysconfig["toudpip"])),
  226. Port: qu.IntAll(config.Sysconfig["toudpport"]),
  227. })
  228. log.Println("ocr_task处理完成,发送下个节点", string(tobyte))
  229. mongodb.Del("ocr_task", bson.M{"_id": ObjectId.(bson.ObjectId)})
  230. tmp["end_time"] = time.Now().Unix()
  231. mongodb.Update("ocr_task_bak", bson.M{"_id": ObjectId.(bson.ObjectId)}, map[string]interface{}{"$set": tmp}, true, false)
  232. config.Sys.Unlock()
  233. return
  234. }
  235. go config.Udpclient.WriteUdp([]byte(`{"id":"`+newId.(bson.ObjectId).Hex()+`","permission":"ocr_task"}`), mu.OP_TYPE_DATA, ra) //分发任务
  236. //log.Println(newId.(bson.ObjectId).Hex())
  237. tmp[config.SidField] = newId.(bson.ObjectId).Hex()
  238. mongodb.Update("ocr_task",
  239. bson.M{"_id": ObjectId.(bson.ObjectId)}, tmp, false, false)
  240. config.Sys.Unlock()
  241. }
  242. }
  243. func reload(ip string) string {
  244. tmp := mongodb.FindOne("ocr_ecs", bson.M{"ip_nw": ip})
  245. if tmp == nil || len(*tmp) <= 0 {
  246. return "ip不存在"
  247. }
  248. config.Sys.Lock()
  249. if config.CID[qu.ObjToString((*tmp)["InstanceId"])] != "" {
  250. delete(config.CID, qu.ObjToString((*tmp)["InstanceId"]))
  251. }
  252. config.Sys.Unlock()
  253. cluster.DeleteInstance(qu.ObjToString((*tmp)["InstanceId"])) //删除要重新部署的实例
  254. now := time.Now()
  255. hours := time.Date(now.Year(), now.Month(), now.Day(), 20, 0, 0, 0, now.Location()).Sub(now).Hours()
  256. cluster.RunInstances("ocr_task_arr", "8", "false", 1, int(math.Round(hours))) //创建新实例
  257. time.Sleep(time.Second * 30)
  258. cluster.DescribeInstances() //查询多台实例的详细信息
  259. escObject := mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, true, -1, -1)
  260. if escObject != nil || len(*escObject) > 0 {
  261. var tmpip string
  262. if tmpip = qu.ObjToString((*escObject)[0]["ip_nw"]); tmpip == "" {
  263. log.Println("没用获取到ip,实例ip异常", tmpip)
  264. time.Sleep(time.Minute)
  265. cluster.DescribeInstances() //查询多台实例的详细信息
  266. escObject = mongodb.Find("ocr_ecs", bson.M{"TaskName": "ocr_task_arr", "OcrTaskStatus": "none"}, bson.M{"_id": -1}, nil, true, -1, -1)
  267. tmpip = qu.ObjToString((*escObject)[0]["ip_nw"])
  268. }
  269. if corntask.DoCMD(tmpip) {
  270. var tmpstr string
  271. isok2, udpstr := cluster.SshPgrep(tmpip, "pgrep udp2019")
  272. tmpstr += udpstr + ";&nbsp;&nbsp;"
  273. isok3, fil2textstr := cluster.SshPgrep(tmpip, "pgrep file2text")
  274. tmpstr += fil2textstr
  275. if isok2 && isok3 {
  276. (*escObject)[0]["OcrTaskStatus"] = "successful"
  277. mongodb.Update("ocr_ecs", bson.M{"_id": (*escObject)[0]["_id"]}, (*escObject)[0], true, false)
  278. config.Sys.Lock()
  279. if config.CID[qu.ObjToString((*escObject)[0]["InstanceId"])] == "" && qu.ObjToString((*escObject)[0]["InstanceId"]) !=""{
  280. config.CID[qu.ObjToString((*escObject)[0]["InstanceId"])] = tmpip
  281. }
  282. config.Sys.Unlock()
  283. log.Println((*escObject)[0]["_id"], tmpip, "部署成功")
  284. return tmpip + "部署成功," + tmpstr
  285. } else {
  286. return tmpip + "部署异常," + tmpstr
  287. }
  288. } else {
  289. return tmpip + "部署失败"
  290. }
  291. }
  292. return "重新部署" + ip + "未知错误,查询多台实例的详细信息,没有查询到新创建实例"
  293. }