main.go 11 KB

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