stats.go 11 KB

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