-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnode_manager.go
100 lines (82 loc) · 1.95 KB
/
node_manager.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
import (
"context"
"goimpulse/conf"
"net/http"
"goimpulse/lib"
"goimpulse/sender"
"time"
"fmt"
"io/ioutil"
"github.com/coreos/etcd/client"
"github.com/facebookgo/grace/gracehttp"
"github.com/labstack/echo"
log "github.com/sirupsen/logrus"
)
var masterHost string
func main() {
masterHost, _ = sender.GetMaster()
go watchMasterHost()
lib.OnReload()
e := echo.New()
e.GET("/getid", func(c echo.Context) error {
result := map[string]interface{}{
"id": -1,
"code": 0,
"msg": "success",
}
typeName := c.QueryParam("type")
httpClient := &http.Client{}
req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s/getid?type=%s", masterHost, typeName), nil)
user, pass, _ := c.Request().BasicAuth()
req.SetBasicAuth(user, pass)
if !lib.CheckAuth(req) {
result["code"] = -1
result["msg"] = "auth failed"
return c.JSON(http.StatusForbidden, result)
}
res, err := httpClient.Do(req)
if err != nil {
pass := false
for i := 0; i < 5; i++ {
res, err = httpClient.Do(req)
if err == nil {
pass = true
break
}
time.Sleep(800 * time.Millisecond)
}
if !pass {
result["code"] = -1
result["msg"] = "error"
return c.JSON(http.StatusInternalServerError, result)
}
}
data, _ := ioutil.ReadAll(res.Body)
res.Body.Close()
return c.JSONBlob(http.StatusOK, data)
})
log.Info("node_manager running...")
e.Server.Addr = conf.Cfg.NodeManager.Host
e.Server.SetKeepAlivesEnabled(false)
e.Logger.Fatal(gracehttp.Serve(e.Server))
}
func watchMasterHost() {
ec := lib.GetEtcd()
kapi := client.NewKeysAPI(ec)
watcher := kapi.Watcher(lib.MasterNode, nil)
for {
resp, _ := watcher.Next(context.Background())
if resp.Action == "expire" || resp.Action == "create" {
for i := 0; i < 3; i++ {
host, err := sender.GetMaster()
if err == nil {
masterHost = host
break
}
time.Sleep(100 * time.Millisecond)
}
}
time.Sleep(100 * time.Millisecond)
}
}