github.com/drone/runner-go@v1.12.0/handler/handler.go (about) 1 // Copyright 2019 Drone.IO Inc. All rights reserved. 2 // Use of this source code is governed by the Polyform License 3 // that can be found in the LICENSE file. 4 5 // Package handler provides HTTP handlers that expose pipeline 6 // state and status. 7 package handler 8 9 import ( 10 "net/http" 11 "sort" 12 "strconv" 13 14 "github.com/drone/drone-go/drone" 15 hook "github.com/drone/runner-go/logger/history" 16 "github.com/drone/runner-go/pipeline/reporter/history" 17 ) 18 19 // HandleHealth returns a http.HandlerFunc that returns a 200 20 // if the service is healthly. 21 func HandleHealth(t *history.History) http.HandlerFunc { 22 return func(w http.ResponseWriter, r *http.Request) { 23 // TODO(bradrydzewski) iterate through the list of 24 // pending or running stages and write an error message 25 // if the timeout is exceeded. 26 nocache(w) 27 w.WriteHeader(200) 28 } 29 } 30 31 // HandleIndex returns a http.HandlerFunc that displays a list 32 // of currently and previously executed builds. 33 func HandleIndex(t *history.History) http.HandlerFunc { 34 return func(w http.ResponseWriter, r *http.Request) { 35 d := t.Entries() 36 37 s1 := history.ByTimestamp(d) 38 s2 := history.ByStatus(d) 39 sort.Sort(s1) 40 sort.Sort(s2) 41 42 if r.Header.Get("Accept") == "application/json" { 43 nocache(w) 44 renderJSON(w, d) 45 } else { 46 nocache(w) 47 render(w, "index.tmpl", &data{Items: d}) 48 } 49 } 50 } 51 52 // HandleStage returns a http.HandlerFunc that displays the 53 // stage details. 54 func HandleStage(hist *history.History, logger *hook.Hook) http.HandlerFunc { 55 return func(w http.ResponseWriter, r *http.Request) { 56 id, _ := strconv.ParseInt(r.FormValue("id"), 10, 64) 57 58 // filter logs by stage id. 59 logs := logger.Filter(func(entry *hook.Entry) bool { 60 return entry.Data["stage.id"] == id 61 }) 62 63 // find pipeline by stage id 64 entry := hist.Entry(id) 65 if entry == nil { 66 w.WriteHeader(404) 67 return 68 } 69 70 nocache(w) 71 render(w, "stage.tmpl", struct { 72 *history.Entry 73 Logs []*hook.Entry 74 }{ 75 Entry: entry, 76 Logs: logs, 77 }) 78 } 79 } 80 81 // HandleLogHistory returns a http.HandlerFunc that displays a 82 // list recent log entries. 83 func HandleLogHistory(t *hook.Hook) http.HandlerFunc { 84 return func(w http.ResponseWriter, r *http.Request) { 85 nocache(w) 86 render(w, "logs.tmpl", struct { 87 Entries []*hook.Entry 88 }{t.Entries()}) 89 } 90 } 91 92 // data is a template data structure that provides helper 93 // functions for calculating the system state. 94 type data struct { 95 Items []*history.Entry 96 } 97 98 // helper function returns true if no running builds exists. 99 func (d *data) Idle() bool { 100 for _, item := range d.Items { 101 switch item.Stage.Status { 102 case drone.StatusPending, drone.StatusRunning: 103 return false 104 } 105 } 106 return true 107 }