Debian Codegraph @

core/lstream_client.go

raw
1 package core
2
3 import (
4 "bufio"
5 "bytes"
6 "compress/gzip"
7 _ "embed"
8 "fmt"
9 "io"
10 "regexp"
11 "strconv"
12 "strings"
13 "time"
14
15 "github.com/juju/errors"
16
17 "github.com/dimonomid/clock"
18 "github.com/dimonomid/nerdlog/log"
19 )
20
21 const SpecialFilenameJournalctl = "journalctl"
22
23 const connectionTimeout = 5 * time.Second
24
25 // Setting useGzip to false is just a simple way to disable gzip, for debugging
26 // purposes or w/e, since it's still experimental. Maybe we need to add a flag
27 // for it, we'll see.
28 const useGzip = true
29
30 const (
31 // gzipStartMarker and gzipEndMarker are echoed in the beginning and the end
32 // of the gzipped output. Effectively we're doing this:
33 //
34 // $ echo gzip_start ; whatever command we need to run | gzip ; echo gzip_end
35 //
36 // and the scanner func (returned by getScannerFunc) sees those markers and
37 // buffers gzipped output until it's done, then gunzips it and sends to the
38 // clients, so it's totally opaque for them.
39 gzipStartMarker = "gzip_start"
40 gzipEndMarker = "gzip_end"
41 )
42
43 // queryLogsArgsTimeLayout is used to format the --from and --to arguments for
44 // nerdlog_agent.sh.
45 //
46 // TODO: make it dynamic; e.g. generating that day string like "02" requires
47 // some extra logic in the agent script for the traditional syslog format
48 // (which has it space-padded, not zero-padded).
49 const queryLogsArgsTimeLayout = "2006-01-02-15:04"
50
51 // queryLogsTimestampUntilSecondsTimeLayout is used to format the
52 // --timestamp-until-seconds arguments for nerdlog_agent.sh.
53 // It needs to match what journalctl *takes as an argument*.
54 // TODO: better naming.
55 const queryLogsTimestampUntilSecondsTimeLayout = "2006-01-02 15:04:05"
56
57 // queryLogsTimestampUntilPreciseTimeLayout is used to format the
58 // --timestamp-until-precise arguments for nerdlog_agent.sh.
59 // It needs to match what journalctl *outputs with --output=short-iso-precise*.
60 // TODO: better naming.
61 const queryLogsTimestampUntilPreciseTimeLayout = "2006-01-02T15:04:05.000000"
62
63 //go:embed nerdlog_agent.sh
64 var nerdlogAgentSh string
65
66 var syslogRegex = regexp.MustCompile(`^(\S+)\s+(\S+?)(?:\[(\d+)\])?:\s+(.*)`)
67
68 type LStreamClient struct {
69 params LStreamClientParams
70
71 transport ShellTransport
72
73 connectUpdCh chan ShellConnUpdate
74 enqueueCmdCh chan lstreamCmd
75
76 // timezone is a string received from the logstream
77 timezone string
78 // location is loaded based on the timezone. If failed, it'll be UTC.
79 location *time.Location
80
81 // exampleLogLines are the lines that we received during logstream bootstrap.
82 // We'll try to do log format autodetection based on that.
83 exampleLogLines []string
84 timeFormat *TimeFormatDescr
85
86 numConnAttempts int
87
88 state LStreamClientState
89 busyStage BusyStage
90
91 conn *connCtx
92
93 // connDebugMessages contains human-readable messages received from the shell
94 // transport regarding the connection.
95 connDebugMessages []string
96
97 cmdQueue []lstreamCmd
98 curCmdCtx *lstreamCmdCtx
99 nextCmdIdx int
100
101 // disconnectReqCh is sent to when Close is called.
102 disconnectReqCh chan disconnectReq
103 tearingDown bool
104 // disconnectedBeforeTeardownCh is closed once tearingDown is true and we're
105 // fully disconnected.
106 disconnectedBeforeTeardownCh chan struct{}
107
108 //debugFile *os.File
109 }
110
111 // disconnectReq represents a request to abort whatever connection we have,
112 // and either teardown or reconnect again.
113 type disconnectReq struct {
114 // If teardown is true, it means the LStreamClient should completely stop. Otherwise,
115 // after disconnecting, it will reconnect.
116 teardown bool
117
118 // If changeName is non-empty, the LStreamClient's Name will be updated;
119 // it's useful for teardowns, to distinguish from potentially-existing
120 // another LStreamClient with the same (old) name.
121 changeName string
122 }
123
124 type connCtx struct {
125 // conn is the actual underlying connection that we've established.
126 conn ShellConn
127
128 // stdoutLinesCh receives lines from conn.Stdout(). If stdout had some
129 // gzipped portion, the lines arrive to stdoutLinesCh already gunzipped.
130 stdoutLinesCh chan string
131
132 // stderrLinesCh receives lines from conn.Stderr(). Technically, the same
133 // gunzipping logic as in stdout applies here as well, however in practice
134 // we don't send gzipped data over stderr.
135 stderrLinesCh chan string
136 }
137
138 type BusyStage struct {
139 // Num is just a stage number. Its meaning depends on the kind of command the
140 // host is executing, but a general rule is that this number starts from 1
141 // and then increases, as the process goes on, so we can compare different
142 // nodes and e.g. find the slowest one.
143 Num int
144
145 // Title is just a human-readable description of the stage.
146 Title string
147
148 // ExtraInfo might contains some additional context, also just a
149 // human-readable string.
150 ExtraInfo string
151
152 // Percentage is a percentage of the current stage.
153 Percentage int
154 }
155
156 type ConnDetails struct {
157 // Messages contains human-readable messages received from shell transport
158 // regarding the connection.
159 Messages []string
160
161 // Err is an error message from the last connection attempt.
162 Err string
163
164 // Connected shows whether the connection has already succeeded. Unlike other
165 // fields in this struct, it's set by the LStreamsManager manually.
166 Connected bool
167 }
168
169 type BootstrapDetails struct {
170 // Err is an error message from the last bootstrap attempt.
171 Err string
172
173 // WarnJournalctlNoAdminAccess is set to true if journalctl is used and the
174 // user doesn't have access to all the system logs. It's a separate bool
175 // instead of a generic warning message to make it possible to suppress it
176 // with a flag.
177 WarnJournalctlNoAdminAccess bool
178 }
179
180 func (c *connCtx) getStdoutLinesCh() chan string {
181 if c == nil {
182 return nil
183 }
184
185 return c.stdoutLinesCh
186 }
187
188 func (c *connCtx) getStderrLinesCh() chan string {
189 if c == nil {
190 return nil
191 }
192
193 return c.stderrLinesCh
194 }
195
196 // LStreamClientUpdate represents an update from logstream client. Name is always
197 // populated and it's the logstream's name, and from all the other fields, exactly
198 // one field must be non-nil.
199 type LStreamClientUpdate struct {
200 Name string
201
202 State *LStreamClientUpdateState
203
204 ConnDetails *ConnDetails
205 BootstrapDetails *BootstrapDetails
206 BusyStage *BusyStage
207
208 DataRequest *ShellConnDataRequest
209
210 // If TornDown is true, it means it's the last update from that client.
211 TornDown bool
212 }
213
214 type LStreamClientUpdateState struct {
215 OldState LStreamClientState
216 NewState LStreamClientState
217 }
218
219 type LStreamClientParams struct {
220 LogStream LogStream
221
222 // SSHKeys specifies paths to ssh keys to try, in the given order, until
223 // an existing key is found.
224 SSHKeys []string
225
226 Logger *log.Logger
227
228 // ClientID is just an arbitrary string (should be filename-friendly though)
229 // which will be appended to the nerdlog_agent.sh and its index filenames.
230 //
231 // Needed to make sure that different clients won't get conflicts over those
232 // files when using the tool concurrently on the same nodes.
233 ClientID string
234
235 UpdatesCh chan<- *LStreamClientUpdate
236
237 Clock clock.Clock
238 }
239
240 // createTransport creates a shell transport accordingly to the provided
241 // config. The config must be valid (e.g. it should contain exactly one item),
242 // otherwise createTransport panics.
243 func createTransport(
244 config ConfigLogStreamShellTransport, sshKeys []string, logger *log.Logger,
245 ) ShellTransport {
246 var transport ShellTransport
247
248 if config.SSHLib != nil {
249 if transport != nil {
250 panic("transport config is ambiguous")
251 }
252
253 transport = NewShellTransportSSHLib(ShellTransportSSHLibParams{
254 SSHKeys: sshKeys,
255 ConnDetails: *config.SSHLib,
256
257 Logger: logger,
258 })
259 }
260
261 if config.SSHBin != nil {
262 if transport != nil {
263 panic("transport config is ambiguous")
264 }
265
266 transport = NewShellTransportSSHBin(ShellTransportSSHBinParams{
267 Host: config.SSHBin.Host,
268 User: config.SSHBin.User,
269 Port: config.SSHBin.Port,
270
271 Logger: logger,
272 })
273 }
274
275 if config.Localhost != nil {
276 if transport != nil {
277 panic("transport config is ambiguous")
278 }
279
280 transport = NewShellTransportLocal(ShellTransportLocalParams{
281 Logger: logger,
282 })
283 }
284
285 if transport == nil {
286 panic("transport config is empty")
287 }
288
289 return transport
290 }
291
292 func NewLStreamClient(params LStreamClientParams) *LStreamClient {
293 if params.Clock == nil {
294 // For details on why not default to the real clock:
295 // https://dmitryfrank.com/articles/mocking_time_in_go#caveat_with_defaulting_to_real_clock
296 panic("Clock is nil")
297 }
298
299 params.Logger = params.Logger.WithNamespaceAppended(
300 fmt.Sprintf("LSClient_%s", params.LogStream.Name),
301 )
302
303 transport := createTransport(params.LogStream.Transport, params.SSHKeys, params.Logger)
304
305 lsc := &LStreamClient{
306 params: params,
307
308 transport: transport,
309
310 timezone: "UTC",
311 location: time.UTC,
312
313 state: LStreamClientStateDisconnected,
314 enqueueCmdCh: make(chan lstreamCmd, 32),
315
316 disconnectReqCh: make(chan disconnectReq, 1),
317 disconnectedBeforeTeardownCh: make(chan struct{}),
318 }
319
320 //debugFile, _ := os.Create("/tmp/lsclient_debug.log")
321 //lsc.debugFile = debugFile
322
323 lsc.changeState(LStreamClientStateConnecting)
324
325 go lsc.run()
326
327 return lsc
328 }
329
330 func (lsc *LStreamClient) SendFoo() {
331 }
332
333 type LStreamClientState string
334
335 const (
336 LStreamClientStateDisconnected LStreamClientState = "disconnected"
337 LStreamClientStateConnecting LStreamClientState = "connecting"
338 LStreamClientStateDisconnecting LStreamClientState = "disconnecting"
339 LStreamClientStateConnectedIdle LStreamClientState = "connected_idle"
340 LStreamClientStateConnectedBusy LStreamClientState = "connected_busy"
341 )
342
343 func isStateConnected(state LStreamClientState) bool {
344 return state == LStreamClientStateConnectedIdle || state == LStreamClientStateConnectedBusy
345 }
346
347 func (lsc *LStreamClient) changeState(newState LStreamClientState) {
348 oldState := lsc.state
349
350 // Properly leave old state
351
352 if isStateConnected(oldState) && !isStateConnected(newState) {
353 // Initiate disconnect
354 lsc.conn.conn.Close()
355 }
356
357 switch oldState {
358 case LStreamClientStateConnecting:
359 lsc.connectUpdCh = nil
360 case LStreamClientStateConnectedBusy:
361 lsc.curCmdCtx = nil
362 lsc.busyStage = BusyStage{}
363 }
364
365 // Enter new state
366
367 lsc.state = newState
368 lsc.sendUpdate(&LStreamClientUpdate{
369 State: &LStreamClientUpdateState{
370 OldState: oldState,
371 NewState: newState,
372 },
373 })
374
375 switch lsc.state {
376 case LStreamClientStateConnecting:
377 // Forget whatever queued command we might have.
378 lsc.cmdQueue = nil
379 // Forget whatever conn debug messages we've accumulated.
380 lsc.connDebugMessages = nil
381
382 // Initiate new connection
383 lsc.numConnAttempts++
384 lsc.connectUpdCh = make(chan ShellConnUpdate, 1)
385 lsc.transport.Connect(lsc.connectUpdCh)
386
387 case LStreamClientStateConnectedIdle:
388 if len(lsc.cmdQueue) > 0 {
389 nextCmd := lsc.cmdQueue[0]
390 lsc.cmdQueue = lsc.cmdQueue[1:]
391
392 lsc.startCmd(nextCmd)
393 }
394
395 case LStreamClientStateDisconnected:
396 lsc.conn = nil
397 }
398 }
399
400 func (lsc *LStreamClient) makeConnDetailsMsg(err string) *ConnDetails {
401 return &ConnDetails{
402 Messages: lsc.connDebugMessages,
403 Err: err,
404 }
405 }
406
407 func (lsc *LStreamClient) sendBusyStageUpdate() {
408 upd := lsc.busyStage
409 lsc.sendUpdate(&LStreamClientUpdate{
410 BusyStage: &upd,
411 })
412 }
413
414 func (lsc *LStreamClient) sendCmdResp(resp interface{}, err error) {
415 if lsc.curCmdCtx == nil {
416 return
417 }
418
419 if lsc.curCmdCtx.cmd.respCh == nil {
420 return
421 }
422
423 lsc.curCmdCtx.cmd.respCh <- lstreamCmdRes{
424 hostname: lsc.params.LogStream.Name,
425 resp: resp,
426 err: err,
427 }
428 }
429
430 func (lsc *LStreamClient) run() {
431 ticker := time.NewTicker(1 * time.Second)
432 var connectAfter time.Time
433 var lastUpdTime time.Time
434
435 for {
436 select {
437 case upd := <-lsc.connectUpdCh:
438 if dbg := upd.DebugInfo; dbg != nil {
439 // Got some debug info about the connection.
440 lsc.connDebugMessages = append(lsc.connDebugMessages, dbg.Message)
441
442 lsc.sendUpdate(&LStreamClientUpdate{
443 ConnDetails: lsc.makeConnDetailsMsg(""),
444 })
445 } else if dataReq := upd.DataRequest; dataReq != nil {
446 // We need some data from the user.
447
448 lsc.sendUpdate(&LStreamClientUpdate{
449 DataRequest: dataReq,
450 })
451 } else if res := upd.Result; res != nil {
452 // The connection has either succeeded or failed.
453
454 if res.Err != nil {
455 lsc.params.Logger.Errorf("Shell connection failed: %s", res.Err.Error())
456 lsc.sendUpdate(&LStreamClientUpdate{
457 ConnDetails: lsc.makeConnDetailsMsg(fmt.Sprintf("attempt %d: %s", lsc.numConnAttempts, res.Err.Error())),
458 })
459
460 lsc.changeState(LStreamClientStateDisconnected)
461 if lsc.tearingDown {
462 close(lsc.disconnectedBeforeTeardownCh)
463 continue
464 }
465
466 connectAfter = lsc.params.Clock.Now().Add(2 * time.Second)
467 continue
468 }
469
470 lsc.params.Logger.Infof("Shell connection succeeded, starting bootstrap")
471
472 lsc.numConnAttempts = 0
473
474 lastUpdTime = lsc.params.Clock.Now()
475
476 stdoutLinesCh := make(chan string, 32)
477 stderrLinesCh := make(chan string, 32)
478
479 go getScannerFunc("stdout", res.Conn.Stdout(), stdoutLinesCh)()
480 go getScannerFunc("stderr", res.Conn.Stderr(), stderrLinesCh)()
481
482 lsc.conn = &connCtx{
483 conn: res.Conn,
484 stdoutLinesCh: stdoutLinesCh,
485 stderrLinesCh: stderrLinesCh,
486 }
487 lsc.changeState(LStreamClientStateConnectedIdle)
488
489 // Send bootstrap command
490 lsc.startCmd(lstreamCmd{
491 bootstrap: &lstreamCmdBootstrap{},
492 })
493 }
494
495 case cmd := <-lsc.enqueueCmdCh:
496 // Require a connection.
497 if !isStateConnected(lsc.state) {
498 lsc.sendCmdResp(nil, errors.Errorf("not connected"))
499 continue
500 }
501
502 // And then, depending on whether we're busy or idle, either act
503 // right away, or enqueue for later.
504 if lsc.state == LStreamClientStateConnectedIdle {
505 lsc.startCmd(cmd)
506 } else {
507 lsc.addCmdToQueue(cmd)
508 }
509
510 case line, ok := <-lsc.conn.getStdoutLinesCh():
511 if !ok {
512 // Stdout was just closed
513 lsc.params.Logger.Verbose3f("Stdout was closed (%s)", lsc.params.LogStream.Name)
514
515 lsc.conn.stdoutLinesCh = nil
516 lsc.checkIfDisconnected()
517 continue
518 }
519
520 lsc.params.Logger.Verbose3f("Got stdout line(%s): %s", lsc.params.LogStream.Name, line)
521
522 lastUpdTime = lsc.params.Clock.Now()
523
524 switch lsc.state {
525 case LStreamClientStateConnectedBusy:
526 cmdCtx := lsc.curCmdCtx
527
528 if cmdCtx == nil {
529 // We received some line before printing any command, must be
530 // just standard welcome message, but we're not interested in that.
531 continue
532 }
533
534 if lsc.checkCommandDone(line, cmdCtx, false) {
535 continue
536 }
537
538 if lsc.checkResetOutput(line, cmdCtx, false) {
539 continue
540 }
541
542 if lsc.checkError(line, cmdCtx) {
543 continue
544 }
545
546 if lsc.checkExitCode(line, cmdCtx) {
547 continue
548 }
549
550 switch {
551 case cmdCtx.cmd.bootstrap != nil:
552 tzPrefix := "host_timezone:"
553 logLinePrefix := "example_log_line:"
554
555 if strings.HasPrefix(line, tzPrefix) {
556 tz := strings.TrimPrefix(line, tzPrefix)
557 lsc.params.Logger.Verbose1f("Got logstream timezone: %s\n", tz)
558
559 location, err := time.LoadLocation(tz)
560 if err != nil {
561 lsc.params.Logger.Errorf("Error: failed to load location %s, will use UTC\n", tz)
562 // TODO: send an update and then the receiver should show a message
563 // to the user
564 } else {
565 lsc.timezone = tz
566 lsc.location = location
567 }
568 } else if strings.HasPrefix(line, logLinePrefix) {
569 exampleLogLine := strings.TrimPrefix(line, logLinePrefix)
570 lsc.params.Logger.Verbose1f("Got example log line: %s\n", exampleLogLine)
571
572 lsc.exampleLogLines = append(lsc.exampleLogLines, exampleLogLine)
573 } else if line == "bootstrap ok" {
574 cmdCtx.bootstrapCtx.receivedSuccess = true
575 } else if line == "bootstrap failed" {
576 cmdCtx.bootstrapCtx.receivedFailure = true
577 } else {
578 cmdCtx.unhandledStdout = append(cmdCtx.unhandledStdout, line)
579 }
580
581 case cmdCtx.cmd.ping != nil:
582 // Nothing special to do
583 cmdCtx.unhandledStdout = append(cmdCtx.unhandledStdout, line)
584
585 case cmdCtx.cmd.queryLogs != nil:
586 respCtx := cmdCtx.queryLogsCtx
587 resp := respCtx.Resp
588
589 switch {
590 case strings.HasPrefix(line, "s:"):
591 parts := strings.Split(strings.TrimPrefix(line, "s:"), ",")
592 if len(parts) < 2 {
593 err := errors.Errorf("malformed mstats %q: expected at least 2 parts", line)
594 cmdCtx.errs = append(cmdCtx.errs, err)
595 continue
596 }
597
598 t, err := time.ParseInLocation(lsc.timeFormat.MinuteKeyLayout, parts[0], lsc.location)
599 if err != nil {
600 cmdCtx.errs = append(cmdCtx.errs, errors.Annotatef(err, "parsing mstats"))
601 continue
602 }
603
604 t = InferYear(lsc.params.Clock.Now(), t)
605 t = t.UTC()
606
607 n, err := strconv.Atoi(parts[1])
608 if err != nil {
609 cmdCtx.errs = append(cmdCtx.errs, errors.Annotatef(err, "parsing mstats"))
610 continue
611 }
612
613 resp.MinuteStats[t.Unix()] = MinuteStatsItem{
614 NumMsgs: n,
615 }
616
617 case strings.HasPrefix(line, "logfile:"):
618 msg := strings.TrimPrefix(line, "logfile:")
619 idx := strings.IndexRune(msg, ':')
620 if idx <= 0 {
621 cmdCtx.errs = append(cmdCtx.errs, errors.Errorf("parsing logfile msg: no number of lines %q", line))
622 continue
623 }
624
625 logFilename := msg[:idx]
626 logNumberOfLinesStr := msg[idx+1:]
627 logNumberOfLines, err := strconv.Atoi(logNumberOfLinesStr)
628 if err != nil {
629 cmdCtx.errs = append(cmdCtx.errs, errors.Annotatef(err, "parsing logfile msg: invalid number in %q", line))
630 continue
631 }
632
633 respCtx.logfiles = append(respCtx.logfiles, logfileWithStartingLinenumber{
634 filename: logFilename,
635 fromLinenumber: logNumberOfLines,
636 })
637
638 case strings.HasPrefix(line, "m:"):
639 // msg:Mar 26 17:08:34 localhost myapp[21134]: Mar 26 17:08:34.476329 foo bar foo bar
640 msg := strings.TrimPrefix(line, "m:")
641 idx := strings.IndexRune(msg, ':')
642 if idx <= 0 {
643 cmdCtx.errs = append(cmdCtx.errs, errors.Errorf("parsing log msg: no line number in %q", line))
644 continue
645 }
646
647 logLinenoStr := msg[:idx]
648 msg = msg[idx+1:]
649
650 logLinenoCombined, err := strconv.Atoi(logLinenoStr)
651 if err != nil {
652 cmdCtx.errs = append(cmdCtx.errs, errors.Annotatef(err, "parsing log msg: invalid line number in %q", line))
653 continue
654 }
655
656 var logFilename string
657 logLineno := logLinenoCombined
658
659 for i := len(respCtx.logfiles) - 1; i >= 0; i-- {
660 logfile := respCtx.logfiles[i]
661 if logfile.filename == SpecialFilenameJournalctl || logLineno > logfile.fromLinenumber {
662 logLineno -= logfile.fromLinenumber
663 logFilename = logfile.filename
664 break
665 }
666 }
667
668 // Put together a basic LogMsg, for now with the raw message and
669 // without even the Time parsed, and then give it to parseLine,
670 // which will encirch it.
671 logMsg := LogMsg{
672 // Time will be set later
673
674 LogFilename: logFilename,
675 LogLinenumber: logLineno,
676
677 CombinedLinenumber: logLinenoCombined,
678
679 Msg: msg,
680 Context: map[string]string{
681 "lstream": lsc.params.LogStream.Name,
682 },
683
684 OrigLine: msg,
685 }
686
687 err = lsc.parseLine(&logMsg)
688 if err != nil {
689 cmdCtx.errs = append(cmdCtx.errs, errors.Annotatef(err, "parsing log msg %q", line))
690 continue
691 }
692
693 if logMsg.Time.Before(respCtx.lastTime) {
694 // Time has decreased: this might happen if the previous log line
695 // had a precise timestamp with microseconds (coming from the app
696 // level), but the current line only has a second precision
697 // (e.g. coming from rsyslog level). Then we just hackishly set the
698 // current timestamp to be the same.
699 logMsg.Time = respCtx.lastTime
700 logMsg.DecreasedTimestamp = true
701 }
702
703 resp.Logs = append(resp.Logs, logMsg)
704
705 respCtx.lastTime = logMsg.Time
706
707 // NOTE: the "p:" lines (process-related) are in stderr and thus
708 // are handled below. Why they are in stderr, see comments there.
709 default:
710 cmdCtx.unhandledStdout = append(cmdCtx.unhandledStdout, line)
711 }
712
713 default:
714 panic("invalid cmdCtx.cmd: no subcontext")
715 }
716 }
717
718 case line, ok := <-lsc.conn.getStderrLinesCh():
719 if !ok {
720 // Stderr was just closed
721 lsc.params.Logger.Verbose3f("Stderr was closed (%s)", lsc.params.LogStream.Name)
722
723 lsc.conn.stderrLinesCh = nil
724 lsc.checkIfDisconnected()
725 continue
726 }
727
728 lsc.params.Logger.Verbose3f("Got stderr line(%s): %s", lsc.params.LogStream.Name, line)
729
730 lastUpdTime = lsc.params.Clock.Now()
731
732 // NOTE: the "p:" lines (process-related) are here in stderr, because
733 // stdout is gzipped and thus we don't have any partial results (we get
734 // them all at once), but for the process info, we actually want it right
735 // when it's printed by the nerdlog_agent.sh.
736 switch lsc.state {
737 case LStreamClientStateConnectedBusy:
738 cmdCtx := lsc.curCmdCtx
739
740 if cmdCtx == nil {
741 // We received some line before printing any command, just ignore that.
742 continue
743 }
744
745 if lsc.checkCommandDone(line, cmdCtx, true) {
746 continue
747 }
748
749 if lsc.checkResetOutput(line, cmdCtx, true) {
750 continue
751 }
752
753 if lsc.checkError(line, cmdCtx) {
754 continue
755 }
756
757 switch {
758 case cmdCtx.cmd.bootstrap != nil:
759 if line == "warn_journalctl_no_admin_access" {
760 cmdCtx.bootstrapCtx.warnJournalctlNoAdminAccess = true
761 } else {
762 cmdCtx.unhandledStderr = append(cmdCtx.unhandledStderr, line)
763 }
764 case cmdCtx.cmd.ping != nil:
765 cmdCtx.unhandledStderr = append(cmdCtx.unhandledStderr, line)
766 case cmdCtx.cmd.queryLogs != nil:
767 switch {
768 case strings.HasPrefix(line, "p:"):
769 // "p:" means process
770 processLine := strings.TrimPrefix(line, "p:")
771
772 switch {
773 case strings.HasPrefix(processLine, "stage:"):
774 stageLine := strings.TrimPrefix(processLine, "stage:")
775 parts := strings.Split(stageLine, ":")
776 if len(parts) < 2 {
777 cmdCtx.errs = append(cmdCtx.errs, errors.Errorf("received malformed p:stage line: %s (expected at least 2 parts, got %d)", line, len(parts)))
778 continue
779 }
780
781 num, err := strconv.Atoi(parts[0])
782 if err != nil {
783 cmdCtx.errs = append(cmdCtx.errs, errors.Annotatef(err, "received malformed p:stage line: %s", line))
784 continue
785 }
786
787 lsc.busyStage = BusyStage{
788 Num: num,
789 Title: parts[1],
790 }
791
792 if len(parts) >= 3 {
793 lsc.busyStage.ExtraInfo = parts[2]
794 }
795
796 lsc.sendBusyStageUpdate()
797
798 case strings.HasPrefix(processLine, "p:"):
799 // second "p:" means percentage
800
801 percentage, err := strconv.Atoi(strings.TrimPrefix(processLine, "p:"))
802 if err != nil {
803 cmdCtx.errs = append(cmdCtx.errs, errors.Annotatef(err, "received malformed p:p line: %s", line))
804 continue
805 }
806
807 lsc.busyStage.Percentage = percentage
808 lsc.sendBusyStageUpdate()
809 default:
810 cmdCtx.unhandledStderr = append(cmdCtx.unhandledStderr, line)
811 }
812 default:
813 cmdCtx.unhandledStderr = append(cmdCtx.unhandledStderr, line)
814 }
815
816 default:
817 panic("invalid cmdCtx.cmd: no subcontext")
818 }
819 }
820
821 //case data := <-lsc.stdinCh:
822 //lsc.stdinBuf.Write([]byte(data))
823 //if len(data) > 0 && data[len(data)-1] != '\n' {
824 //lsc.stdinBuf.Write([]byte("\n"))
825 //}
826
827 case <-ticker.C:
828 if lsc.state == LStreamClientStateConnectedIdle && time.Since(lastUpdTime) > 40*time.Second {
829 lsc.startCmd(lstreamCmd{
830 ping: &lstreamCmdPing{},
831 })
832 } else if !connectAfter.IsZero() {
833 connectAfter = time.Time{}
834 lsc.changeState(LStreamClientStateConnecting)
835 }
836
837 case req := <-lsc.disconnectReqCh:
838 lsc.params.Logger.Infof("Received disconnect message (teardown:%v)", req.teardown)
839
840 if req.teardown {
841 lsc.tearingDown = true
842 }
843
844 if req.changeName != "" {
845 lsc.params.LogStream.Name = req.changeName
846 }
847
848 // If we're already disconnected, consider ourselves torn-down already.
849 // Otherwise, initiate disconnection.
850 if lsc.state == LStreamClientStateDisconnected {
851 if req.teardown {
852 close(lsc.disconnectedBeforeTeardownCh)
853 }
854 } else {
855 lsc.changeState(LStreamClientStateDisconnecting)
856 }
857
858 case <-lsc.disconnectedBeforeTeardownCh:
859 lsc.params.Logger.Infof("Teardown completed")
860 lsc.sendUpdate(&LStreamClientUpdate{
861 TornDown: true,
862 })
863 return
864 }
865 }
866 }
867
868 func (lsc *LStreamClient) sendUpdate(upd *LStreamClientUpdate) {
869 upd.Name = lsc.params.LogStream.Name
870 lsc.params.UpdatesCh <- upd
871 }
872
873 // scanLinesPreserveCarriageReturn is the same as bufio.ScanLines, but it does
874 // not strip the \r characters: it's just a hack to support gzipping. In fact,
875 // since we sometimes read text lines and sometimes gzipped data, we'd better
876 // use some other custom scanner, but for now just this simple hack.
877 func scanLinesPreserveCarriageReturn(data []byte, atEOF bool) (advance int, token []byte, err error) {
878 if atEOF && len(data) == 0 {
879 return 0, nil, nil
880 }
881 if i := bytes.IndexByte(data, '\n'); i >= 0 {
882 // We have a full newline-terminated line.
883 return i + 1, data[0:i], nil
884 }
885 // If we're at EOF, we have a final, non-terminated line. Return it.
886 if atEOF {
887 return len(data), data, nil
888 }
889 // Request more data.
890 return 0, nil, nil
891 }
892
893 func getScannerFunc(name string, reader io.Reader, linesCh chan<- string) func() {
894 return func() {
895 defer func() {
896 close(linesCh)
897 }()
898
899 scanner := bufio.NewScanner(reader)
900
901 // See comments for scanLinesPreserveCarriageReturn for details why we need
902 // this custom split function.
903 scanner.Split(scanLinesPreserveCarriageReturn)
904
905 // TODO: also defer signal to reconnect
906
907 // inGzip is true when we're receiving gzipped data.
908 // gzipBuf accumulates that data, and once we receive the gzipEndMarker,
909 // we gunzip all this data and feed the lines to the channel.
910 //
911 // TODO: instead of accumulating it and then unpacking all at once, do it
912 // gradually as we receive data. Idk how much of an improvement it'd be in
913 // practice though, since we're not receiving some huge chunks of data,
914 // just a bit nicer.
915 inGzip := false
916 var gzipBuf bytes.Buffer
917
918 for scanner.Scan() {
919 lineBytes := scanner.Bytes()
920 line := string(lineBytes)
921
922 if !inGzip && line == gzipStartMarker {
923 // Gzipped data begins
924 inGzip = true
925 gzipBuf.Reset()
926
927 // We also need to continue loop iteration now so that we don't
928 // add this gzipStartMarker line to the gzipBuf below.
929 continue
930 } else if inGzip && strings.HasSuffix(line, gzipEndMarker) {
931 // We just reached the end of the gzipped data
932 inGzip = false
933
934 // Append this last piece
935 gzipBuf.Write(lineBytes[:len(lineBytes)-len(gzipEndMarker)])
936
937 var err error
938
939 // Gunzip the data and feed all the lines to linesCh
940 var r io.Reader
941 r, err = gzip.NewReader(&gzipBuf)
942 if err != nil {
943 linesCh <- fmt.Sprintf("error:failed to gunzip data: %s", err.Error())
944 return
945 }
946
947 scanner := bufio.NewScanner(r)
948 for scanner.Scan() {
949 linesCh <- scanner.Text()
950 }
951
952 continue
953 }
954
955 if !inGzip {
956 // We're not in gzipped data, so just feed this line directly.
957 linesCh <- line
958 } else {
959 // We're reading gzipped data now, so for now just add it to the
960 // gzipBuf (together with the \n which was stripped by the scanner).
961 gzipBuf.Write(lineBytes)
962 gzipBuf.WriteByte('\n')
963 }
964 }
965
966 if err := scanner.Err(); err != nil {
967 return
968 }
969 }
970 }
971
972 func (lsc *LStreamClient) EnqueueCmd(cmd lstreamCmd) {
973 lsc.enqueueCmdCh <- cmd
974 }
975
976 // Close initiates the shutdown. It doesn't wait for the shutdown to complete;
977 // client code needs to wait for the corresponding event (with TornDown: true).
978 //
979 // If changeName is non-empty, the LStreamClient's Name will be updated; it's
980 // useful to distinguish this LStreamClient from potentially-existing another one
981 // with the same (old) name.
982 func (lsc *LStreamClient) Close(changeName string) {
983 select {
984 case lsc.disconnectReqCh <- disconnectReq{
985 teardown: true,
986 changeName: changeName,
987 }:
988 default:
989 }
990 }
991
992 func (lsc *LStreamClient) Reconnect() {
993 select {
994 case lsc.disconnectReqCh <- disconnectReq{
995 teardown: false,
996 }:
997 default:
998 }
999 }
1000
1001 func (lsc *LStreamClient) addCmdToQueue(cmd lstreamCmd) {
1002 lsc.cmdQueue = append(lsc.cmdQueue, cmd)
1003 }
1004
1005 func (lsc *LStreamClient) startCmd(cmd lstreamCmd) {
1006 cmdCtx := &lstreamCmdCtx{
1007 cmd: cmd,
1008 idx: lsc.nextCmdIdx,
1009 }
1010
1011 lsc.curCmdCtx = cmdCtx
1012 lsc.nextCmdIdx++
1013
1014 switch {
1015 case cmdCtx.cmd.bootstrap != nil:
1016 lsc.params.Logger.Verbose3f("Starting command: bootstrap %+v", cmdCtx.cmd.bootstrap)
1017
1018 cmdCtx.bootstrapCtx = &lstreamCmdCtxBootstrap{}
1019
1020 stdinBuf := lsc.conn.conn.Stdin()
1021
1022 stdinBuf.Write([]byte("echo reset_output\n"))
1023 stdinBuf.Write([]byte("echo reset_output 1>&2\n"))
1024
1025 // Make sure that we're in the user's home directory. In most cases it's
1026 // redundant: when we connect via ssh, we're already in the home dir; but
1027 // for localhost, it's not; so setting it explicitly.
1028 stdinBuf.Write([]byte("cd\n"))
1029
1030 // Execute whatever arbitrary init commands.
1031 for _, cmd := range lsc.params.LogStream.Options.ShellInit {
1032 lsc.params.Logger.Verbose3f("Running shell init command: %s", cmd)
1033 stdinBuf.Write([]byte(cmd))
1034 stdinBuf.Write([]byte("\n"))
1035 }
1036
1037 stdinBuf.Write([]byte("("))
1038
1039 stdinBuf.Write([]byte(" cat <<- 'EOF' > " + lsc.getLStreamNerdlogAgentPath() + "\n" + nerdlogAgentSh + "EOF\n"))
1040 stdinBuf.Write([]byte(" if [ $? -ne 0 ]; then echo 'bootstrap failed'; exit 1; fi\n"))
1041
1042 var parts []string
1043
1044 // If requested, run the whole thing with "sudo -n".
1045 if lsc.params.LogStream.Options.SudoMode == SudoModeFull {
1046 parts = append(parts, "sudo", "-n")
1047 }
1048
1049 parts = append(parts, lsc.getTimeEnvVars()...)
1050
1051 parts = append(
1052 parts,
1053 "bash", shellQuote(lsc.getLStreamNerdlogAgentPath()),
1054 "logstream_info",
1055 "--logfile-last", shellQuote(lsc.params.LogStream.LogFileLast()),
1056 )
1057
1058 if logFilePrev, ok := lsc.params.LogStream.LogFilePrev(); ok {
1059 parts = append(parts, "--logfile-prev", shellQuote(logFilePrev))
1060 }
1061
1062 stdinBuf.Write([]byte(strings.Join(parts, " ") + "\n"))
1063 stdinBuf.Write([]byte(" if [ $? -ne 0 ]; then echo 'bootstrap failed'; exit 1; fi\n"))
1064
1065 stdinBuf.Write([]byte(" echo 'bootstrap ok'\n"))
1066 stdinBuf.Write([]byte(")\n"))
1067 stdinBuf.Write([]byte("echo exit_code:$?\n"))
1068
1069 case cmdCtx.cmd.ping != nil:
1070 lsc.params.Logger.Verbose3f("Starting command: ping %+v", cmdCtx.cmd.ping)
1071 cmdCtx.pingCtx = &lstreamCmdCtxPing{}
1072
1073 cmd := "whoami\n"
1074 stdinBuf := lsc.conn.conn.Stdin()
1075 stdinBuf.Write([]byte(cmd))
1076 stdinBuf.Write([]byte("echo exit_code:$?\n"))
1077
1078 case cmdCtx.cmd.queryLogs != nil:
1079 lsc.params.Logger.Verbose3f("Starting command: queryLogs %+v", cmdCtx.cmd.queryLogs)
1080 cmdCtx.queryLogsCtx = &lstreamCmdCtxQueryLogs{
1081 Resp: &LogResp{
1082 MinuteStats: map[int64]MinuteStatsItem{},
1083 },
1084 }
1085
1086 var parts []string
1087
1088 if useGzip {
1089 parts = append(parts, "echo", gzipStartMarker, ";")
1090 }
1091
1092 // If requested, run the whole thing with "sudo -n".
1093 if lsc.params.LogStream.Options.SudoMode == SudoModeFull {
1094 parts = append(parts, "sudo", "-n")
1095 }
1096
1097 parts = append(parts, lsc.getTimeEnvVars()...)
1098
1099 parts = append(
1100 parts,
1101 "bash", shellQuote(lsc.getLStreamNerdlogAgentPath()),
1102 "query",
1103 "--index-file", shellQuote(lsc.getLStreamIndexFilePath()),
1104 "--max-num-lines", shellQuote(strconv.Itoa(cmdCtx.cmd.queryLogs.maxNumLines)),
1105 "--logfile-last", shellQuote(lsc.params.LogStream.LogFileLast()),
1106 )
1107
1108 if logFilePrev, ok := lsc.params.LogStream.LogFilePrev(); ok {
1109 parts = append(parts, "--logfile-prev", shellQuote(logFilePrev))
1110 }
1111
1112 if !cmdCtx.cmd.queryLogs.from.IsZero() {
1113 parts = append(parts, "--from", shellQuote(cmdCtx.cmd.queryLogs.from.In(lsc.location).Format(queryLogsArgsTimeLayout)))
1114 }
1115
1116 if !cmdCtx.cmd.queryLogs.to.IsZero() {
1117 parts = append(parts, "--to", shellQuote(cmdCtx.cmd.queryLogs.to.In(lsc.location).Format(queryLogsArgsTimeLayout)))
1118 }
1119
1120 if cmdCtx.cmd.queryLogs.linesUntil > 0 {
1121 parts = append(parts, "--lines-until", shellQuote(strconv.Itoa(cmdCtx.cmd.queryLogs.linesUntil)))
1122 }
1123
1124 if tu := cmdCtx.cmd.queryLogs.timestampUntil; tu != nil {
1125 nextWholeSecondTime := roundUpToNextSecond(tu.time)
1126
1127 parts = append(parts,
1128 "--timestamp-until-seconds",
1129 shellQuote(
1130 nextWholeSecondTime.In(lsc.location).Format(queryLogsTimestampUntilSecondsTimeLayout),
1131 ),
1132
1133 "--timestamp-until-precise",
1134 shellQuote(
1135 tu.time.In(lsc.location).Format(queryLogsTimestampUntilPreciseTimeLayout),
1136 ),
1137
1138 "--skip-n-latest", shellQuote(strconv.Itoa(tu.numMsgs)),
1139 )
1140 }
1141
1142 if cmdCtx.cmd.queryLogs.refreshIndex {
1143 parts = append(parts, "--refresh-index")
1144 }
1145
1146 parts = append(parts, agentQueryTimeFormatArgs(&lsc.timeFormat.AWKExpr)...)
1147
1148 if cmdCtx.cmd.queryLogs.query != "" {
1149 parts = append(parts, shellQuote(cmdCtx.cmd.queryLogs.query))
1150 }
1151
1152 if useGzip {
1153 parts = append(parts, "|", "gzip", ";", "echo", gzipEndMarker)
1154 }
1155
1156 cmd := strings.Join(parts, " ") + "\n"
1157 lsc.params.Logger.Verbose2f("Executing query command(%s): %s", lsc.params.LogStream.Name, cmd)
1158
1159 lsc.conn.conn.Stdin().Write([]byte(cmd))
1160
1161 // NOTE: we don't print the "exit_code:" here, because we can't reliably
1162 // do that across all possible shells, due to gzipping: the agent script
1163 // is not the last one in the pipeline.
1164 //
1165 // Instead, the agent script itself has a trap which prints this line for
1166 // us.
1167
1168 default:
1169 panic(fmt.Sprintf("invalid command %+v", cmdCtx.cmd))
1170 }
1171
1172 stdinBuf := lsc.conn.conn.Stdin()
1173 stdinBuf.Write([]byte(fmt.Sprintf("echo 'command_done:%d'\n", cmdCtx.idx)))
1174 stdinBuf.Write([]byte(fmt.Sprintf("echo 'command_done:%d' 1>&2\n", cmdCtx.idx)))
1175
1176 lsc.changeState(LStreamClientStateConnectedBusy)
1177 }
1178
1179 // getTimeEnvVars is a helper to get time-related env vars to be passed to the
1180 // agent script: CUR_YEAR and CUR_MONTH, which will affect the year-inferring
1181 // logic.
1182 //
1183 // Outside of tests it's not actually necessary to pass these env vars, since
1184 // the agent script will just use the actual time then; but for simplicity, and
1185 // to make the tested code closer to the actual code, we always pass them when
1186 // calling agent script.
1187 func (lsc *LStreamClient) getTimeEnvVars() []string {
1188 now := lsc.params.Clock.Now()
1189
1190 return []string{
1191 fmt.Sprintf("CUR_YEAR=%d", now.Year()),
1192 fmt.Sprintf("CUR_MONTH=%.2d", now.Month()),
1193 }
1194 }
1195
1196 func roundUpToNextSecond(t time.Time) time.Time {
1197 if t.Nanosecond() == 0 {
1198 return t
1199 }
1200 return t.Truncate(time.Second).Add(time.Second)
1201 }
1202
1203 // getLStreamNerdlogAgentPath returns the logstream-side path to the nerdlog_agent.sh
1204 // for the particular log stream.
1205 func (lsc *LStreamClient) getLStreamNerdlogAgentPath() string {
1206 return fmt.Sprintf(
1207 "/tmp/nerdlog_agent_%s_%s.sh",
1208 lsc.params.ClientID,
1209 filepathToId(lsc.params.LogStream.LogFileLast()),
1210 )
1211 }
1212
1213 // getLStreamIndexFilePath returns the logstream-side path to the index file for
1214 // the particular log stream.
1215 func (lsc *LStreamClient) getLStreamIndexFilePath() string {
1216 return fmt.Sprintf(
1217 "/tmp/nerdlog_agent_index_%s_%s",
1218 lsc.params.ClientID,
1219 filepathToId(lsc.params.LogStream.LogFileLast()),
1220 )
1221 }
1222
1223 // filepathToId takes a path and returns a string suitable to be used as
1224 // part of a filename (with all slashes removed).
1225 func filepathToId(p string) string {
1226 replacer := strings.NewReplacer("/", "_", "\\", "_")
1227 return replacer.Replace(p)
1228 }
1229
1230 func (lsc *LStreamClient) checkIfDisconnected() {
1231 if lsc.conn.stderrLinesCh == nil && lsc.conn.stdoutLinesCh == nil {
1232 // We're fully disconnected
1233 lsc.params.Logger.Verbose3f("Fully disconnected")
1234 lsc.changeState(LStreamClientStateDisconnected)
1235
1236 if lsc.tearingDown {
1237 close(lsc.disconnectedBeforeTeardownCh)
1238 } else {
1239 lsc.changeState(LStreamClientStateConnecting)
1240 }
1241 }
1242 }
1243
1244 func (lsc *LStreamClient) checkCommandDone(
1245 line string, cmdCtx *lstreamCmdCtx, isStderr bool,
1246 ) bool {
1247 if !strings.HasPrefix(line, "command_done:") {
1248 return false
1249 }
1250
1251 _, err := parseCommandDoneLine(line, cmdCtx.idx)
1252 if err != nil {
1253 lsc.params.Logger.Errorf("Got malformed command_done line: %s (%s)", line, err.Error())
1254 return true
1255 }
1256
1257 if isStderr {
1258 cmdCtx.stderrDone = true
1259 } else {
1260 cmdCtx.stdoutDone = true
1261 }
1262
1263 lsc.handleCommandResultsIfDone(cmdCtx)
1264 return true
1265 }
1266
1267 func (lsc *LStreamClient) checkError(
1268 line string, cmdCtx *lstreamCmdCtx,
1269 ) bool {
1270 if !strings.HasPrefix(line, "error:") {
1271 return false
1272 }
1273
1274 // The agent script printed an error; it means that the whole execution will
1275 // be considered failed once it's done. For now we just add the error to the
1276 // resulting response.
1277 errMsg := strings.TrimPrefix(line, "error:")
1278 cmdCtx.errs = append(cmdCtx.errs, errors.New(errMsg))
1279
1280 return true
1281 }
1282
1283 func (lsc *LStreamClient) checkExitCode(
1284 line string, cmdCtx *lstreamCmdCtx,
1285 ) bool {
1286 if !strings.HasPrefix(line, "exit_code:") {
1287 return false
1288 }
1289
1290 cmdCtx.exitCode = strings.TrimPrefix(line, "exit_code:")
1291 lsc.params.Logger.Verbose1f("Received exit code: %q", cmdCtx.exitCode)
1292 return true
1293 }
1294
1295 func (lsc *LStreamClient) checkResetOutput(
1296 line string, cmdCtx *lstreamCmdCtx, isStderr bool,
1297 ) bool {
1298 if line != "reset_output" {
1299 return false
1300 }
1301
1302 if isStderr {
1303 cmdCtx.unhandledStderr = nil
1304 } else {
1305 cmdCtx.unhandledStdout = nil
1306 }
1307
1308 return true
1309 }
1310
1311 // handleCommandResultsIfDone should be called whenever the previously ran
1312 // command is done.
1313 func (lsc *LStreamClient) handleCommandResultsIfDone(cmdCtx *lstreamCmdCtx) {
1314 if !cmdCtx.stdoutDone || !cmdCtx.stderrDone {
1315 return
1316 }
1317
1318 // Command is done.
1319
1320 switch {
1321 case cmdCtx.cmd.bootstrap != nil:
1322 if cmdCtx.bootstrapCtx.receivedSuccess && len(cmdCtx.errs) == 0 {
1323 // Bootstrap script has ran successfully.
1324
1325 // If journalctl is used and we don't have access to all the system
1326 // logs, send a warning update.
1327 if cmdCtx.bootstrapCtx.warnJournalctlNoAdminAccess {
1328 lsc.sendUpdate(&LStreamClientUpdate{
1329 BootstrapDetails: &BootstrapDetails{
1330 WarnJournalctlNoAdminAccess: true,
1331 },
1332 })
1333 }
1334
1335 // Let's now try to autodetect the envelope log format.
1336 timeFormat, err := GetTimeFormatDescrFromLogLines(lsc.exampleLogLines)
1337 if err != nil {
1338 cmdCtx.errs = append(cmdCtx.errs, err)
1339 } else {
1340 // All good
1341 lsc.params.Logger.Infof(
1342 "Detected time format based on %d log lines: %q",
1343 len(lsc.exampleLogLines),
1344 timeFormat.TimestampLayout,
1345 )
1346 lsc.timeFormat = timeFormat
1347 lsc.changeState(LStreamClientStateConnectedIdle)
1348 return
1349 }
1350 }
1351
1352 // There was an issue with bootstrapping.
1353
1354 err := summaryCmdError(cmdCtx)
1355 // If error is nil (which means, there were no "error:" printed, and
1356 // bootstrap exited with 0 code, but since there was also no "bootstrap
1357 // ok" marker, this is very weird), then still generate an error saying
1358 // that there was no "bootstrap ok" message.
1359 if err == nil {
1360 err = errorFromStdoutStderr(
1361 "there was no 'bootstrap ok' message",
1362 cmdCtx.unhandledStdout,
1363 cmdCtx.unhandledStderr,
1364 )
1365 }
1366
1367 lsc.sendUpdate(&LStreamClientUpdate{
1368 BootstrapDetails: &BootstrapDetails{
1369 Err: err.Error(),
1370 },
1371 })
1372
1373 lsc.changeState(LStreamClientStateDisconnected)
1374
1375 case cmdCtx.cmd.ping != nil:
1376 lsc.sendCmdResp(nil, nil)
1377 lsc.changeState(LStreamClientStateConnectedIdle)
1378
1379 case cmdCtx.cmd.queryLogs != nil:
1380 resp := cmdCtx.queryLogsCtx.Resp
1381 resp.DebugInfo.AgentStdout = cmdCtx.unhandledStdout
1382 resp.DebugInfo.AgentStderr = cmdCtx.unhandledStderr
1383 lsc.sendCmdResp(resp, summaryCmdError(cmdCtx))
1384 lsc.changeState(LStreamClientStateConnectedIdle)
1385
1386 default:
1387 panic(fmt.Sprintf("unhandled cmd %+v", cmdCtx.cmd))
1388 }
1389 }
1390
1391 // InferYear infers year from the month of the given timestamp, and the current
1392 // time. Resulting timestamp (with the year populated) is then returned.
1393 //
1394 // Most of the time it just uses the current year, but on the year boundary
1395 // it can return previous or next year.
1396 func InferYear(now, t time.Time) time.Time {
1397 // If month of the syslog being parsed is the same as the current month, just
1398 // use the current year.
1399 if now.Month() == t.Month() {
1400 return timeWithYear(t, now.Year())
1401 }
1402
1403 // Month of the syslog is different from the current month, so we need to
1404 // have logic for the boundary of the year.
1405
1406 if t.Month() == time.December && now.Month() == time.January {
1407 // We're in January now and we're parsing some logs from December.
1408 return timeWithYear(t, now.Year()-1)
1409 } else if t.Month() == time.January && now.Month() == time.December {
1410 // We're in December now and we're parsing some logs from January.
1411 // It's weird to get timestamp from the future, but better to have a case
1412 // for that.
1413 return timeWithYear(t, now.Year()+1)
1414 }
1415
1416 // For all other cases, still use the current year.
1417 return timeWithYear(t, now.Year())
1418 }
1419
1420 func timeWithYear(t time.Time, year int) time.Time {
1421 return time.Date(
1422 year,
1423 t.Month(),
1424 t.Day(),
1425
1426 t.Hour(),
1427 t.Minute(),
1428 t.Second(),
1429 t.Nanosecond(),
1430 t.Location(),
1431 )
1432 }
1433
1434 type parseLineResult struct {
1435 // time might or might not be populated: most of our messages contain an
1436 // extra (more precise) timestamp, so in this case it'll be populated here,
1437 // and client code should use it.
1438 time time.Time
1439 decreasedTimestamp bool
1440
1441 // msg is the actual log message.
1442 msg string
1443
1444 // ctxMap contains context for the message.
1445 ctxMap map[string]string
1446 }
1447
1448 func (lsc *LStreamClient) parseLine(logMsg *LogMsg) error {
1449 if err := lsc.parseLogMsgTimestamp(logMsg); err != nil {
1450 return errors.Annotatef(err, "parsing time")
1451 }
1452
1453 // TODO: offload envelope parsing to Lua (and make it usable from
1454 // the user Lua scripts as well).
1455 if err := lsc.parseLogMsgEnvelopeDefault(logMsg); err != nil {
1456 return errors.Annotatef(err, "parsing envelope")
1457 }
1458
1459 // TODO: offload the custom parsing to Lua
1460 if err := lsc.parseLogMsgLevelDefault(logMsg); err != nil {
1461 return errors.Annotatef(err, "custom parsing")
1462 }
1463
1464 // TODO: invoke user Lua script, if present.
1465
1466 return nil
1467 }
1468
1469 func (lsc *LStreamClient) parseLogMsgTimestamp(logMsg *LogMsg) error {
1470 msg := logMsg.Msg
1471
1472 timeLayout := lsc.timeFormat.TimestampLayout
1473 timestampLen := len(timeLayout)
1474
1475 // If the layout ends with the offset like "Z07" or "Z07:00", but the
1476 // actual timestamp string is in UTC and it ends with just "Z", we then
1477 // need to remove that extra
1478 zIdx := strings.Index(timeLayout, "Z07")
1479 if zIdx >= 0 && len(msg) >= zIdx && msg[zIdx] == 'Z' {
1480 // We have a Z in the timestamp, so there should be no offset after it.
1481 timestampLen = zIdx + 1
1482 }
1483
1484 if len(msg) < timestampLen {
1485 return errors.Errorf("line %q is too short to have a timestamp", msg)
1486 }
1487
1488 t, err := time.ParseInLocation(timeLayout, msg[:timestampLen], lsc.location)
1489 if err != nil {
1490 return errors.Annotatef(err, "parsing time in log msg")
1491 }
1492
1493 // If the location we get from the actual logs doesn't match what we have,
1494 // trust the logs more.
1495 //
1496 // NOTE: this new timezone is still not fully effective until the next query,
1497 // because even the request itself was likely done wrong. Also, if mstats are
1498 // already parsed, their timestamp is also wrong (that one can technically be
1499 // solved by printing mstats after logs). Maybe we should somehow show a
1500 // warning that the timezone was overridden.
1501
1502 // TODO: uncomment when it's well tested; right now it doesn't work well
1503 // because e.g. if the timezone is "America/New_York", but then in the logs
1504 // we have "-05:00", which is a different timezone (not New York, but a fixed
1505 // one), and so we'll always be overwriting this timezone here. Most of the
1506 // time it's pretty much harmless, but on the edge of DST it will do the
1507 // wrong thing.
1508 //if t.Location() != lsc.location {
1509 //lsc.params.Logger.Infof(
1510 //"Log line timestamp has a different location: %s instead of %s; trusting logs more",
1511 //t.Location(), lsc.location,
1512 //)
1513 //lsc.location = t.Location()
1514 //}
1515
1516 if t.Year() == 0 {
1517 t = InferYear(lsc.params.Clock.Now(), t)
1518 }
1519 t = t.UTC()
1520
1521 // Parsed the time successfully; update it in the LogMsg, and also remove the
1522 // leading timestamp from the message.
1523 logMsg.Time = t
1524 logMsg.Msg = strings.TrimSpace(msg[len(timeLayout):])
1525
1526 return nil
1527 }
1528
1529 // parseLogMsgEnvelopeDefault takes the LogMsg where the time was already
1530 // stripped from the Msg, so for syslog, it looks like this:
1531 //
1532 // "myhost myprogram[1234]: Something happened"
1533 //
1534 // If the Msg indeed looks like a syslog message, it extracts the hostname,
1535 // program and pid from it, populates them in the Context, and updates the
1536 // message to contain the rest of the payload.
1537 //
1538 // If the Msg doesn't have this structure, parseLogMsgEnvelopeDefault is a
1539 // no-op.
1540 func (lsc *LStreamClient) parseLogMsgEnvelopeDefault(logMsg *LogMsg) error {
1541 matches := syslogRegex.FindStringSubmatch(logMsg.Msg)
1542 if len(matches) == 0 {
1543 // Message doesn't match syslog pattern, no-op
1544 // TODO: we might want to support more formats
1545 return nil
1546 }
1547
1548 // Extract fields from regex match
1549 hostname := matches[1]
1550 program := matches[2]
1551 pid := matches[3]
1552 rest := matches[4]
1553
1554 logMsg.Context["hostname"] = hostname
1555 logMsg.Context["program"] = program
1556 logMsg.Context["pid"] = pid
1557
1558 logMsg.Msg = rest
1559 return nil
1560 }
1561
1562 // parseLogMsgLevelDefault tries to guess what the level of the message could
1563 // be, based on commonly used patterns in the message like "error", "info",
1564 // "[E]", "[I]" etc.
1565 func (lsc *LStreamClient) parseLogMsgLevelDefault(logMsg *LogMsg) error {
1566 msg := strings.ToLower(logMsg.Msg)
1567
1568 switch {
1569 case strings.Contains(msg, "[f]"):
1570 logMsg.Level = LogLevelError
1571 case strings.Contains(msg, "[e]"):
1572 logMsg.Level = LogLevelError
1573 case strings.Contains(msg, "[w]"):
1574 logMsg.Level = LogLevelWarn
1575 case strings.Contains(msg, "[i]"):
1576 logMsg.Level = LogLevelInfo
1577 case strings.Contains(msg, "[d]"):
1578 logMsg.Level = LogLevelDebug
1579 default:
1580 logMsg.Level = LogLevelUnknown
1581 }
1582
1583 if logMsg.Level != LogLevelUnknown {
1584 return nil
1585 }
1586
1587 // Regex patterns for whole words or bracketed levels
1588 patterns := []struct {
1589 regex *regexp.Regexp
1590 level LogLevel
1591 }{
1592 {regexp.MustCompile(`\berror\b|\berro\b|\berr\b|\bcrit\b|\bcritical\b|\bfatal\b`), LogLevelError},
1593 {regexp.MustCompile(`\bwarn(ing)?\b`), LogLevelWarn},
1594 {regexp.MustCompile(`\binfo\b`), LogLevelInfo},
1595 {regexp.MustCompile(`\bdebu(g)?\b`), LogLevelDebug},
1596 }
1597
1598 for _, p := range patterns {
1599 if p.regex.MatchString(msg) {
1600 logMsg.Level = p.level
1601 return nil
1602 }
1603 }
1604
1605 logMsg.Level = LogLevelUnknown
1606 return nil
1607 }
1608
1609 func combineErrors(errs []error) error {
1610 var err error
1611 if len(errs) == 1 {
1612 err = errs[0]
1613 } else if len(errs) > 0 {
1614 ss := []string{}
1615 for _, e := range errs {
1616 ss = append(ss, e.Error())
1617 }
1618
1619 err = errors.Errorf("%d errors: %s", len(errs), strings.Join(ss, "; "))
1620 }
1621
1622 return err
1623 }
1624
1625 func errorFromStdoutStderr(prefix string, stdout []string, stderr []string) error {
1626 var sb strings.Builder
1627
1628 sb.WriteString(prefix)
1629 sb.WriteString("\n")
1630
1631 if len(stdout) > 0 {
1632 sb.WriteString("stdout:\n")
1633 for _, line := range stdout {
1634 sb.WriteString(line)
1635 sb.WriteString("\n")
1636 }
1637 }
1638
1639 if len(stderr) > 0 {
1640 if sb.Len() > 0 {
1641 sb.WriteString("------\n")
1642 }
1643 sb.WriteString("stderr:\n")
1644 for _, line := range stderr {
1645 sb.WriteString(line)
1646 sb.WriteString("\n")
1647 }
1648 }
1649
1650 return errors.New(sb.String())
1651 }
1652
1653 func summaryCmdError(cmdCtx *lstreamCmdCtx) error {
1654 if len(cmdCtx.errs) > 0 {
1655 return combineErrors(cmdCtx.errs)
1656 } else if cmdCtx.exitCode != "0" {
1657 return errorFromStdoutStderr(
1658 fmt.Sprintf("agent exited with non-zero code '%s'", cmdCtx.exitCode),
1659 cmdCtx.unhandledStdout,
1660 cmdCtx.unhandledStderr,
1661 )
1662 } else {
1663 return nil
1664 }
1665 }
1666
1667 type commandDoneDetails struct {
1668 idx int
1669 }
1670
1671 func parseCommandDoneLine(line string, expectedIdx int) (*commandDoneDetails, error) {
1672 parts := strings.Split(line, ":")
1673 if len(parts) != 2 {
1674 return nil, errors.Errorf("expected two parts, got %d", len(parts))
1675 }
1676
1677 rxIdx, err := strconv.Atoi(parts[1])
1678 if err != nil {
1679 return nil, errors.Annotatef(err, "parsing idx as integer")
1680 }
1681
1682 if rxIdx != expectedIdx {
1683 return nil, errors.Errorf("received unexpected index with command_done: waiting for %d, got %d", expectedIdx, rxIdx)
1684 }
1685
1686 return &commandDoneDetails{
1687 idx: rxIdx,
1688 }, nil
1689 }
1690
1691 // requiresShellQuoting returns whether the given string requires to be quoted
1692 // in a shell.
1693 func requiresShellQuoting(s string) bool {
1694 // Empty string requires quoting
1695 if len(s) == 0 {
1696 return true
1697 }
1698
1699 for _, r := range s {
1700 if !((r >= 'a' && r <= 'z') ||
1701 (r >= 'A' && r <= 'Z') ||
1702 (r >= '0' && r <= '9') ||
1703 r == '_' || r == '.' || r == '/' || r == '-') {
1704 return true
1705 }
1706 }
1707
1708 return false
1709 }
1710
1711 func shellQuote(s string) string {
1712 if !requiresShellQuoting(s) {
1713 return s
1714 }
1715
1716 return fmt.Sprintf("'%s'", strings.Replace(s, "'", "'\"'\"'", -1))
1717 }
1718
1719 func agentQueryTimeFormatArgs(awkExpr *TimeFormatAWKExpr) []string {
1720 return []string{
1721 "--awktime-month", shellQuote(awkExpr.Month),
1722 "--awktime-year", shellQuote(awkExpr.Year),
1723 "--awktime-day", shellQuote(awkExpr.Day),
1724 "--awktime-hhmm", shellQuote(awkExpr.HHMM),
1725 "--awktime-minute-key", shellQuote(awkExpr.MinuteKey),
1726 }
1727 }