-
Notifications
You must be signed in to change notification settings - Fork 52
/
api_logs.go
323 lines (288 loc) · 8.43 KB
/
api_logs.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
// Copyright (c) 2021 Canonical Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package daemon
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/canonical/x-go/strutil"
"github.com/canonical/pebble/internals/logger"
"github.com/canonical/pebble/internals/overlord/servstate"
"github.com/canonical/pebble/internals/servicelog"
)
const (
defaultNumLogs = 30
logReaderSize = 4 * 1024
)
type serviceManager interface {
Services(names []string) ([]*servstate.ServiceInfo, error)
ServiceLogs(services []string, last int) (map[string]servicelog.Iterator, error)
}
func v1GetLogs(c *Command, _ *http.Request, _ *UserState) Response {
return logsResponse{
svcMgr: overlordServiceManager(c.d.overlord),
}
}
// logsResponse is a Response implementation to serve the logs in a custom
// JSON Lines format.
type logsResponse struct {
svcMgr serviceManager
}
func (r logsResponse) ServeHTTP(w http.ResponseWriter, req *http.Request) {
query := req.URL.Query()
services := strutil.MultiCommaSeparatedList(query["services"])
followStr := query.Get("follow")
if followStr != "" && followStr != "true" && followStr != "false" {
response := BadRequest(`follow parameter must be "true" or "false"`)
response.ServeHTTP(w, req)
return
}
follow := followStr == "true"
var numLogs int
nStr := query.Get("n")
if nStr != "" {
n, err := strconv.Atoi(nStr)
if err != nil || n < -1 {
response := BadRequest("n must be -1, 0, or a positive integer")
response.ServeHTTP(w, req)
return
}
numLogs = n
} else if follow {
numLogs = 0
} else {
numLogs = defaultNumLogs
}
// If "services" parameter not specified, fetch logs for all services.
if len(services) == 0 {
infos, err := r.svcMgr.Services(nil)
if err != nil {
response := InternalError("cannot fetch services: %v", err)
response.ServeHTTP(w, req)
return
}
services = make([]string, len(infos))
for i, info := range infos {
services[i] = info.Name
}
}
itsByName, err := r.svcMgr.ServiceLogs(services, numLogs)
if err != nil {
response := InternalError("cannot fetch log iterators: %v", err)
response.ServeHTTP(w, req)
return
}
// Output format is JSON Lines, which doesn't have an official mime type,
// but "application/x-ndjson" is what most people seem to use:
// https://github.com/wardi/jsonlines/issues/9
w.Header().Set("Content-Type", "application/x-ndjson")
encoder := json.NewEncoder(w)
encoder.SetEscapeHTML(false)
// Use a buffered channel as a FIFO for keeping the latest numLogs logs if
// request "n" is set (the default).
var fifo chan servicelog.Entry
if numLogs > 0 {
fifo = make(chan servicelog.Entry, numLogs)
}
flushFifo := func() bool { // helper to flush any logs in the FIFO
if numLogs <= 0 || len(fifo) == 0 {
return true
}
var err error
for len(fifo) > 0 && err == nil {
err = encoder.Encode(newJSONLog(<-fifo))
}
if err != nil {
logger.Noticef("Cannot write logs: %v", err)
return false
}
flushWriter(w)
return true
}
// Background goroutine to stream ordered logs: it sends parsed logs on
// logs channel, any error on errorChan channel, and stops when the request
// is cancelled or this handler returns.
logs := make(chan servicelog.Entry)
errorChan := make(chan error, 1)
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
go func() {
errorChan <- streamLogs(itsByName, logs, ctx.Done())
}()
// Main loop: output earliest log per iteration. Stop when request
// cancelled or there are no more logs (in non-follow mode).
requestStarted := time.Now().UTC()
for {
select {
case log := <-logs:
if log.Time.IsZero() {
// Zero-time log means we've consumed all buffered logs
if !flushFifo() {
return
}
if follow {
// Following, wait for more
numLogs = 0 // so we don't use the FIFO from here on
continue
}
// Not following, we're done
return
}
// Logs are coming faster than we can send them (probably a slow
// client), so stop now.
if !follow && log.Time.After(requestStarted) {
_ = flushFifo()
return
}
if numLogs > 0 {
// Push through FIFO so we only output the most recent "n"
// across all services.
if len(fifo) == cap(fifo) {
// FIFO channel full, discard oldest log entry before
// writing new one so it doesn't block.
<-fifo
}
fifo <- log
continue
}
// Otherwise encode and output log directly.
err := encoder.Encode(newJSONLog(log))
if err != nil {
logger.Noticef("Cannot write logs: %v", err)
return
}
if follow {
flushWriter(w)
}
case err := <-errorChan:
logger.Noticef("%s", err)
return
case <-req.Context().Done():
return
}
}
}
// streamLogs reads and parses logs from the given services, merging the
// log streams and ordering by timestamp. It sends the parsed logs to the
// logs channel, and returns when the done channel is closed.
func streamLogs(itsByName map[string]servicelog.Iterator, logs chan<- servicelog.Entry, done <-chan struct{}) error {
// Need to close iterators in same goroutine we're reading them from.
defer func() {
for _, it := range itsByName {
_ = it.Close()
}
}()
// Make a channel and register it with each of the iterators to be
// notified when new data comes in. We don't strictly need this when not
// following, but it doesn't hurt either.
notification := make(chan bool, 1)
for _, it := range itsByName {
it.Notify(notification)
}
// Make sorted list of service names we have iterators for.
var services []string
for name := range itsByName {
services = append(services, name)
}
sort.Strings(services)
// Create an iterator and log parser for each service.
iterators := make([]servicelog.Iterator, len(services))
parsers := make([]*servicelog.Parser, len(services))
for i, name := range services {
iterators[i] = itsByName[name]
parsers[i] = servicelog.NewParser(iterators[i], logReaderSize)
}
// Slice of next entries for each service
nexts := make([]servicelog.Entry, len(services))
// Main loop: output earliest log per iteration. Stop when done is closed.
for {
// Try to fetch next log from each service (parser/iterator combo).
for i, parser := range parsers {
if !nexts[i].Time.IsZero() {
continue
}
if parser.Next() {
nexts[i] = parser.Entry()
} else if parser.Err() != nil {
return fmt.Errorf("error parsing logs: %w", parser.Err())
} else if iterators[i].Next(nil) {
// Parsed all in parser buffer, but iterator now has more.
if parser.Next() {
nexts[i] = parser.Entry()
}
}
}
// Find the log with the next earliest timestamp.
earliest := -1
for i, next := range nexts {
if next.Time.IsZero() {
continue
}
if earliest < 0 || next.Time.Before(nexts[earliest].Time) {
earliest = i
}
}
// No more logs: send empty log to caller, then wait for more logs
// or done signal.
if earliest < 0 {
select {
case logs <- servicelog.Entry{}:
case <-done:
return nil
}
select {
case <-notification:
case <-done:
return nil
}
continue
}
// Send log to caller.
select {
case logs <- nexts[earliest]:
case <-done:
return nil
}
nexts[earliest].Time = time.Time{} // so corresponding iterator is fetched next loop
}
}
// Each log is written as a JSON object followed by a newline (JSON Lines):
//
// {"time":"2021-04-23T01:28:52.660Z","service":"redis","message":"redis started up"}
// {"time":"2021-04-23T01:28:52.798Z","service":"thing","message":"did something"}
type jsonLog struct {
Time time.Time `json:"time"`
Service string `json:"service"`
Message string `json:"message"`
}
func newJSONLog(entry servicelog.Entry) *jsonLog {
message := strings.TrimSuffix(entry.Message, "\n")
return &jsonLog{
Time: entry.Time,
Service: entry.Service,
Message: message,
}
}
func flushWriter(w io.Writer) {
flusher, ok := w.(interface{ Flush() })
if ok {
flusher.Flush()
}
}