-
Notifications
You must be signed in to change notification settings - Fork 0
/
debuglog.go
372 lines (342 loc) · 11.1 KB
/
debuglog.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
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package apiserver
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"github.com/juju/loggo"
"github.com/juju/names"
"github.com/juju/utils/tailer"
"golang.org/x/net/websocket"
"launchpad.net/tomb"
"github.com/juju/juju/apiserver/params"
)
// debugLogHandler takes requests to watch the debug log.
type debugLogHandler struct {
httpHandler
logDir string
}
var maxLinesReached = fmt.Errorf("max lines reached")
// ServeHTTP will serve up connections as a websocket.
// Args for the HTTP request are as follows:
// includeEntity -> []string - lists entity tags to include in the response
// - tags may finish with a '*' to match a prefix e.g.: unit-mysql-*, machine-2
// - if none are set, then all lines are considered included
// includeModule -> []string - lists logging modules to include in the response
// - if none are set, then all lines are considered included
// excludeEntity -> []string - lists entity tags to exclude from the response
// - as with include, it may finish with a '*'
// excludeModule -> []string - lists logging modules to exclude from the response
// limit -> uint - show *at most* this many lines
// backlog -> uint
// - go back this many lines from the end before starting to filter
// - has no meaning if 'replay' is true
// level -> string one of [TRACE, DEBUG, INFO, WARNING, ERROR]
// replay -> string - one of [true, false], if true, start the file from the start
func (h *debugLogHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
server := websocket.Server{
Handler: func(socket *websocket.Conn) {
logger.Infof("debug log handler starting")
// Validate before authenticate because the authentication is
// dependent on the state connection that is determined during the
// validation.
stateWrapper, err := h.validateEnvironUUID(req)
if err != nil {
h.sendError(socket, err)
socket.Close()
return
}
defer stateWrapper.cleanup()
// TODO (thumper): We need to work out how we are going to filter
// logging information based on environment.
if err := stateWrapper.authenticateUser(req); err != nil {
h.sendError(socket, fmt.Errorf("auth failed: %v", err))
socket.Close()
return
}
stream, err := newLogStream(req.URL.Query())
if err != nil {
h.sendError(socket, err)
socket.Close()
return
}
// Open log file.
logLocation := filepath.Join(h.logDir, "all-machines.log")
logFile, err := os.Open(logLocation)
if err != nil {
h.sendError(socket, fmt.Errorf("cannot open log file: %v", err))
socket.Close()
return
}
defer logFile.Close()
if err := stream.positionLogFile(logFile); err != nil {
h.sendError(socket, fmt.Errorf("cannot position log file: %v", err))
socket.Close()
return
}
// If we get to here, no more errors to report, so we report a nil
// error. This way the first line of the socket is always a json
// formatted simple error.
if err := h.sendError(socket, nil); err != nil {
logger.Errorf("could not send good log stream start")
socket.Close()
return
}
stream.start(logFile, socket)
go func() {
defer stream.tomb.Done()
defer socket.Close()
stream.tomb.Kill(stream.loop())
}()
if err := stream.tomb.Wait(); err != nil {
if err != maxLinesReached {
logger.Errorf("debug-log handler error: %v", err)
}
}
}}
server.ServeHTTP(w, req)
}
func newLogStream(queryMap url.Values) (*logStream, error) {
maxLines := uint(0)
if value := queryMap.Get("maxLines"); value != "" {
num, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return nil, fmt.Errorf("maxLines value %q is not a valid unsigned number", value)
}
maxLines = uint(num)
}
fromTheStart := false
if value := queryMap.Get("replay"); value != "" {
replay, err := strconv.ParseBool(value)
if err != nil {
return nil, fmt.Errorf("replay value %q is not a valid boolean", value)
}
fromTheStart = replay
}
backlog := uint(0)
if value := queryMap.Get("backlog"); value != "" {
num, err := strconv.ParseUint(value, 10, 64)
if err != nil {
return nil, fmt.Errorf("backlog value %q is not a valid unsigned number", value)
}
backlog = uint(num)
}
level := loggo.UNSPECIFIED
if value := queryMap.Get("level"); value != "" {
var ok bool
level, ok = loggo.ParseLevel(value)
if !ok || level < loggo.TRACE || level > loggo.ERROR {
return nil, fmt.Errorf("level value %q is not one of %q, %q, %q, %q, %q",
value, loggo.TRACE, loggo.DEBUG, loggo.INFO, loggo.WARNING, loggo.ERROR)
}
}
return &logStream{
includeEntity: queryMap["includeEntity"],
includeModule: queryMap["includeModule"],
excludeEntity: queryMap["excludeEntity"],
excludeModule: queryMap["excludeModule"],
maxLines: maxLines,
fromTheStart: fromTheStart,
backlog: backlog,
filterLevel: level,
}, nil
}
// sendError sends a JSON-encoded error response.
func (h *debugLogHandler) sendError(w io.Writer, err error) error {
response := ¶ms.ErrorResult{}
if err != nil {
response.Error = ¶ms.Error{Message: fmt.Sprint(err)}
}
message, err := json.Marshal(response)
if err != nil {
// If we are having trouble marshalling the error, we are in big trouble.
logger.Errorf("failure to marshal SimpleError: %v", err)
return err
}
message = append(message, []byte("\n")...)
_, err = w.Write(message)
return err
}
type logLine struct {
line string
agentTag string
agentName string
level loggo.Level
module string
}
func parseLogLine(line string) *logLine {
const (
agentTagIndex = 0
levelIndex = 3
moduleIndex = 4
)
fields := strings.Fields(line)
result := &logLine{
line: line,
}
if len(fields) > agentTagIndex {
agentTag := fields[agentTagIndex]
// Drop mandatory trailing colon (:).
// Since colon is mandatory, agentTag without it is invalid and will be empty ("").
if strings.HasSuffix(agentTag, ":") {
result.agentTag = agentTag[:len(agentTag)-1]
}
/*
Drop unit suffix.
In logs, unit information may be prefixed with either a unit_tag by itself or a unit_tag[nnnn].
The code below caters for both scenarios.
*/
if bracketIndex := strings.Index(agentTag, "["); bracketIndex != -1 {
result.agentTag = agentTag[:bracketIndex]
}
// If, at this stage, result.agentTag is empty, we could not deduce the tag. No point getting the name...
if result.agentTag != "" {
// Entity Name deduced from entity tag
entityTag, err := names.ParseTag(result.agentTag)
if err != nil {
/*
Logging error but effectively swallowing it as there is no where to propogate.
We don't expect ParseTag to fail since the tag was generated by juju in the first place.
*/
logger.Errorf("Could not deduce name from tag %q: %v\n", result.agentTag, err)
}
result.agentName = entityTag.Id()
}
}
if len(fields) > moduleIndex {
if level, valid := loggo.ParseLevel(fields[levelIndex]); valid {
result.level = level
result.module = fields[moduleIndex]
}
}
return result
}
// logStream runs the tailer to read a log file and stream
// it via a web socket.
type logStream struct {
tomb tomb.Tomb
logTailer *tailer.Tailer
filterLevel loggo.Level
includeEntity []string
includeModule []string
excludeEntity []string
excludeModule []string
backlog uint
maxLines uint
lineCount uint
fromTheStart bool
}
// positionLogFile will update the internal read position of the logFile to be
// at the end of the file or somewhere in the middle if backlog has been specified.
func (stream *logStream) positionLogFile(logFile io.ReadSeeker) error {
// Seek to the end, or lines back from the end if we need to.
if !stream.fromTheStart {
return tailer.SeekLastLines(logFile, stream.backlog, stream.filterLine)
}
return nil
}
// start the tailer listening to the logFile, and sending the matching
// lines to the writer.
func (stream *logStream) start(logFile io.ReadSeeker, writer io.Writer) {
stream.logTailer = tailer.NewTailer(logFile, writer, stream.countedFilterLine)
}
// loop starts the tailer with the log file and the web socket.
func (stream *logStream) loop() error {
select {
case <-stream.logTailer.Dead():
return stream.logTailer.Err()
case <-stream.tomb.Dying():
stream.logTailer.Stop()
}
return nil
}
// filterLine checks the received line for one of the configured tags.
func (stream *logStream) filterLine(line []byte) bool {
log := parseLogLine(string(line))
return stream.checkIncludeEntity(log) &&
stream.checkIncludeModule(log) &&
!stream.exclude(log) &&
stream.checkLevel(log)
}
// countedFilterLine checks the received line for one of the configured tags,
// and also checks to make sure the stream doesn't send more than the
// specified number of lines.
func (stream *logStream) countedFilterLine(line []byte) bool {
result := stream.filterLine(line)
if result && stream.maxLines > 0 {
stream.lineCount++
result = stream.lineCount <= stream.maxLines
if stream.lineCount == stream.maxLines {
stream.tomb.Kill(maxLinesReached)
}
}
return result
}
func (stream *logStream) checkIncludeEntity(line *logLine) bool {
if len(stream.includeEntity) == 0 {
return true
}
for _, value := range stream.includeEntity {
if agentMatchesFilter(line, value) {
return true
}
}
return false
}
// agentMatchesFilter checks if agentTag tag or agentTag name match given filter
func agentMatchesFilter(line *logLine, aFilter string) bool {
return hasMatch(line.agentName, aFilter) || hasMatch(line.agentTag, aFilter)
}
// hasMatch determines if value contains filter using regular expressions.
// All wildcard occurrences are changed to `.*`
// Currently, all match exceptions are logged and not propagated.
func hasMatch(value, aFilter string) bool {
/* Special handling: out of 12 regexp metacharacters \^$.|?+()[*{
only asterix (*) can be legally used as a wildcard in this context.
Both machine and unit tag and name specifications do not allow any other metas.
Consequently, if aFilter contains wildcard (*), do not escape it -
transform it into a regexp "any character(s)" sequence.
*/
aFilter = strings.Replace(aFilter, "*", `.*`, -1)
matches, err := regexp.MatchString("^"+aFilter+"$", value)
if err != nil {
// logging errors here... but really should they be swallowed?
logger.Errorf("\nCould not match filter %q and regular expression %q\n.%v\n", value, aFilter, err)
}
return matches
}
func (stream *logStream) checkIncludeModule(line *logLine) bool {
if len(stream.includeModule) == 0 {
return true
}
for _, value := range stream.includeModule {
if strings.HasPrefix(line.module, value) {
return true
}
}
return false
}
func (stream *logStream) exclude(line *logLine) bool {
for _, value := range stream.excludeEntity {
if agentMatchesFilter(line, value) {
return true
}
}
for _, value := range stream.excludeModule {
if strings.HasPrefix(line.module, value) {
return true
}
}
return false
}
func (stream *logStream) checkLevel(line *logLine) bool {
return line.level >= stream.filterLevel
}