forked from evergreen-ci/evergreen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
769 lines (674 loc) · 23.7 KB
/
task.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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
package service
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/apimodels"
"github.com/evergreen-ci/evergreen/model"
"github.com/evergreen-ci/evergreen/model/event"
"github.com/evergreen-ci/evergreen/model/host"
"github.com/evergreen-ci/evergreen/model/task"
"github.com/evergreen-ci/evergreen/model/user"
"github.com/evergreen-ci/evergreen/model/version"
"github.com/evergreen-ci/evergreen/plugin"
"github.com/evergreen-ci/evergreen/util"
"github.com/gorilla/mux"
"github.com/mongodb/grip"
"github.com/pkg/errors"
"gopkg.in/mgo.v2/bson"
)
const (
// status overwrites
TaskBlocked = "blocked"
TaskPending = "pending"
)
var NumTestsToSearchForTestNames = 100
type uiTaskData struct {
Id string `json:"id"`
DisplayName string `json:"display_name"`
Revision string `json:"gitspec"`
BuildVariant string `json:"build_variant"`
Distro string `json:"distro"`
BuildId string `json:"build_id"`
Status string `json:"status"`
TaskWaiting string `json:"task_waiting"`
Activated bool `json:"activated"`
Restarts int `json:"restarts"`
Execution int `json:"execution"`
TotalExecutions int `json:"total_executions"`
StartTime int64 `json:"start_time"`
DispatchTime int64 `json:"dispatch_time"`
FinishTime int64 `json:"finish_time"`
Requester string `json:"r"`
ExpectedDuration time.Duration `json:"expected_duration"`
Priority int64 `json:"priority"`
TimeTaken time.Duration `json:"time_taken"`
TaskEndDetails apimodels.TaskEndDetail `json:"task_end_details"`
TestResults []uiTestResult `json:"test_results"`
Aborted bool `json:"abort"`
MinQueuePos int `json:"min_queue_pos"`
DependsOn []uiDep `json:"depends_on"`
IngestTime time.Time `json:"ingest_time"`
// from the host doc (the dns name)
HostDNS string `json:"host_dns,omitempty"`
// from the host doc (the host id)
HostId string `json:"host_id,omitempty"`
// for breadcrumb
BuildVariantDisplay string `json:"build_variant_display"`
// from version
VersionId string `json:"version_id"`
Message string `json:"message"`
Project string `json:"branch"`
Author string `json:"author"`
AuthorEmail string `json:"author_email"`
CreatedTime int64 `json:"created_time"`
// from project
RepoOwner string `json:"repo_owner"`
Repo string `json:"repo_name"`
// to avoid time skew b/t browser and API server
CurrentTime int64 `json:"current_time"`
// flag to indicate whether this is the current execution of this task, or
// a previous execution
Archived bool `json:"archived"`
PatchInfo *uiPatch `json:"patch_info"`
// display task info
DisplayOnly bool `json:"display_only"`
ExecutionTasks []uiExecTask `json:"execution_tasks"`
PartOfDisplay bool `json:"in_display"`
}
type uiDep struct {
Id string `json:"id"`
Name string `json:"display_name"`
Status string `json:"status"`
RequiredStatus string `json:"required"`
Activated bool `json:"activated"`
BuildVariant string `json:"build_variant"`
Details apimodels.TaskEndDetail `json:"task_end_details"`
Recursive bool `json:"recursive"`
TaskWaiting string `json:"task_waiting"`
}
type uiExecTask struct {
Id string `json:"id"`
Name string `json:"display_name"`
Status string `json:"status"`
}
type uiTestResult struct {
TestResult task.TestResult `json:"test_result"`
TaskId *string `json:"task_id"`
TaskName *string `json:"task_name"`
}
func (uis *UIServer) taskPage(w http.ResponseWriter, r *http.Request) {
projCtx := MustHaveProjectContext(r)
if projCtx.Task == nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
if projCtx.Build == nil {
uis.LoggedError(w, r, http.StatusInternalServerError, errors.New("build not found"))
return
}
if projCtx.Version == nil {
uis.LoggedError(w, r, http.StatusInternalServerError, errors.New("version not found"))
return
}
if projCtx.ProjectRef == nil {
grip.Error("Project ref is nil")
uis.LoggedError(w, r, http.StatusInternalServerError, errors.New("version not found"))
return
}
executionStr := mux.Vars(r)["execution"]
archived := false
// if there is an execution number, the task might be in the old_tasks collection, so we
// query that collection and set projCtx.Task to the old task if it exists.
if executionStr != "" {
execution, err := strconv.Atoi(executionStr)
if err != nil {
http.Error(w, fmt.Sprintf("Bad execution number: %v", executionStr), http.StatusBadRequest)
return
}
// Construct the old task id.
oldTaskId := fmt.Sprintf("%v_%v", projCtx.Task.Id, executionStr)
// Try to find the task in the old_tasks collection.
taskFromDb, err := task.FindOneOld(task.ById(oldTaskId))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
// If we found a task, set the task context. Otherwise, if taskFromDb is nil, check
// that the execution matches the context's execution. If it does not, return an
// error, since that means we are searching for a task that does not exist.
if taskFromDb != nil {
projCtx.Task = taskFromDb
archived = true
} else if execution != projCtx.Task.Execution {
uis.LoggedError(w, r, http.StatusNotFound, errors.New("Error finding task or execution"))
return
}
}
// Build a struct containing the subset of task data needed for display in the UI
tId := projCtx.Task.Id
totalExecutions := projCtx.Task.Execution
if archived {
tId = projCtx.Task.OldTaskId
// Get total number of executions for executions drop down
mostRecentExecution, err := task.FindOne(task.ById(tId))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError,
errors.Wrapf(err, "Error finding most recent execution by id %s", tId))
return
}
totalExecutions = mostRecentExecution.Execution
}
if totalExecutions < 1 {
totalExecutions = 1
}
uiTask := uiTaskData{
Id: tId,
DisplayName: projCtx.Task.DisplayName,
Revision: projCtx.Task.Revision,
Status: projCtx.Task.Status,
TaskEndDetails: projCtx.Task.Details,
Distro: projCtx.Task.DistroId,
BuildVariant: projCtx.Task.BuildVariant,
BuildId: projCtx.Task.BuildId,
Activated: projCtx.Task.Activated,
Restarts: projCtx.Task.Restarts,
Execution: projCtx.Task.Execution,
Requester: projCtx.Task.Requester,
StartTime: projCtx.Task.StartTime.UnixNano(),
DispatchTime: projCtx.Task.DispatchTime.UnixNano(),
FinishTime: projCtx.Task.FinishTime.UnixNano(),
ExpectedDuration: projCtx.Task.ExpectedDuration,
TimeTaken: projCtx.Task.TimeTaken,
Priority: projCtx.Task.Priority,
Aborted: projCtx.Task.Aborted,
DisplayOnly: projCtx.Task.DisplayOnly,
IngestTime: projCtx.Task.IngestTime,
CurrentTime: time.Now().UnixNano(),
BuildVariantDisplay: projCtx.Build.DisplayName,
Message: projCtx.Version.Message,
Project: projCtx.Version.Identifier,
Author: projCtx.Version.Author,
AuthorEmail: projCtx.Version.AuthorEmail,
VersionId: projCtx.Version.Id,
RepoOwner: projCtx.ProjectRef.Owner,
Repo: projCtx.ProjectRef.Repo,
Archived: archived,
TotalExecutions: totalExecutions,
PartOfDisplay: projCtx.Task.IsPartOfDisplay(),
}
deps, taskWaiting, err := getTaskDependencies(projCtx.Task)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uiTask.DependsOn = deps
uiTask.TaskWaiting = taskWaiting
uiTask.MinQueuePos, err = model.FindMinimumQueuePositionForTask(uiTask.Id)
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
if uiTask.MinQueuePos < 0 {
uiTask.MinQueuePos = 0
}
var taskHost *host.Host
if projCtx.Task.HostId != "" {
uiTask.HostDNS = projCtx.Task.HostId
uiTask.HostId = projCtx.Task.HostId
var err error
taskHost, err = host.FindOne(host.ById(projCtx.Task.HostId))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if taskHost != nil {
uiTask.HostDNS = taskHost.Host
}
}
if projCtx.Patch != nil {
taskOnBaseCommit, err := projCtx.Task.FindTaskOnBaseCommit()
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
taskPatch := &uiPatch{Patch: *projCtx.Patch}
if taskOnBaseCommit != nil {
taskPatch.BaseTaskId = taskOnBaseCommit.Id
taskPatch.BaseTimeTaken = taskOnBaseCommit.TimeTaken
}
taskPatch.StatusDiffs = model.StatusDiffTasks(taskOnBaseCommit, projCtx.Task).Tests
uiTask.PatchInfo = taskPatch
}
if uiTask.DisplayOnly {
uiTask.TestResults = []uiTestResult{}
for _, t := range projCtx.Task.ExecutionTasks {
et, err := task.FindOneIdOldOrNew(t, executionStr)
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
uiTask.ExecutionTasks = append(uiTask.ExecutionTasks, uiExecTask{Id: et.Id, Name: et.DisplayName, Status: et.ResultStatus()})
for _, tr := range et.LocalTestResults {
uiTask.TestResults = append(uiTask.TestResults, uiTestResult{TestResult: tr, TaskId: &et.Id, TaskName: &et.DisplayName})
}
}
} else {
for _, tr := range projCtx.Context.Task.LocalTestResults {
uiTask.TestResults = append(uiTask.TestResults, uiTestResult{TestResult: tr})
}
}
pluginContext := projCtx.ToPluginContext(uis.Settings, GetUser(r))
pluginContent := getPluginDataAndHTML(uis, plugin.TaskPage, pluginContext)
uis.WriteHTML(w, http.StatusOK, struct {
Task uiTaskData
Host *host.Host
PluginContent pluginData
JiraHost string
ViewData
}{uiTask, taskHost, pluginContent, uis.Settings.Jira.Host, uis.GetCommonViewData(w, r, false, true)}, "base",
"task.html", "base_angular.html", "menu.html")
}
type taskHistoryPageData struct {
TaskName string
Tasks []bson.M
Variants []string
FailedTests map[string][]task.TestResult
Versions []version.Version
// Flags that indicate whether the beginning/end of history has been reached
ExhaustedBefore bool
ExhaustedAfter bool
// The revision for which the surrounding history was requested
SelectedRevision string
}
// the task's most recent log messages
const DefaultLogMessages = 100 // passed as a limit, so 0 means don't limit
const AllLogsType = "ALL"
func getTaskLogs(taskId string, execution int, limit int, logType string,
loggedIn bool) ([]apimodels.LogMessage, error) {
logTypeFilter := []string{}
if logType != AllLogsType {
logTypeFilter = []string{logType}
}
// auth stuff
if !loggedIn {
if logType == AllLogsType {
logTypeFilter = []string{apimodels.TaskLogPrefix}
}
if logType == apimodels.AgentLogPrefix || logType == apimodels.SystemLogPrefix {
return []apimodels.LogMessage{}, nil
}
}
return model.FindMostRecentLogMessages(taskId, execution, limit, []string{},
logTypeFilter)
}
// getTaskDependencies returns the uiDeps for the task and its status (either its original status,
// "blocked", or "pending")
func getTaskDependencies(t *task.Task) ([]uiDep, string, error) {
depIds := []string{}
for _, dep := range t.DependsOn {
depIds = append(depIds, dep.TaskId)
}
dependencies, err := task.Find(task.ByIds(depIds).WithFields(task.DisplayNameKey, task.StatusKey,
task.ActivatedKey, task.BuildVariantKey, task.DetailsKey, task.DependsOnKey))
if err != nil {
return nil, "", err
}
idToUiDep := make(map[string]uiDep)
// match each task with its dependency requirements
for _, depTask := range dependencies {
for _, dep := range t.DependsOn {
if dep.TaskId == depTask.Id {
idToUiDep[depTask.Id] = uiDep{
Id: depTask.Id,
Name: depTask.DisplayName,
Status: depTask.Status,
RequiredStatus: dep.Status,
Activated: depTask.Activated,
BuildVariant: depTask.BuildVariant,
Details: depTask.Details,
//TODO EVG-614: add "Recursive: dep.Recursive," once Task.DependsOn includes all recursive dependencies
}
}
}
}
idToDep := make(map[string]task.Task)
for _, dep := range dependencies {
idToDep[dep.Id] = dep
}
// TODO EVG 614: delete this section once Task.DependsOn includes all recursive dependencies
err = addRecDeps(idToDep, idToUiDep, make(map[string]bool))
if err != nil {
return nil, "", err
}
// set the status for each of the uiDeps as "blocked" or "pending" if appropriate
// and get the status for task
status := setBlockedOrPending(*t, idToDep, idToUiDep)
uiDeps := make([]uiDep, 0, len(idToUiDep))
for _, dep := range idToUiDep {
uiDeps = append(uiDeps, dep)
}
return uiDeps, status, nil
}
// addRecDeps recursively finds all dependencies of tasks and adds them to tasks and uiDeps.
// done is a hashtable of task IDs whose dependencies we have found.
// TODO EVG-614: delete this function once Task.DependsOn includes all recursive dependencies.
func addRecDeps(tasks map[string]task.Task, uiDeps map[string]uiDep, done map[string]bool) error {
curTask := make(map[string]bool)
depIds := make([]string, 0)
for _, t := range tasks {
if _, ok := done[t.Id]; !ok {
for _, dep := range t.DependsOn {
depIds = append(depIds, dep.TaskId)
}
curTask[t.Id] = true
}
}
if len(depIds) == 0 {
return nil
}
deps, err := task.Find(task.ByIds(depIds).WithFields(task.DisplayNameKey, task.StatusKey, task.ActivatedKey,
task.BuildVariantKey, task.DetailsKey, task.DependsOnKey))
if err != nil {
return err
}
for _, dep := range deps {
tasks[dep.Id] = dep
}
for _, t := range tasks {
if _, ok := curTask[t.Id]; ok {
for _, dep := range t.DependsOn {
if uid, ok := uiDeps[dep.TaskId]; !ok ||
// only replace if the current uiDep is not strict and not recursive
(uid.RequiredStatus == model.AllStatuses && !uid.Recursive) {
depTask := tasks[dep.TaskId]
uiDeps[depTask.Id] = uiDep{
Id: depTask.Id,
Name: depTask.DisplayName,
Status: depTask.Status,
RequiredStatus: dep.Status,
Activated: depTask.Activated,
BuildVariant: depTask.BuildVariant,
Details: depTask.Details,
Recursive: true,
}
}
}
done[t.Id] = true
}
}
return addRecDeps(tasks, uiDeps, done)
}
// setBlockedOrPending sets the status of all uiDeps to "blocked" or "pending" if appropriate
// and returns "blocked", "pending", or the original status of task as appropriate.
// A task is blocked if some recursive dependency is in an undesirable state.
// A task is pending if some dependency has not finished.
func setBlockedOrPending(t task.Task, tasks map[string]task.Task, uiDeps map[string]uiDep) string {
blocked := false
pending := false
for _, dep := range t.DependsOn {
depTask := tasks[dep.TaskId]
uid := uiDeps[depTask.Id]
uid.TaskWaiting = setBlockedOrPending(depTask, tasks, uiDeps)
uiDeps[depTask.Id] = uid
if uid.TaskWaiting == TaskBlocked {
blocked = true
} else if depTask.Status == evergreen.TaskSucceeded || depTask.Status == evergreen.TaskFailed {
if depTask.Status != dep.Status && dep.Status != model.AllStatuses {
blocked = true
}
} else {
pending = true
}
}
if blocked {
return TaskBlocked
}
if pending {
return TaskPending
}
return ""
}
// async handler for polling the task log
type taskLogsWrapper struct {
LogMessages []apimodels.LogMessage
}
func (uis *UIServer) taskLog(w http.ResponseWriter, r *http.Request) {
projCtx := MustHaveProjectContext(r)
if projCtx.Task == nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
execution, err := strconv.Atoi(mux.Vars(r)["execution"])
if err != nil {
http.Error(w, "Invalid execution number", http.StatusBadRequest)
return
}
logType := r.FormValue("type")
wrapper := &taskLogsWrapper{}
if logType == "EV" {
loggedEvents, err := event.Find(event.AllLogCollection, event.MostRecentTaskEvents(projCtx.Task.Id, DefaultLogMessages))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
uis.WriteJSON(w, http.StatusOK, loggedEvents)
return
} else {
taskLogs, err := getTaskLogs(projCtx.Task.Id, execution, DefaultLogMessages, logType, GetUser(r) != nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
wrapper.LogMessages = taskLogs
uis.WriteJSON(w, http.StatusOK, wrapper)
}
}
func (uis *UIServer) taskLogRaw(w http.ResponseWriter, r *http.Request) {
projCtx := MustHaveProjectContext(r)
if projCtx.Task == nil {
http.Error(w, "Not found", http.StatusNotFound)
return
}
execution, err := strconv.Atoi(mux.Vars(r)["execution"])
grip.Warning(err)
logType := r.FormValue("type")
if logType == "" {
logType = AllLogsType
}
logTypeFilter := []string{}
if logType != AllLogsType {
logTypeFilter = []string{logType}
}
// restrict access if the user is not logged in
if GetUser(r) == nil {
if logType == AllLogsType {
logTypeFilter = []string{apimodels.TaskLogPrefix}
}
if logType == apimodels.AgentLogPrefix || logType == apimodels.SystemLogPrefix {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
channel, err := model.GetRawTaskLogChannel(projCtx.Task.Id, execution, []string{}, logTypeFilter)
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, errors.Wrap(err, "Error getting log data"))
return
}
type logTemplateData struct {
Data chan apimodels.LogMessage
User *user.DBUser
}
if (r.FormValue("text") == "true") || (r.Header.Get("Content-Type") == "text/plain") {
err = errors.WithStack(uis.StreamText(w, http.StatusOK, logTemplateData{channel, GetUser(r)}, "base", "task_log_raw.html"))
grip.Error(err)
return
}
grip.CatchError(errors.WithStack(uis.StreamHTML(w, http.StatusOK, logTemplateData{channel, GetUser(r)}, "base", "task_log.html")))
}
// avoids type-checking json params for the below function
func (uis *UIServer) taskModify(w http.ResponseWriter, r *http.Request) {
projCtx := MustHaveProjectContext(r)
if projCtx.Task == nil {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
body := util.NewRequestReader(r)
defer body.Close()
reqBody, err := ioutil.ReadAll(body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
putParams := struct {
Action string `json:"action"`
Priority string `json:"priority"`
// for the set_active option
Active bool `json:"active"`
}{}
err = json.Unmarshal(reqBody, &putParams)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
authUser := GetUser(r)
authName := authUser.DisplayName()
// determine what action needs to be taken
switch putParams.Action {
case "restart":
if err = model.TryResetTask(projCtx.Task.Id, authName, evergreen.UIPackage, nil); err != nil {
http.Error(w, fmt.Sprintf("Error restarting task %v: %v", projCtx.Task.Id, err), http.StatusInternalServerError)
return
}
// Reload the task from db, send it back
projCtx.Task, err = task.FindOne(task.ById(projCtx.Task.Id))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
}
uis.WriteJSON(w, http.StatusOK, projCtx.Task)
return
case "abort":
if err = model.AbortTask(projCtx.Task.Id, authName); err != nil {
http.Error(w, fmt.Sprintf("Error aborting task %v: %v", projCtx.Task.Id, err), http.StatusInternalServerError)
return
}
// Reload the task from db, send it back
projCtx.Task, err = task.FindOne(task.ById(projCtx.Task.Id))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
}
uis.WriteJSON(w, http.StatusOK, projCtx.Task)
return
case "set_active":
active := putParams.Active
if err = model.SetActiveState(projCtx.Task.Id, authUser.Username(), active); err != nil {
http.Error(w, fmt.Sprintf("Error activating task %v: %v", projCtx.Task.Id, err),
http.StatusInternalServerError)
return
}
// Reload the task from db, send it back
projCtx.Task, err = task.FindOne(task.ById(projCtx.Task.Id))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
}
uis.WriteJSON(w, http.StatusOK, projCtx.Task)
return
case "set_priority":
priority, err := strconv.ParseInt(putParams.Priority, 10, 64)
if err != nil {
http.Error(w, "Bad priority value, must be int", http.StatusBadRequest)
return
}
if priority > evergreen.MaxTaskPriority {
if !uis.isSuperUser(authUser) {
http.Error(w, fmt.Sprintf("Insufficient access to set priority %v, can only set priority less than or equal to %v", priority, evergreen.MaxTaskPriority),
http.StatusBadRequest)
return
}
} else if priority < 0 {
http.Error(w, "Cannot set a negative priority. If this task should not run, it should be unscheduled.", http.StatusBadRequest)
return
}
if err = projCtx.Task.SetPriority(priority, authUser.Username()); err != nil {
http.Error(w, fmt.Sprintf("Error setting task priority %v: %v", projCtx.Task.Id, err), http.StatusInternalServerError)
return
}
// Reload the task from db, send it back
projCtx.Task, err = task.FindOne(task.ById(projCtx.Task.Id))
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
}
uis.WriteJSON(w, http.StatusOK, projCtx.Task)
return
default:
uis.WriteJSON(w, http.StatusBadRequest, "Unrecognized action: "+putParams.Action)
}
}
func (uis *UIServer) testLog(w http.ResponseWriter, r *http.Request) {
logId := mux.Vars(r)["log_id"]
var (
testLog *model.TestLog
err error
taskExec int
)
if logId != "" { // direct link to a log document by its ID
testLog, err = model.FindOneTestLogById(logId)
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
} else {
taskID := mux.Vars(r)["task_id"]
testName := mux.Vars(r)["test_name"]
taskExecutionsAsString := mux.Vars(r)["task_execution"]
taskExec, err = strconv.Atoi(taskExecutionsAsString)
if err != nil {
http.Error(w, "task execution num must be an int", http.StatusBadRequest)
return
}
testLog, err = model.FindOneTestLog(testName, taskID, taskExec)
if err != nil {
uis.LoggedError(w, r, http.StatusInternalServerError, err)
return
}
}
if testLog == nil {
http.Error(w, "not found", http.StatusNotFound)
return
}
ctx, cancel := context.WithCancel(r.Context())
defer cancel()
displayLogs := make(chan apimodels.LogMessage)
go func() {
defer close(displayLogs)
for _, line := range testLog.Lines {
if ctx.Err() != nil {
return
}
displayLogs <- apimodels.LogMessage{
Type: apimodels.TaskLogPrefix,
Severity: apimodels.LogInfoPrefix,
Version: evergreen.LogmessageCurrentVersion,
Message: line,
}
}
}()
template := "task_log.html"
data := struct {
Data chan apimodels.LogMessage
User *user.DBUser
}{displayLogs, GetUser(r)}
if (r.FormValue("raw") == "1") || (r.Header.Get("Content-type") == "text/plain") {
template = "task_log_raw.html"
if err = uis.StreamText(w, http.StatusOK, data, "base", template); err != nil {
grip.Error(errors.Wrapf(err, "error streaming log data for log %s", logId))
}
} else {
uis.WriteHTML(w, http.StatusOK, data, "base", template)
}
}