1
0

stats.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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, r *config.Reload) {
  92. if err := s.reload(c, false); err != nil {
  93. s.l.Error("Failed to reload stats from config", "error", err)
  94. r.Failed()
  95. }
  96. })
  97. if err := s.reload(c, true); err != nil {
  98. return s, err
  99. }
  100. return s, nil
  101. }
  102. // reload records the latest config. On the initial call it only records it;
  103. // Control.Start is what launches the first runtime via statsStart. On later
  104. // calls it reconciles the running runtime with the new config:
  105. //
  106. // - newly enabled -> spawn Start
  107. // - newly disabled -> Stop the runtime
  108. // - config changed (still enabled) -> Stop the old, Start the new
  109. // - no change -> no-op
  110. func (s *statsServer) reload(c *config.C, initial bool) error {
  111. newCfg, err := loadStatsConfig(c)
  112. if err != nil {
  113. return err
  114. }
  115. enabled := newCfg.typ != "" && newCfg.typ != "none"
  116. s.runMu.Lock()
  117. sameCfg := s.runCfg != nil && *s.runCfg == newCfg
  118. s.runCfg = &newCfg
  119. s.runMu.Unlock()
  120. s.enabled.Store(enabled)
  121. if initial || sameCfg {
  122. return nil
  123. }
  124. // Even with nothing running, a runtime whose listener failed can still be finishing its last pass
  125. s.Stop()
  126. if enabled && !s.configTest {
  127. go s.Start()
  128. }
  129. return nil
  130. }
  131. // Start builds the runtime from the latest config, spawns the capture loop,
  132. // and blocks until Stop is called or ctx fires. For prometheus it also serves
  133. // the HTTP listener. For graphite it blocks on the capture loop's context.
  134. // Safe to call when stats are disabled or already running (both no-op).
  135. func (s *statsServer) Start() {
  136. if !s.enabled.Load() || s.configTest {
  137. return
  138. }
  139. s.runMu.Lock()
  140. if s.ctx.Err() != nil || s.run != nil || s.runCfg == nil {
  141. s.runMu.Unlock()
  142. return
  143. }
  144. cfg := *s.runCfg
  145. runCtx, cancel := context.WithCancel(s.ctx)
  146. captureFns, listener := s.buildRuntime(runCtx, cfg)
  147. rt := &statsRuntime{cancel: cancel, listener: listener}
  148. s.run = rt
  149. done := make(chan struct{})
  150. s.loopDone = done
  151. s.runMu.Unlock()
  152. // Prime before serving, so a scrape that lands before the first tick sees real values instead of zeros (issue #907)
  153. for _, fn := range captureFns {
  154. fn()
  155. }
  156. go captureStatsLoop(runCtx, cfg.interval, captureFns, done)
  157. cleanExit := true
  158. if listener == nil {
  159. // Graphite: no HTTP listener to serve; block until teardown.
  160. <-runCtx.Done()
  161. } else {
  162. cleanExit = s.serveListener(listener)
  163. }
  164. // Clear our runtime only if nothing has replaced it. Stop races through
  165. // here too but leaves s.run == nil, so the pointer check skips.
  166. s.runMu.Lock()
  167. if s.run == rt {
  168. rt.cancel()
  169. s.run = nil
  170. // A listener that exited with an error (e.g., bind conflict) leaves
  171. // runCfg cached as if it were applied. Drop it so a SIGHUP with the
  172. // same config re-triggers Start once the user fixes the underlying
  173. // problem.
  174. if !cleanExit {
  175. s.runCfg = nil
  176. }
  177. }
  178. s.runMu.Unlock()
  179. }
  180. // serveListener runs ListenAndServe and ensures ctx cancellation unblocks it.
  181. // Returns true if the listener exited cleanly (Stop, ctx cancellation, or any
  182. // other http.ErrServerClosed path), false on an unexpected error.
  183. func (s *statsServer) serveListener(listener *http.Server) bool {
  184. // Per-invocation watcher: ctx cancellation triggers a listener shutdown
  185. // which in turn unblocks ListenAndServe. Closing `done` on exit keeps
  186. // the watcher from outliving this call.
  187. done := make(chan struct{})
  188. go func() {
  189. select {
  190. case <-s.ctx.Done():
  191. shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  192. defer cancel()
  193. if err := listener.Shutdown(shutdownCtx); err != nil {
  194. s.l.Warn("Failed to shut down prometheus stats listener", "error", err)
  195. }
  196. case <-done:
  197. }
  198. }()
  199. defer close(done)
  200. s.l.Info("Starting prometheus stats listener", "addr", listener.Addr)
  201. err := listener.ListenAndServe()
  202. if err == nil || errors.Is(err, http.ErrServerClosed) {
  203. return true
  204. }
  205. s.l.Error("Prometheus stats listener exited", "error", err)
  206. return false
  207. }
  208. // Stop tears down the active runtime, if any. Idempotent.
  209. func (s *statsServer) Stop() {
  210. // Held until the last pass is done, a Start that slipped in after s.run cleared would capture alongside it
  211. s.runMu.Lock()
  212. defer s.runMu.Unlock()
  213. rt := s.run
  214. s.run = nil
  215. if rt != nil {
  216. rt.cancel()
  217. if rt.listener != nil {
  218. shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  219. if err := rt.listener.Shutdown(shutdownCtx); err != nil {
  220. s.l.Warn("Failed to shut down prometheus stats listener", "error", err)
  221. }
  222. cancel()
  223. }
  224. }
  225. // Nothing captures once Stop returns. The last runtime is cancelled by now, whoever cleared it, so this is at most
  226. // the pass it was in. Nothing in a pass takes runMu
  227. if s.loopDone != nil {
  228. <-s.loopDone
  229. }
  230. }
  231. // buildRuntime produces the capture functions and, for prometheus, an un-served
  232. // http.Server from cfg. cfg has already been validated by loadStatsConfig.
  233. // A graphite send in progress is abandoned when ctx is done.
  234. func (s *statsServer) buildRuntime(ctx context.Context, cfg statsConfig) ([]func(), *http.Server) {
  235. // rcrowley/go-metrics guards these registrations with a private sync.Once,
  236. // so subsequent reloads are no-ops.
  237. metrics.RegisterDebugGCStats(metrics.DefaultRegistry)
  238. metrics.RegisterRuntimeMemStats(metrics.DefaultRegistry)
  239. captureFns := []func(){
  240. func() { metrics.CaptureDebugGCStatsOnce(metrics.DefaultRegistry) },
  241. func() { metrics.CaptureRuntimeMemStatsOnce(metrics.DefaultRegistry) },
  242. }
  243. if s.emitStats != nil {
  244. captureFns = append(captureFns, s.emitStats)
  245. }
  246. switch cfg.typ {
  247. case "graphite":
  248. // loadStatsConfig already resolved and validated the address; re-parse
  249. // the resolved form (no DNS lookup) to get a *net.TCPAddr.
  250. addr, _ := net.ResolveTCPAddr(cfg.graphite.protocol, cfg.graphite.resolvedAddr)
  251. gcfg := graphiteConfigExport{
  252. Addr: addr,
  253. Registry: metrics.DefaultRegistry,
  254. FlushInterval: cfg.interval,
  255. DurationUnit: time.Nanosecond,
  256. Prefix: cfg.graphite.prefix,
  257. Percentiles: []float64{0.5, 0.75, 0.95, 0.99, 0.999},
  258. }
  259. captureFns = append(captureFns, func() {
  260. if err := graphiteOnce(ctx, gcfg, graphiteTimeout); err != nil && ctx.Err() == nil {
  261. s.l.Error("Graphite export failed", "error", err)
  262. }
  263. })
  264. s.l.Info("Starting graphite stats",
  265. "interval", cfg.interval,
  266. "prefix", cfg.graphite.prefix,
  267. "addr", addr,
  268. )
  269. return captureFns, nil
  270. case "prometheus":
  271. pr := prometheus.NewRegistry()
  272. pClient := mp.NewPrometheusProvider(metrics.DefaultRegistry, cfg.prom.namespace, cfg.prom.subsystem, pr, cfg.interval)
  273. captureFns = append(captureFns, func() {
  274. if err := pClient.UpdatePrometheusMetricsOnce(); err != nil {
  275. s.l.Error("Prometheus metrics update failed", "error", err)
  276. }
  277. })
  278. g := prometheus.NewGauge(prometheus.GaugeOpts{
  279. Namespace: cfg.prom.namespace,
  280. Subsystem: cfg.prom.subsystem,
  281. Name: "info",
  282. Help: "Version information for the Nebula binary",
  283. ConstLabels: prometheus.Labels{
  284. "version": s.buildVersion,
  285. "goversion": runtime.Version(),
  286. "boringcrypto": strconv.FormatBool(boringEnabled()),
  287. "fips140Version": fips140.Version(),
  288. "fips140Enabled": strconv.FormatBool(fips140.Enabled()),
  289. "fips140Enforced": strconv.FormatBool(fips140.Enforced()),
  290. },
  291. })
  292. pr.MustRegister(g)
  293. g.Set(1)
  294. // promhttp.HandlerOpts.ErrorLog needs a stdlib-shaped Println logger,
  295. // so bridge our slog.Logger back to a *log.Logger that emits at Error.
  296. errLog := slog.NewLogLogger(s.l.Handler(), slog.LevelError)
  297. mux := http.NewServeMux()
  298. mux.Handle(cfg.prom.path, promhttp.HandlerFor(pr, promhttp.HandlerOpts{ErrorLog: errLog}))
  299. return captureFns, &http.Server{Addr: cfg.prom.listen, Handler: mux}
  300. }
  301. return captureFns, nil
  302. }
  303. // captureStatsLoop runs each fn on every tick of d until ctx is cancelled, then
  304. // closes done.
  305. func captureStatsLoop(ctx context.Context, d time.Duration, fns []func(), done chan struct{}) {
  306. defer close(done)
  307. t := time.NewTicker(d)
  308. defer t.Stop()
  309. for {
  310. select {
  311. case <-ctx.Done():
  312. return
  313. case <-t.C:
  314. for _, fn := range fns {
  315. fn()
  316. }
  317. }
  318. }
  319. }
  320. func loadStatsConfig(c *config.C) (statsConfig, error) {
  321. cfg := statsConfig{
  322. typ: c.GetString("stats.type", ""),
  323. }
  324. if cfg.typ == "" || cfg.typ == "none" {
  325. return cfg, nil
  326. }
  327. cfg.interval = c.GetDuration("stats.interval", 0)
  328. if cfg.interval <= 0 {
  329. return cfg, fmt.Errorf("stats.interval was an invalid duration: %s", c.GetString("stats.interval", ""))
  330. }
  331. switch cfg.typ {
  332. case "graphite":
  333. cfg.graphite.protocol = c.GetString("stats.protocol", "tcp")
  334. cfg.graphite.host = c.GetString("stats.host", "")
  335. if cfg.graphite.host == "" {
  336. return cfg, errors.New("stats.host can not be empty")
  337. }
  338. addr, err := net.ResolveTCPAddr(cfg.graphite.protocol, cfg.graphite.host)
  339. if err != nil {
  340. return cfg, fmt.Errorf("error while setting up graphite sink: %s", err)
  341. }
  342. cfg.graphite.resolvedAddr = addr.String()
  343. cfg.graphite.prefix = c.GetString("stats.prefix", "nebula")
  344. case "prometheus":
  345. cfg.prom.listen = c.GetString("stats.listen", "")
  346. if cfg.prom.listen == "" {
  347. return cfg, errors.New("stats.listen should not be empty")
  348. }
  349. cfg.prom.path = c.GetString("stats.path", "")
  350. if cfg.prom.path == "" {
  351. return cfg, errors.New("stats.path should not be empty")
  352. }
  353. cfg.prom.namespace = c.GetString("stats.namespace", "")
  354. cfg.prom.subsystem = c.GetString("stats.subsystem", "")
  355. default:
  356. return cfg, fmt.Errorf("stats.type was not understood: %s", cfg.typ)
  357. }
  358. return cfg, nil
  359. }