log/sockstatlog: also shutdown the poll goroutine

Co-authored-by: Will Norris <will@tailscale.com>
Signed-off-by: Maisem Ali <maisem@tailscale.com>
pull/7555/head
Maisem Ali 2 years ago committed by Will Norris
parent c87782ba9d
commit 8c4adde083

@ -5,6 +5,7 @@
package sockstatlog package sockstatlog
import ( import (
"context"
"encoding/json" "encoding/json"
"io" "io"
"os" "os"
@ -22,6 +23,9 @@ const pollPeriod = time.Second / 10
// Logger logs statistics about network sockets. // Logger logs statistics about network sockets.
type Logger struct { type Logger struct {
ctx context.Context
cancelFn context.CancelFunc
ticker time.Ticker ticker time.Ticker
logf logger.Logf logf logger.Logf
logbuffer *filch.Filch logbuffer *filch.Filch
@ -63,7 +67,10 @@ func NewLogger(logdir string, logf logger.Logf) (*Logger, error) {
return nil, err return nil, err
} }
ctx, cancel := context.WithCancel(context.Background())
return &Logger{ return &Logger{
ctx: ctx,
cancelFn: cancel,
ticker: *time.NewTicker(pollPeriod), ticker: *time.NewTicker(pollPeriod),
logf: logf, logf: logf,
logbuffer: filch, logbuffer: filch,
@ -83,32 +90,38 @@ func (l *Logger) poll() {
var lastTime time.Time var lastTime time.Time
enc := json.NewEncoder(l.logbuffer) enc := json.NewEncoder(l.logbuffer)
for t := range l.ticker.C { for {
stats := sockstats.Get() select {
if lastStats != nil { case <-l.ctx.Done():
diffstats := delta(lastStats, stats) return
if len(diffstats) > 0 { case t := <-l.ticker.C:
e := event{ stats := sockstats.Get()
Time: lastTime.UnixMilli(), if lastStats != nil {
Duration: t.Sub(lastTime).Milliseconds(), diffstats := delta(lastStats, stats)
Stats: diffstats, if len(diffstats) > 0 {
} e := event{
if stats.CurrentInterfaceCellular { Time: lastTime.UnixMilli(),
e.IsCellularInterface = 1 Duration: t.Sub(lastTime).Milliseconds(),
} Stats: diffstats,
if err := enc.Encode(e); err != nil { }
l.logf("sockstatlog: error encoding log: %v", err) if stats.CurrentInterfaceCellular {
e.IsCellularInterface = 1
}
if err := enc.Encode(e); err != nil {
l.logf("sockstatlog: error encoding log: %v", err)
}
} }
} }
lastTime = t
lastStats = stats
} }
lastTime = t
lastStats = stats
} }
} }
func (l *Logger) Shutdown() { func (l *Logger) Shutdown() {
l.ticker.Stop() l.ticker.Stop()
l.logbuffer.Close() l.logbuffer.Close()
l.cancelFn()
} }
// WriteLogs reads local logs, combining logs into events, and writes them to w. // WriteLogs reads local logs, combining logs into events, and writes them to w.

Loading…
Cancel
Save