| 1 |
package nebula |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"errors" |
| 6 |
"fmt" |
| 7 |
"log/slog" |
| 8 |
"net" |
| 9 |
"net/http" |
| 10 |
"runtime" |
| 11 |
"strconv" |
| 12 |
"sync" |
| 13 |
"sync/atomic" |
| 14 |
"time" |
| 15 |
|
| 16 |
graphite "github.com/cyberdelia/go-metrics-graphite" |
| 17 |
mp "github.com/nbrownus/go-metrics-prometheus" |
| 18 |
"github.com/prometheus/client_golang/prometheus" |
| 19 |
"github.com/prometheus/client_golang/prometheus/promhttp" |
| 20 |
"github.com/rcrowley/go-metrics" |
| 21 |
"github.com/slackhq/nebula/config" |
| 22 |
) |
| 23 |
|
| 24 |
// statsServer owns nebula's stats subsystem: the periodic metric capture |
| 25 |
// goroutine and (for prometheus) an HTTP listener. It mirrors the lifecycle |
| 26 |
// shape of dnsServer: constructor wires the reload callback, reload records |
| 27 |
// config, Start builds and runs the runtime, Stop tears it down. |
| 28 |
type statsServer struct { |
| 29 |
l *slog.Logger |
| 30 |
ctx context.Context |
| 31 |
buildVersion string |
| 32 |
configTest bool |
| 33 |
|
| 34 |
// enabled mirrors "stats configured to a real backend". Start consults |
| 35 |
// it so callers don't need to know the gating rules. |
| 36 |
enabled atomic.Bool |
| 37 |
|
| 38 |
runMu sync.Mutex |
| 39 |
runCfg *statsConfig |
| 40 |
run *statsRuntime // non-nil while a runtime is live |
| 41 |
} |
| 42 |
|
| 43 |
// statsRuntime is the live state owned by a single Start invocation. Start |
| 44 |
// stashes a pointer under runMu; Stop and Start's own exit path use pointer |
| 45 |
// equality to tell "my runtime" apart from one that replaced it after a |
| 46 |
// reload. |
| 47 |
type statsRuntime struct { |
| 48 |
cancel context.CancelFunc |
| 49 |
listener *http.Server // nil for graphite |
| 50 |
} |
| 51 |
|
| 52 |
// statsConfig is the snapshot of stats-related config that drives the runtime. |
| 53 |
// It is comparable with == so reload can detect "no change" cheaply. |
| 54 |
type statsConfig struct { |
| 55 |
typ string |
| 56 |
interval time.Duration |
| 57 |
graphite graphiteConfig |
| 58 |
prom promConfig |
| 59 |
} |
| 60 |
|
| 61 |
type graphiteConfig struct { |
| 62 |
protocol string |
| 63 |
host string |
| 64 |
// resolvedAddr is the string form of host resolved at config-load time. |
| 65 |
// Including it in the struct means a SIGHUP picks up DNS changes even |
| 66 |
// when stats.host hasn't been edited. |
| 67 |
resolvedAddr string |
| 68 |
prefix string |
| 69 |
} |
| 70 |
|
| 71 |
type promConfig struct { |
| 72 |
listen string |
| 73 |
path string |
| 74 |
namespace string |
| 75 |
subsystem string |
| 76 |
} |
| 77 |
|
| 78 |
// newStatsServerFromConfig builds a statsServer, applies the initial config, |
| 79 |
// and registers a reload callback. The reload callback is registered before |
| 80 |
// the initial config is applied so a SIGHUP can later enable, fix, or disable |
| 81 |
// stats even if the initial application failed. |
| 82 |
// |
| 83 |
// Start is safe to call unconditionally: it no-ops when stats are disabled. |
| 84 |
// The returned pointer is always non-nil, even on error. |
| 85 |
func newStatsServerFromConfig(ctx context.Context, l *slog.Logger, c *config.C, buildVersion string, configTest bool) (*statsServer, error) { |
| 86 |
s := &statsServer{ |
| 87 |
l: l, |
| 88 |
ctx: ctx, |
| 89 |
buildVersion: buildVersion, |
| 90 |
configTest: configTest, |
| 91 |
} |
| 92 |
|
| 93 |
c.RegisterReloadCallback(func(c *config.C) { |
| 94 |
if err := s.reload(c, false); err != nil { |
| 95 |
s.l.Error("Failed to reload stats from config", "error", err) |
| 96 |
} |
| 97 |
}) |
| 98 |
|
| 99 |
if err := s.reload(c, true); err != nil { |
| 100 |
return s, err |
| 101 |
} |
| 102 |
return s, nil |
| 103 |
} |
| 104 |
|
| 105 |
// reload records the latest config. On the initial call it only records it; |
| 106 |
// Control.Start is what launches the first runtime via statsStart. On later |
| 107 |
// calls it reconciles the running runtime with the new config: |
| 108 |
// |
| 109 |
// - newly enabled -> spawn Start |
| 110 |
// - newly disabled -> Stop the runtime |
| 111 |
// - config changed (still enabled) -> Stop the old, Start the new |
| 112 |
// - no change -> no-op |
| 113 |
func (s *statsServer) reload(c *config.C, initial bool) error { |
| 114 |
newCfg, err := loadStatsConfig(c) |
| 115 |
if err != nil { |
| 116 |
return err |
| 117 |
} |
| 118 |
enabled := newCfg.typ != "" && newCfg.typ != "none" |
| 119 |
|
| 120 |
s.runMu.Lock() |
| 121 |
sameCfg := s.runCfg != nil && *s.runCfg == newCfg |
| 122 |
s.runCfg = &newCfg |
| 123 |
running := s.run != nil |
| 124 |
s.runMu.Unlock() |
| 125 |
|
| 126 |
s.enabled.Store(enabled) |
| 127 |
|
| 128 |
if initial || sameCfg { |
| 129 |
return nil |
| 130 |
} |
| 131 |
|
| 132 |
if running { |
| 133 |
s.Stop() |
| 134 |
} |
| 135 |
if enabled && !s.configTest { |
| 136 |
go s.Start() |
| 137 |
} |
| 138 |
return nil |
| 139 |
} |
| 140 |
|
| 141 |
// Start builds the runtime from the latest config, spawns the capture loop, |
| 142 |
// and blocks until Stop is called or ctx fires. For prometheus it also serves |
| 143 |
// the HTTP listener. For graphite it blocks on the capture loop's context. |
| 144 |
// Safe to call when stats are disabled or already running (both no-op). |
| 145 |
func (s *statsServer) Start() { |
| 146 |
if !s.enabled.Load() || s.configTest { |
| 147 |
return |
| 148 |
} |
| 149 |
|
| 150 |
s.runMu.Lock() |
| 151 |
if s.ctx.Err() != nil || s.run != nil || s.runCfg == nil { |
| 152 |
s.runMu.Unlock() |
| 153 |
return |
| 154 |
} |
| 155 |
cfg := *s.runCfg |
| 156 |
captureFns, listener := s.buildRuntime(cfg) |
| 157 |
runCtx, cancel := context.WithCancel(s.ctx) |
| 158 |
rt := &statsRuntime{cancel: cancel, listener: listener} |
| 159 |
s.run = rt |
| 160 |
s.runMu.Unlock() |
| 161 |
|
| 162 |
go captureStatsLoop(runCtx, cfg.interval, captureFns) |
| 163 |
|
| 164 |
cleanExit := true |
| 165 |
if listener == nil { |
| 166 |
// Graphite: no HTTP listener to serve; block until teardown. |
| 167 |
<-runCtx.Done() |
| 168 |
} else { |
| 169 |
cleanExit = s.serveListener(listener) |
| 170 |
} |
| 171 |
|
| 172 |
// Clear our runtime only if nothing has replaced it. Stop races through |
| 173 |
// here too but leaves s.run == nil, so the pointer check skips. |
| 174 |
s.runMu.Lock() |
| 175 |
if s.run == rt { |
| 176 |
rt.cancel() |
| 177 |
s.run = nil |
| 178 |
// A listener that exited with an error (e.g., bind conflict) leaves |
| 179 |
// runCfg cached as if it were applied. Drop it so a SIGHUP with the |
| 180 |
// same config re-triggers Start once the user fixes the underlying |
| 181 |
// problem. |
| 182 |
if !cleanExit { |
| 183 |
s.runCfg = nil |
| 184 |
} |
| 185 |
} |
| 186 |
s.runMu.Unlock() |
| 187 |
} |
| 188 |
|
| 189 |
// serveListener runs ListenAndServe and ensures ctx cancellation unblocks it. |
| 190 |
// Returns true if the listener exited cleanly (Stop, ctx cancellation, or any |
| 191 |
// other http.ErrServerClosed path), false on an unexpected error. |
| 192 |
func (s *statsServer) serveListener(listener *http.Server) bool { |
| 193 |
// Per-invocation watcher: ctx cancellation triggers a listener shutdown |
| 194 |
// which in turn unblocks ListenAndServe. Closing `done` on exit keeps |
| 195 |
// the watcher from outliving this call. |
| 196 |
done := make(chan struct{}) |
| 197 |
go func() { |
| 198 |
select { |
| 199 |
case <-s.ctx.Done(): |
| 200 |
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 201 |
defer cancel() |
| 202 |
if err := listener.Shutdown(shutdownCtx); err != nil { |
| 203 |
s.l.Warn("Failed to shut down prometheus stats listener", "error", err) |
| 204 |
} |
| 205 |
case <-done: |
| 206 |
} |
| 207 |
}() |
| 208 |
defer close(done) |
| 209 |
|
| 210 |
s.l.Info("Starting prometheus stats listener", "addr", listener.Addr) |
| 211 |
err := listener.ListenAndServe() |
| 212 |
if err == nil || errors.Is(err, http.ErrServerClosed) { |
| 213 |
return true |
| 214 |
} |
| 215 |
s.l.Error("Prometheus stats listener exited", "error", err) |
| 216 |
return false |
| 217 |
} |
| 218 |
|
| 219 |
// Stop tears down the active runtime, if any. Idempotent. |
| 220 |
func (s *statsServer) Stop() { |
| 221 |
s.runMu.Lock() |
| 222 |
rt := s.run |
| 223 |
s.run = nil |
| 224 |
s.runMu.Unlock() |
| 225 |
if rt == nil { |
| 226 |
return |
| 227 |
} |
| 228 |
rt.cancel() |
| 229 |
if rt.listener != nil { |
| 230 |
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 231 |
if err := rt.listener.Shutdown(shutdownCtx); err != nil { |
| 232 |
s.l.Warn("Failed to shut down prometheus stats listener", "error", err) |
| 233 |
} |
| 234 |
cancel() |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
// buildRuntime produces the capture functions and, for prometheus, an un-served |
| 239 |
// http.Server from cfg. cfg has already been validated by loadStatsConfig. |
| 240 |
func (s *statsServer) buildRuntime(cfg statsConfig) ([]func(), *http.Server) { |
| 241 |
// rcrowley/go-metrics guards these registrations with a private sync.Once, |
| 242 |
// so subsequent reloads are no-ops. |
| 243 |
metrics.RegisterDebugGCStats(metrics.DefaultRegistry) |
| 244 |
metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry) |
| 245 |
|
| 246 |
captureFns := []func(){ |
| 247 |
func() { metrics.CaptureDebugGCStatsOnce(metrics.DefaultRegistry) }, |
| 248 |
func() { metrics.CaptureRuntimeMemStatsOnce(metrics.DefaultRegistry) }, |
| 249 |
} |
| 250 |
|
| 251 |
switch cfg.typ { |
| 252 |
case "graphite": |
| 253 |
// loadStatsConfig already resolved and validated the address; re-parse |
| 254 |
// the resolved form (no DNS lookup) to get a *net.TCPAddr. |
| 255 |
addr, _ := net.ResolveTCPAddr(cfg.graphite.protocol, cfg.graphite.resolvedAddr) |
| 256 |
gcfg := graphite.Config{ |
| 257 |
Addr: addr, |
| 258 |
Registry: metrics.DefaultRegistry, |
| 259 |
FlushInterval: cfg.interval, |
| 260 |
DurationUnit: time.Nanosecond, |
| 261 |
Prefix: cfg.graphite.prefix, |
| 262 |
Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999}, |
| 263 |
} |
| 264 |
captureFns = append(captureFns, func() { |
| 265 |
if err := graphite.Once(gcfg); err != nil { |
| 266 |
s.l.Error("Graphite export failed", "error", err) |
| 267 |
} |
| 268 |
}) |
| 269 |
s.l.Info("Starting graphite stats", |
| 270 |
"interval", cfg.interval, |
| 271 |
"prefix", cfg.graphite.prefix, |
| 272 |
"addr", addr, |
| 273 |
) |
| 274 |
return captureFns, nil |
| 275 |
|
| 276 |
case "prometheus": |
| 277 |
pr := prometheus.NewRegistry() |
| 278 |
pClient := mp.NewPrometheusProvider(metrics.DefaultRegistry, cfg.prom.namespace, cfg.prom.subsystem, pr, cfg.interval) |
| 279 |
captureFns = append(captureFns, func() { |
| 280 |
if err := pClient.UpdatePrometheusMetricsOnce(); err != nil { |
| 281 |
s.l.Error("Prometheus metrics update failed", "error", err) |
| 282 |
} |
| 283 |
}) |
| 284 |
|
| 285 |
g := prometheus.NewGauge(prometheus.GaugeOpts{ |
| 286 |
Namespace: cfg.prom.namespace, |
| 287 |
Subsystem: cfg.prom.subsystem, |
| 288 |
Name: "info", |
| 289 |
Help: "Version information for the Nebula binary", |
| 290 |
ConstLabels: prometheus.Labels{ |
| 291 |
"version": s.buildVersion, |
| 292 |
"goversion": runtime.Version(), |
| 293 |
"boringcrypto": strconv.FormatBool(boringEnabled()), |
| 294 |
}, |
| 295 |
}) |
| 296 |
pr.MustRegister(g) |
| 297 |
g.Set(1) |
| 298 |
|
| 299 |
// promhttp.HandlerOpts.ErrorLog needs a stdlib-shaped Println logger, |
| 300 |
// so bridge our slog.Logger back to a *log.Logger that emits at Error. |
| 301 |
errLog := slog.NewLogLogger(s.l.Handler(), slog.LevelError) |
| 302 |
mux := http.NewServeMux() |
| 303 |
mux.Handle(cfg.prom.path, promhttp.HandlerFor(pr, promhttp.HandlerOpts{ErrorLog: errLog})) |
| 304 |
return captureFns, &http.Server{Addr: cfg.prom.listen, Handler: mux} |
| 305 |
} |
| 306 |
return captureFns, nil |
| 307 |
} |
| 308 |
|
| 309 |
// captureStatsLoop runs each fn on every tick of d until ctx is cancelled. |
| 310 |
func captureStatsLoop(ctx context.Context, d time.Duration, fns []func()) { |
| 311 |
t := time.NewTicker(d) |
| 312 |
defer t.Stop() |
| 313 |
for { |
| 314 |
select { |
| 315 |
case <-ctx.Done(): |
| 316 |
return |
| 317 |
case <-t.C: |
| 318 |
for _, fn := range fns { |
| 319 |
fn() |
| 320 |
} |
| 321 |
} |
| 322 |
} |
| 323 |
} |
| 324 |
|
| 325 |
func loadStatsConfig(c *config.C) (statsConfig, error) { |
| 326 |
cfg := statsConfig{ |
| 327 |
typ: c.GetString("stats.type", ""), |
| 328 |
} |
| 329 |
if cfg.typ == "" || cfg.typ == "none" { |
| 330 |
return cfg, nil |
| 331 |
} |
| 332 |
|
| 333 |
cfg.interval = c.GetDuration("stats.interval", 0) |
| 334 |
if cfg.interval <= 0 { |
| 335 |
return cfg, fmt.Errorf("stats.interval was an invalid duration: %s", c.GetString("stats.interval", "")) |
| 336 |
} |
| 337 |
|
| 338 |
switch cfg.typ { |
| 339 |
case "graphite": |
| 340 |
cfg.graphite.protocol = c.GetString("stats.protocol", "tcp") |
| 341 |
cfg.graphite.host = c.GetString("stats.host", "") |
| 342 |
if cfg.graphite.host == "" { |
| 343 |
return cfg, errors.New("stats.host can not be empty") |
| 344 |
} |
| 345 |
addr, err := net.ResolveTCPAddr(cfg.graphite.protocol, cfg.graphite.host) |
| 346 |
if err != nil { |
| 347 |
return cfg, fmt.Errorf("error while setting up graphite sink: %s", err) |
| 348 |
} |
| 349 |
cfg.graphite.resolvedAddr = addr.String() |
| 350 |
cfg.graphite.prefix = c.GetString("stats.prefix", "nebula") |
| 351 |
case "prometheus": |
| 352 |
cfg.prom.listen = c.GetString("stats.listen", "") |
| 353 |
if cfg.prom.listen == "" { |
| 354 |
return cfg, errors.New("stats.listen should not be empty") |
| 355 |
} |
| 356 |
cfg.prom.path = c.GetString("stats.path", "") |
| 357 |
if cfg.prom.path == "" { |
| 358 |
return cfg, errors.New("stats.path should not be empty") |
| 359 |
} |
| 360 |
cfg.prom.namespace = c.GetString("stats.namespace", "") |
| 361 |
cfg.prom.subsystem = c.GetString("stats.subsystem", "") |
| 362 |
default: |
| 363 |
return cfg, fmt.Errorf("stats.type was not understood: %s", cfg.typ) |
| 364 |
} |
| 365 |
|
| 366 |
return cfg, nil |
| 367 |
} |