/
host.go
542 lines (459 loc) · 15 KB
/
host.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
package route
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/apimodels"
"github.com/evergreen-ci/evergreen/cloud"
"github.com/evergreen-ci/evergreen/model/host"
"github.com/evergreen-ci/evergreen/model/task"
"github.com/evergreen-ci/evergreen/rest/data"
"github.com/evergreen-ci/evergreen/rest/model"
"github.com/evergreen-ci/evergreen/units"
"github.com/evergreen-ci/gimlet"
"github.com/evergreen-ci/utility"
"github.com/pkg/errors"
)
type hostStatus struct {
Status string `json:"status"`
}
////////////////////////////////////////////////////////////////////////
//
// PATCH /rest/v2/hosts
type hostsChangeStatusesHandler struct {
HostToStatus map[string]hostStatus
}
func makeChangeHostsStatuses() gimlet.RouteHandler {
return &hostsChangeStatusesHandler{}
}
// Factory creates an instance of the handler.
//
// @Summary Fetch all hosts
// @Description Returns a paginated list of all hosts in Evergreen
// @Tags hosts
// @Router /hosts [get]
// @Security Api-User || Api-Key
// @Param start_at query string false "The identifier of the host to start at in the pagination"
// @Param limit query int false "The number of hosts to be returned per page of pagination. Defaults to 100"
// @Param status query string false "A status of host to limit the results to"
// @Success 200 {object} model.APIHost
func (h *hostsChangeStatusesHandler) Factory() gimlet.RouteHandler {
return &hostsChangeStatusesHandler{}
}
func (h *hostsChangeStatusesHandler) Parse(ctx context.Context, r *http.Request) error {
body := utility.NewRequestReader(r)
defer body.Close()
if err := utility.ReadJSON(body, &h.HostToStatus); err != nil {
return errors.Wrap(err, "reading host-status mapping from JSON request body")
}
if len(h.HostToStatus) == 0 {
return errors.New("must give at least one host ID to status mapping")
}
for hostID, status := range h.HostToStatus {
if !utility.StringSliceContains(evergreen.ValidUserSetHostStatus, status.Status) {
return errors.Errorf("invalid host status '%s' for host '%s'", status.Status, hostID)
}
}
return nil
}
func (h *hostsChangeStatusesHandler) Run(ctx context.Context) gimlet.Responder {
user := MustHaveUser(ctx)
resp := gimlet.NewResponseBuilder()
for id, status := range h.HostToStatus {
foundHost, err := data.FindHostByIdWithOwner(ctx, id, user)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding host '%s' with owner '%s'", id, user.Id))
}
switch status.Status {
case evergreen.HostTerminated:
err = errors.WithStack(cloud.TerminateSpawnHost(ctx, evergreen.GetEnvironment(), foundHost, user.Id, "terminated via REST API"))
default:
err = foundHost.SetStatus(ctx, status.Status, user.Id, fmt.Sprintf("changed by %s from API", user.Id))
}
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(err)
}
h := &model.APIHost{}
h.BuildFromService(foundHost, nil)
if err = resp.AddData(h); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "adding response data for host '%s'", utility.FromStringPtr(h.Id)))
}
}
return resp
}
////////////////////////////////////////////////////////////////////////
//
// GET /rest/v2/hosts/{host_id}
func makeGetHostByID() gimlet.RouteHandler {
return &hostIDGetHandler{}
}
type hostIDGetHandler struct {
hostID string
}
// Factory creates an instance of the handler.
//
// @Summary Fetch hosts by ID
// @Description Fetches a single host using its ID
// @Tags hosts
// @Router /hosts/{host_id} [get]
// @Security Api-User || Api-Key
// @Param host_id path string true "the host ID"
// @Success 200 {object} model.APIHost
func (h *hostIDGetHandler) Factory() gimlet.RouteHandler {
return &hostIDGetHandler{}
}
// ParseAndValidate fetches the hostId from the http request.
func (h *hostIDGetHandler) Parse(ctx context.Context, r *http.Request) error {
h.hostID = gimlet.GetVars(r)["host_id"]
return nil
}
// Execute calls the data FindHostById function and returns the host
// from the provider.
func (h *hostIDGetHandler) Run(ctx context.Context) gimlet.Responder {
foundHost, err := host.FindOneId(ctx, h.hostID)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding host '%s'", h.hostID))
}
if foundHost == nil {
return gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{
StatusCode: http.StatusNotFound,
Message: fmt.Sprintf("host '%s' not found", h.hostID),
})
}
var runningTask *task.Task
if foundHost.RunningTask != "" {
runningTask, err = task.FindOneIdAndExecution(foundHost.RunningTask, foundHost.RunningTaskExecution)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding host's running task '%s' execution '%d'", foundHost.RunningTask, foundHost.RunningTaskExecution))
}
if runningTask == nil {
return gimlet.MakeJSONInternalErrorResponder(gimlet.ErrorResponse{
StatusCode: http.StatusNotFound,
Message: fmt.Sprintf("host's running task '%s' execution '%d' not found", foundHost.RunningTask, foundHost.RunningTaskExecution),
})
}
}
hostModel := &model.APIHost{}
hostModel.BuildFromService(foundHost, runningTask)
return gimlet.NewJSONResponse(hostModel)
}
////////////////////////////////////////////////////////////////////////
//
// GET /hosts
// GET /users/{user_id}/hosts
func makeFetchHosts(url string) gimlet.RouteHandler {
return &hostGetHandler{url: url}
}
type hostGetHandler struct {
limit int
key string
status string
user string
url string
}
// Factory creates an instance of the handler.
//
// @Summary Fetch hosts spawned by user
// @Description Returns a list of hosts spawned by the given user.
// @Tags hosts
// @Router /users/{user_id}/hosts [get]
// @Security Api-User || Api-Key
// @Param user_id path string true "the user ID"
// @Param start_at query string false "The identifier of the host to start at in the pagination"
// @Param limit query int false "The number of hosts to be returned per page of pagination. Defaults to 100"
// @Param status query string false "A status of host to limit the results to"
// @Success 200 {object} model.APIHost
func (hgh *hostGetHandler) Factory() gimlet.RouteHandler {
return &hostGetHandler{url: hgh.url}
}
func (hgh *hostGetHandler) Parse(ctx context.Context, r *http.Request) error {
vals := r.URL.Query()
hgh.status = vals.Get("status")
hgh.key = vals.Get("host_id")
var err error
hgh.limit, err = getLimit(vals)
if err != nil {
return errors.WithStack(err)
}
// only populated in the case of the /users/{user}/hosts route
hgh.user = gimlet.GetVars(r)["user_id"]
return nil
}
func (hgh *hostGetHandler) Run(ctx context.Context) gimlet.Responder {
hosts, err := host.GetHostsByFromIDWithStatus(ctx, hgh.key, hgh.status, hgh.user, hgh.limit+1)
if err != nil {
return gimlet.NewJSONInternalErrorResponse(errors.Wrap(err, "finding hosts with filters"))
}
if len(hosts) == 0 {
gimlet.NewJSONErrorResponse(gimlet.ErrorResponse{
StatusCode: http.StatusNotFound,
Message: "no hosts found",
})
}
resp := gimlet.NewResponseBuilder()
lastIndex := len(hosts)
if len(hosts) > hgh.limit {
lastIndex = hgh.limit
err = resp.SetPages(&gimlet.ResponsePages{
Next: &gimlet.Page{
BaseURL: hgh.url,
LimitQueryParam: "limit",
KeyQueryParam: "host_id",
Relation: "next",
Key: hosts[hgh.limit].Id,
Limit: hgh.limit,
},
})
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "paginating response"))
}
}
// Truncate the hosts to just those that will be returned.
hosts = hosts[:lastIndex]
// Grab the taskIds associated as running on the hosts.
taskIds := []string{}
for _, h := range hosts {
if h.RunningTask != "" {
taskIds = append(taskIds, h.RunningTask)
}
}
var tasks []task.Task
if len(taskIds) > 0 {
tasks, err = task.Find(task.ByIds(taskIds))
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding tasks %s", taskIds))
}
if len(tasks) == 0 {
return gimlet.MakeJSONInternalErrorResponder(errors.New("no tasks found"))
}
}
tasksById := make(map[string]task.Task, len(tasks))
for _, t := range tasks {
tasksById[t.Id] = t
}
for _, h := range hosts {
apiHost := &model.APIHost{}
var runningTask *task.Task
if h.RunningTask != "" {
t, ok := tasksById[h.RunningTask]
if ok {
runningTask = &t
}
}
apiHost.BuildFromService(&h, runningTask)
if err = resp.AddData(apiHost); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "adding host data to response"))
}
}
return resp
}
func getLimit(vals url.Values) (int, error) {
var (
limit int
err error
)
if l, ok := vals["limit"]; ok && len(l) > 0 {
limit, err = strconv.Atoi(l[0])
if err != nil {
return 0, gimlet.ErrorResponse{
Message: errors.Wrap(err, "invalid limit").Error(),
StatusCode: http.StatusBadRequest,
}
}
}
if limit <= 0 {
return defaultLimit, nil
}
return limit, nil
}
////////////////////////////////////////////////////////////////////////
//
// GET /host/filter
func makeFetchHostFilter() gimlet.RouteHandler {
return &hostFilterGetHandler{}
}
type hostFilterGetHandler struct {
params model.APIHostParams
}
func (h *hostFilterGetHandler) Factory() gimlet.RouteHandler {
return &hostFilterGetHandler{}
}
func (h *hostFilterGetHandler) Parse(ctx context.Context, r *http.Request) error {
body := utility.NewRequestReader(r)
defer body.Close()
if err := utility.ReadJSON(body, &h.params); err != nil {
return errors.Wrap(err, "reading host filter parameters from request body")
}
return nil
}
func (h *hostFilterGetHandler) Run(ctx context.Context) gimlet.Responder {
dbUser := MustHaveUser(ctx)
username := ""
// only admins see hosts that aren't theirs
if h.params.Mine || !dbUser.HasPermission(gimlet.PermissionOpts{
Resource: evergreen.SuperUserPermissionsID,
ResourceType: evergreen.SuperUserResourceType,
Permission: evergreen.PermissionDistroCreate,
RequiredLevel: evergreen.DistroCreate.Value,
}) {
username = dbUser.Username()
}
hosts, err := data.FindHostsInRange(ctx, h.params, username)
if err != nil {
return gimlet.NewJSONInternalErrorResponse(errors.Wrap(err, "finding hosts matching parameters"))
}
resp := gimlet.NewResponseBuilder()
for _, h := range hosts {
apiHost := &model.APIHost{}
apiHost.BuildFromService(&h, nil)
if err = resp.AddData(apiHost); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "adding response data for host '%s'", utility.FromStringPtr(apiHost.Id)))
}
}
return resp
}
// GET /hosts/{host_id}/provisioning_options
type hostProvisioningOptionsGetHandler struct {
hostID string
env evergreen.Environment
}
func makeHostProvisioningOptionsGetHandler(env evergreen.Environment) gimlet.RouteHandler {
return &hostProvisioningOptionsGetHandler{
env: env,
}
}
func (rh *hostProvisioningOptionsGetHandler) Factory() gimlet.RouteHandler {
return &hostProvisioningOptionsGetHandler{
env: rh.env,
}
}
func (rh *hostProvisioningOptionsGetHandler) Parse(ctx context.Context, r *http.Request) error {
hostID := gimlet.GetVars(r)["host_id"]
if hostID == "" {
return errors.New("missing host ID")
}
rh.hostID = hostID
return nil
}
func (rh *hostProvisioningOptionsGetHandler) Run(ctx context.Context) gimlet.Responder {
script, err := data.GenerateHostProvisioningScript(ctx, rh.env, rh.hostID)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "generating host provisioning script"))
}
apiOpts := model.APIHostProvisioningOptions{
Content: script,
}
return gimlet.NewJSONResponse(apiOpts)
}
// GET /hosts/{host_id}/is_up
type hostIsUpPostHandler struct {
params model.APIHostIsUpOptions
}
func makeHostIsUpPostHandler() gimlet.RouteHandler {
return &hostIsUpPostHandler{}
}
func (rh *hostIsUpPostHandler) Factory() gimlet.RouteHandler {
return &hostIsUpPostHandler{}
}
func (rh *hostIsUpPostHandler) Parse(ctx context.Context, r *http.Request) error {
if err := utility.ReadJSON(r.Body, &rh.params); err != nil {
return errors.Wrap(err, "reading host is up parameters from JSON request body")
}
return nil
}
func (rh *hostIsUpPostHandler) Run(ctx context.Context) gimlet.Responder {
apiHost, err := data.PostHostIsUp(ctx, rh.params)
if err != nil {
return gimlet.MakeJSONErrorResponder(err)
}
return gimlet.NewJSONResponse(apiHost)
}
// //////////////////////////////////////////////////////////////////////
//
// POST /rest/v2/hosts/{host_id}/disable
type disableHost struct {
env evergreen.Environment
hostID string
reason string
}
func makeDisableHostHandler(env evergreen.Environment) gimlet.RouteHandler {
return &disableHost{
env: env,
}
}
func (h *disableHost) Factory() gimlet.RouteHandler {
return &disableHost{
env: h.env,
}
}
func (h *disableHost) Parse(ctx context.Context, r *http.Request) error {
body := utility.NewRequestReader(r)
defer body.Close()
h.hostID = gimlet.GetVars(r)["host_id"]
if h.hostID == "" {
return errors.New("host ID must be specified")
}
info := apimodels.DisableInfo{}
if err := utility.ReadJSON(body, &info); err != nil {
return errors.Wrap(err, "unable to parse request body")
}
h.reason = info.Reason
return nil
}
func (h *disableHost) Run(ctx context.Context) gimlet.Responder {
host, err := host.FindOneId(ctx, h.hostID)
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "getting host"))
}
if host == nil {
return gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{
StatusCode: http.StatusNotFound,
Message: fmt.Sprintf("host '%s' not found", h.hostID)},
)
}
if err = units.HandlePoisonedHost(ctx, h.env, host, h.reason); err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrap(err, "disabling host"))
}
return gimlet.NewJSONResponse(struct{}{})
}
////////////////////////////////////////////////////////////////////////
//
// GET /rest/v2/hosts/ip_address/{ip_address}
type hostIpAddressGetHandler struct {
IP string
Host *host.Host
}
func makeGetHostByIpAddress() gimlet.RouteHandler {
return &hostIpAddressGetHandler{}
}
func (h *hostIpAddressGetHandler) Factory() gimlet.RouteHandler {
return &hostIpAddressGetHandler{}
}
func (h *hostIpAddressGetHandler) Parse(ctx context.Context, r *http.Request) error {
h.IP = gimlet.GetVars(r)["ip_address"]
if h.IP == "" {
return gimlet.ErrorResponse{
StatusCode: http.StatusBadRequest,
Message: "ip_address cannot be empty",
}
}
return nil
}
func (h *hostIpAddressGetHandler) Run(ctx context.Context) gimlet.Responder {
host, err := host.FindOne(ctx, host.ByIPAndRunning(h.IP))
if err != nil {
return gimlet.MakeJSONInternalErrorResponder(errors.Wrapf(err, "finding host with IP '%s'", h.IP))
}
if host == nil {
return gimlet.MakeJSONErrorResponder(gimlet.ErrorResponse{
StatusCode: http.StatusNotFound,
Message: fmt.Sprintf("host with IP address '%s' not found", h.IP),
})
}
hostModel := &model.APIHost{}
hostModel.BuildFromService(host, nil)
return gimlet.NewJSONResponse(hostModel)
}