forked from puppetlabs-toy-chest/wash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhistory.go
187 lines (167 loc) · 4.3 KB
/
history.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
package api
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/puppetlabs/wash/activity"
apitypes "github.com/puppetlabs/wash/api/types"
log "github.com/sirupsen/logrus"
)
// swagger:parameters retrieveHistory getJournal
//nolint:deadcode,unused
type historyParams struct {
// stream updates when true
//
// in: query
Follow bool
}
// swagger:route GET /history history retrieveHistory
//
// Get command history
//
// Get a list of commands that have been run via 'wash' and when they were run.
//
// Produces:
// - application/json
//
// Schemes: http
//
// Responses:
// 200: HistoryResponse
// 400: errorResp
// 404: errorResp
// 500: errorResp
var historyHandler = handler{logOnly: true, fn: func(w http.ResponseWriter, r *http.Request) *errorResponse {
follow, err := getBoolParam(r.URL, "follow")
if err != nil {
return err
}
var enc *json.Encoder
if follow {
// Ensure every write is a flush.
f, ok := w.(flushableWriter)
if !ok {
return unknownErrorResponse(fmt.Errorf("Cannot stream history, response handler does not support flushing"))
}
enc = json.NewEncoder(&streamableResponseWriter{f})
} else {
enc = json.NewEncoder(w)
}
history := activity.History()
if err := writeHistory(r.Context(), enc, history); err != nil {
return err
}
if follow {
last := len(history)
for {
// Continue sending updates
select {
case <-r.Context().Done():
return nil
case <-time.After(1 * time.Second):
// Retry
}
history = activity.History()
if len(history) > last {
if err := writeHistory(r.Context(), enc, history[last:]); err != nil {
return err
}
last = len(history)
}
}
}
return nil
}}
func writeHistory(ctx context.Context, enc *json.Encoder, history []activity.Journal) *errorResponse {
var act apitypes.Activity
for _, item := range history {
act.Description = item.Description
act.Start = item.Start()
if err := enc.Encode(&act); err != nil {
return unknownErrorResponse(fmt.Errorf("Could not marshal %v: %v", history, err))
}
}
return nil
}
// swagger:route GET /history/{id} journal getJournal
//
// Get logs for a particular entry in history
//
// Get the logs related to a particular command run via 'wash', requested by
// index within its activity history.
//
// Produces:
// - application/json
// - application/octet-stream
//
// Schemes: http
//
// Responses:
// 200: octetResponse
// 400: errorResp
// 404: errorResp
// 500: errorResp
var historyEntryHandler = handler{logOnly: true, fn: func(w http.ResponseWriter, r *http.Request) *errorResponse {
history := activity.History()
index := mux.Vars(r)["index"]
idx, err := strconv.Atoi(index)
if err != nil || idx < 0 || idx >= len(history) {
if err == nil {
err = fmt.Errorf("index out of bounds")
}
return outOfBoundsRequest(len(history), err.Error())
}
follow, errResp := getBoolParam(r.URL, "follow")
if errResp != nil {
return errResp
}
journal := history[idx]
streamCleanup := func(cleanup func() error) {
<-r.Context().Done()
log.Printf("API: Journal %v closed by completed context: %v", journal, cleanup())
}
if follow {
// Ensure every write is a flush.
f, ok := w.(flushableWriter)
if !ok {
return unknownErrorResponse(fmt.Errorf("Cannot stream history, response handler does not support flushing"))
}
rdr, err := journal.Tail()
if err != nil {
return journalUnavailableResponse(journal.String(), err.Error())
}
// Ensure the reader is closed when context stops.
go streamCleanup(func() error {
rdr.Cleanup()
return rdr.Stop()
})
// Do an initial flush to send the header.
w.WriteHeader(http.StatusOK)
f.Flush()
for line := range rdr.Lines {
if line.Err != nil {
return unknownErrorResponse(line.Err)
}
if _, err := fmt.Fprintln(f, line.Text); err != nil {
return unknownErrorResponse(err)
}
// Flush every line to the client.
f.Flush()
}
} else {
rdr, err := journal.Open()
if err != nil {
return journalUnavailableResponse(journal.String(), err.Error())
}
go streamCleanup(rdr.Close)
if _, err := io.Copy(w, rdr); err != nil {
return unknownErrorResponse(fmt.Errorf("Could not read journal %v: %v", journal, err))
}
}
return nil
}}