Debian Codegraph @

core/lstreams_manager.go

raw
1 package core
2
3 import (
4 "fmt"
5 "math/rand"
6 "os/user"
7 "sort"
8 "strings"
9 "time"
10
11 "github.com/dimonomid/clock"
12 "github.com/dimonomid/ssh_config"
13 "github.com/juju/errors"
14
15 "github.com/dimonomid/nerdlog/log"
16 )
17
18 var ErrBusyWithAnotherQuery = errors.Errorf("busy with another query")
19 var ErrNotYetConnected = errors.Errorf("not connected to all lstreams yet")
20
21 type LStreamsManager struct {
22 params LStreamsManagerParams
23
24 lstreamsStr string
25 parsedLogStreams map[string]LogStream
26
27 lscs map[string]*LStreamClient
28 lscStates map[string]LStreamClientState
29 // lscConnDetails contains items for all selected lstreams, even after the
30 // connection is done (which is indicated by ConnDetails.Connected being
31 // true).
32 lscConnDetails map[string]ConnDetails
33 // lscBusyStages only contains items for lstreams which are in the
34 // LStreamClientStateConnectedBusy state.
35 lscBusyStages map[string]BusyStage
36
37 // lscPendingTeardown contains info about LStreamClient-s that are being torn
38 // down. NOTE that when a LStreamClient starts tearing down, its key changes
39 // (gets prepended with OLD_XXXX_), so re remove an item from the `has` map
40 // with one key, and add an item here with a different key.
41 lscPendingTeardown map[string]int
42
43 lstreamsByState map[LStreamClientState]map[string]struct{}
44 numNotConnected int
45
46 lstreamUpdatesCh chan *LStreamClientUpdate
47 reqCh chan lstreamsManagerReq
48 respCh chan lstreamCmdRes
49
50 // teardownReqCh is written to once when Close is called.
51 teardownReqCh chan struct{}
52 // tearingDown is true if the teardown is in progress (after Close is called).
53 tearingDown bool
54 // torndownCh is closed once the teardown is fully completed.
55 // Wait waits for it.
56 torndownCh chan struct{}
57
58 curQueryLogsCtx *manQueryLogsCtx
59
60 curLogs manLogsCtx
61
62 useExternalSSH bool
63 }
64
65 type LStreamsManagerParams struct {
66 // ConfigLogStreams contains nerdlog-specific config, typically coming from
67 // ~/.config/nerdlog/logstreams.yaml.
68 ConfigLogStreams ConfigLogStreams
69
70 // SSHConfig contains the general ssh config, typically coming from
71 // ~/.ssh/config.
72 SSHConfig *ssh_config.Config
73
74 // SSHKeys specifies paths to ssh keys to try, in the given order, until
75 // an existing key is found.
76 SSHKeys []string
77
78 Logger *log.Logger
79
80 InitialLStreams string
81
82 InitialUseExternalSSH bool
83
84 // ClientID is just an arbitrary string (should be filename-friendly though)
85 // which will be appended to the nerdlog_agent.sh and its index filenames.
86 //
87 // Needed to make sure that different clients won't get conflicts over those
88 // files when using the tool concurrently on the same nodes.
89 ClientID string
90
91 UpdatesCh chan<- LStreamsManagerUpdate
92
93 Clock clock.Clock
94 }
95
96 func NewLStreamsManager(params LStreamsManagerParams) *LStreamsManager {
97 if params.Clock == nil {
98 // For details on why not default to the real clock:
99 // https://dmitryfrank.com/articles/mocking_time_in_go#caveat_with_defaulting_to_real_clock
100 panic("Clock is nil")
101 }
102
103 params.Logger = params.Logger.WithNamespaceAppended("LSMan")
104
105 lsman := &LStreamsManager{
106 params: params,
107
108 lscs: map[string]*LStreamClient{},
109 lscStates: map[string]LStreamClientState{},
110 lscConnDetails: map[string]ConnDetails{},
111 lscBusyStages: map[string]BusyStage{},
112 lscPendingTeardown: map[string]int{},
113
114 lstreamUpdatesCh: make(chan *LStreamClientUpdate, 1024),
115 reqCh: make(chan lstreamsManagerReq, 8),
116 respCh: make(chan lstreamCmdRes),
117
118 teardownReqCh: make(chan struct{}, 1),
119 torndownCh: make(chan struct{}, 1),
120
121 useExternalSSH: params.InitialUseExternalSSH,
122 }
123
124 if err := lsman.setLStreams(params.InitialLStreams); err != nil {
125 panic("setLStreams didn't like the initial logStreamsSpec: " + err.Error())
126 }
127
128 lsman.updateHAs()
129 lsman.updateLStreamsByState()
130 lsman.sendStateUpdate()
131
132 go lsman.run()
133
134 return lsman
135 }
136
137 func (lsman *LStreamsManager) SetUseExternalSSH(useExternalSSH bool) {
138 resCh := make(chan struct{}, 1)
139
140 lsman.reqCh <- lstreamsManagerReq{
141 setUseExternalSSH: &lstreamsManagerReqSetUseExternalSSH{
142 useExternalSSH: useExternalSSH,
143 resCh: resCh,
144 },
145 }
146
147 <-resCh
148 }
149
150 func (lsman *LStreamsManager) setUseExternalSSH(useExternalSSH bool) {
151 // If unchanged, then do nothing.
152 if lsman.useExternalSSH == useExternalSSH {
153 return
154 }
155
156 // Transport mode has changed: remember it, and reconnect using it.
157
158 lsman.useExternalSSH = useExternalSSH
159
160 lstreamsStr := lsman.lstreamsStr
161 lsman.setLStreams("")
162 lsman.updateHAs()
163 lsman.updateLStreamsByState()
164
165 lsman.setLStreams(lstreamsStr)
166 lsman.updateHAs()
167 lsman.updateLStreamsByState()
168
169 lsman.sendStateUpdate()
170 }
171
172 func (lsman *LStreamsManager) setLStreams(lstreamsStr string) error {
173 u, err := user.Current()
174 if err != nil {
175 return errors.Annotatef(err, "getting current OS user")
176 }
177
178 resolver := NewLStreamsResolver(LStreamsResolverParams{
179 CurOSUser: u.Username,
180
181 UseExternalSSH: lsman.useExternalSSH,
182
183 ConfigLogStreams: lsman.params.ConfigLogStreams,
184 SSHConfig: lsman.params.SSHConfig,
185 })
186
187 parsedLogStreams, err := resolver.Resolve(lstreamsStr)
188 if err != nil {
189 return errors.Trace(err)
190 }
191
192 // All went well, remember the logstreams spec
193 lsman.lstreamsStr = lstreamsStr
194 lsman.parsedLogStreams = parsedLogStreams
195
196 return nil
197 }
198
199 func (lsman *LStreamsManager) updateHAs() {
200 // Close unused logstream clients
201 for key, oldHA := range lsman.lscs {
202 if _, ok := lsman.parsedLogStreams[key]; ok {
203 // The logstream is still used
204 continue
205 }
206
207 // We used to use this logstream, but now it's filtered out, so close it
208 lsman.params.Logger.Verbose1f("Closing LSClient %s", key)
209 delete(lsman.lscs, key)
210 delete(lsman.lscStates, key)
211 delete(lsman.lscConnDetails, key)
212 delete(lsman.lscBusyStages, key)
213
214 keyNew := fmt.Sprintf("OLD_%s_%s", lsman.randomString(4), key)
215 lsman.lscPendingTeardown[keyNew] += 1
216 oldHA.Close(keyNew)
217 }
218
219 // Create new logstream clients
220 for key, ls := range lsman.parsedLogStreams {
221 if _, ok := lsman.lscs[key]; ok {
222 // This logstream client already exists
223 continue
224 }
225
226 // We need to create a new logstream client
227 lsc := NewLStreamClient(LStreamClientParams{
228 LogStream: ls,
229 SSHKeys: lsman.params.SSHKeys,
230 Logger: lsman.params.Logger,
231 ClientID: lsman.params.ClientID, //fmt.Sprintf("%s-%d", lsman.params.ClientID, rand.Int()),
232 UpdatesCh: lsman.lstreamUpdatesCh,
233 Clock: lsman.params.Clock,
234 })
235 lsman.lscs[key] = lsc
236 lsman.lscStates[key] = LStreamClientStateDisconnected
237 }
238 }
239
240 func (lsman *LStreamsManager) run() {
241 lsclientsByState := map[LStreamClientState]map[string]struct{}{}
242 for name := range lsman.lscs {
243 lsclientsByState[LStreamClientStateDisconnected] = map[string]struct{}{
244 name: {},
245 }
246 }
247
248 for {
249 select {
250 case upd := <-lsman.lstreamUpdatesCh:
251 if upd.State != nil {
252 if _, ok := lsman.lscStates[upd.Name]; ok {
253 lsman.params.Logger.Verbose1f(
254 "Got state update from %s: %s -> %s",
255 upd.Name, upd.State.OldState, upd.State.NewState,
256 )
257
258 lsman.lscStates[upd.Name] = upd.State.NewState
259
260 // Maintain lsman.lscConnDetails
261 if upd.State.NewState == LStreamClientStateConnectedIdle ||
262 upd.State.NewState == LStreamClientStateConnectedBusy {
263 cd := lsman.lscConnDetails[upd.Name]
264 cd.Connected = true
265 lsman.lscConnDetails[upd.Name] = cd
266 }
267
268 // Maintain lsman.lscBusyStages
269 if upd.State.NewState != LStreamClientStateConnectedBusy {
270 delete(lsman.lscBusyStages, upd.Name)
271 }
272 } else if _, ok := lsman.lscPendingTeardown[upd.Name]; ok {
273 lsman.params.Logger.Verbose1f(
274 "Got state update from tearing-down %s: %s -> %s",
275 upd.Name, upd.State.OldState, upd.State.NewState,
276 )
277 } else {
278 lsman.params.Logger.Warnf(
279 "Got state update from unknown %s: %s -> %s",
280 upd.Name, upd.State.OldState, upd.State.NewState,
281 )
282 }
283
284 lsman.updateLStreamsByState()
285 lsman.sendStateUpdate()
286 } else if upd.ConnDetails != nil {
287 lsman.params.Logger.Verbose1f("ConnDetails for %s: %+v", upd.Name, *upd.ConnDetails)
288 lsman.lscConnDetails[upd.Name] = *upd.ConnDetails
289 lsman.sendStateUpdate()
290 } else if upd.BootstrapDetails != nil {
291 lsman.params.Logger.Verbose1f("BootstrapDetails for %s: %+v", upd.Name, *upd.BootstrapDetails)
292
293 upd := LStreamsManagerUpdate{
294 BootstrapIssue: &BootstrapIssue{
295 LStreamName: upd.Name,
296 Err: upd.BootstrapDetails.Err,
297
298 WarnJournalctlNoAdminAccess: upd.BootstrapDetails.WarnJournalctlNoAdminAccess,
299 },
300 }
301 lsman.params.UpdatesCh <- upd
302 } else if upd.BusyStage != nil {
303 lsman.lscBusyStages[upd.Name] = *upd.BusyStage
304 lsman.sendStateUpdate()
305 } else if upd.DataRequest != nil {
306 lsman.params.UpdatesCh <- LStreamsManagerUpdate{
307 DataRequest: upd.DataRequest,
308 }
309 } else if upd.TornDown {
310 // One of our LStreamClient-s has just shut down, account for it properly.
311 lsman.lscPendingTeardown[upd.Name] -= 1
312
313 // Sanity check.
314 if lsman.lscPendingTeardown[upd.Name] < 0 {
315 panic(fmt.Sprintf("got TornDown update and lscPendingTeardown[%s] becomes %d", upd.Name, lsman.lscPendingTeardown[upd.Name]))
316 }
317
318 // Check how many LStreamClient-s are still in the process of teardown,
319 // and if needed, finish the teardown of the whole LStreamsManager.
320 numPending := lsman.getNumLStreamClientsTearingDown()
321 if numPending != 0 {
322 pendingSB := strings.Builder{}
323 i := 0
324 for k, v := range lsman.lscPendingTeardown {
325 if v == 0 {
326 continue
327 }
328
329 i++
330 if i > 3 {
331 pendingSB.WriteString("...")
332 break
333 }
334
335 if pendingSB.Len() > 0 {
336 pendingSB.WriteString(", ")
337 }
338
339 pendingSB.WriteString(k)
340 }
341
342 lsman.params.Logger.Verbose1f(
343 "LStreamClient %s teardown is completed, %d more are still pending: %s",
344 upd.Name, numPending, pendingSB.String(),
345 )
346 } else {
347 lsman.params.Logger.Verbose1f("LStreamClient %s teardown is completed, no more pending teardowns", upd.Name)
348
349 // If the whole LStreamsManager was shutting down, we're done now.
350 if lsman.tearingDown {
351 lsman.params.Logger.Infof("LStreamsManager teardown is completed")
352 close(lsman.torndownCh)
353 return
354 }
355 }
356
357 lsman.sendStateUpdate()
358 }
359
360 case req := <-lsman.reqCh:
361 switch {
362 case req.queryLogs != nil:
363 if len(lsman.lscs) == 0 {
364 lsman.sendLogRespUpdate(&LogRespTotal{
365 Errs: []error{errors.Errorf("no matching lstreams to get logs from")},
366 })
367 continue
368 }
369
370 if lsman.numNotConnected > 0 {
371 lsman.sendLogRespUpdate(&LogRespTotal{
372 Errs: []error{ErrNotYetConnected},
373 })
374 continue
375 }
376
377 if lsman.curQueryLogsCtx != nil {
378 lsman.sendLogRespUpdate(&LogRespTotal{
379 Errs: []error{ErrBusyWithAnotherQuery},
380 })
381 continue
382 }
383
384 if req.queryLogs.MaxNumLines == 0 {
385 panic("req.queryLogs.MaxNumLines is zero")
386 }
387
388 lsman.curQueryLogsCtx = &manQueryLogsCtx{
389 req: req.queryLogs,
390 startTime: lsman.params.Clock.Now(),
391 resps: make(map[string]*LogResp, len(lsman.lscs)),
392 errs: map[string]error{},
393 }
394
395 // sendStateUpdate must be done after setting curQueryLogsCtx.
396 lsman.sendStateUpdate()
397
398 for lstreamName, lsc := range lsman.lscs {
399 cmdQueryLogs := lstreamCmdQueryLogs{
400 maxNumLines: req.queryLogs.MaxNumLines,
401
402 from: req.queryLogs.From,
403 to: req.queryLogs.To,
404 query: req.queryLogs.Query,
405
406 refreshIndex: req.queryLogs.RefreshIndex,
407 }
408
409 if req.queryLogs.LoadEarlier {
410 // TODO: right now, this loadEarlier case isn't optimized at all:
411 // we again query the whole timerange, and every node goes through
412 // all same lines and builds all the same mstats again (which we
413 // then ignore). We can optimize it; however honestly the actual
414 // performance, as per my experiments, isn't going to be
415 // SPECTACULARLY better. Just kinda marginally better (try loading
416 // older logs with time period 5h or 1m: the 1m is somewhat faster,
417 // but not super fast. That's the difference we're talking about)
418 //
419 // Anyway, the way to optimize it is as follows: we already have
420 // mstats, so we know what kind of timeframe we should query to get
421 // the next maxNumLines messages. So we should query only this time
422 // range, and we should avoid building any mstats. This way, no
423 // matter how large the current time period is, loading more
424 // messages will be as fast as possible.
425
426 if nodeCtx, ok := lsman.curLogs.perNode[lstreamName]; ok {
427 if len(nodeCtx.logs) > 0 {
428 if nodeCtx.logs[0].LogFilename == SpecialFilenameJournalctl {
429 cmdQueryLogs.timestampUntil = getEarliestTimeAndNumMsgs(nodeCtx.logs)
430 } else {
431 cmdQueryLogs.linesUntil = nodeCtx.logs[0].CombinedLinenumber
432 }
433 }
434 }
435 }
436
437 lsc.EnqueueCmd(lstreamCmd{
438 respCh: lsman.respCh,
439 queryLogs: &cmdQueryLogs,
440 })
441 }
442
443 case req.updLStreams != nil:
444 r := req.updLStreams
445 lsman.params.Logger.Infof("LStreams manager: update logstreams spec: %s", r.logStreamsSpec)
446
447 if lsman.curQueryLogsCtx != nil {
448 r.resCh <- ErrBusyWithAnotherQuery
449 continue
450 }
451
452 if err := lsman.setLStreams(r.logStreamsSpec); err != nil {
453 r.resCh <- errors.Trace(err)
454 continue
455 }
456
457 lsman.updateHAs()
458 lsman.updateLStreamsByState()
459 lsman.sendStateUpdate()
460
461 r.resCh <- nil
462
463 case req.setUseExternalSSH != nil:
464 r := req.setUseExternalSSH
465 lsman.params.Logger.Infof("LStreams manager: setting useExternalSSH: %v", r.useExternalSSH)
466
467 lsman.setUseExternalSSH(r.useExternalSSH)
468
469 r.resCh <- struct{}{}
470
471 case req.ping:
472 for _, lsc := range lsman.lscs {
473 lsc.EnqueueCmd(lstreamCmd{
474 ping: &lstreamCmdPing{},
475 })
476 }
477
478 case req.reconnect:
479 lsman.params.Logger.Infof("Reconnect command")
480 if lsman.curQueryLogsCtx != nil {
481 lsman.params.Logger.Infof("Forgetting the in-progress query")
482 lsman.curQueryLogsCtx = nil
483 }
484 for _, lsc := range lsman.lscs {
485 lsc.Reconnect()
486 }
487
488 // NOTE: we don't call updateHAs, updateLStreamsByState and sendStateUpdate
489 // here, because it would operate on outdated info: after we've called
490 // Reconnect for every LStreamClient just above, their statuses are changing
491 // already, but we don't know it yet (we'll know once we receive updates
492 // in this same event loop, and _then_ we'll update all the data etc).
493
494 case req.disconnect:
495 lsman.params.Logger.Infof("Disconnect command")
496 if lsman.curQueryLogsCtx != nil {
497 lsman.params.Logger.Infof("Forgetting the in-progress query")
498 lsman.curQueryLogsCtx = nil
499 }
500 lsman.setLStreams("")
501
502 lsman.updateHAs()
503 lsman.updateLStreamsByState()
504 lsman.sendStateUpdate()
505 }
506
507 case resp := <-lsman.respCh:
508 lsman.params.Logger.Verbose1f("Got a response from %v: %+v", resp.hostname, resp)
509
510 switch {
511 case lsman.curQueryLogsCtx != nil:
512 if resp.err != nil {
513 lsman.params.Logger.Errorf("Got an error response from %v: %s", resp.hostname, resp.err)
514 lsman.curQueryLogsCtx.errs[resp.hostname] = resp.err
515 }
516
517 switch v := resp.resp.(type) {
518 case *LogResp:
519 lsman.curQueryLogsCtx.resps[resp.hostname] = v
520
521 // If we collected responses from all nodes, handle them.
522 if len(lsman.curQueryLogsCtx.resps) == len(lsman.lscs) {
523 lsman.params.Logger.Verbose1f(
524 "Got logs from %v, this was the last one, query is completed",
525 resp.hostname,
526 )
527
528 lsman.mergeLogRespsAndSend()
529
530 lsman.curQueryLogsCtx = nil
531
532 // sendStateUpdate must be done after setting curQueryLogsCtx.
533 lsman.sendStateUpdate()
534 } else {
535 lsman.params.Logger.Verbose1f(
536 "Got logs from %v, %d more to go",
537 resp.hostname,
538 len(lsman.lscs)-len(lsman.curQueryLogsCtx.resps),
539 )
540 }
541
542 default:
543 panic(fmt.Sprintf("unexpected resp type %T", v))
544 }
545
546 default:
547 lsman.params.Logger.Errorf("Dropping update from %s on the floor", resp.hostname)
548 }
549
550 case <-lsman.teardownReqCh:
551 lsman.params.Logger.Infof("LStreamsManager teardown is started")
552 lsman.tearingDown = true
553 lsman.setLStreams("")
554
555 lsman.updateHAs()
556 lsman.updateLStreamsByState()
557
558 // Check if we don't need to wait for anything, and can teardown right away.
559 numPending := lsman.getNumLStreamClientsTearingDown()
560 if numPending == 0 {
561 lsman.params.Logger.Infof("LStreamsManager teardown is completed")
562 close(lsman.torndownCh)
563 return
564 }
565
566 // We still need to wait for some LStreamClient-s to teardown, so send an
567 // update for now and keep going.
568 lsman.sendStateUpdate()
569 }
570 }
571 }
572
573 type timeAndNumMsgs struct {
574 // time is the timestamp of some log message.
575 time time.Time
576 // numMsgs is the number of messages on the timestamp time.
577 numMsgs int
578 }
579
580 func getEarliestTimeAndNumMsgs(logs []LogMsg) *timeAndNumMsgs {
581 if len(logs) == 0 {
582 return nil
583 }
584
585 ret := &timeAndNumMsgs{
586 time: logs[0].Time,
587 numMsgs: 1,
588 }
589
590 for _, logMsg := range logs[1:] {
591 if !logMsg.Time.Equal(ret.time) {
592 break
593 }
594
595 ret.numMsgs++
596 }
597
598 return ret
599 }
600
601 func (lsman *LStreamsManager) getNumLStreamClientsTearingDown() int {
602 numPending := 0
603 for _, v := range lsman.lscPendingTeardown {
604 numPending += v
605 }
606
607 return numPending
608 }
609
610 // Close initiates the shutdown. It doesn't wait for the shutdown to complete;
611 // use Wait for it.
612 func (lsman *LStreamsManager) Close() {
613 select {
614 case lsman.teardownReqCh <- struct{}{}:
615 default:
616 }
617 }
618
619 // Wait waits for the LStreamsManager to tear down. Typically used after calling Close().
620 func (lsman *LStreamsManager) Wait() {
621 <-lsman.torndownCh
622 }
623
624 type lstreamsManagerReq struct {
625 // Exactly one field must be non-nil
626
627 queryLogs *QueryLogsParams
628 updLStreams *lstreamsManagerReqUpdLStreams
629 setUseExternalSSH *lstreamsManagerReqSetUseExternalSSH
630 ping bool
631 reconnect bool
632 disconnect bool
633 }
634
635 type lstreamsManagerReqUpdLStreams struct {
636 logStreamsSpec string
637 resCh chan<- error
638 }
639
640 type lstreamsManagerReqSetUseExternalSSH struct {
641 useExternalSSH bool
642 resCh chan<- struct{}
643 }
644
645 func (lsman *LStreamsManager) QueryLogs(params QueryLogsParams) {
646 lsman.params.Logger.Verbose1f("QueryLogs: %+v", params)
647 lsman.reqCh <- lstreamsManagerReq{
648 queryLogs: &params,
649 }
650 }
651
652 func (lsman *LStreamsManager) SetLStreams(logStreamsSpec string) error {
653 resCh := make(chan error, 1)
654
655 lsman.reqCh <- lstreamsManagerReq{
656 updLStreams: &lstreamsManagerReqUpdLStreams{
657 logStreamsSpec: logStreamsSpec,
658 resCh: resCh,
659 },
660 }
661
662 return <-resCh
663 }
664
665 func (lsman *LStreamsManager) Ping() {
666 lsman.reqCh <- lstreamsManagerReq{
667 ping: true,
668 }
669 }
670
671 func (lsman *LStreamsManager) Reconnect() {
672 lsman.reqCh <- lstreamsManagerReq{
673 reconnect: true,
674 }
675 }
676
677 func (lsman *LStreamsManager) Disconnect() {
678 lsman.reqCh <- lstreamsManagerReq{
679 disconnect: true,
680 }
681 }
682
683 type manQueryLogsCtx struct {
684 req *QueryLogsParams
685
686 startTime time.Time
687
688 // resps is a map from logstream name to its response. Once all responses have
689 // been collected, we'll start merging them together.
690 resps map[string]*LogResp
691 errs map[string]error
692 }
693
694 type manLogsCtx struct {
695 minuteStats map[int64]MinuteStatsItem
696 numMsgsTotal int
697
698 perNode map[string]*manLogsNodeCtx
699 }
700
701 type manLogsNodeCtx struct {
702 logs []LogMsg
703 isMaxNumLines bool
704 }
705
706 type LStreamsManagerUpdate struct {
707 // Exactly one of the fields below must be non-nil
708
709 State *LStreamsManagerState
710 LogResp *LogRespTotal
711
712 BootstrapIssue *BootstrapIssue
713
714 DataRequest *ShellConnDataRequest
715 }
716
717 type LStreamsManagerState struct {
718 NumLStreams int
719
720 LStreamsByState map[LStreamClientState]map[string]struct{}
721
722 // NumConnected is how many nodes are actually connected
723 NumConnected int
724
725 // NoMatchingLStreams is true when there are no matching lstreams.
726 NoMatchingLStreams bool
727
728 // Connected is true when all matching lstreams (which should be more than 0)
729 // are connected.
730 Connected bool
731
732 // Busy is true when a query is in progress.
733 Busy bool
734
735 ConnDetailsByLStream map[string]ConnDetails
736 BusyStageByLStream map[string]BusyStage
737
738 // TearingDown contains logstream names whic are in the process of teardown.
739 TearingDown []string
740 }
741
742 type BootstrapIssue struct {
743 LStreamName string
744 Err string
745
746 // WarnJournalctlNoAdminAccess is set to true if journalctl is used and the
747 // user doesn't have access to all the system logs. It's a separate bool
748 // instead of a generic warning message to make it possible to suppress it
749 // with a flag.
750 WarnJournalctlNoAdminAccess bool
751 }
752
753 func (lsman *LStreamsManager) updateLStreamsByState() {
754 lsman.numNotConnected = 0
755 lsman.lstreamsByState = map[LStreamClientState]map[string]struct{}{}
756
757 for name, state := range lsman.lscStates {
758 set, ok := lsman.lstreamsByState[state]
759 if !ok {
760 set = map[string]struct{}{}
761 lsman.lstreamsByState[state] = set
762 }
763
764 set[name] = struct{}{}
765
766 if !isStateConnected(state) {
767 lsman.numNotConnected++
768 }
769 }
770 }
771
772 func (lsman *LStreamsManager) sendStateUpdate() {
773 numConnected := 0
774 for _, state := range lsman.lscStates {
775 if isStateConnected(state) {
776 numConnected++
777 }
778 }
779
780 connDetailsCopy := make(map[string]ConnDetails, len(lsman.lscConnDetails))
781 for k, v := range lsman.lscConnDetails {
782 connDetailsCopy[k] = v
783 }
784
785 busyStagesCopy := make(map[string]BusyStage, len(lsman.lscBusyStages))
786 for k, v := range lsman.lscBusyStages {
787 busyStagesCopy[k] = v
788 }
789
790 tearingDown := make([]string, 0, len(lsman.lscPendingTeardown))
791 for k, num := range lsman.lscPendingTeardown {
792 for i := 0; i < num; i++ {
793 tearingDown = append(tearingDown, k)
794 }
795 }
796 sort.Strings(tearingDown)
797
798 upd := LStreamsManagerUpdate{
799 State: &LStreamsManagerState{
800 NumLStreams: len(lsman.lscs),
801 LStreamsByState: lsman.lstreamsByState,
802 NumConnected: numConnected,
803 NoMatchingLStreams: lsman.numNotConnected == 0 && numConnected == 0,
804 Connected: lsman.numNotConnected == 0 && numConnected > 0,
805 Busy: lsman.curQueryLogsCtx != nil,
806 ConnDetailsByLStream: connDetailsCopy,
807 BusyStageByLStream: busyStagesCopy,
808 TearingDown: tearingDown,
809 },
810 }
811
812 lsman.params.UpdatesCh <- upd
813 }
814
815 func (lsman *LStreamsManager) sendLogRespUpdate(resp *LogRespTotal) {
816 if lsman.curQueryLogsCtx != nil {
817 resp.QueryDur = time.Since(lsman.curQueryLogsCtx.startTime)
818 }
819
820 lsman.params.UpdatesCh <- LStreamsManagerUpdate{
821 LogResp: resp,
822 }
823 }
824
825 func (lsman *LStreamsManager) mergeLogRespsAndSend() {
826 resps := lsman.curQueryLogsCtx.resps
827 errs := lsman.curQueryLogsCtx.errs
828
829 if len(errs) != 0 {
830 errs2 := make([]error, 0, len(errs))
831 for hostname, err := range errs {
832 errs2 = append(errs2, errors.Annotatef(err, "%s", hostname))
833 }
834
835 sort.Slice(errs2, func(i, j int) bool {
836 return errs2[i].Error() < errs2[j].Error()
837 })
838
839 lsman.sendLogRespUpdate(&LogRespTotal{
840 Errs: errs2,
841 })
842
843 return
844 }
845
846 // If we're not adding to already existing logs, reset w/e we've had already,
847 // and calculate minuteStats from the resps.
848 if !lsman.curQueryLogsCtx.req.LoadEarlier {
849 lsman.curLogs = manLogsCtx{
850 minuteStats: map[int64]MinuteStatsItem{},
851 perNode: map[string]*manLogsNodeCtx{},
852 }
853
854 for nodeName, resp := range resps {
855 for k, v := range resp.MinuteStats {
856 lsman.curLogs.minuteStats[k] = MinuteStatsItem{
857 NumMsgs: lsman.curLogs.minuteStats[k].NumMsgs + v.NumMsgs,
858 }
859
860 lsman.curLogs.numMsgsTotal += v.NumMsgs
861 }
862
863 lsman.curLogs.perNode[nodeName] = &manLogsNodeCtx{
864 logs: resp.Logs,
865 isMaxNumLines: len(resp.Logs) == lsman.curQueryLogsCtx.req.MaxNumLines,
866 }
867 }
868 } else {
869 // Add to existing logs
870 for nodeName, resp := range resps {
871 pn := lsman.curLogs.perNode[nodeName]
872 pn.logs = append(resp.Logs, pn.logs...)
873 pn.isMaxNumLines = len(resp.Logs) == lsman.curQueryLogsCtx.req.MaxNumLines
874 }
875 }
876
877 // Collect debug info
878 debugInfo := make(map[string]LogstreamDebugInfo, len(resps))
879 for lstreamName, resp := range resps {
880 debugInfo[lstreamName] = resp.DebugInfo
881 }
882
883 ret := &LogRespTotal{
884 MinuteStats: lsman.curLogs.minuteStats,
885 NumMsgsTotal: lsman.curLogs.numMsgsTotal,
886 LoadedEarlier: lsman.curQueryLogsCtx.req.LoadEarlier,
887 DebugInfo: debugInfo,
888 }
889
890 var logsCoveredSince time.Time
891
892 for _, pn := range lsman.curLogs.perNode {
893 ret.Logs = append(ret.Logs, pn.logs...)
894
895 // If the timespan covered by logs from this logstream is shorter than what
896 // we've seen before, remember it.
897 if pn.isMaxNumLines && logsCoveredSince.Before(pn.logs[0].Time) {
898 logsCoveredSince = pn.logs[0].Time
899 }
900 }
901
902 sort.SliceStable(ret.Logs, func(i, j int) bool {
903 if !ret.Logs[i].Time.Equal(ret.Logs[j].Time) {
904 return ret.Logs[i].Time.Before(ret.Logs[j].Time)
905 }
906
907 // TODO: make it less hacky, store lstream somewhere outside of Context as well.
908 return ret.Logs[i].Context["lstream"] < ret.Logs[j].Context["lstream"]
909 })
910
911 // Cut all potentially incomplete logs, only leave timespan that we're sure
912 // we have covered from all nodes
913 coveredSinceIdx := sort.Search(len(ret.Logs), func(i int) bool {
914 return !ret.Logs[i].Time.Before(logsCoveredSince)
915 })
916 ret.Logs = ret.Logs[coveredSinceIdx:]
917
918 lsman.sendLogRespUpdate(ret)
919 }
920
921 func (lsman *LStreamsManager) randomString(length int) string {
922 const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
923
924 rand.Seed(lsman.params.Clock.Now().UnixNano()) // Seed once per call
925 prefix := make([]byte, length)
926 for i := range prefix {
927 prefix[i] = charset[rand.Intn(len(charset))]
928 }
929 return string(prefix)
930 }