-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
211 lines (182 loc) · 4.86 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
203
204
205
206
207
208
209
210
211
package main
import (
"bytes"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"path/filepath"
"regexp"
"strconv"
"strings"
)
var numNodes = flag.Int("n", 0, "number of nodes")
var attrs = make(perNodeAttribute)
var localities = make(perNodeAttribute)
var tmpls = map[string]*template.Template{}
// stringString conforms to the flag.Value interface
type perNodeAttribute map[int]string
func (p *perNodeAttribute) String() string {
var ids []int
for id := range *p {
ids = append(ids, id)
}
var buffer bytes.Buffer
for i, id := range ids {
if i != 0 {
_, _ = buffer.WriteRune(' ')
}
_, _ = buffer.WriteString(fmt.Sprintf("%d:%s", id, (*p)[id]))
}
return buffer.String()
}
func (p *perNodeAttribute) Set(value string) error {
splits := strings.SplitN(value, ":", 2)
if len(splits) != 2 {
return fmt.Errorf("could not parse value: %s", value)
}
id, err := strconv.ParseInt(splits[0], 10, 64)
if err != nil {
return fmt.Errorf("node id could not be parsed: %s", err)
}
(*p)[int(id)] = splits[1]
return nil
}
func render(asset string, data map[string]interface{}) (string, error) {
t, ok := tmpls[asset]
if !ok {
return "", fmt.Errorf("%s not found", asset)
}
var b bytes.Buffer
err := t.Execute(&b, data)
if err != nil {
log.Printf("failed executing template %s: %s", asset, err)
return "", err
}
return b.String(), nil
}
func renderSimple(rw http.ResponseWriter, asset string, data map[string]interface{}) {
html, err := render(asset, data)
if err != nil {
log.Fatal(err)
}
_, err = rw.Write([]byte(html))
if err != nil {
log.Print(err)
}
}
func renderError(rw http.ResponseWriter, message string) {
renderSimple(rw, "error.html", map[string]interface{}{"Error": message})
}
func renderLayout(rw http.ResponseWriter, asset string, layout string, key string,
data map[string]interface{}) {
html, err := render(asset, data)
if err != nil {
log.Fatal(err)
}
data[key] = template.HTML(html)
renderSimple(rw, layout, data)
}
type routeFn func(rw http.ResponseWriter, req *http.Request, args map[string]string)
type route struct {
re *regexp.Regexp
fn routeFn
}
func makeRoute(s string, fn routeFn) route {
return route{
re: regexp.MustCompile("^" + s + "$"),
fn: fn,
}
}
type routes []route
func (routes routes) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
path := req.URL.Path
for _, r := range routes {
m := r.re.FindStringSubmatch(path)
if m == nil {
continue
}
args := map[string]string{}
names := r.re.SubexpNames()
for i := range names {
if n := names[i]; n != "" {
args[n] = m[i]
}
}
r.fn(rw, req, args)
return
}
rw.WriteHeader(http.StatusNotFound)
renderSimple(rw, "notfound.html", nil)
}
func getCSS(rw http.ResponseWriter, req *http.Request, args map[string]string) {
asset, err := Asset("assets" + req.URL.Path)
if err != nil {
log.Print(err)
rw.WriteHeader(http.StatusNotFound)
renderError(rw, fmt.Sprintf("assets%s not found", req.URL.Path))
return
}
rw.Header().Add("Content-Type", "text/css")
_, err = rw.Write(asset)
if err != nil {
log.Print(err)
return
}
}
func init() {
flag.Var(&attrs, "a", "(repeatable) attrs to be assigned to specific nodes in the form node_id:value e.g. -a=1:ssd -a=2:x16c:ssd")
flag.Var(&localities, "l", "(repeatable) localities to be assigned to specific nodes in the form node_id:locality e.g. -l=1:country=us,region=us-west -l=2:country=ca,region=ca-east")
}
func main() {
flag.Parse()
for _, path := range AssetNames() {
if !strings.HasSuffix(path, ".html") {
continue
}
t := template.New(path)
asset, err := Asset(path)
if err != nil {
log.Fatal(err)
}
if _, err := t.Parse(string(asset)); err != nil {
log.Fatal(err)
}
tmpls[filepath.Base(path)] = t
}
c := newCluster(flag.Args(), attrs, localities)
defer c.close()
paths, _ := filepath.Glob(filepath.Join(dataDir, "*"))
for range paths {
c.newNode()
}
for len(c.Nodes) < *numNodes {
c.newNode()
}
routes := routes{
makeRoute(`/`, c.showCluster),
makeRoute(`/add`, c.addNode),
makeRoute(`/stopall`, c.stopAll),
makeRoute(`/startall`, c.startAll),
makeRoute(`/pauseall`, c.pauseAll),
makeRoute(`/resumeall`, c.resumeAll),
makeRoute(`/node/(?P<node>[^/]+)/start`, c.startNode),
makeRoute(`/node/(?P<node>[^/]+)/stop`, c.stopNode),
makeRoute(`/node/(?P<node>[^/]+)/pause`, c.pauseNode),
makeRoute(`/node/(?P<node>[^/]+)/resume`, c.resumeNode),
makeRoute(`/node/(?P<node>[^/]+)`, c.nodeHistory),
makeRoute(`/node/(?P<node>[^/]+)/run/(?P<run>\d+)`, c.nodeRunPage),
makeRoute(`/node/(?P<node>[^/]+)/run/(?P<run>\d+)/stdout`, c.nodeRunStdout),
makeRoute(`/node/(?P<node>[^/]+)/run/(?P<run>\d+)/stderr`, c.nodeRunStderr),
makeRoute(`/css/(?P<file>.*)`, getCSS),
}
s := &http.Server{
Addr: "localhost:9999",
Handler: routes,
}
log.Printf("serving: http://%s", s.Addr)
if err := s.ListenAndServe(); err != nil {
log.Fatal(err)
}
}