main.go 14 KB

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