This repository has been archived by the owner on Jul 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
202 lines (176 loc) · 5.33 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"bytes"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
"sort"
"strings"
)
const (
demoLabelKey = "com.infosiftr.kubecon-demo.active"
demoLabelVal = "yes"
randomBytes = 1024 * 1024
verboseDebugOutput = false
)
func docker(args ...string) (string, error) {
fmt.Fprintf(os.Stderr, "$ docker %q\n", args)
cmd := exec.Command("docker", args...)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = os.Stderr
err := cmd.Run()
outStr := strings.TrimSpace(out.String())
fmt.Fprintf(os.Stderr, "%s\n\n", outStr)
return outStr, err
}
func js(in interface{}) string {
b, err := json.MarshalIndent(in, "", "\t")
if err != nil {
panic(err)
}
return string(b)
}
func apiNodes(w http.ResponseWriter, r *http.Request) {
nodeServices := map[string]map[string]string{} // [node][service] = CurrentState
servicesTxt, _ := docker("service", "ls", "--format", "{{ .Name }}")
if servicesTxt != "" {
serviceNames := strings.Split(servicesTxt, "\n")
servicesTxt, _ = docker(append([]string{"service", "ps", "--filter", "desired-state=running", "--format", "{{ .Node }}|{{ .Name }}|{{ .CurrentState }}"}, serviceNames...)...)
for _, service := range strings.Split(servicesTxt, "\n") {
serviceParts := strings.SplitN(service, "|", 3)
if _, ok := nodeServices[serviceParts[0]]; !ok {
nodeServices[serviceParts[0]] = map[string]string{}
}
nodeServices[serviceParts[0]][serviceParts[1]] = serviceParts[2]
}
}
nodesTxt, err := docker("node", "ls", "--filter", "role=worker", "--format", "{{ .Hostname }}|{{ .ID }}|{{ .Availability }}")
if err != nil {
log.Print("docker node ls: ", err)
return
}
ret := []map[string]interface{}{}
nodes := strings.Split(nodesTxt, "\n")
sort.Strings(nodes)
for _, node := range nodes {
nodeParts := strings.SplitN(node, "|", 3)
if nodeParts[2] != "Active" {
// ignore unavailable nodes
continue
}
nodeRet := map[string]interface{}{
"ID": nodeParts[1],
"Hostname": nodeParts[0],
}
nodeRet["Services"] = nodeServices[nodeRet["Hostname"].(string)]
nodeActive, err := docker("node", "inspect", "--format", fmt.Sprintf("{{ index .Spec.Labels %q }}", demoLabelKey), nodeRet["ID"].(string))
nodeRet["DemoActive"] = err == nil && nodeActive == demoLabelVal
nodePlatform, err := docker("node", "inspect", "--format", "{{ .Description.Platform.OS }}|{{ .Description.Platform.Architecture }}", nodeRet["ID"].(string))
if err == nil {
nodePlatformParts := strings.SplitN(nodePlatform, "|", 2)
nodeRet["OS"] = nodePlatformParts[0]
nodeRet["Architecture"] = nodePlatformParts[1]
} else {
nodeRet["OS"] = nil
nodeRet["Architecture"] = nil
}
ret = append(ret, nodeRet)
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, js(ret))
}
func apiNodeActivate(w http.ResponseWriter, r *http.Request) {
node := r.URL.Query().Get("node")
if node == "" {
return
}
_, err := docker("node", "update", "--label-add", demoLabelKey+"="+demoLabelVal, node)
if err != nil {
log.Print("docker node update: ", err)
return
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, js(true))
}
func apiNodeDeactivate(w http.ResponseWriter, r *http.Request) {
node := r.URL.Query().Get("node")
if node == "" {
return
}
_, err := docker("node", "update", "--label-rm", demoLabelKey, node)
if err != nil {
log.Print("docker node update: ", err)
return
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, js(true))
}
func apiEcho(w http.ResponseWriter, r *http.Request) {
contentType := r.Header.Get("Content-Type")
if contentType != "" && r.Body != nil {
w.Header().Add("Content-Type", contentType)
io.Copy(w, r.Body)
} else {
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, js(true))
}
}
func wwwHome(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/static/", http.StatusFound)
}
func www() {
http.HandleFunc("/api/nodes", apiNodes)
http.HandleFunc("/api/node/activate", apiNodeActivate)
http.HandleFunc("/api/node/deactivate", apiNodeDeactivate)
http.HandleFunc("/api/echo", apiEcho)
http.HandleFunc("/", wwwHome)
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
log.Fatal(http.ListenAndServe(":8080", nil))
}
func md5sum(r io.Reader) string {
hash := md5.New()
io.Copy(hash, r)
return hex.EncodeToString(hash.Sum(nil))
}
func workerApiDump(apiServer string) {
echoEndpoint := fmt.Sprintf("http://%s:8080/api/echo", apiServer)
buf := make([]byte, randomBytes)
_, err := rand.Read(buf)
if err != nil {
log.Print("rand error: ", err)
return
}
log.Print("sending ", md5sum(bytes.NewReader(buf)))
resp, err := http.Post(echoEndpoint, "application/octet-stream", bytes.NewReader(buf))
if err != nil {
log.Print("post error: ", err)
return
}
defer resp.Body.Close()
log.Print("received ", md5sum(resp.Body))
}
// usage: kubecon-demo [api-server]
//
// run without arguments to start an api-server instance
// run with a single argument to blast data at "/api/echo" endpoint of the given api-server instance (blink blink blink go the lights)
func main() {
if len(os.Args) == 1 {
www()
} else {
if len(os.Args) != 2 {
log.Fatalf("wrong number of arguments! expected 1 or 2, not %d", len(os.Args)-1)
}
apiServer := os.Args[1]
for {
workerApiDump(apiServer)
}
}
}