blob: 07185ed7b0beb1001858eb8ccb6e924ce5451f64 [file] [log] [blame]
Serge Bazanski0ab4eda2021-03-12 17:43:57 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package logtree
18
19import (
20 "fmt"
21 "io"
22 "regexp"
Serge Bazanski0ab4eda2021-03-12 17:43:57 +010023 "strconv"
24 "strings"
25 "time"
Serge Bazanski96043bc2021-10-05 12:10:13 +020026
27 "source.monogon.dev/metropolis/pkg/logbuffer"
Serge Bazanski0ab4eda2021-03-12 17:43:57 +010028)
29
30// KLogParser returns an io.WriteCloser to which raw logging from a klog emitter
31// can be piped. It will attempt to parse all lines from this log as
32// glog/klog-style entries, and pass them over to a LeveledLogger as if they were
33// emitted locally.
34//
35// This allows for piping in external processes that emit klog logging into a
36// logtree, leading to niceties like transparently exposing the log severity or
37// source file/line.
38//
39// One caveat, however, is that V-leveled logs will not be translated
40// appropriately - anything that the klog-emitter pumps out as Info will be
41// directly ingested as Info logging. There is no way to work around this.
42//
43// Another important limitation is that any written line is interpreted as having
44// happened recently (ie. within one hour of the time of execution of this
45// function). This is important as klog/glog-formatted loglines don't have a year
46// attached, so we have to infer it based on the current timestamp (note: parsed
47// lines do not necessarily have their year aleays equal to the current year, as
48// the code handles the edge case of parsing a line from the end of a previous
49// year at the beginning of the next).
50func KLogParser(logger LeveledLogger) io.WriteCloser {
51 n, ok := logger.(*node)
52 if !ok {
53 // Fail fast, as this is a programming error.
54 panic("Expected *node in LeveledLogger from supervisor")
55 }
56
57 k := &klogParser{
58 n: n,
59 }
60 // klog seems to have no line length limit. Let's assume some sane sort of default.
61 k.buffer = logbuffer.NewLineBuffer(1024, k.consumeLine)
62 return k
63}
64
Serge Bazanski0ab4eda2021-03-12 17:43:57 +010065type klogParser struct {
Serge Bazanski216fe7b2021-05-21 18:36:16 +020066 n *node
Serge Bazanski0ab4eda2021-03-12 17:43:57 +010067 buffer *logbuffer.LineBuffer
68}
69
70func (k *klogParser) Write(p []byte) (n int, err error) {
71 return k.buffer.Write(p)
72}
73
74// Close must be called exactly once after the parser is done being used. It will
75// pipe any leftover data in its write buffer as one last line to parse.
76func (k *klogParser) Close() error {
77 return k.buffer.Close()
78}
79
80// consumeLine is called by the internal LineBuffer any time a new line is fully
81// written.
82func (k *klogParser) consumeLine(l *logbuffer.Line) {
83 p := parse(time.Now(), l.Data)
84 if p == nil {
85 // We could instead emit that line as a raw log - however, this would lead to
86 // interleaving raw logging and leveled logging.
87 k.n.Errorf("Invalid klog line: %s", l.Data)
88 }
89 // TODO(q3k): should this be exposed as an API on LeveledLogger? How much should
90 // we permit library users to 'fake' logs? This would also permit us to get rid
91 // of the type assertion in KLogParser().
92 e := &entry{
Serge Bazanski216fe7b2021-05-21 18:36:16 +020093 origin: k.n.dn,
Serge Bazanski0ab4eda2021-03-12 17:43:57 +010094 leveled: p,
95 }
96 k.n.tree.journal.append(e)
97 k.n.tree.journal.notify(e)
98}
99
100var (
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200101 // reKLog matches and parses klog/glog-formatted log lines. Format: I0312
102 // 14:20:04.240540 204 shared_informer.go:247] Caches are synced for attach
103 // detach
Serge Bazanski0ab4eda2021-03-12 17:43:57 +0100104 reKLog = regexp.MustCompile(`^([IEWF])(\d{4})\s+(\d{2}:\d{2}:\d{2}(\.\d+)?)\s+(\d+)\s+([^:]+):(\d+)]\s+(.+)$`)
105)
106
107// parse attempts to parse a klog-formatted line. Returns nil if the line
108// couldn't have been parsed successfully.
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200109func parse(now time.Time, s string) *LeveledPayload {
Serge Bazanski0ab4eda2021-03-12 17:43:57 +0100110 parts := reKLog.FindStringSubmatch(s)
111 if parts == nil {
112 return nil
113 }
114
115 severityS := parts[1]
116 date := parts[2]
117 timestamp := parts[3]
118 pid := parts[5]
119 file := parts[6]
120 lineS := parts[7]
121 message := parts[8]
122
123 var severity Severity
124 switch severityS {
125 case "I":
126 severity = INFO
127 case "W":
128 severity = WARNING
129 case "E":
130 severity = ERROR
131 case "F":
132 severity = FATAL
133 default:
134 return nil
135 }
136
137 // Possible race due to klog's/glog's format not containing a year.
138 // On 2020/12/31 at 23:59:59.99999 a klog logger emits this line:
139 //
140 // I1231 23:59:59.99999 1 example.go:10] It's almost 2021! Hooray.
141 //
142 // Then, if this library parses that line at 2021/01/01 00:00:00.00001, the
143 // time will be interpreted as:
144 //
145 // 2021/12/31 23:59:59
146 //
147 // So around one year in the future. We attempt to fix this case further down in
148 // this function.
149 year := now.Year()
150 ts, err := parseKLogTime(year, date, timestamp)
151 if err != nil {
152 return nil
153 }
154
155 // Attempt to fix the aforementioned year-in-the-future issue.
156 if ts.After(now) && ts.Sub(now) > time.Hour {
157 // Parsed timestamp is in the future. How close is it to One-Year-From-Now?
158 oyfn := now.Add(time.Hour * 24 * 365)
159 dOyfn := ts.Sub(oyfn)
160 // Let's make sure Duration-To-One-Year-From-Now is always positive. This
161 // simplifies the rest of the checks and papers over some possible edge cases.
162 if dOyfn < 0 {
163 dOyfn = -dOyfn
164 }
165
166 // Okay, is that very close? Then the issue above happened and we should
167 // attempt to reparse it with last year. We can't just manipulate the date we
168 // already have, as it's difficult to 'subtract one year'.
169 if dOyfn < (time.Hour * 24 * 2) {
170 ts, err = parseKLogTime(year-1, date, timestamp)
171 if err != nil {
172 return nil
173 }
174 } else {
175 // Otherwise, we received some seriously time traveling log entry. Abort.
176 return nil
177 }
178 }
179
180 line, err := strconv.Atoi(lineS)
181 if err != nil {
182 return nil
183 }
184
185 // The PID is discarded.
186 _ = pid
187
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200188 // Finally we have extracted all the data from the line. Inject into the log
189 // publisher.
Serge Bazanski0ab4eda2021-03-12 17:43:57 +0100190 return &LeveledPayload{
191 timestamp: ts,
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200192 severity: severity,
193 messages: []string{message},
194 file: file,
195 line: line,
Serge Bazanski0ab4eda2021-03-12 17:43:57 +0100196 }
197}
198
199// parseKLogTime parses a klog date and time (eg. "0314", "12:13:14.12345") into
200// a time.Time happening at a given year.
201func parseKLogTime(year int, d, t string) (time.Time, error) {
202 var layout string
203 if strings.Contains(t, ".") {
204 layout = "2006 0102 15:04:05.000000"
205 } else {
206 layout = "2006 0102 15:04:05"
207 }
208 // Make up a string that contains the current year. This permits us to parse
209 // fully into an actual timestamp.
210 // TODO(q3k): add a timezone? This currently behaves as UTC, which is probably
211 // what we want, but we should formalize this.
212 return time.Parse(layout, fmt.Sprintf("%d %s %s", year, d, t))
213}