-
Notifications
You must be signed in to change notification settings - Fork 32
/
server.go
381 lines (326 loc) · 8.54 KB
/
server.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package hrp
import (
"context"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/test-instructor/yangfan/parsing/hrp/internal/json"
"github.com/test-instructor/yangfan/parsing/hrp/pkg/boomer"
)
const jsonContentType = "application/json; encoding=utf-8"
func methods(h http.HandlerFunc, methods ...string) http.HandlerFunc {
methodMap := make(map[string]struct{}, len(methods))
for _, m := range methods {
methodMap[m] = struct{}{}
// GET implies support for HEAD
if m == "GET" {
methodMap["HEAD"] = struct{}{}
}
}
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := methodMap[r.Method]; !ok {
http.Error(w, fmt.Sprintf("method %s not allowed", r.Method), http.StatusMethodNotAllowed)
return
}
h.ServeHTTP(w, r)
}
}
func parseBody(r *http.Request) (data map[string]interface{}, err error) {
if r.Body == nil {
return nil, nil
}
// Always set resp.Data to the incoming request body, in case we don't know
// how to handle the content type
body, err := ioutil.ReadAll(r.Body)
if err != nil {
r.Body.Close()
return nil, err
}
err = json.Unmarshal(body, &data)
if err != nil {
return nil, err
}
return data, nil
}
func writeJSON(w http.ResponseWriter, body []byte, status int) {
w.Header().Set("Content-Type", jsonContentType)
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body)))
w.WriteHeader(status)
w.Write(body)
}
type ServerCode int
// server response code
const (
Success ServerCode = iota
ParamsError
ServerError
StopError
)
// ServerStatus stores http response code and message
type ServerStatus struct {
Code ServerCode `json:"code"`
Message string `json:"message"`
}
var EnumAPIResponseSuccess = ServerStatus{
Code: Success,
Message: "success",
}
func EnumAPIResponseParamError(errMsg string) ServerStatus {
return ServerStatus{
Code: ParamsError,
Message: errMsg,
}
}
func EnumAPIResponseServerError(errMsg string) ServerStatus {
return ServerStatus{
Code: ServerError,
Message: errMsg,
}
}
func EnumAPIResponseStopError(errMsg string) ServerStatus {
return ServerStatus{
Code: StopError,
Message: errMsg,
}
}
func CustomAPIResponse(errCode ServerCode, errMsg string) ServerStatus {
return ServerStatus{
Code: errCode,
Message: errMsg,
}
}
type StartRequestBody struct {
boomer.Profile `mapstructure:",squash"`
Worker string `json:"worker,omitempty" yaml:"worker,omitempty" mapstructure:"worker"` // all
TestCasePath string `json:"testcase-path" yaml:"testcase-path" mapstructure:"testcase-path"`
Other map[string]interface{} `mapstructure:",remain"`
}
type RebalanceRequestBody struct {
boomer.Profile `mapstructure:",squash"`
Worker string `json:"worker,omitempty" yaml:"worker,omitempty" mapstructure:"worker"`
Other map[string]interface{} `mapstructure:",remain"`
}
type StopRequestBody struct {
Worker string `json:"worker"`
}
type QuitRequestBody struct {
Worker string `json:"worker"`
}
type CommonResponseBody struct {
ServerStatus
}
type APIGetWorkersRequestBody struct{}
type APIGetWorkersResponseBody struct {
ServerStatus
Data []boomer.WorkerNode `json:"data"`
}
type APIGetMasterRequestBody struct{}
type APIGetMasterResponseBody struct {
ServerStatus
Data map[string]interface{} `json:"data"`
}
type apiHandler struct {
boomer *HRPBoomer
}
func (b *HRPBoomer) NewAPIHandler() *apiHandler {
return &apiHandler{boomer: b}
}
// Index renders an HTML index page
func (api *apiHandler) Index(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' www.httprunner.com")
fmt.Fprintf(w, "Welcome to httprunner page!")
}
func (api *apiHandler) Start(w http.ResponseWriter, r *http.Request) {
var resp *CommonResponseBody
var err error
defer func() {
if err != nil {
resp = &CommonResponseBody{
ServerStatus: EnumAPIResponseServerError(err.Error()),
}
} else {
resp = &CommonResponseBody{
ServerStatus: EnumAPIResponseSuccess,
}
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
}()
// parse body
data, err := parseBody(r)
if err != nil {
return
}
req := StartRequestBody{
Profile: *boomer.NewProfile(),
}
err = mapstructure.Decode(data, &req)
if err != nil {
return
}
// recognize invalid parameters
if len(req.Other) > 0 {
keys := make([]string, 0, len(req.Other))
for k := range req.Other {
keys = append(keys, k)
}
err = fmt.Errorf("failed to recognize params: %v", keys)
return
}
// parse testcase path
if req.TestCasePath == "" {
err = errors.New("missing testcases path")
return
}
paths := strings.Split(req.TestCasePath, ",")
// set testcase path
api.boomer.SetTestCasesPath(paths)
// start boomer with profile
err = api.boomer.Start(&req.Profile)
}
func (api *apiHandler) ReBalance(w http.ResponseWriter, r *http.Request) {
var resp *CommonResponseBody
var err error
defer func() {
if err != nil {
resp = &CommonResponseBody{
ServerStatus: EnumAPIResponseServerError(err.Error()),
}
} else {
resp = &CommonResponseBody{
ServerStatus: EnumAPIResponseSuccess,
}
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
}()
// parse body
data, err := parseBody(r)
if err != nil {
return
}
req := RebalanceRequestBody{
Profile: *api.boomer.GetProfile(),
}
err = mapstructure.Decode(data, &req)
if err != nil {
return
}
// recognize invalid parameters
if len(req.Other) > 0 {
keys := make([]string, 0, len(req.Other))
for k := range req.Other {
keys = append(keys, k)
}
err = fmt.Errorf("failed to recognize params: %v", keys)
return
}
// rebalance boomer with profile
err = api.boomer.ReBalance(&req.Profile)
}
func (api *apiHandler) Stop(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{}
args := r.URL.Query()
for k, vs := range args {
for _, v := range vs {
data[k] = v
}
}
var resp *CommonResponseBody
var err error
defer func() {
if err != nil {
resp = &CommonResponseBody{
ServerStatus: EnumAPIResponseStopError(err.Error()),
}
} else {
resp = &CommonResponseBody{
ServerStatus: EnumAPIResponseSuccess,
}
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
}()
// stop boomer
err = api.boomer.Stop()
}
func (api *apiHandler) Quit(w http.ResponseWriter, r *http.Request) {
data := map[string]interface{}{}
args := r.URL.Query()
for k, vs := range args {
for _, v := range vs {
data[k] = v
}
}
defer func() {
resp := &CommonResponseBody{
ServerStatus: EnumAPIResponseSuccess,
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
}()
// quit boomer
api.boomer.Quit()
}
func (api *apiHandler) GetWorkersInfo(w http.ResponseWriter, r *http.Request) {
resp := &APIGetWorkersResponseBody{
ServerStatus: EnumAPIResponseSuccess,
Data: api.boomer.GetWorkersInfo(),
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
}
func (api *apiHandler) GetMasterInfo(w http.ResponseWriter, r *http.Request) {
resp := &APIGetMasterResponseBody{
ServerStatus: EnumAPIResponseSuccess,
Data: api.boomer.GetMasterInfo(),
}
body, _ := json.Marshal(resp)
writeJSON(w, body, http.StatusOK)
}
func (api *apiHandler) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/", methods(api.Index, "GET"))
mux.HandleFunc("/start", methods(api.Start, "POST"))
mux.HandleFunc("/rebalance", methods(api.ReBalance, "POST"))
mux.HandleFunc("/stop", methods(api.Stop, "GET"))
mux.HandleFunc("/quit", methods(api.Quit, "GET"))
mux.HandleFunc("/workers", methods(api.GetWorkersInfo, "GET"))
mux.HandleFunc("/master", methods(api.GetMasterInfo, "GET"))
return mux
}
func (apiHandler) ServeHTTP(http.ResponseWriter, *http.Request) {}
func (b *HRPBoomer) StartServer(ctx context.Context, addr string) {
h := b.NewAPIHandler()
mux := h.Handler()
server := &http.Server{
Addr: addr,
Handler: mux,
}
go func() {
select {
case <-ctx.Done():
case <-b.GetCloseChan():
}
if err := server.Shutdown(context.Background()); err != nil {
log.Fatal("shutdown server:", err)
}
}()
log.Printf("starting HTTP server (%v), please use the API to control master", server.Addr)
err := server.ListenAndServe()
if err != nil {
if err == http.ErrServerClosed {
log.Print("server closed under request")
} else {
log.Fatal("server closed unexpected")
}
}
}