stats.go 13 KB

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