1
#pragma once
2

            
3
#include <atomic>
4
#include <chrono>
5
#include <cstdint>
6
#include <functional>
7
#include <list>
8
#include <memory>
9
#include <string>
10

            
11
#include "envoy/common/regex.h"
12
#include "envoy/config/bootstrap/v3/bootstrap.pb.h"
13
#include "envoy/event/timer.h"
14
#include "envoy/server/bootstrap_extension_config.h"
15
#include "envoy/server/configuration.h"
16
#include "envoy/server/drain_manager.h"
17
#include "envoy/server/guarddog.h"
18
#include "envoy/server/instance.h"
19
#include "envoy/server/process_context.h"
20
#include "envoy/server/tracer_config.h"
21
#include "envoy/server/transport_socket_config.h"
22
#include "envoy/ssl/context_manager.h"
23
#include "envoy/stats/stats_macros.h"
24
#include "envoy/stats/timespan.h"
25
#include "envoy/tracing/tracer.h"
26

            
27
#include "source/common/access_log/access_log_manager_impl.h"
28
#include "source/common/common/assert.h"
29
#include "source/common/common/cleanup.h"
30
#include "source/common/common/logger_delegates.h"
31
#include "source/common/common/perf_tracing.h"
32
#include "source/common/grpc/async_client_manager_impl.h"
33
#include "source/common/grpc/context_impl.h"
34
#include "source/common/http/context_impl.h"
35
#include "source/common/init/manager_impl.h"
36
#include "source/common/memory/stats.h"
37
#include "source/common/protobuf/message_validator_impl.h"
38
#include "source/common/quic/quic_stat_names.h"
39
#include "source/common/router/context_impl.h"
40
#include "source/common/runtime/runtime_impl.h"
41
#include "source/common/secret/secret_manager_impl.h"
42
#include "source/common/singleton/manager_impl.h"
43

            
44
#ifdef ENVOY_ADMIN_FUNCTIONALITY
45
#include "source/server/admin/admin.h"
46
#endif
47
#include "source/server/configuration_impl.h"
48
#include "source/server/listener_hooks.h"
49
#include "source/server/worker_impl.h"
50

            
51
#include "absl/container/node_hash_map.h"
52
#include "absl/types/optional.h"
53

            
54
namespace Envoy {
55
namespace Server {
56
namespace CompilationSettings {
57
/**
58
 * All server compilation settings stats. @see stats_macros.h
59
 */
60
#define ALL_SERVER_COMPILATION_SETTINGS_STATS(COUNTER, GAUGE, HISTOGRAM)                           \
61
10681
  GAUGE(fips_mode, NeverImport)
62

            
63
struct ServerCompilationSettingsStats {
64
  ALL_SERVER_COMPILATION_SETTINGS_STATS(GENERATE_COUNTER_STRUCT, GENERATE_GAUGE_STRUCT,
65
                                        GENERATE_HISTOGRAM_STRUCT)
66
};
67
} // namespace CompilationSettings
68

            
69
/**
70
 * All server wide stats. @see stats_macros.h
71
 */
72
#define ALL_SERVER_STATS(COUNTER, GAUGE, HISTOGRAM)                                                \
73
10681
  COUNTER(debug_assertion_failures)                                                                \
74
10681
  COUNTER(envoy_bug_failures)                                                                      \
75
10681
  COUNTER(envoy_notifications)                                                                     \
76
10681
  COUNTER(dynamic_unknown_fields)                                                                  \
77
10681
  COUNTER(static_unknown_fields)                                                                   \
78
10681
  COUNTER(wip_protos)                                                                              \
79
10681
  COUNTER(dropped_stat_flushes)                                                                    \
80
10681
  GAUGE(concurrency, NeverImport)                                                                  \
81
10681
  GAUGE(days_until_first_cert_expiring, NeverImport)                                               \
82
10681
  GAUGE(seconds_until_first_ocsp_response_expiring, NeverImport)                                   \
83
10681
  GAUGE(hot_restart_epoch, NeverImport)                                                            \
84
10681
  /* hot_restart_generation is an Accumulate gauge; we omit it here for testing dynamics. */       \
85
10681
  GAUGE(live, NeverImport)                                                                         \
86
10681
  GAUGE(memory_allocated, Accumulate)                                                              \
87
10681
  GAUGE(memory_heap_size, Accumulate)                                                              \
88
10681
  GAUGE(memory_physical_size, Accumulate)                                                          \
89
10681
  GAUGE(parent_connections, Accumulate)                                                            \
90
10681
  GAUGE(state, NeverImport)                                                                        \
91
10681
  GAUGE(stats_recent_lookups, NeverImport)                                                         \
92
10681
  GAUGE(total_connections, Accumulate)                                                             \
93
10681
  GAUGE(uptime, Accumulate)                                                                        \
94
10681
  GAUGE(version, NeverImport)                                                                      \
95
10681
  HISTOGRAM(initialization_time_ms, Milliseconds)
96

            
97
struct ServerStats {
98
  ALL_SERVER_STATS(GENERATE_COUNTER_STRUCT, GENERATE_GAUGE_STRUCT, GENERATE_HISTOGRAM_STRUCT)
99
};
100

            
101
/**
102
 * Interface for creating service components during boot.
103
 */
104
class ComponentFactory {
105
public:
106
10761
  virtual ~ComponentFactory() = default;
107

            
108
  /**
109
   * @return DrainManagerPtr a new drain manager for the server.
110
   */
111
  virtual DrainManagerPtr createDrainManager(Instance& server) PURE;
112

            
113
  /**
114
   * @return Runtime::LoaderPtr the runtime implementation for the server.
115
   */
116
  virtual Runtime::LoaderPtr createRuntime(Instance& server, Configuration::Initial& config) PURE;
117
};
118

            
119
/**
120
 * Helpers used during server creation.
121
 */
122
class InstanceUtil : Logger::Loggable<Logger::Id::main> {
123
public:
124
  /**
125
   * Default implementation of runtime loader creation used in the real server and in most
126
   * integration tests where a mock runtime is not needed.
127
   */
128
  static Runtime::LoaderPtr createRuntime(Instance& server, Server::Configuration::Initial& config);
129

            
130
  /**
131
   * Helper for flushing counters, gauges and histograms to sinks. This takes care of calling
132
   * flush() on each sink.
133
   * @param sinks supplies the list of sinks.
134
   * @param store provides the store being flushed.
135
   */
136
  static void flushMetricsToSinks(const std::list<Stats::SinkPtr>& sinks, Stats::Store& store,
137
                                  Upstream::ClusterManager& cm, TimeSource& time_source);
138

            
139
  /**
140
   * Load a bootstrap config and perform validation.
141
   * @param bootstrap supplies the bootstrap to fill.
142
   * @param options supplies the server options.
143
   * @param validation_visitor message validation visitor instance.
144
   * @param api reference to the Api object
145
   */
146
  static absl::Status loadBootstrapConfig(envoy::config::bootstrap::v3::Bootstrap& bootstrap,
147
                                          const Options& options,
148
                                          ProtobufMessage::ValidationVisitor& validation_visitor,
149
                                          Api::Api& api);
150

            
151
  /**
152
   * Raises soft file limit to the hard limit.
153
   */
154
  static void raiseFileLimits();
155
};
156

            
157
/**
158
 * This is a helper used by InstanceBase::run() on the stack. It's broken out to make testing
159
 * easier.
160
 */
161
class RunHelper : Logger::Loggable<Logger::Id::main> {
162
public:
163
  RunHelper(Instance& instance, const Options& options, Event::Dispatcher& dispatcher,
164
            Config::XdsManager& xds_manager, Upstream::ClusterManager& cm,
165
            AccessLog::AccessLogManager& access_log_manager, Init::Manager& init_manager,
166
            OverloadManager& overload_manager, OverloadManager& null_overload_manager,
167
            std::function<void()> workers_start_cb);
168

            
169
private:
170
  Init::WatcherImpl init_watcher_;
171
  Event::SignalEventPtr sigterm_;
172
  Event::SignalEventPtr sigint_;
173
  Event::SignalEventPtr sig_usr_1_;
174
  Event::SignalEventPtr sig_hup_;
175
};
176

            
177
// ServerFactoryContextImpl implements both ServerFactoryContext and
178
// TransportSocketFactoryContext for convenience as these two contexts
179
// share common member functions and member variables.
180
class ServerFactoryContextImpl : public Configuration::ServerFactoryContext,
181
                                 public Configuration::TransportSocketFactoryContext {
182
public:
183
  explicit ServerFactoryContextImpl(Instance& server)
184
10852
      : server_(server), server_scope_(server_.stats().createScope("")) {}
185

            
186
  // Configuration::ServerFactoryContext
187
230831
  Upstream::ClusterManager& clusterManager() override { return server_.clusterManager(); }
188
12305
  Config::XdsManager& xdsManager() override { return server_.xdsManager(); }
189
10830
  Http::HttpServerPropertiesCacheManager& httpServerPropertiesCacheManager() override {
190
10830
    return server_.httpServerPropertiesCacheManager();
191
10830
  }
192
138851
  Event::Dispatcher& mainThreadDispatcher() override { return server_.dispatcher(); }
193
13940
  const Server::Options& options() override { return server_.options(); }
194
66756
  const LocalInfo::LocalInfo& localInfo() const override { return server_.localInfo(); }
195
19478
  ProtobufMessage::ValidationContext& messageValidationContext() override {
196
19478
    return server_.messageValidationContext();
197
19478
  }
198
186220
  Envoy::Runtime::Loader& runtime() override { return server_.runtime(); }
199
33929
  Stats::Scope& scope() override { return *server_scope_; }
200
39525
  Stats::Scope& serverScope() override { return *server_scope_; }
201
123687
  Singleton::Manager& singletonManager() override { return server_.singletonManager(); }
202
48723
  ThreadLocal::Instance& threadLocal() override { return server_.threadLocal(); }
203
30568
  OptRef<Admin> admin() override { return server_.admin(); }
204
54374
  TimeSource& timeSource() override { return api().timeSource(); }
205
20328
  AccessLog::AccessLogManager& accessLogManager() override { return server_.accessLogManager(); }
206
219347
  Api::Api& api() override { return server_.api(); }
207
43323
  Http::Context& httpContext() override { return server_.httpContext(); }
208
10859
  Grpc::Context& grpcContext() override { return server_.grpcContext(); }
209
31098
  Router::Context& routerContext() override { return server_.routerContext(); }
210
2
  ProcessContextOptRef processContext() override { return server_.processContext(); }
211
16
  Envoy::Server::DrainManager& drainManager() override { return server_.drainManager(); }
212
3190
  ServerLifecycleNotifier& lifecycleNotifier() override { return server_.lifecycleNotifier(); }
213
5565
  Regex::Engine& regexEngine() override { return server_.regexEngine(); }
214
17376
  Configuration::StatsConfig& statsConfig() override { return server_.statsConfig(); }
215
381
  envoy::config::bootstrap::v3::Bootstrap& bootstrap() override { return server_.bootstrap(); }
216
34220
  OverloadManager& overloadManager() override { return server_.overloadManager(); }
217
14
  OverloadManager& nullOverloadManager() override { return server_.nullOverloadManager(); }
218
522
  bool healthCheckFailed() const override { return server_.healthCheckFailed(); }
219
3144
  Ssl::ContextManager& sslContextManager() override { return server_.sslContextManager(); }
220
4588
  Secret::SecretManager& secretManager() override { return server_.secretManager(); }
221

            
222
  // Configuration::TransportSocketFactoryContext
223
  ServerFactoryContext& serverFactoryContext() override { return *this; }
224
  Stats::Scope& statsScope() override { return *server_scope_; }
225
424
  Init::Manager& initManager() override { return server_.initManager(); }
226
80739
  ProtobufMessage::ValidationVisitor& messageValidationVisitor() override {
227
80739
    return server_.messageValidationVisitor();
228
80739
  }
229

            
230
private:
231
  Instance& server_;
232
  Stats::ScopeSharedPtr server_scope_;
233
};
234

            
235
/**
236
 * This is the base class for the standalone server which stitches together various common
237
 * components. Some components are optional (so PURE) and can be created or not by subclasses.
238
 */
239
class InstanceBase : Logger::Loggable<Logger::Id::main>,
240
                     public Instance,
241
                     public ServerLifecycleNotifier {
242
public:
243
  /**
244
   * @throw EnvoyException if initialization fails.
245
   */
246
  InstanceBase(Init::Manager& init_manager, const Options& options, Event::TimeSystem& time_system,
247
               ListenerHooks& hooks, HotRestart& restarter, Stats::StoreRoot& store,
248
               Thread::BasicLockable& access_log_lock,
249
               Random::RandomGeneratorPtr&& random_generator, ThreadLocal::Instance& tls,
250
               Thread::ThreadFactory& thread_factory, Filesystem::Instance& file_system,
251
               std::unique_ptr<ProcessContext> process_context,
252
               Buffer::WatermarkFactorySharedPtr watermark_factory = nullptr);
253

            
254
  // initialize the server. This must be called before run().
255
  void initialize(Network::Address::InstanceConstSharedPtr local_address,
256
                  ComponentFactory& component_factory);
257
  ~InstanceBase() override;
258

            
259
  virtual void maybeCreateHeapShrinker() PURE;
260
  virtual absl::StatusOr<std::unique_ptr<OverloadManager>> createOverloadManager() PURE;
261
  virtual std::unique_ptr<OverloadManager> createNullOverloadManager() PURE;
262
  virtual std::unique_ptr<Server::GuardDog>
263
  maybeCreateGuardDog(absl::string_view name, const Server::Configuration::Watchdog& config) PURE;
264
  virtual std::unique_ptr<HdsDelegateApi>
265
  maybeCreateHdsDelegate(Configuration::ServerFactoryContext& server_context, Stats::Scope& scope,
266
                         Grpc::RawAsyncClientPtr&& async_client, Envoy::Stats::Store& stats,
267
                         Ssl::ContextManager& ssl_context_manager) PURE;
268

            
269
  void run() override;
270

            
271
  // Server::Instance
272
96850
  OptRef<Admin> admin() override { return makeOptRefFromPtr(admin_.get()); }
273
305152
  Api::Api& api() override { return *api_; }
274
  Upstream::ClusterManager& clusterManager() override;
275
  const Upstream::ClusterManager& clusterManager() const override;
276
10693
  Http::HttpServerPropertiesCacheManager& httpServerPropertiesCacheManager() override {
277
10693
    return *http_server_properties_cache_manager_;
278
10693
  }
279
47823
  Ssl::ContextManager& sslContextManager() override { return *ssl_context_manager_; }
280
237189
  Event::Dispatcher& dispatcher() override { return *dispatcher_; }
281
  Network::DnsResolverSharedPtr dnsResolver() override { return dns_resolver_; }
282
  void drainListeners(OptRef<const Network::ExtraShutdownListenerOptions> options) override;
283
47262
  DrainManager& drainManager() override { return *drain_manager_; }
284
20274
  AccessLog::AccessLogManager& accessLogManager() override { return access_log_manager_; }
285
  void failHealthcheck(bool fail) override;
286
12649
  HotRestart& hotRestart() override { return restarter_; }
287
56640
  Init::Manager& initManager() override { return init_manager_; }
288
3132
  ServerLifecycleNotifier& lifecycleNotifier() override { return *this; }
289
33312
  ListenerManager& listenerManager() override { return *listener_manager_; }
290
13323
  Secret::SecretManager& secretManager() override { return *secret_manager_; }
291
4
  Envoy::MutexTracer* mutexTracer() override { return mutex_tracer_; }
292
66357
  OverloadManager& overloadManager() override { return *overload_manager_; }
293
21918
  OverloadManager& nullOverloadManager() override { return *null_overload_manager_; }
294
  Runtime::Loader& runtime() override;
295
  void shutdown() override;
296
31539
  bool isShutdown() final { return shutdown_; }
297
  void shutdownAdmin() override;
298
122321
  Singleton::Manager& singletonManager() override { return singleton_manager_; }
299
  bool healthCheckFailed() override;
300
135334
  const Options& options() override { return options_; }
301
3
  time_t startTimeCurrentEpoch() override { return start_time_; }
302
3
  time_t startTimeFirstEpoch() override { return original_start_time_; }
303
150916
  Stats::Store& stats() override { return stats_store_; }
304
10724
  Grpc::Context& grpcContext() override { return grpc_context_; }
305
43496
  Http::Context& httpContext() override { return http_context_; }
306
30726
  Router::Context& routerContext() override { return router_context_; }
307
  ProcessContextOptRef processContext() override;
308
90844
  ThreadLocal::Instance& threadLocal() override { return thread_local_; }
309
77891
  LocalInfo::LocalInfo& localInfo() const override { return *local_info_; }
310
44347
  TimeSource& timeSource() override { return time_source_; }
311
  void flushStats() override;
312
17256
  Configuration::StatsConfig& statsConfig() override { return config_.statsConfig(); }
313
5591
  Regex::Engine& regexEngine() override { return *regex_engine_; }
314
11069
  envoy::config::bootstrap::v3::Bootstrap& bootstrap() override { return bootstrap_; }
315
395110
  Configuration::ServerFactoryContext& serverFactoryContext() override { return server_contexts_; }
316
  Configuration::TransportSocketFactoryContext& transportSocketFactoryContext() override {
317
    return server_contexts_;
318
  }
319
105169
  ProtobufMessage::ValidationContext& messageValidationContext() override {
320
105169
    return validation_context_;
321
105169
  }
322
80146
  ProtobufMessage::ValidationVisitor& messageValidationVisitor() override {
323
    // Server has two message validation visitors, one for static and
324
    // other for dynamic configuration. Choose the dynamic validation
325
    // visitor if server main dispatch loop started, as if all configuration
326
    // after main dispatch loop started should be dynamic.
327
80146
    return main_dispatch_loop_started_.load() ? validation_context_.dynamicValidationVisitor()
328
80146
                                              : validation_context_.staticValidationVisitor();
329
80146
  }
330
10667
  void setDefaultTracingConfig(const envoy::config::trace::v3::Tracing& tracing_config) override {
331
10667
    http_context_.setDefaultTracingConfig(tracing_config);
332
10667
  }
333
  bool enableReusePortDefault() override;
334

            
335
  Quic::QuicStatNames& quicStatNames() { return quic_stat_names_; }
336

            
337
  void setSinkPredicates(std::unique_ptr<Envoy::Stats::SinkPredicates>&& sink_predicates) override {
338
    stats_store_.setSinkPredicates(std::move(sink_predicates));
339
  }
340
33120
  Config::XdsManager& xdsManager() override { return *xds_manager_; }
341

            
342
  // ServerLifecycleNotifier
343
  ServerLifecycleNotifier::HandlePtr registerCallback(Stage stage, StageCallback callback) override;
344
  ServerLifecycleNotifier::HandlePtr
345
  registerCallback(Stage stage, StageCallbackWithCompletion callback) override;
346

            
347
private:
348
  Network::DnsResolverSharedPtr getOrCreateDnsResolver();
349

            
350
  ProtobufTypes::MessagePtr dumpBootstrapConfig();
351
  void flushStatsInternal();
352
  void updateServerStats();
353
  // This does most of the work of initialization, but can throw or return errors caught
354
  // by initialize().
355
  absl::Status initializeOrThrow(Network::Address::InstanceConstSharedPtr local_address,
356
                                 ComponentFactory& component_factory);
357
  void loadServerFlags(const absl::optional<std::string>& flags_path);
358
  void startWorkers();
359
  void terminate();
360
21088
  void notifyCallbacksForStage(Stage stage, std::function<void()> completion_cb = [] {});
361
  void onRuntimeReady();
362
  void onClusterManagerPrimaryInitializationComplete();
363
  using LifecycleNotifierCallbacks = std::list<StageCallback>;
364
  using LifecycleNotifierCompletionCallbacks = std::list<StageCallbackWithCompletion>;
365

            
366
  // init_manager_ must come before any member that participates in initialization, and destructed
367
  // only after referencing members are gone, since initialization continuation can potentially
368
  // occur at any point during member lifetime. This init manager is populated with LdsApi targets.
369
  Init::Manager& init_manager_;
370
  // secret_manager_ must come before listener_manager_, config_ and dispatcher_, and destructed
371
  // only after these members can no longer reference it, since:
372
  // - There may be active filter chains referencing it in listener_manager_.
373
  // - There may be active clusters referencing it in config_.cluster_manager_.
374
  // - There may be active connections referencing it.
375
  std::unique_ptr<Secret::SecretManager> secret_manager_;
376
  bool workers_started_{false};
377
  std::atomic<bool> live_;
378
  bool shutdown_{false};
379
  const Options& options_;
380
  ProtobufMessage::ProdValidationContextImpl validation_context_;
381
  std::atomic<bool> main_dispatch_loop_started_{false};
382
  TimeSource& time_source_;
383
  // Delete local_info_ as late as possible as some members below may reference it during their
384
  // destruction.
385
  LocalInfo::LocalInfoPtr local_info_;
386
  HotRestart& restarter_;
387
  const time_t start_time_;
388
  time_t original_start_time_;
389
  Stats::StoreRoot& stats_store_;
390
  std::unique_ptr<ServerStats> server_stats_;
391
  std::unique_ptr<CompilationSettings::ServerCompilationSettingsStats>
392
      server_compilation_settings_stats_;
393
  Assert::ActionRegistrationPtr assert_action_registration_;
394
  Assert::ActionRegistrationPtr envoy_bug_action_registration_;
395
  Assert::ActionRegistrationPtr envoy_notification_registration_;
396
  ThreadLocal::Instance& thread_local_;
397
  Random::RandomGeneratorPtr random_generator_;
398
  envoy::config::bootstrap::v3::Bootstrap bootstrap_;
399
  Api::ApiPtr api_;
400
  // ssl_context_manager_ must come before dispatcher_, since ClusterInfo
401
  // references SslSocketFactory and is deleted on the main thread via the dispatcher.
402
  std::unique_ptr<Ssl::ContextManager> ssl_context_manager_;
403
  Event::DispatcherPtr dispatcher_;
404
  AccessLog::AccessLogManagerImpl access_log_manager_;
405
  std::shared_ptr<Admin> admin_;
406
  Singleton::ManagerImpl singleton_manager_;
407
  Network::ConnectionHandlerPtr handler_;
408
  std::unique_ptr<Runtime::Loader> runtime_;
409
  ProdWorkerFactory worker_factory_;
410
  std::unique_ptr<ListenerManager> listener_manager_;
411
  absl::node_hash_map<Stage, LifecycleNotifierCallbacks> stage_callbacks_;
412
  absl::node_hash_map<Stage, LifecycleNotifierCompletionCallbacks> stage_completable_callbacks_;
413
  Configuration::MainImpl config_;
414
  Network::DnsResolverSharedPtr dns_resolver_;
415
  Event::TimerPtr stat_flush_timer_;
416
  DrainManagerPtr drain_manager_;
417
  std::unique_ptr<Upstream::ClusterManagerFactory> cluster_manager_factory_;
418
  std::unique_ptr<Server::GuardDog> main_thread_guard_dog_;
419
  std::unique_ptr<Server::GuardDog> worker_guard_dog_;
420
  bool terminated_{false};
421
  std::unique_ptr<Logger::FileSinkDelegate> file_logger_;
422
  ConfigTracker::EntryOwnerPtr config_tracker_entry_;
423
  SystemTime bootstrap_config_update_time_;
424
  Grpc::AsyncClientManagerPtr async_client_manager_;
425
  Config::XdsManagerPtr xds_manager_;
426
  std::unique_ptr<HdsDelegateApi> hds_delegate_;
427
  std::unique_ptr<OverloadManager> overload_manager_;
428
  std::unique_ptr<OverloadManager> null_overload_manager_;
429
  std::vector<BootstrapExtensionPtr> bootstrap_extensions_;
430
  std::unique_ptr<Http::HttpServerPropertiesCacheManager> http_server_properties_cache_manager_;
431
  Envoy::MutexTracer* mutex_tracer_;
432
  Grpc::ContextImpl grpc_context_;
433
  Http::ContextImpl http_context_;
434
  Router::ContextImpl router_context_;
435
  std::unique_ptr<ProcessContext> process_context_;
436
  // initialization_time is a histogram for tracking the initialization time across hot restarts
437
  // whenever we have support for histogram merge across hot restarts.
438
  Stats::TimespanPtr initialization_timer_;
439
  ListenerHooks& hooks_;
440
  Quic::QuicStatNames quic_stat_names_;
441
  ServerFactoryContextImpl server_contexts_;
442
  bool enable_reuse_port_default_{false};
443
  Regex::EnginePtr regex_engine_;
444
  bool stats_flush_in_progress_ : 1;
445
  std::unique_ptr<Memory::AllocatorManager> memory_allocator_manager_;
446

            
447
  template <class T>
448
  class LifecycleCallbackHandle : public ServerLifecycleNotifier::Handle, RaiiListElement<T> {
449
  public:
450
    LifecycleCallbackHandle(std::list<T>& callbacks, T& callback)
451
51
        : RaiiListElement<T>(callbacks, callback) {}
452
  };
453

            
454
  uint32_t stats_eviction_counter_{0};
455

            
456
#ifdef ENVOY_PERFETTO
457
  std::unique_ptr<perfetto::TracingSession> tracing_session_{};
458
  os_fd_t tracing_fd_{INVALID_HANDLE};
459
#endif
460
};
461

            
462
// Local implementation of Stats::MetricSnapshot used to flush metrics to sinks. We could
463
// potentially have a single class instance held in a static and have a clear() method to avoid some
464
// vector constructions and reservations, but I'm not sure it's worth the extra complexity until it
465
// shows up in perf traces.
466
// TODO(mattklein123): One thing we probably want to do is switch from returning vectors of metrics
467
//                     to a lambda based callback iteration API. This would require less vector
468
//                     copying and probably be a cleaner API in general.
469
class MetricSnapshotImpl : public Stats::MetricSnapshot {
470
public:
471
  // MetricSnapshotImpl captures a snapshot of metrics by latching the delta usage, and optionally
472
  // marking the stats as used.
473
  explicit MetricSnapshotImpl(Stats::Store& store, Upstream::ClusterManager& cluster_manager,
474
                              TimeSource& time_source);
475

            
476
  // Stats::MetricSnapshot
477
35
  const std::vector<CounterSnapshot>& counters() override { return counters_; }
478
39
  const std::vector<std::reference_wrapper<const Stats::Gauge>>& gauges() override {
479
39
    return gauges_;
480
39
  };
481
32
  const std::vector<std::reference_wrapper<const Stats::ParentHistogram>>& histograms() override {
482
32
    return histograms_;
483
32
  }
484
5
  const std::vector<std::reference_wrapper<const Stats::TextReadout>>& textReadouts() override {
485
5
    return text_readouts_;
486
5
  }
487
20
  const std::vector<Stats::PrimitiveCounterSnapshot>& hostCounters() override {
488
20
    return host_counters_;
489
20
  }
490
20
  const std::vector<Stats::PrimitiveGaugeSnapshot>& hostGauges() override { return host_gauges_; }
491
44
  SystemTime snapshotTime() const override { return snapshot_time_; }
492

            
493
private:
494
  std::vector<Stats::CounterSharedPtr> snapped_counters_;
495
  std::vector<CounterSnapshot> counters_;
496
  std::vector<Stats::GaugeSharedPtr> snapped_gauges_;
497
  std::vector<std::reference_wrapper<const Stats::Gauge>> gauges_;
498
  std::vector<Stats::ParentHistogramSharedPtr> snapped_histograms_;
499
  std::vector<std::reference_wrapper<const Stats::ParentHistogram>> histograms_;
500
  std::vector<Stats::TextReadoutSharedPtr> snapped_text_readouts_;
501
  std::vector<std::reference_wrapper<const Stats::TextReadout>> text_readouts_;
502
  std::vector<Stats::PrimitiveCounterSnapshot> host_counters_;
503
  std::vector<Stats::PrimitiveGaugeSnapshot> host_gauges_;
504
  SystemTime snapshot_time_;
505
};
506

            
507
} // namespace Server
508
} // namespace Envoy