main.go 14 KB

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