/
cluster.go
106 lines (89 loc) · 2.11 KB
/
cluster.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
101
102
103
104
105
106
package api
import (
disc "github.com/jeffjen/go-discovery"
_ "github.com/Sirupsen/logrus"
etcd "github.com/coreos/etcd/client"
ctx "golang.org/x/net/context"
"encoding/json"
"net/http"
"path"
"strconv"
"time"
)
const (
DefaultRootPath = "/"
DefaultListClusterSize = 10
)
type Clusters struct {
Root string
Size int
Nodes []string
}
func checkCluster(c *Clusters, n *etcd.Node) {
if !n.Dir {
return // skipping because a cluster root is always a dir
}
for _, node := range n.Nodes { // traverse Depth First
if c.Size <= len(c.Nodes) {
return // capacity reached for this query
}
if node.Dir {
if path.Base(node.Key) == "docker" {
c.Nodes = append(c.Nodes, n.Key[1:len(n.Key)])
} else {
checkCluster(c, node)
}
}
}
}
func ClusterList(w http.ResponseWriter, r *http.Request) {
if err := common("GET", r); err != nil {
http.Error(w, err.Error(), 400)
return
}
// We are sending json data
w.Header().Add("Content-Type", "application/json")
var RootPath = DefaultRootPath
if root := r.Form.Get("root"); root != "" {
RootPath = root
}
var ClusterSize = DefaultListClusterSize
if projSizeStr := r.Form.Get("size"); projSizeStr != "" {
projSize, err := strconv.ParseInt(projSizeStr, 10, 0)
if err == nil {
ClusterSize = int(projSize)
}
}
var ClusterNodes = &Clusters{
Root: RootPath,
Size: ClusterSize,
Nodes: make([]string, 0, ClusterSize),
}
kAPI, _ := disc.NewKeysAPI(etcd.Config{
Endpoints: disc.Endpoints(),
})
work, abort := ctx.WithTimeout(ctx.Background(), 3*time.Second)
defer abort()
resp, err := kAPI.Get(work, RootPath, &etcd.GetOptions{
Recursive: true,
})
if err != nil {
json.NewEncoder(w).Encode(ClusterNodes)
return
}
// Go traverse the discovery tree
for _, node := range resp.Node.Nodes {
checkCluster(ClusterNodes, node)
}
ClusterNodes.Size = len(ClusterNodes.Nodes)
json.NewEncoder(w).Encode(ClusterNodes)
return
}
func ClusterCreate(w http.ResponseWriter, r *http.Request) {
if err := common("POST", r); err != nil {
http.Error(w, err.Error(), 400)
return
}
http.Error(w, ErrNotImplemented.Error(), 403)
return
}