diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 701d01bcd7f4e..b6c73aadb24b2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -29,6 +29,14 @@ We welcome contributions from the community. Here are some guidelines. * Global static non-pod variables are allowed because Envoy correctly joins all threads on exit. However, care is needed during init and static accessor functions may be required. * OOM events (both memory and FDs) are considered fatal crashing errors. +* Use your GitHub name in TODO comments, e.g. `TODO(foobar): blah`. +* Smart pointers are type aliased: + * `typedef std::unique_ptr FooPtr;` + * `typedef std::shared_ptr BarSharedPtr;` + * `typedef std::shareD_ptr BlahConstSharedPtr;` + * Regular pointers (e.g. `int* foo`) should not be type aliased. +* API-level comments should follow normal Doxygen conventions. Use `@param` to describe + parameters, `@return ` for return values. * There are probably a few other things missing from this list. We will add them as they are brought to our attention. diff --git a/include/envoy/access_log/access_log.h b/include/envoy/access_log/access_log.h index fa10a87c3c8d5..b83b370c3f212 100644 --- a/include/envoy/access_log/access_log.h +++ b/include/envoy/access_log/access_log.h @@ -19,7 +19,7 @@ class AccessLogManager { * @param file_name specifies the file to create/open. * @return the opened file. */ - virtual Filesystem::FilePtr createAccessLog(const std::string& file_name) PURE; + virtual Filesystem::FileSharedPtr createAccessLog(const std::string& file_name) PURE; }; typedef std::unique_ptr AccessLogManagerPtr; diff --git a/include/envoy/api/api.h b/include/envoy/api/api.h index 4fe6730dc5d2f..dda965ca087c9 100644 --- a/include/envoy/api/api.h +++ b/include/envoy/api/api.h @@ -25,9 +25,10 @@ class Api { * @param dispatcher supplies the dispatcher uses for async flushing. * @param lock supplies the lock to use for cross thread appends. */ - virtual Filesystem::FilePtr createFile(const std::string& path, Event::Dispatcher& dispatcher, - Thread::BasicLockable& lock, - Stats::Store& stats_store) PURE; + virtual Filesystem::FileSharedPtr createFile(const std::string& path, + Event::Dispatcher& dispatcher, + Thread::BasicLockable& lock, + Stats::Store& stats_store) PURE; /** * @return bool whether a file exists and can be opened for read on disk. diff --git a/include/envoy/event/dispatcher.h b/include/envoy/event/dispatcher.h index 8102f12ab9147..9fd02ae268d3e 100644 --- a/include/envoy/event/dispatcher.h +++ b/include/envoy/event/dispatcher.h @@ -37,7 +37,7 @@ class Dispatcher { * @return Network::ClientConnectionPtr a client connection that is owned by the caller. */ virtual Network::ClientConnectionPtr - createClientConnection(Network::Address::InstancePtr address) PURE; + createClientConnection(Network::Address::InstanceConstSharedPtr address) PURE; /** * Create an SSL client connection. @@ -47,7 +47,7 @@ class Dispatcher { */ virtual Network::ClientConnectionPtr createSslClientConnection(Ssl::ClientContext& ssl_ctx, - Network::Address::InstancePtr address) PURE; + Network::Address::InstanceConstSharedPtr address) PURE; /** * Create an async DNS resolver. Only a single resolver can exist in the process at a time and it diff --git a/include/envoy/filesystem/filesystem.h b/include/envoy/filesystem/filesystem.h index 7a43bc5053172..28d8781d280b2 100644 --- a/include/envoy/filesystem/filesystem.h +++ b/include/envoy/filesystem/filesystem.h @@ -47,7 +47,7 @@ class File { virtual void reopen() PURE; }; -typedef std::shared_ptr FilePtr; +typedef std::shared_ptr FileSharedPtr; /** * Abstraction for a file watcher. diff --git a/include/envoy/http/access_log.h b/include/envoy/http/access_log.h index d136ef6053b51..968b56a6fd986 100644 --- a/include/envoy/http/access_log.h +++ b/include/envoy/http/access_log.h @@ -52,7 +52,7 @@ class RequestInfo { /** * Filter can trigger this callback when an upstream host has been selected. */ - virtual void onUpstreamHostSelected(Upstream::HostDescriptionPtr host) PURE; + virtual void onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) PURE; /** * @return the time that the first byte of the request was received. @@ -97,7 +97,7 @@ class RequestInfo { /** * @return upstream host description. */ - virtual Upstream::HostDescriptionPtr upstreamHost() const PURE; + virtual Upstream::HostDescriptionConstSharedPtr upstreamHost() const PURE; /** * @return whether the request is a health check request or not. @@ -144,7 +144,7 @@ class Instance { const RequestInfo& request_info) PURE; }; -typedef std::shared_ptr InstancePtr; +typedef std::shared_ptr InstanceSharedPtr; /** * Interface for access log formatter. diff --git a/include/envoy/http/conn_pool.h b/include/envoy/http/conn_pool.h index 512a76d37b70b..3b0ee2358ad3f 100644 --- a/include/envoy/http/conn_pool.h +++ b/include/envoy/http/conn_pool.h @@ -45,7 +45,8 @@ class Callbacks { * @param host supplies the description of the host that caused the failure. This may be nullptr * if no host was involved in the failure (for example overflow). */ - virtual void onPoolFailure(PoolFailureReason reason, Upstream::HostDescriptionPtr host) PURE; + virtual void onPoolFailure(PoolFailureReason reason, + Upstream::HostDescriptionConstSharedPtr host) PURE; /** * Called when a connection is available to process a request/response. @@ -53,7 +54,8 @@ class Callbacks { * @param host supplies the description of the host that will carry the request. For logical * connection pools the description may be different each time this is called. */ - virtual void onPoolReady(Http::StreamEncoder& encoder, Upstream::HostDescriptionPtr host) PURE; + virtual void onPoolReady(Http::StreamEncoder& encoder, + Upstream::HostDescriptionConstSharedPtr host) PURE; }; /** diff --git a/include/envoy/http/filter.h b/include/envoy/http/filter.h index 127c4ad4c149d..36492c57aae4a 100644 --- a/include/envoy/http/filter.h +++ b/include/envoy/http/filter.h @@ -99,7 +99,7 @@ class StreamFilterCallbacks { * knows that it has modified the headers in a way that would affect routing. In the future * we may also want to allow the filter to override the route entry. */ - virtual Router::RoutePtr route() PURE; + virtual Router::RouteConstSharedPtr route() PURE; /** * @return uint64_t the ID of the originating stream for logging purposes. @@ -202,7 +202,7 @@ class StreamDecoderFilter { virtual void setDecoderFilterCallbacks(StreamDecoderFilterCallbacks& callbacks) PURE; }; -typedef std::shared_ptr StreamDecoderFilterPtr; +typedef std::shared_ptr StreamDecoderFilterSharedPtr; /** * Stream encoder filter callbacks add additional callbacks that allow a encoding filter to restart @@ -264,14 +264,14 @@ class StreamEncoderFilter { virtual void setEncoderFilterCallbacks(StreamEncoderFilterCallbacks& callbacks) PURE; }; -typedef std::shared_ptr StreamEncoderFilterPtr; +typedef std::shared_ptr StreamEncoderFilterSharedPtr; /** * A filter that handles both encoding and decoding. */ class StreamFilter : public StreamDecoderFilter, public StreamEncoderFilter {}; -typedef std::shared_ptr StreamFilterPtr; +typedef std::shared_ptr StreamFilterSharedPtr; /** * These callbacks are provided by the connection manager to the factory so that the factory can @@ -285,25 +285,25 @@ class FilterChainFactoryCallbacks { * Add a decoder filter that is used when reading stream data. * @param filter supplies the filter to add. */ - virtual void addStreamDecoderFilter(Http::StreamDecoderFilterPtr filter) PURE; + virtual void addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr filter) PURE; /** * Add an encoder filter that is used when writing stream data. * @param filter supplies the filter to add. */ - virtual void addStreamEncoderFilter(Http::StreamEncoderFilterPtr filter) PURE; + virtual void addStreamEncoderFilter(Http::StreamEncoderFilterSharedPtr filter) PURE; /** * Add a decoder/encoder filter that is used both when reading and writing stream data. * @param filter supplies the filter to add. */ - virtual void addStreamFilter(Http::StreamFilterPtr filter) PURE; + virtual void addStreamFilter(Http::StreamFilterSharedPtr filter) PURE; /** * Add an access log handler that is called when the stream is destroyed. * @param handler supplies the handler to add. */ - virtual void addAccessLogHandler(Http::AccessLog::InstancePtr handler) PURE; + virtual void addAccessLogHandler(Http::AccessLog::InstanceSharedPtr handler) PURE; }; /** diff --git a/include/envoy/local_info/local_info.h b/include/envoy/local_info/local_info.h index 18bd0a5bfdeb9..8bebb644dbbdc 100644 --- a/include/envoy/local_info/local_info.h +++ b/include/envoy/local_info/local_info.h @@ -15,7 +15,7 @@ class LocalInfo { /** * @return the local (non-loopback) address of the server. */ - virtual Network::Address::InstancePtr address() const PURE; + virtual Network::Address::InstanceConstSharedPtr address() const PURE; /** * Human readable zone name. E.g., "us-east-1a". diff --git a/include/envoy/mongo/bson.h b/include/envoy/mongo/bson.h index 0bc003edb1332..8216740bf2cda 100644 --- a/include/envoy/mongo/bson.h +++ b/include/envoy/mongo/bson.h @@ -9,7 +9,7 @@ namespace Bson { class Document; -typedef std::shared_ptr DocumentPtr; +typedef std::shared_ptr DocumentSharedPtr; /** * A BSON document field. This is essentially a variably typed parameter that can be "cast" to @@ -85,19 +85,19 @@ class Document { public: virtual ~Document() {} - virtual DocumentPtr addDouble(const std::string& key, double value) PURE; - virtual DocumentPtr addString(const std::string& key, std::string&& value) PURE; - virtual DocumentPtr addDocument(const std::string& key, DocumentPtr value) PURE; - virtual DocumentPtr addArray(const std::string& key, DocumentPtr value) PURE; - virtual DocumentPtr addBinary(const std::string& key, std::string&& value) PURE; - virtual DocumentPtr addObjectId(const std::string& key, Field::ObjectId&& value) PURE; - virtual DocumentPtr addBoolean(const std::string& key, bool value) PURE; - virtual DocumentPtr addDatetime(const std::string& key, int64_t value) PURE; - virtual DocumentPtr addNull(const std::string& key) PURE; - virtual DocumentPtr addRegex(const std::string& key, Field::Regex&& value) PURE; - virtual DocumentPtr addInt32(const std::string& key, int32_t value) PURE; - virtual DocumentPtr addTimestamp(const std::string& key, int64_t value) PURE; - virtual DocumentPtr addInt64(const std::string& key, int64_t value) PURE; + virtual DocumentSharedPtr addDouble(const std::string& key, double value) PURE; + virtual DocumentSharedPtr addString(const std::string& key, std::string&& value) PURE; + virtual DocumentSharedPtr addDocument(const std::string& key, DocumentSharedPtr value) PURE; + virtual DocumentSharedPtr addArray(const std::string& key, DocumentSharedPtr value) PURE; + virtual DocumentSharedPtr addBinary(const std::string& key, std::string&& value) PURE; + virtual DocumentSharedPtr addObjectId(const std::string& key, Field::ObjectId&& value) PURE; + virtual DocumentSharedPtr addBoolean(const std::string& key, bool value) PURE; + virtual DocumentSharedPtr addDatetime(const std::string& key, int64_t value) PURE; + virtual DocumentSharedPtr addNull(const std::string& key) PURE; + virtual DocumentSharedPtr addRegex(const std::string& key, Field::Regex&& value) PURE; + virtual DocumentSharedPtr addInt32(const std::string& key, int32_t value) PURE; + virtual DocumentSharedPtr addTimestamp(const std::string& key, int64_t value) PURE; + virtual DocumentSharedPtr addInt64(const std::string& key, int64_t value) PURE; virtual bool operator==(const Document& rhs) const PURE; virtual int32_t byteSize() const PURE; diff --git a/include/envoy/mongo/codec.h b/include/envoy/mongo/codec.h index 6feb577ccd7f8..28d0df6986152 100644 --- a/include/envoy/mongo/codec.h +++ b/include/envoy/mongo/codec.h @@ -58,8 +58,8 @@ class InsertMessage : public virtual Message { virtual void flags(int32_t flags) PURE; virtual const std::string& fullCollectionName() const PURE; virtual void fullCollectionName(const std::string& name) PURE; - virtual const std::list& documents() const PURE; - virtual std::list& documents() PURE; + virtual const std::list& documents() const PURE; + virtual std::list& documents() PURE; }; typedef std::unique_ptr InsertMessagePtr; @@ -104,9 +104,9 @@ class QueryMessage : public virtual Message { virtual int32_t numberToReturn() const PURE; virtual void numberToReturn(int32_t to_return) PURE; virtual const Bson::Document* query() const PURE; - virtual void query(Bson::DocumentPtr&& query) PURE; + virtual void query(Bson::DocumentSharedPtr&& query) PURE; virtual const Bson::Document* returnFieldsSelector() const PURE; - virtual void returnFieldsSelector(Bson::DocumentPtr&& fields) PURE; + virtual void returnFieldsSelector(Bson::DocumentSharedPtr&& fields) PURE; }; typedef std::unique_ptr QueryMessagePtr; @@ -133,8 +133,8 @@ class ReplyMessage : public virtual Message { virtual void startingFrom(int32_t starting_from) PURE; virtual int32_t numberReturned() const PURE; virtual void numberReturned(int32_t number_returned) PURE; - virtual const std::list& documents() const PURE; - virtual std::list& documents() PURE; + virtual const std::list& documents() const PURE; + virtual std::list& documents() PURE; }; typedef std::unique_ptr ReplyMessagePtr; diff --git a/include/envoy/network/address.h b/include/envoy/network/address.h index 702242696dedb..7fd166f2fb609 100644 --- a/include/envoy/network/address.h +++ b/include/envoy/network/address.h @@ -128,7 +128,7 @@ class Instance { virtual Type type() const PURE; }; -typedef std::shared_ptr InstancePtr; +typedef std::shared_ptr InstanceConstSharedPtr; } // Address } // Network diff --git a/include/envoy/network/dns.h b/include/envoy/network/dns.h index 74327df544ab3..88c00598576c9 100644 --- a/include/envoy/network/dns.h +++ b/include/envoy/network/dns.h @@ -30,7 +30,7 @@ class DnsResolver { * @param address_list supplies the list of resolved IP addresses. The list will be empty if * the resolution failed. */ - typedef std::function&& address_list)> ResolveCb; + typedef std::function&& address_list)> ResolveCb; /** * Initiate an async DNS resolution. diff --git a/include/envoy/network/filter.h b/include/envoy/network/filter.h index 1646c3105b208..ff53637b804bc 100644 --- a/include/envoy/network/filter.h +++ b/include/envoy/network/filter.h @@ -32,7 +32,7 @@ class WriteFilter { virtual FilterStatus onWrite(Buffer::Instance& data) PURE; }; -typedef std::shared_ptr WriteFilterPtr; +typedef std::shared_ptr WriteFilterSharedPtr; /** * Callbacks used by individual read filter instances to communicate with the filter manager. @@ -58,12 +58,12 @@ class ReadFilterCallbacks { * between multiple network level filters, for example the TCP proxy filter communicating its * selection to another filter for logging. */ - virtual Upstream::HostDescriptionPtr upstreamHost() PURE; + virtual Upstream::HostDescriptionConstSharedPtr upstreamHost() PURE; /** * Set the currently selected upstream host for the connection. */ - virtual void upstreamHost(Upstream::HostDescriptionPtr host) PURE; + virtual void upstreamHost(Upstream::HostDescriptionConstSharedPtr host) PURE; }; /** @@ -102,14 +102,14 @@ class ReadFilter { virtual void initializeReadFilterCallbacks(ReadFilterCallbacks& callbacks) PURE; }; -typedef std::shared_ptr ReadFilterPtr; +typedef std::shared_ptr ReadFilterSharedPtr; /** * A combination read and write filter. This allows a single filter instance to cover * both the read and write paths. */ class Filter : public WriteFilter, public ReadFilter {}; -typedef std::shared_ptr FilterPtr; +typedef std::shared_ptr FilterSharedPtr; /** * Interface for adding individual network filters to a manager. @@ -122,19 +122,19 @@ class FilterManager { * Add a write filter to the connection. Filters are invoked in LIFO order (the last added * filter is called first). */ - virtual void addWriteFilter(WriteFilterPtr filter) PURE; + virtual void addWriteFilter(WriteFilterSharedPtr filter) PURE; /** * Add a combination filter to the connection. Equivalent to calling both addWriteFilter() * and addReadFilter() with the same filter instance. */ - virtual void addFilter(FilterPtr filter) PURE; + virtual void addFilter(FilterSharedPtr filter) PURE; /** * Add a read filter to the connection. Filters are invoked in FIFO order (the filter added * first is called first). */ - virtual void addReadFilter(ReadFilterPtr filter) PURE; + virtual void addReadFilter(ReadFilterSharedPtr filter) PURE; /** * Initialize all of the installed read filters. This effectively calls onNewConnection() on diff --git a/include/envoy/network/listen_socket.h b/include/envoy/network/listen_socket.h index a375ee87330e7..574f7ce8c1196 100644 --- a/include/envoy/network/listen_socket.h +++ b/include/envoy/network/listen_socket.h @@ -15,7 +15,7 @@ class ListenSocket { /** * @return the address that the socket is listening on. */ - virtual Address::InstancePtr localAddress() PURE; + virtual Address::InstanceConstSharedPtr localAddress() PURE; /** * @return fd the listen socket's file descriptor. diff --git a/include/envoy/redis/conn_pool.h b/include/envoy/redis/conn_pool.h index 16b19d828935c..a783a0652b755 100644 --- a/include/envoy/redis/conn_pool.h +++ b/include/envoy/redis/conn_pool.h @@ -77,7 +77,7 @@ class ClientFactory { /** * Create a client given an upstream host. */ - virtual ClientPtr create(Upstream::ConstHostPtr host, Event::Dispatcher& dispatcher) PURE; + virtual ClientPtr create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher) PURE; }; /** diff --git a/include/envoy/router/rds.h b/include/envoy/router/rds.h index 38099865ed596..5531b50190e44 100644 --- a/include/envoy/router/rds.h +++ b/include/envoy/router/rds.h @@ -12,11 +12,12 @@ class RouteConfigProvider { virtual ~RouteConfigProvider() {} /** - * @return Router::ConfigPtr a route configuration for use during a single request. The returned + * @return Router::ConfigConstSharedPtr a route configuration for use during a single request. The + * returned * config may be different on a subsequent call, so a new config should be acquired for * each request flow. */ - virtual Router::ConfigPtr config() PURE; + virtual Router::ConfigConstSharedPtr config() PURE; }; typedef std::unique_ptr RouteConfigProviderPtr; diff --git a/include/envoy/router/router.h b/include/envoy/router/router.h index 05ad97306e119..fb7de37548d3c 100644 --- a/include/envoy/router/router.h +++ b/include/envoy/router/router.h @@ -251,7 +251,7 @@ class Route { virtual const RouteEntry* routeEntry() const PURE; }; -typedef std::shared_ptr RoutePtr; +typedef std::shared_ptr RouteConstSharedPtr; /** * The router configuration. @@ -268,7 +268,8 @@ class Config { * allows stable choices between calls if desired. * @return the route or nullptr if there is no matching route for the request. */ - virtual RoutePtr route(const Http::HeaderMap& headers, uint64_t random_value) const PURE; + virtual RouteConstSharedPtr route(const Http::HeaderMap& headers, + uint64_t random_value) const PURE; /** * Return a list of headers that will be cleaned from any requests that are not from an internal @@ -297,6 +298,6 @@ class Config { virtual bool usesRuntime() const PURE; }; -typedef std::shared_ptr ConfigPtr; +typedef std::shared_ptr ConfigConstSharedPtr; } // Router diff --git a/include/envoy/server/configuration.h b/include/envoy/server/configuration.h index dffa7a34720c8..f68efe6e18cbc 100644 --- a/include/envoy/server/configuration.h +++ b/include/envoy/server/configuration.h @@ -23,9 +23,9 @@ class Listener { virtual Network::FilterChainFactory& filterChainFactory() PURE; /** - * @return Network::Address::InstancePtr the address. + * @return Network::Address::InstanceConstSharedPtr the address. */ - virtual Network::Address::InstancePtr address() PURE; + virtual Network::Address::InstanceConstSharedPtr address() PURE; /** * @return Ssl::ServerContext* the SSL context @@ -147,9 +147,9 @@ class Admin { virtual const std::string& accessLogPath() PURE; /** - * @return Network::Address::InstancePtr the server address. + * @return Network::Address::InstanceConstSharedPtr the server address. */ - virtual Network::Address::InstancePtr address() PURE; + virtual Network::Address::InstanceConstSharedPtr address() PURE; }; /** diff --git a/include/envoy/stats/stats.h b/include/envoy/stats/stats.h index 10f2ad6d06de8..e04e2c973798d 100644 --- a/include/envoy/stats/stats.h +++ b/include/envoy/stats/stats.h @@ -29,7 +29,7 @@ class Counter { virtual uint64_t value() PURE; }; -typedef std::shared_ptr CounterPtr; +typedef std::shared_ptr CounterSharedPtr; /** * A gauge that can both increment and decrement. @@ -48,7 +48,7 @@ class Gauge { virtual uint64_t value() PURE; }; -typedef std::shared_ptr GaugePtr; +typedef std::shared_ptr GaugeSharedPtr; /** * An individual timespan that is owned by a timer. The initial time is captured on construction. @@ -84,7 +84,7 @@ class Timer { virtual std::string name() PURE; }; -typedef std::shared_ptr TimerPtr; +typedef std::shared_ptr TimerSharedPtr; /** * A sink for stats. Each sink is responsible for writing stats to a backing store. @@ -168,12 +168,12 @@ class Store : public Scope { /** * @return a list of all known counters. */ - virtual std::list counters() const PURE; + virtual std::list counters() const PURE; /** * @return a list of all known gauges. */ - virtual std::list gauges() const PURE; + virtual std::list gauges() const PURE; }; /** diff --git a/include/envoy/thread_local/thread_local.h b/include/envoy/thread_local/thread_local.h index 4e777f9150d08..e175d36094e8e 100644 --- a/include/envoy/thread_local/thread_local.h +++ b/include/envoy/thread_local/thread_local.h @@ -19,7 +19,7 @@ class ThreadLocalObject { virtual void shutdown() PURE; }; -typedef std::shared_ptr ThreadLocalObjectPtr; +typedef std::shared_ptr ThreadLocalObjectSharedPtr; /** * Interface for getting and setting thread local data as well as registering a thread @@ -36,7 +36,7 @@ class Instance { /** * Get a thread local index stored in the specified slot ID. */ - virtual ThreadLocalObjectPtr get(uint32_t index) PURE; + virtual ThreadLocalObjectSharedPtr get(uint32_t index) PURE; /** * This is a helper on top of get() that casts the object stored in the slot to the specified @@ -69,7 +69,7 @@ class Instance { * a shared_ptr. Thus, this is a flexible mechanism that can be used to share * the same data across all threads or to share different data on each thread. */ - typedef std::function InitializeCb; + typedef std::function InitializeCb; virtual void set(uint32_t index, InitializeCb cb) PURE; /** diff --git a/include/envoy/upstream/cluster_manager.h b/include/envoy/upstream/cluster_manager.h index 84fb0ac631fdb..74ad3c461f161 100644 --- a/include/envoy/upstream/cluster_manager.h +++ b/include/envoy/upstream/cluster_manager.h @@ -41,7 +41,8 @@ class ClusterManager { virtual ClusterInfoMap clusters() PURE; /** - * @return ClusterInfoPtr the thread local cluster with the given name or nullptr if it does not + * @return ClusterInfoConstSharedPtr the thread local cluster with the given name or nullptr if it + *does not * exist. This is thread safe. * * NOTE: The pointer returned by this function is ONLY safe to use in the context of the owning @@ -136,7 +137,7 @@ class ClusterManagerFactory { * Allocate an HTTP connection pool. */ virtual Http::ConnectionPool::InstancePtr allocateConnPool(Event::Dispatcher& dispatcher, - ConstHostPtr host, + HostConstSharedPtr host, ResourcePriority priority) PURE; /** @@ -144,7 +145,7 @@ class ClusterManagerFactory { */ virtual ClusterPtr clusterFromJson(const Json::Object& cluster, ClusterManager& cm, const Optional& sds_config, - Outlier::EventLoggerPtr outlier_event_logger) PURE; + Outlier::EventLoggerSharedPtr outlier_event_logger) PURE; /** * Create a CDS API provider from configuration JSON. diff --git a/include/envoy/upstream/health_checker.h b/include/envoy/upstream/health_checker.h index 5c24ce6190ed9..07d4b981d8ce2 100644 --- a/include/envoy/upstream/health_checker.h +++ b/include/envoy/upstream/health_checker.h @@ -17,7 +17,7 @@ class HealthChecker { * @param changed_state supplies whether the health check resulted in a host moving from healthy * to not healthy or vice versa. */ - typedef std::function HostStatusCb; + typedef std::function HostStatusCb; /** * Install a callback that will be invoked every time a health check round is completed for diff --git a/include/envoy/upstream/host_description.h b/include/envoy/upstream/host_description.h index 00d73c3d50405..4fecf92ed128a 100644 --- a/include/envoy/upstream/host_description.h +++ b/include/envoy/upstream/host_description.h @@ -59,7 +59,7 @@ class HostDescription { /** * @return the address used to connect to the host. */ - virtual Network::Address::InstancePtr address() const PURE; + virtual Network::Address::InstanceConstSharedPtr address() const PURE; /** * @return host specific stats. @@ -72,6 +72,6 @@ class HostDescription { virtual const std::string& zone() const PURE; }; -typedef std::shared_ptr HostDescriptionPtr; +typedef std::shared_ptr HostDescriptionConstSharedPtr; } // Upstream diff --git a/include/envoy/upstream/load_balancer.h b/include/envoy/upstream/load_balancer.h index 9d97748f1ac02..ba0cc41fd2411 100644 --- a/include/envoy/upstream/load_balancer.h +++ b/include/envoy/upstream/load_balancer.h @@ -32,7 +32,7 @@ class LoadBalancer { * context information. Load balancers should be written to assume that context information * is missing and use sensible defaults. */ - virtual ConstHostPtr chooseHost(const LoadBalancerContext* context) PURE; + virtual HostConstSharedPtr chooseHost(const LoadBalancerContext* context) PURE; }; typedef std::unique_ptr LoadBalancerPtr; diff --git a/include/envoy/upstream/outlier_detection.h b/include/envoy/upstream/outlier_detection.h index fc8dc8be49e72..263639f1dabd2 100644 --- a/include/envoy/upstream/outlier_detection.h +++ b/include/envoy/upstream/outlier_detection.h @@ -7,10 +7,10 @@ namespace Upstream { class Host; -typedef std::shared_ptr HostPtr; +typedef std::shared_ptr HostSharedPtr; class HostDescription; -typedef std::shared_ptr HostDescriptionPtr; +typedef std::shared_ptr HostDescriptionConstSharedPtr; namespace Outlier { @@ -66,16 +66,16 @@ class EventLogger { * @param host supplies the host that generated the event. * @param type supplies the type of the event. */ - virtual void logEject(HostDescriptionPtr host, EjectionType type) PURE; + virtual void logEject(HostDescriptionConstSharedPtr host, EjectionType type) PURE; /** * Log an unejection event. * @param host supplies the host that generated the event. */ - virtual void logUneject(HostDescriptionPtr host) PURE; + virtual void logUneject(HostDescriptionConstSharedPtr host) PURE; }; -typedef std::shared_ptr EventLoggerPtr; +typedef std::shared_ptr EventLoggerSharedPtr; /** * Interface for an outlier detection engine. Uses per host data to determine which hosts in a @@ -88,7 +88,7 @@ class Detector { /** * Outlier detection change state callback. */ - typedef std::function ChangeStateCb; + typedef std::function ChangeStateCb; /** * Add a changed state callback to the detector. The callback will be called whenever any host @@ -97,7 +97,7 @@ class Detector { virtual void addChangedStateCb(ChangeStateCb cb) PURE; }; -typedef std::shared_ptr DetectorPtr; +typedef std::shared_ptr DetectorSharedPtr; } // Outlier } // Upstream diff --git a/include/envoy/upstream/thread_local_cluster.h b/include/envoy/upstream/thread_local_cluster.h index 257fd4068dac0..98128fb34c460 100644 --- a/include/envoy/upstream/thread_local_cluster.h +++ b/include/envoy/upstream/thread_local_cluster.h @@ -18,10 +18,11 @@ class ThreadLocalCluster { virtual const HostSet& hostSet() PURE; /** - * @return ClusterInfoPtr the info for this cluster. The info is safe to store beyond the + * @return ClusterInfoConstSharedPtr the info for this cluster. The info is safe to store beyond + * the * lifetime of the ThreadLocalCluster instance itself. */ - virtual ClusterInfoPtr info() PURE; + virtual ClusterInfoConstSharedPtr info() PURE; /** * @return LoadBalancer& the backing load balancer. diff --git a/include/envoy/upstream/upstream.h b/include/envoy/upstream/upstream.h index b4dbcd0a97e97..9ac2bb5c05ae4 100644 --- a/include/envoy/upstream/upstream.h +++ b/include/envoy/upstream/upstream.h @@ -15,7 +15,7 @@ class Host : virtual public HostDescription { public: struct CreateConnectionData { Network::ClientConnectionPtr connection_; - HostDescriptionPtr host_description_; + HostDescriptionConstSharedPtr host_description_; }; enum class HealthFlag { @@ -28,7 +28,7 @@ class Host : virtual public HostDescription { /** * @return host specific counters. */ - virtual std::list counters() const PURE; + virtual std::list counters() const PURE; /** * Create a connection for this host. @@ -44,7 +44,7 @@ class Host : virtual public HostDescription { /** * @return host specific gauges. */ - virtual std::list gauges() const PURE; + virtual std::list gauges() const PURE; /** * Atomically clear a health flag for a host. Flags are specified in HealthFlags. @@ -85,7 +85,7 @@ class Host : virtual public HostDescription { virtual void weight(uint32_t new_weight) PURE; }; -typedef std::shared_ptr ConstHostPtr; +typedef std::shared_ptr HostConstSharedPtr; /** * Base host set interface. This is used both for clusters, as well as per thread/worker host sets @@ -100,8 +100,8 @@ class HostSet { * @param hosts_added supplies the newly added hosts, if any. * @param hosts_removed supplies the removed hosts, if any. */ - typedef std::function& hosts_added, - const std::vector& hosts_removed)> MemberUpdateCb; + typedef std::function& hosts_added, + const std::vector& hosts_removed)> MemberUpdateCb; /** * Install a callback that will be invoked when the cluster membership changes. @@ -112,7 +112,7 @@ class HostSet { /** * @return all hosts that make up the set at the current time. */ - virtual const std::vector& hosts() const PURE; + virtual const std::vector& hosts() const PURE; /** * @return all healthy hosts contained in the set at the current time. NOTE: This set is @@ -120,7 +120,7 @@ class HostSet { * unhealthy and calling healthy() on it will return false. Code should be written to * deal with this case if it matters. */ - virtual const std::vector& healthyHosts() const PURE; + virtual const std::vector& healthyHosts() const PURE; /** * @return hosts per zone, index 0 is dedicated to local zone hosts. @@ -129,12 +129,12 @@ class HostSet { * * Note, that we sort zones in alphabetical order starting from index 1. */ - virtual const std::vector>& hostsPerZone() const PURE; + virtual const std::vector>& hostsPerZone() const PURE; /** * @return same as hostsPerZone but only contains healthy hosts. */ - virtual const std::vector>& healthyHostsPerZone() const PURE; + virtual const std::vector>& healthyHostsPerZone() const PURE; }; /** @@ -285,7 +285,7 @@ class ClusterInfo { virtual Stats::Scope& statsScope() const PURE; }; -typedef std::shared_ptr ClusterInfoPtr; +typedef std::shared_ptr ClusterInfoConstSharedPtr; /** * An upstream cluster (group of hosts). This class is the "primary" singleton cluster used amongst @@ -298,7 +298,7 @@ class Cluster : public virtual HostSet { /** * @return the information about this upstream cluster. */ - virtual ClusterInfoPtr info() const PURE; + virtual ClusterInfoConstSharedPtr info() const PURE; /** * Initialize the cluster. This will be called either immediately at creation or after all primary diff --git a/source/common/access_log/access_log_manager_impl.cc b/source/common/access_log/access_log_manager_impl.cc index 3b2f413706f6a..f3220d2c1b27d 100644 --- a/source/common/access_log/access_log_manager_impl.cc +++ b/source/common/access_log/access_log_manager_impl.cc @@ -8,7 +8,7 @@ void AccessLogManagerImpl::reopen() { } } -Filesystem::FilePtr AccessLogManagerImpl::createAccessLog(const std::string& file_name) { +Filesystem::FileSharedPtr AccessLogManagerImpl::createAccessLog(const std::string& file_name) { if (access_logs_.count(file_name)) { return access_logs_[file_name]; } diff --git a/source/common/access_log/access_log_manager_impl.h b/source/common/access_log/access_log_manager_impl.h index ab1be3adf6ef1..060d1787fd967 100644 --- a/source/common/access_log/access_log_manager_impl.h +++ b/source/common/access_log/access_log_manager_impl.h @@ -13,14 +13,14 @@ class AccessLogManagerImpl : public AccessLogManager { // AccessLog::AccessLogManager void reopen() override; - Filesystem::FilePtr createAccessLog(const std::string& file_name) override; + Filesystem::FileSharedPtr createAccessLog(const std::string& file_name) override; private: Api::Api& api_; Event::Dispatcher& dispatcher_; Thread::BasicLockable& lock_; Stats::Store& stats_store_; - std::unordered_map access_logs_; + std::unordered_map access_logs_; }; } // AccessLog diff --git a/source/common/api/api_impl.cc b/source/common/api/api_impl.cc index 542979675a32f..f69f61d759e17 100644 --- a/source/common/api/api_impl.cc +++ b/source/common/api/api_impl.cc @@ -13,10 +13,10 @@ Impl::Impl(std::chrono::milliseconds file_flush_interval_msec) : os_sys_calls_(new Filesystem::OsSysCallsImpl()), file_flush_interval_msec_(file_flush_interval_msec) {} -Filesystem::FilePtr Impl::createFile(const std::string& path, Event::Dispatcher& dispatcher, - Thread::BasicLockable& lock, Stats::Store& stats_store) { - return Filesystem::FilePtr{new Filesystem::FileImpl(path, dispatcher, lock, *os_sys_calls_, - stats_store, file_flush_interval_msec_)}; +Filesystem::FileSharedPtr Impl::createFile(const std::string& path, Event::Dispatcher& dispatcher, + Thread::BasicLockable& lock, Stats::Store& stats_store) { + return Filesystem::FileSharedPtr{new Filesystem::FileImpl( + path, dispatcher, lock, *os_sys_calls_, stats_store, file_flush_interval_msec_)}; } bool Impl::fileExists(const std::string& path) { return Filesystem::fileExists(path); } diff --git a/source/common/api/api_impl.h b/source/common/api/api_impl.h index bf52424ae74ec..35f88530845f0 100644 --- a/source/common/api/api_impl.h +++ b/source/common/api/api_impl.h @@ -14,8 +14,9 @@ class Impl : public Api::Api { // Api::Api Event::DispatcherPtr allocateDispatcher() override; - Filesystem::FilePtr createFile(const std::string& path, Event::Dispatcher& dispatcher, - Thread::BasicLockable& lock, Stats::Store& stats_store) override; + Filesystem::FileSharedPtr createFile(const std::string& path, Event::Dispatcher& dispatcher, + Thread::BasicLockable& lock, + Stats::Store& stats_store) override; bool fileExists(const std::string& path) override; std::string fileReadToEnd(const std::string& path) override; diff --git a/source/common/event/dispatcher_impl.cc b/source/common/event/dispatcher_impl.cc index 15c42168203c8..40cdca51ecb1b 100644 --- a/source/common/event/dispatcher_impl.cc +++ b/source/common/event/dispatcher_impl.cc @@ -56,13 +56,13 @@ void DispatcherImpl::clearDeferredDeleteList() { } Network::ClientConnectionPtr -DispatcherImpl::createClientConnection(Network::Address::InstancePtr address) { +DispatcherImpl::createClientConnection(Network::Address::InstanceConstSharedPtr address) { return Network::ClientConnectionPtr{new Network::ClientConnectionImpl(*this, address)}; } Network::ClientConnectionPtr DispatcherImpl::createSslClientConnection(Ssl::ClientContext& ssl_ctx, - Network::Address::InstancePtr address) { + Network::Address::InstanceConstSharedPtr address) { return Network::ClientConnectionPtr{new Ssl::ClientConnectionImpl(*this, ssl_ctx, address)}; } diff --git a/source/common/event/dispatcher_impl.h b/source/common/event/dispatcher_impl.h index d2aa988c9ad31..c876e8286ecf6 100644 --- a/source/common/event/dispatcher_impl.h +++ b/source/common/event/dispatcher_impl.h @@ -26,10 +26,10 @@ class DispatcherImpl : Logger::Loggable, public Dispatcher { // Event::Dispatcher void clearDeferredDeleteList() override; Network::ClientConnectionPtr - createClientConnection(Network::Address::InstancePtr address) override; + createClientConnection(Network::Address::InstanceConstSharedPtr address) override; Network::ClientConnectionPtr createSslClientConnection(Ssl::ClientContext& ssl_ctx, - Network::Address::InstancePtr address) override; + Network::Address::InstanceConstSharedPtr address) override; Network::DnsResolverPtr createDnsResolver() override; FileEventPtr createFileEvent(int fd, FileReadyCb cb, FileTriggerType trigger, uint32_t events) override; diff --git a/source/common/filter/auth/client_ssl.cc b/source/common/filter/auth/client_ssl.cc index 299815363e087..f97078d9c8413 100644 --- a/source/common/filter/auth/client_ssl.cc +++ b/source/common/filter/auth/client_ssl.cc @@ -29,15 +29,15 @@ Config::Config(const Json::Object& config, ThreadLocal::Instance& tls, Upstream: fmt::format("unknown cluster '{}' in client ssl auth config", remote_cluster_name_)); } - AllowedPrincipalsPtr empty(new AllowedPrincipals()); - tls_.set(tls_slot_, - [empty](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectPtr { return empty; }); + AllowedPrincipalsSharedPtr empty(new AllowedPrincipals()); + tls_.set(tls_slot_, [empty](Event::Dispatcher&) + -> ThreadLocal::ThreadLocalObjectSharedPtr { return empty; }); } -ConfigPtr Config::create(const Json::Object& config, ThreadLocal::Instance& tls, - Upstream::ClusterManager& cm, Event::Dispatcher& dispatcher, - Stats::Store& stats_store, Runtime::RandomGenerator& random) { - ConfigPtr new_config(new Config(config, tls, cm, dispatcher, stats_store, random)); +ConfigSharedPtr Config::create(const Json::Object& config, ThreadLocal::Instance& tls, + Upstream::ClusterManager& cm, Event::Dispatcher& dispatcher, + Stats::Store& stats_store, Runtime::RandomGenerator& random) { + ConfigSharedPtr new_config(new Config(config, tls, cm, dispatcher, stats_store, random)); new_config->initialize(); return new_config; } @@ -54,14 +54,14 @@ GlobalStats Config::generateStats(Stats::Store& store, const std::string& prefix } void Config::parseResponse(const Http::Message& message) { - AllowedPrincipalsPtr new_principals(new AllowedPrincipals()); + AllowedPrincipalsSharedPtr new_principals(new AllowedPrincipals()); Json::ObjectPtr loader = Json::Factory::LoadFromString(message.bodyAsString()); for (const Json::ObjectPtr& certificate : loader->getObjectArray("certificates")) { new_principals->add(certificate->getString("fingerprint_sha256")); } tls_.set(tls_slot_, [new_principals](Event::Dispatcher&) - -> ThreadLocal::ThreadLocalObjectPtr { return new_principals; }); + -> ThreadLocal::ThreadLocalObjectSharedPtr { return new_principals; }); stats_.update_success_.inc(); stats_.total_principals_.set(new_principals->size()); diff --git a/source/common/filter/auth/client_ssl.h b/source/common/filter/auth/client_ssl.h index d85e6f04e6cc3..843601c24f8e7 100644 --- a/source/common/filter/auth/client_ssl.h +++ b/source/common/filter/auth/client_ssl.h @@ -57,10 +57,10 @@ class AllowedPrincipals : public ThreadLocal::ThreadLocalObject { std::unordered_set allowed_sha256_digests_; }; -typedef std::shared_ptr AllowedPrincipalsPtr; +typedef std::shared_ptr AllowedPrincipalsSharedPtr; class Config; -typedef std::shared_ptr ConfigPtr; +typedef std::shared_ptr ConfigSharedPtr; /** * Global configuration for client SSL authentication. The config contacts a JSON API to fetch the @@ -69,9 +69,9 @@ typedef std::shared_ptr ConfigPtr; */ class Config : public Http::RestApiFetcher { public: - static ConfigPtr create(const Json::Object& config, ThreadLocal::Instance& tls, - Upstream::ClusterManager& cm, Event::Dispatcher& dispatcher, - Stats::Store& stats_store, Runtime::RandomGenerator& random); + static ConfigSharedPtr create(const Json::Object& config, ThreadLocal::Instance& tls, + Upstream::ClusterManager& cm, Event::Dispatcher& dispatcher, + Stats::Store& stats_store, Runtime::RandomGenerator& random); const AllowedPrincipals& allowedPrincipals(); const Network::IpList& ipWhiteList() { return ip_white_list_; } @@ -101,7 +101,7 @@ class Config : public Http::RestApiFetcher { */ class Instance : public Network::ReadFilter, public Network::ConnectionCallbacks { public: - Instance(ConfigPtr config) : config_(config) {} + Instance(ConfigSharedPtr config) : config_(config) {} // Network::ReadFilter Network::FilterStatus onData(Buffer::Instance& data) override; @@ -115,7 +115,7 @@ class Instance : public Network::ReadFilter, public Network::ConnectionCallbacks void onEvent(uint32_t events) override; private: - ConfigPtr config_; + ConfigSharedPtr config_; Network::ReadFilterCallbacks* read_callbacks_{}; }; diff --git a/source/common/filter/ratelimit.h b/source/common/filter/ratelimit.h index f632c46072e31..bd19b11f5d663 100644 --- a/source/common/filter/ratelimit.h +++ b/source/common/filter/ratelimit.h @@ -51,7 +51,7 @@ class Config { Runtime::Loader& runtime_; }; -typedef std::shared_ptr ConfigPtr; +typedef std::shared_ptr ConfigSharedPtr; /** * TCP rate limit filter instance. This filter will call the rate limit service with the given @@ -63,7 +63,8 @@ class Instance : public Network::ReadFilter, public Network::ConnectionCallbacks, public RequestCallbacks { public: - Instance(ConfigPtr config, ClientPtr&& client) : config_(config), client_(std::move(client)) {} + Instance(ConfigSharedPtr config, ClientPtr&& client) + : config_(config), client_(std::move(client)) {} // Network::ReadFilter Network::FilterStatus onData(Buffer::Instance& data) override; @@ -82,7 +83,7 @@ class Instance : public Network::ReadFilter, private: enum class Status { NotStarted, Calling, Complete }; - ConfigPtr config_; + ConfigSharedPtr config_; ClientPtr client_; Network::ReadFilterCallbacks* filter_callbacks_{}; Status status_{Status::NotStarted}; diff --git a/source/common/filter/tcp_proxy.cc b/source/common/filter/tcp_proxy.cc index cef3f4be58d07..0b72f13f5d288 100644 --- a/source/common/filter/tcp_proxy.cc +++ b/source/common/filter/tcp_proxy.cc @@ -88,7 +88,7 @@ const std::string& TcpProxyConfig::getRouteFromEntries(Network::Connection& conn return EMPTY_STRING; } -TcpProxy::TcpProxy(TcpProxyConfigPtr config, Upstream::ClusterManager& cluster_manager) +TcpProxy::TcpProxy(TcpProxyConfigSharedPtr config, Upstream::ClusterManager& cluster_manager) : config_(config), cluster_manager_(cluster_manager), downstream_callbacks_(*this), upstream_callbacks_(new UpstreamCallbacks(*this)) {} @@ -137,7 +137,7 @@ Network::FilterStatus TcpProxy::initializeUpstreamConnection() { return Network::FilterStatus::StopIteration; } - Upstream::ClusterInfoPtr cluster = thread_local_cluster->info(); + Upstream::ClusterInfoConstSharedPtr cluster = thread_local_cluster->info(); if (!cluster->resourceManager(Upstream::ResourcePriority::Default).connections().canCreate()) { cluster->stats().upstream_cx_overflow_.inc(); read_callbacks_->connection().close(Network::ConnectionCloseType::NoFlush); diff --git a/source/common/filter/tcp_proxy.h b/source/common/filter/tcp_proxy.h index 6b87be460cb13..7e2b0d4cbb25e 100644 --- a/source/common/filter/tcp_proxy.h +++ b/source/common/filter/tcp_proxy.h @@ -70,7 +70,7 @@ class TcpProxyConfig { const TcpProxyStats stats_; }; -typedef std::shared_ptr TcpProxyConfigPtr; +typedef std::shared_ptr TcpProxyConfigSharedPtr; /** * An implementation of a TCP (L3/L4) proxy. This filter will instantiate a new outgoing TCP @@ -79,7 +79,7 @@ typedef std::shared_ptr TcpProxyConfigPtr; */ class TcpProxy : public Network::ReadFilter, Logger::Loggable { public: - TcpProxy(TcpProxyConfigPtr config, Upstream::ClusterManager& cluster_manager); + TcpProxy(TcpProxyConfigSharedPtr config, Upstream::ClusterManager& cluster_manager); ~TcpProxy(); // Network::ReadFilter @@ -119,7 +119,7 @@ class TcpProxy : public Network::ReadFilter, Logger::Loggableroute(); + Router::RouteConstSharedPtr route = decoder_callbacks_->route(); if (!route || !route->routeEntry()) { return; } diff --git a/source/common/grpc/http1_bridge_filter.h b/source/common/grpc/http1_bridge_filter.h index 28d2dfccae98a..dcf7f3cac24d2 100644 --- a/source/common/grpc/http1_bridge_filter.h +++ b/source/common/grpc/http1_bridge_filter.h @@ -42,7 +42,7 @@ class Http1BridgeFilter : public Http::StreamFilter { Http::HeaderMap* response_headers_{}; bool do_bridging_{}; bool do_stat_tracking_{}; - Upstream::ClusterInfoPtr cluster_; + Upstream::ClusterInfoConstSharedPtr cluster_; std::string grpc_service_; std::string grpc_method_; }; diff --git a/source/common/grpc/rpc_channel_impl.h b/source/common/grpc/rpc_channel_impl.h index 94f055df6e1e5..0ea7c1d9c51a7 100644 --- a/source/common/grpc/rpc_channel_impl.h +++ b/source/common/grpc/rpc_channel_impl.h @@ -50,7 +50,7 @@ class RpcChannelImpl : public RpcChannel, public Http::AsyncClient::Callbacks { void onFailure(Http::AsyncClient::FailureReason reason) override; Upstream::ClusterManager& cm_; - Upstream::ClusterInfoPtr cluster_; + Upstream::ClusterInfoConstSharedPtr cluster_; Http::AsyncClient::Request* http_request_{}; const proto::MethodDescriptor* grpc_method_{}; proto::Message* grpc_response_{}; diff --git a/source/common/http/access_log/access_log_impl.cc b/source/common/http/access_log/access_log_impl.cc index b525eaa0e863f..c5e47160572b4 100644 --- a/source/common/http/access_log/access_log_impl.cc +++ b/source/common/http/access_log/access_log_impl.cc @@ -164,8 +164,8 @@ InstanceImpl::InstanceImpl(const std::string& access_log_path, FilterPtr&& filte log_file_ = log_manager.createAccessLog(access_log_path); } -InstancePtr InstanceImpl::fromJson(Json::Object& json, Runtime::Loader& runtime, - ::AccessLog::AccessLogManager& log_manager) { +InstanceSharedPtr InstanceImpl::fromJson(Json::Object& json, Runtime::Loader& runtime, + ::AccessLog::AccessLogManager& log_manager) { std::string access_log_path = json.getString("path"); FilterPtr filter; @@ -181,7 +181,7 @@ InstancePtr InstanceImpl::fromJson(Json::Object& json, Runtime::Loader& runtime, formatter = AccessLogFormatUtils::defaultAccessLogFormatter(); } - return InstancePtr{ + return InstanceSharedPtr{ new InstanceImpl(access_log_path, std::move(filter), std::move(formatter), log_manager)}; } diff --git a/source/common/http/access_log/access_log_impl.h b/source/common/http/access_log/access_log_impl.h index 830e7daccdd14..af9515cb1f86d 100644 --- a/source/common/http/access_log/access_log_impl.h +++ b/source/common/http/access_log/access_log_impl.h @@ -130,15 +130,15 @@ class InstanceImpl : public Instance { InstanceImpl(const std::string& access_log_path, FilterPtr&& filter, FormatterPtr&& formatter, ::AccessLog::AccessLogManager& log_manager); - static InstancePtr fromJson(Json::Object& json, Runtime::Loader& runtime, - ::AccessLog::AccessLogManager& log_manager); + static InstanceSharedPtr fromJson(Json::Object& json, Runtime::Loader& runtime, + ::AccessLog::AccessLogManager& log_manager); // Http::AccessLog::Instance void log(const HeaderMap* request_headers, const HeaderMap* response_headers, const RequestInfo& request_info) override; private: - Filesystem::FilePtr log_file_; + Filesystem::FileSharedPtr log_file_; FilterPtr filter_; FormatterPtr formatter_; }; diff --git a/source/common/http/access_log/request_info_impl.h b/source/common/http/access_log/request_info_impl.h index 967f1365960df..5c8bebf9b76b0 100644 --- a/source/common/http/access_log/request_info_impl.h +++ b/source/common/http/access_log/request_info_impl.h @@ -32,9 +32,11 @@ struct RequestInfoImpl : public RequestInfo { bool getResponseFlag(ResponseFlag flag) const override { return response_flags_ & flag; } - void onUpstreamHostSelected(Upstream::HostDescriptionPtr host) override { upstream_host_ = host; } + void onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) override { + upstream_host_ = host; + } - Upstream::HostDescriptionPtr upstreamHost() const override { return upstream_host_; } + Upstream::HostDescriptionConstSharedPtr upstreamHost() const override { return upstream_host_; } bool healthCheck() const override { return hc_request_; } @@ -46,7 +48,7 @@ struct RequestInfoImpl : public RequestInfo { Optional response_code_; uint64_t bytes_sent_{}; uint64_t response_flags_{}; - Upstream::HostDescriptionPtr upstream_host_{}; + Upstream::HostDescriptionConstSharedPtr upstream_host_{}; bool hc_request_{}; }; diff --git a/source/common/http/async_client_impl.h b/source/common/http/async_client_impl.h index b619315351c11..91e9c9c38a399 100644 --- a/source/common/http/async_client_impl.h +++ b/source/common/http/async_client_impl.h @@ -168,7 +168,7 @@ class AsyncStreamImpl : public AsyncClient::Stream, Ssl::Connection* ssl() override { return nullptr; } Event::Dispatcher& dispatcher() override { return parent_.dispatcher_; } void resetStream() override; - Router::RoutePtr route() override { return route_; } + Router::RouteConstSharedPtr route() override { return route_; } uint64_t streamId() override { return stream_id_; } AccessLog::RequestInfo& requestInfo() override { return request_info_; } const std::string& downstreamAddress() override { return EMPTY_STRING; } diff --git a/source/common/http/codec_client.cc b/source/common/http/codec_client.cc index 810603dd357d2..a2de1dbc50347 100644 --- a/source/common/http/codec_client.cc +++ b/source/common/http/codec_client.cc @@ -9,11 +9,11 @@ namespace Http { CodecClient::CodecClient(Type type, Network::ClientConnectionPtr&& connection, - Upstream::HostDescriptionPtr host) + Upstream::HostDescriptionConstSharedPtr host) : type_(type), connection_(std::move(connection)), host_(host) { connection_->addConnectionCallbacks(*this); - connection_->addReadFilter(Network::ReadFilterPtr{new CodecReadFilter(*this)}); + connection_->addReadFilter(Network::ReadFilterSharedPtr{new CodecReadFilter(*this)}); conn_log_info("connecting", *connection_); connection_->connect(); @@ -112,7 +112,7 @@ void CodecClient::onData(Buffer::Instance& data) { } CodecClientProd::CodecClientProd(Type type, Network::ClientConnectionPtr&& connection, - Upstream::HostDescriptionPtr host) + Upstream::HostDescriptionConstSharedPtr host) : CodecClient(type, std::move(connection), host) { switch (type) { case Type::HTTP1: { diff --git a/source/common/http/codec_client.h b/source/common/http/codec_client.h index 8bc038ef53090..25dff7e3bcf8d 100644 --- a/source/common/http/codec_client.h +++ b/source/common/http/codec_client.h @@ -106,7 +106,7 @@ class CodecClient : Logger::Loggable, * @param host supplies the owning host. */ CodecClient(Type type, Network::ClientConnectionPtr&& connection, - Upstream::HostDescriptionPtr host); + Upstream::HostDescriptionConstSharedPtr host); // Http::ConnectionCallbacks void onGoAway() override { @@ -118,7 +118,7 @@ class CodecClient : Logger::Loggable, const Type type_; ClientConnectionPtr codec_; Network::ClientConnectionPtr connection_; - Upstream::HostDescriptionPtr host_; + Upstream::HostDescriptionConstSharedPtr host_; private: /** @@ -189,7 +189,7 @@ typedef std::unique_ptr CodecClientPtr; class CodecClientProd : public CodecClient { public: CodecClientProd(Type type, Network::ClientConnectionPtr&& connection, - Upstream::HostDescriptionPtr host); + Upstream::HostDescriptionConstSharedPtr host); }; } // Http diff --git a/source/common/http/conn_manager_impl.cc b/source/common/http/conn_manager_impl.cc index eb5cbb21ef24c..12db84b7f5388 100644 --- a/source/common/http/conn_manager_impl.cc +++ b/source/common/http/conn_manager_impl.cc @@ -304,7 +304,7 @@ ConnectionManagerImpl::ActiveStream::ActiveStream(ConnectionManagerImpl& connect ConnectionManagerImpl::ActiveStream::~ActiveStream() { connection_manager_.stats_.named_.downstream_rq_active_.dec(); - for (AccessLog::InstancePtr access_log : connection_manager_.config_.accessLogs()) { + for (AccessLog::InstanceSharedPtr access_log : connection_manager_.config_.accessLogs()) { access_log->log(request_headers_.get(), response_headers_.get(), request_info_); } for (const auto& log_handler : access_log_handlers_) { @@ -320,25 +320,27 @@ ConnectionManagerImpl::ActiveStream::~ActiveStream() { } } -void ConnectionManagerImpl::ActiveStream::addStreamDecoderFilter(StreamDecoderFilterPtr filter) { +void ConnectionManagerImpl::ActiveStream::addStreamDecoderFilter( + StreamDecoderFilterSharedPtr filter) { ActiveStreamDecoderFilterPtr wrapper(new ActiveStreamDecoderFilter(*this, filter)); filter->setDecoderFilterCallbacks(*wrapper); wrapper->moveIntoListBack(std::move(wrapper), decoder_filters_); } -void ConnectionManagerImpl::ActiveStream::addStreamEncoderFilter(StreamEncoderFilterPtr filter) { +void ConnectionManagerImpl::ActiveStream::addStreamEncoderFilter( + StreamEncoderFilterSharedPtr filter) { ActiveStreamEncoderFilterPtr wrapper(new ActiveStreamEncoderFilter(*this, filter)); filter->setEncoderFilterCallbacks(*wrapper); wrapper->moveIntoListBack(std::move(wrapper), encoder_filters_); } -void ConnectionManagerImpl::ActiveStream::addStreamFilter(StreamFilterPtr filter) { +void ConnectionManagerImpl::ActiveStream::addStreamFilter(StreamFilterSharedPtr filter) { addStreamDecoderFilter(filter); addStreamEncoderFilter(filter); } void ConnectionManagerImpl::ActiveStream::addAccessLogHandler( - Http::AccessLog::InstancePtr handler) { + Http::AccessLog::InstanceSharedPtr handler) { access_log_handlers_.push_back(handler); } @@ -826,7 +828,7 @@ AccessLog::RequestInfo& ConnectionManagerImpl::ActiveStreamFilterBase::requestIn return parent_.request_info_; } -Router::RoutePtr ConnectionManagerImpl::ActiveStreamFilterBase::route() { +Router::RouteConstSharedPtr ConnectionManagerImpl::ActiveStreamFilterBase::route() { if (!parent_.cached_route_.valid()) { parent_.cached_route_.value( parent_.snapped_route_config_->route(*parent_.request_headers_, parent_.stream_id_)); diff --git a/source/common/http/conn_manager_impl.h b/source/common/http/conn_manager_impl.h index 2a34729c5c558..db4267a9ddc1a 100644 --- a/source/common/http/conn_manager_impl.h +++ b/source/common/http/conn_manager_impl.h @@ -115,9 +115,9 @@ class ConnectionManagerConfig { virtual ~ConnectionManagerConfig() {} /** - * @return const std::list& the access logs to write to. + * @return const std::list& the access logs to write to. */ - virtual const std::list& accessLogs() PURE; + virtual const std::list& accessLogs() PURE; /** * Called to create a codec for the connection manager. This function will be called when the @@ -269,7 +269,7 @@ class ConnectionManagerImpl : Logger::Loggable, Ssl::Connection* ssl() override; Event::Dispatcher& dispatcher() override; void resetStream() override; - Router::RoutePtr route() override; + Router::RouteConstSharedPtr route() override; uint64_t streamId() override; AccessLog::RequestInfo& requestInfo() override; const std::string& downstreamAddress() override; @@ -285,7 +285,7 @@ class ConnectionManagerImpl : Logger::Loggable, struct ActiveStreamDecoderFilter : public ActiveStreamFilterBase, public StreamDecoderFilterCallbacks, LinkedObject { - ActiveStreamDecoderFilter(ActiveStream& parent, StreamDecoderFilterPtr filter) + ActiveStreamDecoderFilter(ActiveStream& parent, StreamDecoderFilterSharedPtr filter) : ActiveStreamFilterBase(parent), handle_(filter) {} // ActiveStreamFilterBase @@ -309,7 +309,7 @@ class ConnectionManagerImpl : Logger::Loggable, void encodeData(Buffer::Instance& data, bool end_stream) override; void encodeTrailers(HeaderMapPtr&& trailers) override; - StreamDecoderFilterPtr handle_; + StreamDecoderFilterSharedPtr handle_; }; typedef std::unique_ptr ActiveStreamDecoderFilterPtr; @@ -320,7 +320,7 @@ class ConnectionManagerImpl : Logger::Loggable, struct ActiveStreamEncoderFilter : public ActiveStreamFilterBase, public StreamEncoderFilterCallbacks, LinkedObject { - ActiveStreamEncoderFilter(ActiveStream& parent, StreamEncoderFilterPtr filter) + ActiveStreamEncoderFilter(ActiveStream& parent, StreamEncoderFilterSharedPtr filter) : ActiveStreamFilterBase(parent), handle_(filter) {} // ActiveStreamFilterBase @@ -341,7 +341,7 @@ class ConnectionManagerImpl : Logger::Loggable, return parent_.buffered_response_data_.get(); } - StreamEncoderFilterPtr handle_; + StreamEncoderFilterSharedPtr handle_; }; typedef std::unique_ptr ActiveStreamEncoderFilterPtr; @@ -382,10 +382,10 @@ class ConnectionManagerImpl : Logger::Loggable, void decodeTrailers(HeaderMapPtr&& trailers) override; // Http::FilterChainFactoryCallbacks - void addStreamDecoderFilter(StreamDecoderFilterPtr filter) override; - void addStreamEncoderFilter(StreamEncoderFilterPtr filter) override; - void addStreamFilter(StreamFilterPtr filter) override; - void addAccessLogHandler(Http::AccessLog::InstancePtr handler) override; + void addStreamDecoderFilter(StreamDecoderFilterSharedPtr filter) override; + void addStreamEncoderFilter(StreamEncoderFilterSharedPtr filter) override; + void addStreamFilter(StreamFilterSharedPtr filter) override; + void addAccessLogHandler(Http::AccessLog::InstanceSharedPtr handler) override; // Tracing::TracingConfig virtual const std::string& operationName() const override; @@ -401,7 +401,7 @@ class ConnectionManagerImpl : Logger::Loggable, }; ConnectionManagerImpl& connection_manager_; - Router::ConfigPtr snapped_route_config_; + Router::ConfigConstSharedPtr snapped_route_config_; Tracing::SpanPtr active_span_; const uint64_t stream_id_; StreamEncoder* response_encoder_{}; @@ -413,13 +413,13 @@ class ConnectionManagerImpl : Logger::Loggable, HeaderMapPtr request_trailers_; std::list decoder_filters_; std::list encoder_filters_; - std::list access_log_handlers_; + std::list access_log_handlers_; Stats::TimespanPtr request_timer_; std::list> reset_callbacks_; State state_; AccessLog::RequestInfoImpl request_info_; std::string downstream_address_; - Optional cached_route_; + Optional cached_route_; }; typedef std::unique_ptr ActiveStreamPtr; diff --git a/source/common/http/date_provider_impl.cc b/source/common/http/date_provider_impl.cc index b09e4f468a919..bc548b301255c 100644 --- a/source/common/http/date_provider_impl.cc +++ b/source/common/http/date_provider_impl.cc @@ -14,9 +14,10 @@ TlsCachingDateProviderImpl::TlsCachingDateProviderImpl(Event::Dispatcher& dispat void TlsCachingDateProviderImpl::onRefreshDate() { std::string new_date_string = date_formatter_.now(); - tls_.set(tls_slot_, [new_date_string](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectPtr { - return ThreadLocal::ThreadLocalObjectPtr{new ThreadLocalCachedDate(new_date_string)}; - }); + tls_.set( + tls_slot_, [new_date_string](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectSharedPtr { + return ThreadLocal::ThreadLocalObjectSharedPtr{new ThreadLocalCachedDate(new_date_string)}; + }); refresh_timer_->enableTimer(std::chrono::milliseconds(500)); } diff --git a/source/common/http/filter/buffer_filter.cc b/source/common/http/filter/buffer_filter.cc index 04573c9aa1ea7..f5148e139c18d 100644 --- a/source/common/http/filter/buffer_filter.cc +++ b/source/common/http/filter/buffer_filter.cc @@ -12,7 +12,7 @@ namespace Http { -BufferFilter::BufferFilter(BufferFilterConfigPtr config) : config_(config) {} +BufferFilter::BufferFilter(BufferFilterConfigConstSharedPtr config) : config_(config) {} BufferFilter::~BufferFilter() { ASSERT(!request_timeout_); } diff --git a/source/common/http/filter/buffer_filter.h b/source/common/http/filter/buffer_filter.h index ffd852e7c2816..e57fd7fdbf217 100644 --- a/source/common/http/filter/buffer_filter.h +++ b/source/common/http/filter/buffer_filter.h @@ -32,14 +32,14 @@ struct BufferFilterConfig { std::chrono::seconds max_request_time_; }; -typedef std::shared_ptr BufferFilterConfigPtr; +typedef std::shared_ptr BufferFilterConfigConstSharedPtr; /** * A filter that is capable of buffering an entire request before dispatching it upstream. */ class BufferFilter : public StreamDecoderFilter { public: - BufferFilter(BufferFilterConfigPtr config); + BufferFilter(BufferFilterConfigConstSharedPtr config); ~BufferFilter(); static BufferFilterStats generateStats(const std::string& prefix, Stats::Store& store); @@ -55,7 +55,7 @@ class BufferFilter : public StreamDecoderFilter { void onRequestTimeout(); void resetInternalState(); - BufferFilterConfigPtr config_; + BufferFilterConfigConstSharedPtr config_; StreamDecoderFilterCallbacks* callbacks_{}; Event::TimerPtr request_timeout_; }; diff --git a/source/common/http/filter/fault_filter.cc b/source/common/http/filter/fault_filter.cc index c803cdd9597f2..4a97569d21197 100644 --- a/source/common/http/filter/fault_filter.cc +++ b/source/common/http/filter/fault_filter.cc @@ -74,7 +74,7 @@ FaultFilterConfig::FaultFilterConfig(const Json::Object& json_config, Runtime::L upstream_cluster_ = json_config.getString("upstream_cluster", EMPTY_STRING); } -FaultFilter::FaultFilter(FaultFilterConfigPtr config) : config_(config) {} +FaultFilter::FaultFilter(FaultFilterConfigSharedPtr config) : config_(config) {} FaultFilter::~FaultFilter() { ASSERT(!delay_timer_); } @@ -158,7 +158,7 @@ bool FaultFilter::matchesTargetCluster() { bool matches = true; if (!config_->upstreamCluster().empty()) { - Router::RoutePtr route = callbacks_->route(); + Router::RouteConstSharedPtr route = callbacks_->route(); matches = route && route->routeEntry() && (route->routeEntry()->clusterName() == config_->upstreamCluster()); } diff --git a/source/common/http/filter/fault_filter.h b/source/common/http/filter/fault_filter.h index 07e1fb4263e8a..4c0cb5bfecb28 100644 --- a/source/common/http/filter/fault_filter.h +++ b/source/common/http/filter/fault_filter.h @@ -56,14 +56,14 @@ class FaultFilterConfig { FaultFilterStats stats_; }; -typedef std::shared_ptr FaultFilterConfigPtr; +typedef std::shared_ptr FaultFilterConfigSharedPtr; /** * A filter that is capable of faulting an entire request before dispatching it upstream. */ class FaultFilter : public StreamDecoderFilter { public: - FaultFilter(FaultFilterConfigPtr config); + FaultFilter(FaultFilterConfigSharedPtr config); ~FaultFilter(); FilterHeadersStatus decodeHeaders(HeaderMap& headers, bool end_stream) override; @@ -78,7 +78,7 @@ class FaultFilter : public StreamDecoderFilter { void abortWithHTTPStatus(); bool matchesTargetCluster(); - FaultFilterConfigPtr config_; + FaultFilterConfigSharedPtr config_; StreamDecoderFilterCallbacks* callbacks_{}; Event::TimerPtr delay_timer_; }; diff --git a/source/common/http/filter/ratelimit.cc b/source/common/http/filter/ratelimit.cc index 1ebdc731a77fe..18f39724b532d 100644 --- a/source/common/http/filter/ratelimit.cc +++ b/source/common/http/filter/ratelimit.cc @@ -16,7 +16,7 @@ const std::unique_ptr Filter::TOO_MANY_REQUESTS_HEADER{ {Http::Headers::get().Status, std::to_string(enumToInt(Code::TooManyRequests))}}}; void Filter::initiateCall(const HeaderMap& headers) { - Router::RoutePtr route = callbacks_->route(); + Router::RouteConstSharedPtr route = callbacks_->route(); if (!route || !route->routeEntry()) { return; } diff --git a/source/common/http/filter/ratelimit.h b/source/common/http/filter/ratelimit.h index eefd98686568f..a34f976be7181 100644 --- a/source/common/http/filter/ratelimit.h +++ b/source/common/http/filter/ratelimit.h @@ -42,7 +42,7 @@ class FilterConfig : Json::JsonValidator { Upstream::ClusterManager& cm_; }; -typedef std::shared_ptr FilterConfigPtr; +typedef std::shared_ptr FilterConfigSharedPtr; /** * HTTP rate limit filter. Depending on the route configuration, this filter calls the global @@ -50,7 +50,7 @@ typedef std::shared_ptr FilterConfigPtr; */ class Filter : public StreamDecoderFilter, public ::RateLimit::RequestCallbacks { public: - Filter(FilterConfigPtr config, ::RateLimit::ClientPtr&& client) + Filter(FilterConfigSharedPtr config, ::RateLimit::ClientPtr&& client) : config_(config), client_(std::move(client)) {} // Http::StreamDecoderFilter @@ -73,12 +73,12 @@ class Filter : public StreamDecoderFilter, public ::RateLimit::RequestCallbacks static const std::unique_ptr TOO_MANY_REQUESTS_HEADER; - FilterConfigPtr config_; + FilterConfigSharedPtr config_; ::RateLimit::ClientPtr client_; StreamDecoderFilterCallbacks* callbacks_{}; bool initiating_call_{}; State state_{State::NotStarted}; - Upstream::ClusterInfoPtr cluster_; + Upstream::ClusterInfoConstSharedPtr cluster_; }; } // RateLimit diff --git a/source/common/http/http1/conn_pool.h b/source/common/http/http1/conn_pool.h index 214a8c5e3f13c..5aa2b8aeeda69 100644 --- a/source/common/http/http1/conn_pool.h +++ b/source/common/http/http1/conn_pool.h @@ -22,7 +22,7 @@ namespace Http1 { */ class ConnPoolImpl : Logger::Loggable, public ConnectionPool::Instance { public: - ConnPoolImpl(Event::Dispatcher& dispatcher, Upstream::ConstHostPtr host, + ConnPoolImpl(Event::Dispatcher& dispatcher, Upstream::HostConstSharedPtr host, Upstream::ResourcePriority priority) : dispatcher_(dispatcher), host_(host), priority_(priority) {} @@ -74,7 +74,7 @@ class ConnPoolImpl : Logger::Loggable, public ConnectionPool:: ConnPoolImpl& parent_; CodecClientPtr codec_client_; - Upstream::HostDescriptionPtr real_host_description_; + Upstream::HostDescriptionConstSharedPtr real_host_description_; StreamWrapperPtr stream_wrapper_; Event::TimerPtr connect_timer_; Stats::TimespanPtr conn_length_; @@ -111,7 +111,7 @@ class ConnPoolImpl : Logger::Loggable, public ConnectionPool:: Stats::TimespanPtr conn_connect_ms_; Event::Dispatcher& dispatcher_; - Upstream::ConstHostPtr host_; + Upstream::HostConstSharedPtr host_; std::list ready_clients_; std::list busy_clients_; std::list pending_requests_; @@ -124,7 +124,7 @@ class ConnPoolImpl : Logger::Loggable, public ConnectionPool:: */ class ConnPoolImplProd : public ConnPoolImpl { public: - ConnPoolImplProd(Event::Dispatcher& dispatcher, Upstream::ConstHostPtr host, + ConnPoolImplProd(Event::Dispatcher& dispatcher, Upstream::HostConstSharedPtr host, Upstream::ResourcePriority priority) : ConnPoolImpl(dispatcher, host, priority) {} diff --git a/source/common/http/http2/conn_pool.cc b/source/common/http/http2/conn_pool.cc index 8aee8646425ef..5a27411dde084 100644 --- a/source/common/http/http2/conn_pool.cc +++ b/source/common/http/http2/conn_pool.cc @@ -11,7 +11,7 @@ namespace Http { namespace Http2 { -ConnPoolImpl::ConnPoolImpl(Event::Dispatcher& dispatcher, Upstream::ConstHostPtr host, +ConnPoolImpl::ConnPoolImpl(Event::Dispatcher& dispatcher, Upstream::HostConstSharedPtr host, Upstream::ResourcePriority priority) : dispatcher_(dispatcher), host_(host), priority_(priority) {} diff --git a/source/common/http/http2/conn_pool.h b/source/common/http/http2/conn_pool.h index 259f2eee91d53..a990c8b8ab1e2 100644 --- a/source/common/http/http2/conn_pool.h +++ b/source/common/http/http2/conn_pool.h @@ -17,7 +17,7 @@ namespace Http2 { */ class ConnPoolImpl : Logger::Loggable, public ConnectionPool::Instance { public: - ConnPoolImpl(Event::Dispatcher& dispatcher, Upstream::ConstHostPtr host, + ConnPoolImpl(Event::Dispatcher& dispatcher, Upstream::HostConstSharedPtr host, Upstream::ResourcePriority priority); ~ConnPoolImpl(); @@ -50,7 +50,7 @@ class ConnPoolImpl : Logger::Loggable, public ConnectionPool:: ConnPoolImpl& parent_; CodecClientPtr client_; - Upstream::HostDescriptionPtr real_host_description_; + Upstream::HostDescriptionConstSharedPtr real_host_description_; uint64_t total_streams_{}; Event::TimerPtr connect_timer_; Stats::TimespanPtr conn_length_; @@ -72,7 +72,7 @@ class ConnPoolImpl : Logger::Loggable, public ConnectionPool:: Stats::TimespanPtr conn_connect_ms_; Event::Dispatcher& dispatcher_; - Upstream::ConstHostPtr host_; + Upstream::HostConstSharedPtr host_; ActiveClientPtr primary_client_; ActiveClientPtr draining_client_; std::list drained_callbacks_; diff --git a/source/common/local_info/local_info_impl.h b/source/common/local_info/local_info_impl.h index 8358600d22810..2ab839662b51d 100644 --- a/source/common/local_info/local_info_impl.h +++ b/source/common/local_info/local_info_impl.h @@ -6,18 +6,18 @@ namespace LocalInfo { class LocalInfoImpl : public LocalInfo { public: - LocalInfoImpl(Network::Address::InstancePtr address, const std::string zone_name, + LocalInfoImpl(Network::Address::InstanceConstSharedPtr address, const std::string zone_name, const std::string cluster_name, const std::string node_name) : address_(address), zone_name_(zone_name), cluster_name_(cluster_name), node_name_(node_name) {} - Network::Address::InstancePtr address() const override { return address_; } + Network::Address::InstanceConstSharedPtr address() const override { return address_; } const std::string& zoneName() const override { return zone_name_; } const std::string& clusterName() const override { return cluster_name_; } const std::string& nodeName() const override { return node_name_; } private: - Network::Address::InstancePtr address_; + Network::Address::InstanceConstSharedPtr address_; const std::string zone_name_; const std::string cluster_name_; const std::string node_name_; diff --git a/source/common/mongo/bson_impl.h b/source/common/mongo/bson_impl.h index 5c3842ec5c00d..6383c3c742b90 100644 --- a/source/common/mongo/bson_impl.h +++ b/source/common/mongo/bson_impl.h @@ -41,7 +41,7 @@ class FieldImpl : public Field { value_.string_value_ = std::move(value); } - explicit FieldImpl(Type type, const std::string& key, DocumentPtr value) + explicit FieldImpl(Type type, const std::string& key, DocumentSharedPtr value) : type_(type), key_(key) { value_.document_value_ = value; } @@ -150,7 +150,7 @@ class FieldImpl : public Field { struct Value { double double_value_; std::string string_value_; - DocumentPtr document_value_; + DocumentSharedPtr document_value_; Field::ObjectId object_id_value_; bool bool_value_; int32_t int32_value_; @@ -167,75 +167,75 @@ class DocumentImpl : public Document, Logger::Loggable, public std::enable_shared_from_this { public: - static DocumentPtr create() { return DocumentPtr{new DocumentImpl()}; } - static DocumentPtr create(Buffer::Instance& data) { + static DocumentSharedPtr create() { return DocumentSharedPtr{new DocumentImpl()}; } + static DocumentSharedPtr create(Buffer::Instance& data) { std::shared_ptr new_doc{new DocumentImpl()}; new_doc->fromBuffer(data); return new_doc; } // Mongo::Document - DocumentPtr addDouble(const std::string& key, double value) override { + DocumentSharedPtr addDouble(const std::string& key, double value) override { fields_.emplace_back(new FieldImpl(key, value)); return shared_from_this(); } - DocumentPtr addString(const std::string& key, std::string&& value) override { + DocumentSharedPtr addString(const std::string& key, std::string&& value) override { fields_.emplace_back(new FieldImpl(Field::Type::STRING, key, std::move(value))); return shared_from_this(); } - DocumentPtr addDocument(const std::string& key, DocumentPtr value) override { + DocumentSharedPtr addDocument(const std::string& key, DocumentSharedPtr value) override { fields_.emplace_back(new FieldImpl(Field::Type::DOCUMENT, key, value)); return shared_from_this(); } - DocumentPtr addArray(const std::string& key, DocumentPtr value) override { + DocumentSharedPtr addArray(const std::string& key, DocumentSharedPtr value) override { fields_.emplace_back(new FieldImpl(Field::Type::ARRAY, key, value)); return shared_from_this(); } - DocumentPtr addBinary(const std::string& key, std::string&& value) override { + DocumentSharedPtr addBinary(const std::string& key, std::string&& value) override { fields_.emplace_back(new FieldImpl(Field::Type::BINARY, key, std::move(value))); return shared_from_this(); } - DocumentPtr addObjectId(const std::string& key, Field::ObjectId&& value) override { + DocumentSharedPtr addObjectId(const std::string& key, Field::ObjectId&& value) override { fields_.emplace_back(new FieldImpl(key, std::move(value))); return shared_from_this(); } - DocumentPtr addBoolean(const std::string& key, bool value) override { + DocumentSharedPtr addBoolean(const std::string& key, bool value) override { fields_.emplace_back(new FieldImpl(key, value)); return shared_from_this(); } - DocumentPtr addDatetime(const std::string& key, int64_t value) override { + DocumentSharedPtr addDatetime(const std::string& key, int64_t value) override { fields_.emplace_back(new FieldImpl(Field::Type::DATETIME, key, value)); return shared_from_this(); } - DocumentPtr addNull(const std::string& key) override { + DocumentSharedPtr addNull(const std::string& key) override { fields_.emplace_back(new FieldImpl(key)); return shared_from_this(); } - DocumentPtr addRegex(const std::string& key, Field::Regex&& value) override { + DocumentSharedPtr addRegex(const std::string& key, Field::Regex&& value) override { fields_.emplace_back(new FieldImpl(key, std::move(value))); return shared_from_this(); } - DocumentPtr addInt32(const std::string& key, int32_t value) override { + DocumentSharedPtr addInt32(const std::string& key, int32_t value) override { fields_.emplace_back(new FieldImpl(key, value)); return shared_from_this(); } - DocumentPtr addTimestamp(const std::string& key, int64_t value) override { + DocumentSharedPtr addTimestamp(const std::string& key, int64_t value) override { fields_.emplace_back(new FieldImpl(Field::Type::TIMESTAMP, key, value)); return shared_from_this(); } - DocumentPtr addInt64(const std::string& key, int64_t value) override { + DocumentSharedPtr addInt64(const std::string& key, int64_t value) override { fields_.emplace_back(new FieldImpl(Field::Type::INT64, key, value)); return shared_from_this(); } diff --git a/source/common/mongo/codec_impl.cc b/source/common/mongo/codec_impl.cc index 01d55e427b9b9..e1ec4ae73646f 100644 --- a/source/common/mongo/codec_impl.cc +++ b/source/common/mongo/codec_impl.cc @@ -9,12 +9,13 @@ namespace Mongo { -std::string MessageImpl::documentListToString(const std::list& documents) const { +std::string +MessageImpl::documentListToString(const std::list& documents) const { std::stringstream out; out << "["; bool first = true; - for (const Bson::DocumentPtr& document : documents) { + for (const Bson::DocumentSharedPtr& document : documents) { if (!first) { out << ", "; } @@ -310,14 +311,14 @@ void EncoderImpl::encodeInsert(const InsertMessage& message) { // https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#op-insert int32_t total_size = 16 + 4 + message.fullCollectionName().size() + 1; - for (const Bson::DocumentPtr& document : message.documents()) { + for (const Bson::DocumentSharedPtr& document : message.documents()) { total_size += document->byteSize(); } encodeCommonHeader(total_size, message, Message::OpCode::OP_INSERT); Bson::BufferHelper::writeInt32(output_, message.flags()); Bson::BufferHelper::writeCString(output_, message.fullCollectionName()); - for (const Bson::DocumentPtr& document : message.documents()) { + for (const Bson::DocumentSharedPtr& document : message.documents()) { document->encode(output_); } } @@ -366,7 +367,7 @@ void EncoderImpl::encodeQuery(const QueryMessage& message) { void EncoderImpl::encodeReply(const ReplyMessage& message) { // https://docs.mongodb.org/manual/reference/mongodb-wire-protocol/#op-reply int32_t total_size = 16 + 20; - for (const Bson::DocumentPtr& document : message.documents()) { + for (const Bson::DocumentSharedPtr& document : message.documents()) { total_size += document->byteSize(); } @@ -375,7 +376,7 @@ void EncoderImpl::encodeReply(const ReplyMessage& message) { Bson::BufferHelper::writeInt64(output_, message.cursorId()); Bson::BufferHelper::writeInt32(output_, message.startingFrom()); Bson::BufferHelper::writeInt32(output_, message.numberReturned()); - for (const Bson::DocumentPtr& document : message.documents()) { + for (const Bson::DocumentSharedPtr& document : message.documents()) { document->encode(output_); } } diff --git a/source/common/mongo/codec_impl.h b/source/common/mongo/codec_impl.h index a99c903c027f6..3da64a7397370 100644 --- a/source/common/mongo/codec_impl.h +++ b/source/common/mongo/codec_impl.h @@ -18,7 +18,7 @@ class MessageImpl : public virtual Message { int32_t responseTo() const override { return response_to_; } protected: - std::string documentListToString(const std::list& documents) const; + std::string documentListToString(const std::list& documents) const; const int32_t request_id_; const int32_t response_to_; @@ -69,13 +69,13 @@ class InsertMessageImpl : public MessageImpl, void flags(int32_t flags) override { flags_ = flags; } const std::string& fullCollectionName() const override { return full_collection_name_; } void fullCollectionName(const std::string& name) override { full_collection_name_ = name; } - const std::list& documents() const override { return documents_; } - std::list& documents() override { return documents_; } + const std::list& documents() const override { return documents_; } + std::list& documents() override { return documents_; } private: int32_t flags_{}; std::string full_collection_name_; - std::list documents_; + std::list documents_; }; class KillCursorsMessageImpl : public MessageImpl, @@ -129,11 +129,11 @@ class QueryMessageImpl : public MessageImpl, int32_t numberToReturn() const override { return number_to_return_; } void numberToReturn(int32_t to_return) override { number_to_return_ = to_return; } virtual const Bson::Document* query() const override { return query_.get(); } - void query(Bson::DocumentPtr&& query) override { query_ = std::move(query); } + void query(Bson::DocumentSharedPtr&& query) override { query_ = std::move(query); } virtual const Bson::Document* returnFieldsSelector() const override { return return_fields_selector_.get(); } - void returnFieldsSelector(Bson::DocumentPtr&& fields) override { + void returnFieldsSelector(Bson::DocumentSharedPtr&& fields) override { return_fields_selector_ = std::move(fields); } @@ -142,8 +142,8 @@ class QueryMessageImpl : public MessageImpl, std::string full_collection_name_; int32_t number_to_skip_{}; int32_t number_to_return_{}; - Bson::DocumentPtr query_; - Bson::DocumentPtr return_fields_selector_; + Bson::DocumentSharedPtr query_; + Bson::DocumentSharedPtr return_fields_selector_; }; class ReplyMessageImpl : public MessageImpl, @@ -168,15 +168,15 @@ class ReplyMessageImpl : public MessageImpl, void startingFrom(int32_t starting_from) override { starting_from_ = starting_from; } int32_t numberReturned() const override { return number_returned_; } void numberReturned(int32_t number_returned) override { number_returned_ = number_returned; } - const std::list& documents() const override { return documents_; } - std::list& documents() override { return documents_; } + const std::list& documents() const override { return documents_; } + std::list& documents() override { return documents_; } private: int32_t flags_{}; int64_t cursor_id_{}; int32_t starting_from_{}; int32_t number_returned_{}; - std::list documents_; + std::list documents_; }; class DecoderImpl : public Decoder, Logger::Loggable { diff --git a/source/common/mongo/proxy.cc b/source/common/mongo/proxy.cc index 9154602b0991b..a304c6e443127 100644 --- a/source/common/mongo/proxy.cc +++ b/source/common/mongo/proxy.cc @@ -28,7 +28,7 @@ void AccessLog::logMessage(const Message& message, const std::string&, bool full } ProxyFilter::ProxyFilter(const std::string& stat_prefix, Stats::Store& store, - Runtime::Loader& runtime, AccessLogPtr access_log) + Runtime::Loader& runtime, AccessLogSharedPtr access_log) : stat_prefix_(stat_prefix), stat_store_(store), stats_(generateStats(stat_prefix, store)), runtime_(runtime), access_log_(access_log) { @@ -166,7 +166,7 @@ void ProxyFilter::decodeReply(ReplyMessagePtr&& message) { void ProxyFilter::chargeReplyStats(ActiveQuery& active_query, const std::string& prefix, const ReplyMessage& message) { uint64_t reply_documents_byte_size = 0; - for (const Bson::DocumentPtr& document : message.documents()) { + for (const Bson::DocumentSharedPtr& document : message.documents()) { reply_documents_byte_size += document->byteSize(); } diff --git a/source/common/mongo/proxy.h b/source/common/mongo/proxy.h index 4f3bf9cfcb8b2..5bbf0ee884170 100644 --- a/source/common/mongo/proxy.h +++ b/source/common/mongo/proxy.h @@ -60,10 +60,10 @@ class AccessLog { const Upstream::HostDescription* upstream_host); private: - Filesystem::FilePtr file_; + Filesystem::FileSharedPtr file_; }; -typedef std::shared_ptr AccessLogPtr; +typedef std::shared_ptr AccessLogSharedPtr; /** * A sniffing filter for mongo traffic. The current implementation makes a copy of read/written @@ -75,7 +75,7 @@ class ProxyFilter : public Network::Filter, Logger::Loggable { public: ProxyFilter(const std::string& stat_prefix, Stats::Store& store, Runtime::Loader& runtime, - AccessLogPtr access_log); + AccessLogSharedPtr access_log); ~ProxyFilter(); virtual DecoderPtr createDecoder(DecoderCallbacks& callbacks) PURE; @@ -139,7 +139,7 @@ class ProxyFilter : public Network::Filter, Buffer::OwnedImpl write_buffer_; bool sniffing_{true}; std::list active_query_list_; - AccessLogPtr access_log_; + AccessLogSharedPtr access_log_; std::string last_base64_op_; Network::ReadFilterCallbacks* read_callbacks_{}; }; diff --git a/source/common/network/address_impl.cc b/source/common/network/address_impl.cc index 7cf88fec7b1b8..a1700e5ace84b 100644 --- a/source/common/network/address_impl.cc +++ b/source/common/network/address_impl.cc @@ -144,18 +144,18 @@ int PipeInstance::socket(SocketType type) const { return ::socket(AF_UNIX, flagsFromSocketType(type), 0); } -InstancePtr parseInternetAddress(const std::string& ip_addr) { +InstanceConstSharedPtr parseInternetAddress(const std::string& ip_addr) { sockaddr_in sa4; if (inet_pton(AF_INET, ip_addr.c_str(), &sa4.sin_addr) == 1) { sa4.sin_family = AF_INET; sa4.sin_port = 0; - return InstancePtr(new Ipv4Instance(&sa4)); + return InstanceConstSharedPtr(new Ipv4Instance(&sa4)); } sockaddr_in6 sa6; if (inet_pton(AF_INET6, ip_addr.c_str(), &sa6.sin6_addr) == 1) { sa6.sin6_family = AF_INET6; sa6.sin6_port = 0; - return InstancePtr(new Ipv6Instance(sa6)); + return InstanceConstSharedPtr(new Ipv6Instance(sa6)); } return nullptr; } diff --git a/source/common/network/address_impl.h b/source/common/network/address_impl.h index dbe07bb1156b1..62588578cc955 100644 --- a/source/common/network/address_impl.h +++ b/source/common/network/address_impl.h @@ -146,7 +146,7 @@ class Ipv6Instance : public InstanceBase { * @param ip_addr string to be parsed as an internet address. * @return pointer to the Instance, or nullptr if unable to parse the address. */ -InstancePtr parseInternetAddress(const std::string& ip_addr); +InstanceConstSharedPtr parseInternetAddress(const std::string& ip_addr); /** * Implementation of a pipe address (unix domain socket on unix). diff --git a/source/common/network/cidr_range.cc b/source/common/network/cidr_range.cc index 6c1c578c674c9..bf81fd7c38587 100644 --- a/source/common/network/cidr_range.cc +++ b/source/common/network/cidr_range.cc @@ -12,7 +12,7 @@ namespace Address { CidrRange::CidrRange() : length_(-1) {} -CidrRange::CidrRange(InstancePtr address, int length) +CidrRange::CidrRange(InstanceConstSharedPtr address, int length) : address_(std::move(address)), length_(length) { // This is a private ctor, so only checking these asserts in debug builds. if (address_ == nullptr) { @@ -66,7 +66,7 @@ IpVersion CidrRange::version() const { return IpVersion::v4; } -bool CidrRange::isInRange(InstancePtr address) const { +bool CidrRange::isInRange(InstanceConstSharedPtr address) const { if (address == nullptr || length_ < 0 || address->type() != Type::Ip || address->ip()->version() != version()) { return false; @@ -88,8 +88,8 @@ std::string CidrRange::asString() const { } // static -CidrRange CidrRange::create(InstancePtr address, int length) { - InstancePtr ptr = truncateIpAddressAndLength(std::move(address), &length); +CidrRange CidrRange::create(InstanceConstSharedPtr address, int length) { + InstanceConstSharedPtr ptr = truncateIpAddressAndLength(std::move(address), &length); return CidrRange(std::move(ptr), length); } @@ -102,7 +102,7 @@ CidrRange CidrRange::create(const std::string& address, int length) { CidrRange CidrRange::create(const std::string& range) { std::vector parts = StringUtil::split(range, '/'); if (parts.size() == 2) { - InstancePtr ptr = parseInternetAddress(parts[0]); + InstanceConstSharedPtr ptr = parseInternetAddress(parts[0]); if (ptr != nullptr && ptr->type() == Type::Ip) { uint64_t length64; if (StringUtil::atoul(parts[1].c_str(), length64, 10)) { @@ -117,7 +117,8 @@ CidrRange CidrRange::create(const std::string& range) { } // static -InstancePtr CidrRange::truncateIpAddressAndLength(InstancePtr address, int* length_io) { +InstanceConstSharedPtr CidrRange::truncateIpAddressAndLength(InstanceConstSharedPtr address, + int* length_io) { int length = *length_io; if (address == nullptr || length < 0 || address->type() != Type::Ip) { *length_io = -1; @@ -131,7 +132,7 @@ InstancePtr CidrRange::truncateIpAddressAndLength(InstancePtr address, int* leng return address; } else if (length == 0) { // Create an Ipv4Instance with only a port, which will thus have the any address. - return InstancePtr(new Ipv4Instance(uint32_t(0))); + return InstanceConstSharedPtr(new Ipv4Instance(uint32_t(0))); } // Need to mask out the unused bits, and create an Ipv4Instance with this address. uint32_t ip4 = ntohl(address->ip()->ipv4()->address()); @@ -140,7 +141,7 @@ InstancePtr CidrRange::truncateIpAddressAndLength(InstancePtr address, int* leng sa4.sin_family = AF_INET; sa4.sin_port = htons(0); sa4.sin_addr.s_addr = htonl(ip4); - return InstancePtr(new Ipv4Instance(&sa4)); + return InstanceConstSharedPtr(new Ipv4Instance(&sa4)); } case IpVersion::v6: { @@ -150,7 +151,7 @@ InstancePtr CidrRange::truncateIpAddressAndLength(InstancePtr address, int* leng return address; } else if (length == 0) { // Create an Ipv6Instance with only a port, which will thus have the any address. - return InstancePtr(new Ipv6Instance(uint32_t(0))); + return InstanceConstSharedPtr(new Ipv6Instance(uint32_t(0))); } // We need to mask out the unused bits, but we don't have a uint128_t available. // However, we know that the array returned by Ipv6::address() represents the address @@ -174,7 +175,7 @@ InstancePtr CidrRange::truncateIpAddressAndLength(InstancePtr address, int* leng length -= 8; } } - return InstancePtr(new Ipv6Instance(sa6)); + return InstanceConstSharedPtr(new Ipv6Instance(sa6)); } } NOT_REACHED diff --git a/source/common/network/cidr_range.h b/source/common/network/cidr_range.h index 22599c1b88e9d..059d7882313df 100644 --- a/source/common/network/cidr_range.h +++ b/source/common/network/cidr_range.h @@ -60,7 +60,7 @@ class CidrRange { * @return true if the address argument is in the range of this object, false if not, including if the range is uninitialized or if the argument is not of the same IpVersion. */ - bool isInRange(InstancePtr address) const; + bool isInRange(InstanceConstSharedPtr address) const; /** * @return a human readable string for the range. This string will be in the following format: @@ -82,7 +82,7 @@ class CidrRange { * in the appropriate range (0 to 32 for IPv4, 0 to 128 for IPv6). If the the address or * length is invalid, then the range will be invalid (i.e. length == -1). */ - static CidrRange create(InstancePtr address, int length); + static CidrRange create(InstanceConstSharedPtr address, int length); static CidrRange create(const std::string& address, int length); /** @@ -104,12 +104,13 @@ class CidrRange { * from address, and *length_io is in the range 0 to N, where N is the number of bits * in an address of the IP version (i.e. address->ip()->version()). */ - static InstancePtr truncateIpAddressAndLength(InstancePtr address, int* length_io); + static InstanceConstSharedPtr truncateIpAddressAndLength(InstanceConstSharedPtr address, + int* length_io); private: - CidrRange(InstancePtr address, int length); + CidrRange(InstanceConstSharedPtr address, int length); - InstancePtr address_; + InstanceConstSharedPtr address_; int length_; }; diff --git a/source/common/network/connection_impl.cc b/source/common/network/connection_impl.cc index 642a167083f82..577f63d14712f 100644 --- a/source/common/network/connection_impl.cc +++ b/source/common/network/connection_impl.cc @@ -36,12 +36,12 @@ std::atomic ConnectionImpl::next_global_id_; // TODO(mattklein123): Currently we don't populate local address for client connections. Nothing // looks at this currently, but we may want to populate this later for logging purposes. -const Address::InstancePtr +const Address::InstanceConstSharedPtr ConnectionImpl::null_local_address_(new Address::Ipv4Instance("0.0.0.0")); ConnectionImpl::ConnectionImpl(Event::DispatcherImpl& dispatcher, int fd, - Address::InstancePtr remote_address, - Address::InstancePtr local_address) + Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address) : filter_manager_(*this, *this), remote_address_(remote_address), local_address_(local_address), dispatcher_(dispatcher), fd_(fd), id_(++next_global_id_) { @@ -66,13 +66,15 @@ ConnectionImpl::~ConnectionImpl() { close(ConnectionCloseType::NoFlush); } -void ConnectionImpl::addWriteFilter(WriteFilterPtr filter) { +void ConnectionImpl::addWriteFilter(WriteFilterSharedPtr filter) { filter_manager_.addWriteFilter(filter); } -void ConnectionImpl::addFilter(FilterPtr filter) { filter_manager_.addFilter(filter); } +void ConnectionImpl::addFilter(FilterSharedPtr filter) { filter_manager_.addFilter(filter); } -void ConnectionImpl::addReadFilter(ReadFilterPtr filter) { filter_manager_.addReadFilter(filter); } +void ConnectionImpl::addReadFilter(ReadFilterSharedPtr filter) { + filter_manager_.addReadFilter(filter); +} bool ConnectionImpl::initializeReadFilters() { return filter_manager_.initializeReadFilters(); } @@ -437,7 +439,7 @@ void ConnectionImpl::updateWriteBufferStats(uint64_t num_written, uint64_t new_s } ClientConnectionImpl::ClientConnectionImpl(Event::DispatcherImpl& dispatcher, - Address::InstancePtr address) + Address::InstanceConstSharedPtr address) : ConnectionImpl(dispatcher, address->socket(Address::SocketType::Stream), address, null_local_address_) {} diff --git a/source/common/network/connection_impl.h b/source/common/network/connection_impl.h index a8be3339562aa..ba94b49c10b3c 100644 --- a/source/common/network/connection_impl.h +++ b/source/common/network/connection_impl.h @@ -37,15 +37,16 @@ class ConnectionImpl : public virtual Connection, public BufferSource, protected Logger::Loggable { public: - ConnectionImpl(Event::DispatcherImpl& dispatcher, int fd, Address::InstancePtr remote_address, - Address::InstancePtr local_address); + ConnectionImpl(Event::DispatcherImpl& dispatcher, int fd, + Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address); ~ConnectionImpl(); // Network::FilterManager - void addWriteFilter(WriteFilterPtr filter) override; - void addFilter(FilterPtr filter) override; - void addReadFilter(ReadFilterPtr filter) override; + void addWriteFilter(WriteFilterSharedPtr filter) override; + void addFilter(FilterSharedPtr filter) override; + void addReadFilter(ReadFilterSharedPtr filter) override; bool initializeReadFilters() override; // Network::Connection @@ -92,11 +93,11 @@ class ConnectionImpl : public virtual Connection, // Reconsider how to make fairness happen. void setReadBufferReady() { file_event_->activate(Event::FileReadyType::Read); } - static const Address::InstancePtr null_local_address_; + static const Address::InstanceConstSharedPtr null_local_address_; FilterManagerImpl filter_manager_; - Address::InstancePtr remote_address_; - Address::InstancePtr local_address_; + Address::InstanceConstSharedPtr remote_address_; + Address::InstanceConstSharedPtr local_address_; Buffer::OwnedImpl read_buffer_; Buffer::OwnedImpl write_buffer_; uint32_t read_buffer_limit_ = 0; @@ -140,7 +141,7 @@ class ConnectionImpl : public virtual Connection, */ class ClientConnectionImpl : public ConnectionImpl, virtual public ClientConnection { public: - ClientConnectionImpl(Event::DispatcherImpl& dispatcher, Address::InstancePtr address); + ClientConnectionImpl(Event::DispatcherImpl& dispatcher, Address::InstanceConstSharedPtr address); // Network::ClientConnection void connect() override { doConnect(); } diff --git a/source/common/network/dns_impl.cc b/source/common/network/dns_impl.cc index 5566d5ef0f929..970bfd69b9d98 100644 --- a/source/common/network/dns_impl.cc +++ b/source/common/network/dns_impl.cc @@ -41,7 +41,7 @@ void DnsResolverImpl::PendingResolution::onAresHostCallback(int status, hostent* delete this; return; } - std::list address_list; + std::list address_list; completed_ = true; if (status == ARES_SUCCESS) { ASSERT(hostent->h_addrtype == AF_INET); diff --git a/source/common/network/filter_manager_impl.cc b/source/common/network/filter_manager_impl.cc index 34d7e8a9b33d1..6bbe78a5f8456 100644 --- a/source/common/network/filter_manager_impl.cc +++ b/source/common/network/filter_manager_impl.cc @@ -6,17 +6,17 @@ namespace Network { -void FilterManagerImpl::addWriteFilter(WriteFilterPtr filter) { +void FilterManagerImpl::addWriteFilter(WriteFilterSharedPtr filter) { ASSERT(connection_.state() == Connection::State::Open); downstream_filters_.emplace_back(filter); } -void FilterManagerImpl::addFilter(FilterPtr filter) { +void FilterManagerImpl::addFilter(FilterSharedPtr filter) { addReadFilter(filter); addWriteFilter(filter); } -void FilterManagerImpl::addReadFilter(ReadFilterPtr filter) { +void FilterManagerImpl::addReadFilter(ReadFilterSharedPtr filter) { ASSERT(connection_.state() == Connection::State::Open); ActiveReadFilterPtr new_filter(new ActiveReadFilter{*this, filter}); filter->initializeReadFilterCallbacks(*new_filter); @@ -69,7 +69,7 @@ void FilterManagerImpl::onRead() { } FilterStatus FilterManagerImpl::onWrite() { - for (const WriteFilterPtr& filter : downstream_filters_) { + for (const WriteFilterSharedPtr& filter : downstream_filters_) { FilterStatus status = filter->onWrite(buffer_source_.getWriteBuffer()); if (status == FilterStatus::StopIteration) { return status; diff --git a/source/common/network/filter_manager_impl.h b/source/common/network/filter_manager_impl.h index ba87eb5f8b6df..bf6ae99dda653 100644 --- a/source/common/network/filter_manager_impl.h +++ b/source/common/network/filter_manager_impl.h @@ -32,9 +32,9 @@ class FilterManagerImpl { FilterManagerImpl(Connection& connection, BufferSource& buffer_source) : connection_(connection), buffer_source_(buffer_source) {} - void addWriteFilter(WriteFilterPtr filter); - void addFilter(FilterPtr filter); - void addReadFilter(ReadFilterPtr filter); + void addWriteFilter(WriteFilterSharedPtr filter); + void addFilter(FilterSharedPtr filter); + void addReadFilter(ReadFilterSharedPtr filter); void destroyFilters(); bool initializeReadFilters(); void onRead(); @@ -42,18 +42,20 @@ class FilterManagerImpl { private: struct ActiveReadFilter : public ReadFilterCallbacks, LinkedObject { - ActiveReadFilter(FilterManagerImpl& parent, ReadFilterPtr filter) + ActiveReadFilter(FilterManagerImpl& parent, ReadFilterSharedPtr filter) : parent_(parent), filter_(filter) {} Connection& connection() override { return parent_.connection_; } void continueReading() override { parent_.onContinueReading(this); } - Upstream::HostDescriptionPtr upstreamHost() override { return parent_.host_description_; } - void upstreamHost(Upstream::HostDescriptionPtr host) override { + Upstream::HostDescriptionConstSharedPtr upstreamHost() override { + return parent_.host_description_; + } + void upstreamHost(Upstream::HostDescriptionConstSharedPtr host) override { parent_.host_description_ = host; } FilterManagerImpl& parent_; - ReadFilterPtr filter_; + ReadFilterSharedPtr filter_; bool initialized_{}; }; @@ -63,9 +65,9 @@ class FilterManagerImpl { Connection& connection_; BufferSource& buffer_source_; - Upstream::HostDescriptionPtr host_description_; + Upstream::HostDescriptionConstSharedPtr host_description_; std::list upstream_filters_; - std::list downstream_filters_; + std::list downstream_filters_; }; } // Network diff --git a/source/common/network/listen_socket_impl.cc b/source/common/network/listen_socket_impl.cc index c76c255eded9e..f24cb7ece6be5 100644 --- a/source/common/network/listen_socket_impl.cc +++ b/source/common/network/listen_socket_impl.cc @@ -19,7 +19,7 @@ void ListenSocketImpl::doBind() { } // TODO(wattli): remove this once the admin port is updated with address. -TcpListenSocket::TcpListenSocket(Address::InstancePtr address, bool bind_to_port) { +TcpListenSocket::TcpListenSocket(Address::InstanceConstSharedPtr address, bool bind_to_port) { // TODO(mattklein123): IPv6 support. local_address_ = address; fd_ = local_address_->socket(Address::SocketType::Stream); @@ -54,7 +54,7 @@ TcpListenSocket::TcpListenSocket(int fd, uint32_t port) { local_address_.reset(new Address::Ipv4Instance(port)); } -TcpListenSocket::TcpListenSocket(int fd, Address::InstancePtr address) { +TcpListenSocket::TcpListenSocket(int fd, Address::InstanceConstSharedPtr address) { fd_ = fd; local_address_ = address; } diff --git a/source/common/network/listen_socket_impl.h b/source/common/network/listen_socket_impl.h index feb3a8e5a99f4..57ef76b1c4c85 100644 --- a/source/common/network/listen_socket_impl.h +++ b/source/common/network/listen_socket_impl.h @@ -11,7 +11,7 @@ class ListenSocketImpl : public ListenSocket { ~ListenSocketImpl() { close(); } // Network::ListenSocket - Address::InstancePtr localAddress() override { return local_address_; } + Address::InstanceConstSharedPtr localAddress() override { return local_address_; } int fd() override { return fd_; } void close() override { @@ -25,7 +25,7 @@ class ListenSocketImpl : public ListenSocket { void doBind(); int fd_; - Address::InstancePtr local_address_; + Address::InstanceConstSharedPtr local_address_; }; /** @@ -33,10 +33,10 @@ class ListenSocketImpl : public ListenSocket { */ class TcpListenSocket : public ListenSocketImpl { public: - TcpListenSocket(Address::InstancePtr address, bool bind_to_port); + TcpListenSocket(Address::InstanceConstSharedPtr address, bool bind_to_port); TcpListenSocket(uint32_t port, bool bind_to_port); TcpListenSocket(int fd, uint32_t port); - TcpListenSocket(int fd, Address::InstancePtr address); + TcpListenSocket(int fd, Address::InstanceConstSharedPtr address); }; typedef std::unique_ptr TcpListenSocketPtr; diff --git a/source/common/network/listener_impl.cc b/source/common/network/listener_impl.cc index 55108d56c1d73..d5c4f3cef955a 100644 --- a/source/common/network/listener_impl.cc +++ b/source/common/network/listener_impl.cc @@ -15,15 +15,17 @@ namespace Network { -Address::InstancePtr ListenerImpl::getOriginalDst(int fd) { return Utility::getOriginalDst(fd); } +Address::InstanceConstSharedPtr ListenerImpl::getOriginalDst(int fd) { + return Utility::getOriginalDst(fd); +} void ListenerImpl::listenCallback(evconnlistener*, evutil_socket_t fd, sockaddr* remote_addr, int, void* arg) { ListenerImpl* listener = static_cast(arg); - Address::InstancePtr final_local_address = listener->socket_.localAddress(); + Address::InstanceConstSharedPtr final_local_address = listener->socket_.localAddress(); if (listener->options_.use_original_dst_ && final_local_address->type() == Address::Type::Ip) { - Address::InstancePtr original_local_address = listener->getOriginalDst(fd); + Address::InstanceConstSharedPtr original_local_address = listener->getOriginalDst(fd); if (original_local_address) { final_local_address = original_local_address; } @@ -48,7 +50,7 @@ void ListenerImpl::listenCallback(evconnlistener*, evutil_socket_t fd, sockaddr* if (listener->options_.use_proxy_proto_) { listener->proxy_protocol_.newConnection(listener->dispatcher_, fd, *listener); } else { - Address::InstancePtr final_remote_address; + Address::InstanceConstSharedPtr final_remote_address; if (remote_addr->sa_family == AF_INET) { final_remote_address.reset( new Address::Ipv4Instance(reinterpret_cast(remote_addr))); @@ -88,15 +90,15 @@ void ListenerImpl::errorCallback(evconnlistener*, void*) { PANIC(fmt::format("listener accept failure: {}", strerror(errno))); } -void ListenerImpl::newConnection(int fd, Address::InstancePtr remote_address, - Address::InstancePtr local_address) { +void ListenerImpl::newConnection(int fd, Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address) { ConnectionPtr new_connection(new ConnectionImpl(dispatcher_, fd, remote_address, local_address)); new_connection->setReadBufferLimit(options_.per_connection_buffer_limit_bytes_); cb_.onNewConnection(std::move(new_connection)); } -void SslListenerImpl::newConnection(int fd, Address::InstancePtr remote_address, - Address::InstancePtr local_address) { +void SslListenerImpl::newConnection(int fd, Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address) { ConnectionPtr new_connection(new Ssl::ConnectionImpl(dispatcher_, fd, remote_address, local_address, ssl_ctx_, Ssl::ConnectionImpl::InitialState::Server)); diff --git a/source/common/network/listener_impl.h b/source/common/network/listener_impl.h index 3dcb8146c5c4c..57faffc05f896 100644 --- a/source/common/network/listener_impl.h +++ b/source/common/network/listener_impl.h @@ -28,8 +28,8 @@ class ListenerImpl : public Listener { * @param remote_address supplies the remote address for the new connection. * @param local_address supplies the local address for the new connection. */ - virtual void newConnection(int fd, Address::InstancePtr remote_address, - Address::InstancePtr local_address); + virtual void newConnection(int fd, Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address); /** * @return the socket supplied to the listener at construction time @@ -37,7 +37,7 @@ class ListenerImpl : public Listener { ListenSocket& socket() { return socket_; } protected: - virtual Address::InstancePtr getOriginalDst(int fd); + virtual Address::InstanceConstSharedPtr getOriginalDst(int fd); Network::ConnectionHandler& connection_handler_; Event::DispatcherImpl& dispatcher_; @@ -62,8 +62,8 @@ class SslListenerImpl : public ListenerImpl { ssl_ctx_(ssl_ctx) {} // ListenerImpl - void newConnection(int fd, Address::InstancePtr remote_address, - Address::InstancePtr local_address) override; + void newConnection(int fd, Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address) override; private: Ssl::Context& ssl_ctx_; diff --git a/source/common/network/proxy_protocol.cc b/source/common/network/proxy_protocol.cc index d656f1414b9c6..f0d75f5bf3c4d 100644 --- a/source/common/network/proxy_protocol.cc +++ b/source/common/network/proxy_protocol.cc @@ -74,9 +74,10 @@ void ProxyProtocol::ActiveConnection::onReadWorker() { // TODO(mattklein123): Parse the remote port instead of passing zero. // TODO(mattklein123): IPv6 support. - listener.newConnection( - fd, Network::Address::InstancePtr{new Network::Address::Ipv4Instance(remote_address, 0)}, - listener.socket().localAddress()); + listener.newConnection(fd, + Network::Address::InstanceConstSharedPtr{ + new Network::Address::Ipv4Instance(remote_address, 0)}, + listener.socket().localAddress()); } void ProxyProtocol::ActiveConnection::close() { diff --git a/source/common/network/utility.cc b/source/common/network/utility.cc index 13d135ec4eac3..06bc2f67bdb72 100644 --- a/source/common/network/utility.cc +++ b/source/common/network/utility.cc @@ -75,15 +75,16 @@ IpList::IpList(const Json::Object& config, const std::string& member_name) const std::string Utility::TCP_SCHEME = "tcp://"; const std::string Utility::UNIX_SCHEME = "unix://"; -Address::InstancePtr Utility::resolveUrl(const std::string& url) { +Address::InstanceConstSharedPtr Utility::resolveUrl(const std::string& url) { // TODO(mattklein123): IPv6 support. // TODO(mattklein123): We still support the legacy tcp:// and unix:// names. We should // support/parse ip:// and pipe:// as better names. if (url.find(TCP_SCHEME) == 0) { - return Address::InstancePtr{ + return Address::InstanceConstSharedPtr{ new Address::Ipv4Instance(hostFromTcpUrl(url), portFromTcpUrl(url))}; } else if (url.find(UNIX_SCHEME) == 0) { - return Address::InstancePtr{new Address::PipeInstance(url.substr(UNIX_SCHEME.size()))}; + return Address::InstanceConstSharedPtr{ + new Address::PipeInstance(url.substr(UNIX_SCHEME.size()))}; } else { throw EnvoyException(fmt::format("unknown protocol scheme: {}", url)); } @@ -121,10 +122,10 @@ uint32_t Utility::portFromTcpUrl(const std::string& url) { } } -Address::InstancePtr Utility::getLocalAddress() { +Address::InstanceConstSharedPtr Utility::getLocalAddress() { struct ifaddrs* ifaddr; struct ifaddrs* ifa; - Address::InstancePtr ret; + Address::InstanceConstSharedPtr ret; int rc = getifaddrs(&ifaddr); RELEASE_ASSERT(!rc); @@ -178,19 +179,19 @@ bool Utility::isLoopbackAddress(const Address::Instance& address) { return address.ip()->ipv4()->address() == htonl(INADDR_LOOPBACK); } -Address::InstancePtr Utility::getIpv4AnyAddress() { +Address::InstanceConstSharedPtr Utility::getIpv4AnyAddress() { // Initialized on first call in a thread-safe manner. - static Address::InstancePtr any(new Address::Ipv4Instance(static_cast(0))); + static Address::InstanceConstSharedPtr any(new Address::Ipv4Instance(static_cast(0))); return any; } -Address::InstancePtr Utility::getIpv6AnyAddress() { +Address::InstanceConstSharedPtr Utility::getIpv6AnyAddress() { // Initialized on first call in a thread-safe manner. - static Address::InstancePtr any(new Address::Ipv6Instance(static_cast(0))); + static Address::InstanceConstSharedPtr any(new Address::Ipv6Instance(static_cast(0))); return any; } -Address::InstancePtr Utility::getOriginalDst(int fd) { +Address::InstanceConstSharedPtr Utility::getOriginalDst(int fd) { sockaddr_storage orig_addr; socklen_t addr_len = sizeof(sockaddr_storage); int status = getsockopt(fd, SOL_IP, SO_ORIGINAL_DST, &orig_addr, &addr_len); @@ -198,7 +199,7 @@ Address::InstancePtr Utility::getOriginalDst(int fd) { if (status == 0) { // TODO(mattklein123): IPv6 support ASSERT(orig_addr.ss_family == AF_INET); - return Address::InstancePtr{ + return Address::InstanceConstSharedPtr{ new Address::Ipv4Instance(reinterpret_cast(&orig_addr))}; } else { return nullptr; diff --git a/source/common/network/utility.h b/source/common/network/utility.h index d53d3160fd122..3050b228c8bb2 100644 --- a/source/common/network/utility.h +++ b/source/common/network/utility.h @@ -55,9 +55,9 @@ class Utility { /** * Resolve a URL. * @param url supplies the url to resolve. - * @return Address::InstancePtr the resolved address. + * @return Address::InstanceConstSharedPtr the resolved address. */ - static Address::InstancePtr resolveUrl(const std::string& url); + static Address::InstanceConstSharedPtr resolveUrl(const std::string& url); /** * Parses the host from a TCP URL @@ -76,7 +76,7 @@ class Utility { /** * @return the local IP address of the server */ - static Address::InstancePtr getLocalAddress(); + static Address::InstanceConstSharedPtr getLocalAddress(); /** * Determine whether this is an internal (RFC1918) address. @@ -91,18 +91,19 @@ class Utility { static bool isLoopbackAddress(const Address::Instance& address); /** - * @return Address::InstancePtr an address that represents the IPv4 wildcard address + * @return Address::InstanceConstSharedPtr an address that represents the IPv4 wildcard address * (i.e. "0.0.0.0"). Used during binding to indicate that incoming connections to any * local IPv4 address are to be accepted. */ - static Address::InstancePtr getIpv4AnyAddress(); + static Address::InstanceConstSharedPtr getIpv4AnyAddress(); /** - * @return Address::InstancePtr an address that represents the IPv6 wildcard address (i.e. "::"). + * @return Address::InstanceConstSharedPtr an address that represents the IPv6 wildcard address + * (i.e. "::"). * Used during binding to indicate that incoming connections to any local IPv6 address * are to be accepted. */ - static Address::InstancePtr getIpv6AnyAddress(); + static Address::InstanceConstSharedPtr getIpv6AnyAddress(); /** * Retrieve the original destination address from an accepted fd. @@ -111,7 +112,7 @@ class Utility { * @param fd is the descriptor returned by accept() * @return the original destination or nullptr if not available. */ - static Address::InstancePtr getOriginalDst(int fd); + static Address::InstanceConstSharedPtr getOriginalDst(int fd); /** * Parses a string containing a comma-separated list of port numbers and/or diff --git a/source/common/redis/conn_pool_impl.cc b/source/common/redis/conn_pool_impl.cc index fb5396e7fa22d..35c55cedbcdcd 100644 --- a/source/common/redis/conn_pool_impl.cc +++ b/source/common/redis/conn_pool_impl.cc @@ -5,13 +5,13 @@ namespace Redis { namespace ConnPool { -ClientPtr ClientImpl::create(Upstream::ConstHostPtr host, Event::Dispatcher& dispatcher, +ClientPtr ClientImpl::create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher, EncoderPtr&& encoder, DecoderFactory& decoder_factory) { std::unique_ptr client(new ClientImpl(std::move(encoder), decoder_factory)); client->connection_ = host->createConnection(dispatcher).connection_; client->connection_->addConnectionCallbacks(*client); - client->connection_->addReadFilter(Network::ReadFilterPtr{new UpstreamReadFilter(*client)}); + client->connection_->addReadFilter(Network::ReadFilterSharedPtr{new UpstreamReadFilter(*client)}); client->connection_->connect(); client->connection_->noDelay(true); return std::move(client); @@ -72,17 +72,18 @@ void ClientImpl::PendingRequest::cancel() { ClientFactoryImpl ClientFactoryImpl::instance_; -ClientPtr ClientFactoryImpl::create(Upstream::ConstHostPtr host, Event::Dispatcher& dispatcher) { +ClientPtr ClientFactoryImpl::create(Upstream::HostConstSharedPtr host, + Event::Dispatcher& dispatcher) { return ClientImpl::create(host, dispatcher, EncoderPtr{new EncoderImpl()}, decoder_factory_); } InstanceImpl::InstanceImpl(const std::string& cluster_name, Upstream::ClusterManager& cm, ClientFactory& client_factory, ThreadLocal::Instance& tls) : cm_(cm), client_factory_(client_factory), tls_(tls), tls_slot_(tls.allocateSlot()) { - tls.set(tls_slot_, - [this, cluster_name](Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectPtr { - return std::make_shared(*this, dispatcher, cluster_name); - }); + tls.set(tls_slot_, [this, cluster_name]( + Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectSharedPtr { + return std::make_shared(*this, dispatcher, cluster_name); + }); } ActiveRequest* InstanceImpl::makeRequest(const std::string& hash_key, const RespValue& value, @@ -94,13 +95,14 @@ InstanceImpl::ThreadLocalPool::ThreadLocalPool(InstanceImpl& parent, Event::Disp const std::string& cluster_name) : parent_(parent), dispatcher_(dispatcher), cluster_(parent_.cm_.get(cluster_name)) { - cluster_->hostSet().addMemberUpdateCb([this](const std::vector&, - const std::vector& hosts_removed) - -> void { onHostsRemoved(hosts_removed); }); + cluster_->hostSet().addMemberUpdateCb( + [this](const std::vector&, + const std::vector& hosts_removed) + -> void { onHostsRemoved(hosts_removed); }); } void InstanceImpl::ThreadLocalPool::onHostsRemoved( - const std::vector& hosts_removed) { + const std::vector& hosts_removed) { for (auto host : hosts_removed) { auto it = client_map_.find(host); if (it != client_map_.end()) { @@ -115,7 +117,7 @@ ActiveRequest* InstanceImpl::ThreadLocalPool::makeRequest(const std::string& has const RespValue& request, ActiveRequestCallbacks& callbacks) { LbContextImpl lb_context(hash_key); - Upstream::ConstHostPtr host = cluster_->loadBalancer().chooseHost(&lb_context); + Upstream::HostConstSharedPtr host = cluster_->loadBalancer().chooseHost(&lb_context); if (!host) { return nullptr; } diff --git a/source/common/redis/conn_pool_impl.h b/source/common/redis/conn_pool_impl.h index 9b9577cb19ba1..e22b92b7c88ff 100644 --- a/source/common/redis/conn_pool_impl.h +++ b/source/common/redis/conn_pool_impl.h @@ -18,7 +18,7 @@ namespace ConnPool { class ClientImpl : public Client, public DecoderCallbacks, public Network::ConnectionCallbacks { public: - static ClientPtr create(Upstream::ConstHostPtr host, Event::Dispatcher& dispatcher, + static ClientPtr create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher, EncoderPtr&& encoder, DecoderFactory& decoder_factory); ~ClientImpl(); @@ -74,7 +74,7 @@ class ClientImpl : public Client, public DecoderCallbacks, public Network::Conne class ClientFactoryImpl : public ClientFactory { public: // Redis::ConnPool::ClientFactoryImpl - ClientPtr create(Upstream::ConstHostPtr host, Event::Dispatcher& dispatcher) override; + ClientPtr create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher) override; static ClientFactoryImpl instance_; @@ -102,7 +102,7 @@ class InstanceImpl : public Instance { void onEvent(uint32_t events) override; ThreadLocalPool& parent_; - Upstream::ConstHostPtr host_; + Upstream::HostConstSharedPtr host_; ClientPtr redis_client_; }; @@ -114,7 +114,7 @@ class InstanceImpl : public Instance { ActiveRequest* makeRequest(const std::string& hash_key, const RespValue& request, ActiveRequestCallbacks& callbacks); - void onHostsRemoved(const std::vector& hosts_removed); + void onHostsRemoved(const std::vector& hosts_removed); // ThreadLocal::ThreadLocalObject void shutdown() override; @@ -122,7 +122,7 @@ class InstanceImpl : public Instance { InstanceImpl& parent_; Event::Dispatcher& dispatcher_; Upstream::ThreadLocalCluster* cluster_; - std::unordered_map client_map_; + std::unordered_map client_map_; }; struct LbContextImpl : public Upstream::LoadBalancerContext { diff --git a/source/common/router/config_impl.cc b/source/common/router/config_impl.cc index cf7826cf815af..5be726ecce444 100644 --- a/source/common/router/config_impl.cc +++ b/source/common/router/config_impl.cc @@ -241,8 +241,8 @@ const RouteEntry* RouteEntryImplBase::routeEntry() const { } } -RoutePtr RouteEntryImplBase::clusterEntry(const Http::HeaderMap& headers, - uint64_t random_value) const { +RouteConstSharedPtr RouteEntryImplBase::clusterEntry(const Http::HeaderMap& headers, + uint64_t random_value) const { // Gets the route object chosen from the list of weighted clusters // (if there is one) or returns self. if (weighted_clusters_.empty()) { @@ -272,7 +272,7 @@ RoutePtr RouteEntryImplBase::clusterEntry(const Http::HeaderMap& headers, // Find the right cluster to route to based on the interval in which // the selected value falls. The intervals are determined as // [0, cluster1_weight), [cluster1_weight, cluster1_weight+cluster2_weight),.. - for (const WeightedClusterEntryPtr& cluster : weighted_clusters_) { + for (const WeightedClusterEntrySharedPtr& cluster : weighted_clusters_) { end = begin + cluster->clusterWeight(); if (((selected_value >= begin) && (selected_value < end)) || (end >= WeightedClusterEntry::MAX_CLUSTER_WEIGHT)) { @@ -304,7 +304,7 @@ void RouteEntryImplBase::validateClusters(Upstream::ClusterManager& cm) const { throw EnvoyException(fmt::format("route: unknown cluster '{}'", cluster_name_)); } } else if (!weighted_clusters_.empty()) { - for (const WeightedClusterEntryPtr& cluster : weighted_clusters_) { + for (const WeightedClusterEntrySharedPtr& cluster : weighted_clusters_) { if (!cm.get(cluster->clusterName())) { throw EnvoyException( fmt::format("route: unknown weighted cluster '{}'", cluster->clusterName())); @@ -323,8 +323,8 @@ void PrefixRouteEntryImpl::finalizeRequestHeaders(Http::HeaderMap& headers) cons finalizePathHeader(headers, prefix_); } -RoutePtr PrefixRouteEntryImpl::matches(const Http::HeaderMap& headers, - uint64_t random_value) const { +RouteConstSharedPtr PrefixRouteEntryImpl::matches(const Http::HeaderMap& headers, + uint64_t random_value) const { if (RouteEntryImplBase::matchRoute(headers, random_value) && StringUtil::startsWith(headers.Path()->value().c_str(), prefix_, case_sensitive_)) { return clusterEntry(headers, random_value); @@ -342,7 +342,8 @@ void PathRouteEntryImpl::finalizeRequestHeaders(Http::HeaderMap& headers) const finalizePathHeader(headers, path_); } -RoutePtr PathRouteEntryImpl::matches(const Http::HeaderMap& headers, uint64_t random_value) const { +RouteConstSharedPtr PathRouteEntryImpl::matches(const Http::HeaderMap& headers, + uint64_t random_value) const { if (RouteEntryImplBase::matchRoute(headers, random_value)) { // TODO(mattklein123) PERF: Avoid copy. std::string path = headers.Path()->value().c_str(); @@ -414,7 +415,7 @@ VirtualHostImpl::VirtualHostImpl(const Json::Object& virtual_host, Runtime::Load bool VirtualHostImpl::usesRuntime() const { bool uses = false; - for (const RouteEntryImplBasePtr& route : routes_) { + for (const RouteEntryImplBaseConstSharedPtr& route : routes_) { // Currently a base runtime rule as well as a shadow rule can use runtime. uses |= (route->usesRuntime() || !route->shadowPolicy().runtimeKey().empty()); } @@ -438,7 +439,7 @@ RouteMatcher::RouteMatcher(const Json::Object& config, Runtime::Loader& runtime, config.validateSchema(Json::Schema::ROUTE_CONFIGURATION_SCHEMA); for (const Json::ObjectPtr& virtual_host_config : config.getObjectArray("virtual_hosts")) { - VirtualHostPtr virtual_host( + VirtualHostSharedPtr virtual_host( new VirtualHostImpl(*virtual_host_config, runtime, cm, validate_clusters)); uses_runtime_ |= virtual_host->usesRuntime(); @@ -460,8 +461,8 @@ RouteMatcher::RouteMatcher(const Json::Object& config, Runtime::Loader& runtime, } } -RoutePtr VirtualHostImpl::getRouteFromEntries(const Http::HeaderMap& headers, - uint64_t random_value) const { +RouteConstSharedPtr VirtualHostImpl::getRouteFromEntries(const Http::HeaderMap& headers, + uint64_t random_value) const { // First check for ssl redirect. if (ssl_requirements_ == SslRequirements::ALL && headers.ForwardedProto()->value() != "https") { return SSL_REDIRECT_ROUTE; @@ -471,8 +472,8 @@ RoutePtr VirtualHostImpl::getRouteFromEntries(const Http::HeaderMap& headers, } // Check for a route that matches the request. - for (const RouteEntryImplBasePtr& route : routes_) { - RoutePtr route_entry = route->matches(headers, random_value); + for (const RouteEntryImplBaseConstSharedPtr& route : routes_) { + RouteConstSharedPtr route_entry = route->matches(headers, random_value); if (nullptr != route_entry) { return route_entry; } @@ -497,7 +498,8 @@ const VirtualHostImpl* RouteMatcher::findVirtualHost(const Http::HeaderMap& head return nullptr; } -RoutePtr RouteMatcher::route(const Http::HeaderMap& headers, uint64_t random_value) const { +RouteConstSharedPtr RouteMatcher::route(const Http::HeaderMap& headers, + uint64_t random_value) const { const VirtualHostImpl* virtual_host = findVirtualHost(headers); if (virtual_host) { return virtual_host->getRouteFromEntries(headers, random_value); diff --git a/source/common/router/config_impl.h b/source/common/router/config_impl.h index 4861e0edf1dab..c6d374ce63a81 100644 --- a/source/common/router/config_impl.h +++ b/source/common/router/config_impl.h @@ -25,11 +25,12 @@ class Matchable { * allows stable choices between calls if desired. * @return true if input headers match this object. */ - virtual RoutePtr matches(const Http::HeaderMap& headers, uint64_t random_value) const PURE; + virtual RouteConstSharedPtr matches(const Http::HeaderMap& headers, + uint64_t random_value) const PURE; }; class RouteEntryImplBase; -typedef std::shared_ptr RouteEntryImplBasePtr; +typedef std::shared_ptr RouteEntryImplBaseConstSharedPtr; /** * Redirect entry that does an SSL redirect. @@ -58,7 +59,8 @@ class VirtualHostImpl : public VirtualHost { VirtualHostImpl(const Json::Object& virtual_host, Runtime::Loader& runtime, Upstream::ClusterManager& cm, bool validate_clusters); - RoutePtr getRouteFromEntries(const Http::HeaderMap& headers, uint64_t random_value) const; + RouteConstSharedPtr getRouteFromEntries(const Http::HeaderMap& headers, + uint64_t random_value) const; bool usesRuntime() const; const VirtualCluster* virtualClusterFromEntries(const Http::HeaderMap& headers) const; @@ -96,13 +98,13 @@ class VirtualHostImpl : public VirtualHost { static const std::shared_ptr SSL_REDIRECT_ROUTE; const std::string name_; - std::vector routes_; + std::vector routes_; std::vector virtual_clusters_; SslRequirements ssl_requirements_; const RateLimitPolicyImpl rate_limit_policy_; }; -typedef std::shared_ptr VirtualHostPtr; +typedef std::shared_ptr VirtualHostSharedPtr; /** * Implementation of RetryPolicy that reads from the JSON route config. @@ -199,7 +201,7 @@ class RouteEntryImplBase : public RouteEntry, const std::string prefix_rewrite_; const std::string host_rewrite_; - RoutePtr clusterEntry(const Http::HeaderMap& headers, uint64_t random_value) const; + RouteConstSharedPtr clusterEntry(const Http::HeaderMap& headers, uint64_t random_value) const; void finalizePathHeader(Http::HeaderMap& headers, const std::string& matched_path) const; private: @@ -272,7 +274,7 @@ class RouteEntryImplBase : public RouteEntry, const uint64_t cluster_weight_; }; - typedef std::shared_ptr WeightedClusterEntryPtr; + typedef std::shared_ptr WeightedClusterEntrySharedPtr; static Optional loadRuntimeData(const Json::Object& route); @@ -295,7 +297,7 @@ class RouteEntryImplBase : public RouteEntry, const ShadowPolicyImpl shadow_policy_; const Upstream::ResourcePriority priority_; std::vector config_headers_; - std::vector weighted_clusters_; + std::vector weighted_clusters_; std::unique_ptr hash_policy_; const std::multimap opaque_config_; }; @@ -312,7 +314,7 @@ class PrefixRouteEntryImpl : public RouteEntryImplBase { void finalizeRequestHeaders(Http::HeaderMap& headers) const override; // Router::Matchable - RoutePtr matches(const Http::HeaderMap& headers, uint64_t random_value) const override; + RouteConstSharedPtr matches(const Http::HeaderMap& headers, uint64_t random_value) const override; private: const std::string prefix_; @@ -330,7 +332,7 @@ class PathRouteEntryImpl : public RouteEntryImplBase { void finalizeRequestHeaders(Http::HeaderMap& headers) const override; // Router::Matchable - RoutePtr matches(const Http::HeaderMap& headers, uint64_t random_value) const override; + RouteConstSharedPtr matches(const Http::HeaderMap& headers, uint64_t random_value) const override; private: const std::string path_; @@ -345,14 +347,14 @@ class RouteMatcher { RouteMatcher(const Json::Object& config, Runtime::Loader& runtime, Upstream::ClusterManager& cm, bool validate_clusters); - RoutePtr route(const Http::HeaderMap& headers, uint64_t random_value) const; + RouteConstSharedPtr route(const Http::HeaderMap& headers, uint64_t random_value) const; bool usesRuntime() const { return uses_runtime_; } private: const VirtualHostImpl* findVirtualHost(const Http::HeaderMap& headers) const; - std::unordered_map virtual_hosts_; - VirtualHostPtr default_virtual_host_; + std::unordered_map virtual_hosts_; + VirtualHostSharedPtr default_virtual_host_; bool uses_runtime_{}; }; @@ -365,7 +367,7 @@ class ConfigImpl : public Config { bool validate_clusters); // Router::Config - RoutePtr route(const Http::HeaderMap& headers, uint64_t random_value) const override { + RouteConstSharedPtr route(const Http::HeaderMap& headers, uint64_t random_value) const override { return route_matcher_->route(headers, random_value); } @@ -397,7 +399,7 @@ class ConfigImpl : public Config { class NullConfigImpl : public Config { public: // Router::Config - RoutePtr route(const Http::HeaderMap&, uint64_t) const override { return nullptr; } + RouteConstSharedPtr route(const Http::HeaderMap&, uint64_t) const override { return nullptr; } const std::list& internalOnlyHeaders() const override { return internal_only_headers_; diff --git a/source/common/router/rds_impl.cc b/source/common/router/rds_impl.cc index 7b7ba26e3f9db..8a38f4d758f1c 100644 --- a/source/common/router/rds_impl.cc +++ b/source/common/router/rds_impl.cc @@ -56,13 +56,14 @@ RdsRouteConfigProviderImpl::RdsRouteConfigProviderImpl( throw EnvoyException(fmt::format("rds: unknown remote cluster '{}'", remote_cluster_name_)); } - ConfigPtr initial_config(new NullConfigImpl()); - tls_.set(tls_slot_, [initial_config](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectPtr { - return ThreadLocal::ThreadLocalObjectPtr{new ThreadLocalConfig(initial_config)}; - }); + ConfigConstSharedPtr initial_config(new NullConfigImpl()); + tls_.set(tls_slot_, + [initial_config](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectSharedPtr { + return ThreadLocal::ThreadLocalObjectSharedPtr{new ThreadLocalConfig(initial_config)}; + }); } -Router::ConfigPtr RdsRouteConfigProviderImpl::config() { +Router::ConfigConstSharedPtr RdsRouteConfigProviderImpl::config() { return tls_.getTyped(tls_slot_).config_; } @@ -81,7 +82,7 @@ void RdsRouteConfigProviderImpl::parseResponse(const Http::Message& response) { uint64_t new_hash = response_json->hash(); if (new_hash != last_config_hash_ || !initialized_) { response_json->validateSchema(Json::Schema::ROUTE_CONFIGURATION_SCHEMA); - ConfigPtr new_config(new ConfigImpl(*response_json, runtime_, cm_, false)); + ConfigConstSharedPtr new_config(new ConfigImpl(*response_json, runtime_, cm_, false)); initialized_ = true; last_config_hash_ = new_hash; stats_.config_reload_.inc(); diff --git a/source/common/router/rds_impl.h b/source/common/router/rds_impl.h index f7be67dfb721a..95eea7b21e613 100644 --- a/source/common/router/rds_impl.h +++ b/source/common/router/rds_impl.h @@ -37,10 +37,10 @@ class StaticRouteConfigProviderImpl : public RouteConfigProvider { Upstream::ClusterManager& cm); // Router::RouteConfigProvider - Router::ConfigPtr config() override { return config_; } + Router::ConfigConstSharedPtr config() override { return config_; } private: - ConfigPtr config_; + ConfigConstSharedPtr config_; }; /** @@ -77,7 +77,7 @@ class RdsRouteConfigProviderImpl : public RouteConfigProvider, } // Router::RouteConfigProvider - Router::ConfigPtr config() override; + Router::ConfigConstSharedPtr config() override; // Http::RestApiFetcher void createRequest(Http::Message& request) override; @@ -87,12 +87,12 @@ class RdsRouteConfigProviderImpl : public RouteConfigProvider, private: struct ThreadLocalConfig : public ThreadLocal::ThreadLocalObject { - ThreadLocalConfig(ConfigPtr initial_config) : config_(initial_config) {} + ThreadLocalConfig(ConfigConstSharedPtr initial_config) : config_(initial_config) {} // ThreadLocal::ThreadLocalObject void shutdown() override {} - ConfigPtr config_; + ConfigConstSharedPtr config_; }; RdsRouteConfigProviderImpl(const Json::Object& config, Runtime::Loader& runtime, diff --git a/source/common/router/router.cc b/source/common/router/router.cc index 67b1a69f80b6b..514b9e8d82144 100644 --- a/source/common/router/router.cc +++ b/source/common/router/router.cc @@ -92,12 +92,12 @@ Filter::~Filter() { ASSERT(!retry_state_); } -const std::string& Filter::upstreamZone(Upstream::HostDescriptionPtr upstream_host) { +const std::string& Filter::upstreamZone(Upstream::HostDescriptionConstSharedPtr upstream_host) { return upstream_host ? upstream_host->zone() : EMPTY_STRING; } void Filter::chargeUpstreamCode(const Http::HeaderMap& response_headers, - Upstream::HostDescriptionPtr upstream_host) { + Upstream::HostDescriptionConstSharedPtr upstream_host) { if (config_.emit_dynamic_stats_ && !callbacks_->requestInfo().healthCheck()) { const Http::HeaderEntry* upstream_canary_header = response_headers.EnvoyUpstreamCanary(); const Http::HeaderEntry* internal_request_header = downstream_headers_->EnvoyInternalRequest(); @@ -125,7 +125,8 @@ void Filter::chargeUpstreamCode(const Http::HeaderMap& response_headers, } } -void Filter::chargeUpstreamCode(Http::Code code, Upstream::HostDescriptionPtr upstream_host) { +void Filter::chargeUpstreamCode(Http::Code code, + Upstream::HostDescriptionConstSharedPtr upstream_host) { Http::HeaderMapImpl fake_response_headers{ {Http::Headers::get().Status, std::to_string(enumToInt(code))}}; chargeUpstreamCode(fake_response_headers, upstream_host); @@ -371,7 +372,7 @@ void Filter::onUpstreamReset(UpstreamResetType type, stream_log_debug("upstream reset", *callbacks_); } - Upstream::HostDescriptionPtr upstream_host; + Upstream::HostDescriptionConstSharedPtr upstream_host; if (upstream_request_) { upstream_host = upstream_request_->upstream_host_; if (upstream_host) { @@ -680,7 +681,7 @@ void Filter::UpstreamRequest::onPerTryTimeout() { } void Filter::UpstreamRequest::onPoolFailure(Http::ConnectionPool::PoolFailureReason reason, - Upstream::HostDescriptionPtr host) { + Upstream::HostDescriptionConstSharedPtr host) { Http::StreamResetReason reset_reason = Http::StreamResetReason::ConnectionFailure; switch (reason) { case Http::ConnectionPool::PoolFailureReason::Overflow: @@ -697,7 +698,7 @@ void Filter::UpstreamRequest::onPoolFailure(Http::ConnectionPool::PoolFailureRea } void Filter::UpstreamRequest::onPoolReady(Http::StreamEncoder& request_encoder, - Upstream::HostDescriptionPtr host) { + Upstream::HostDescriptionConstSharedPtr host) { stream_log_debug("pool ready", *parent_.callbacks_); onUpstreamHostSelected(host); request_encoder.getStream().addCallbacks(*this); diff --git a/source/common/router/router.h b/source/common/router/router.h index 7a0b8b2542c6f..76a9bfbaf99f0 100644 --- a/source/common/router/router.h +++ b/source/common/router/router.h @@ -93,7 +93,7 @@ class FilterConfig { ShadowWriterPtr shadow_writer_; }; -typedef std::shared_ptr FilterConfigPtr; +typedef std::shared_ptr FilterConfigSharedPtr; /** * Service routing filter. @@ -132,7 +132,7 @@ class Filter : Logger::Loggable, public Http::StreamDecoderF void setupPerTryTimeout(); void onPerTryTimeout(); - void onUpstreamHostSelected(Upstream::HostDescriptionPtr host) { + void onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) { upstream_host_ = host; parent_.callbacks_->requestInfo().onUpstreamHostSelected(host); } @@ -147,9 +147,9 @@ class Filter : Logger::Loggable, public Http::StreamDecoderF // Http::ConnectionPool::Callbacks void onPoolFailure(Http::ConnectionPool::PoolFailureReason reason, - Upstream::HostDescriptionPtr host) override; + Upstream::HostDescriptionConstSharedPtr host) override; void onPoolReady(Http::StreamEncoder& request_encoder, - Upstream::HostDescriptionPtr host) override; + Upstream::HostDescriptionConstSharedPtr host) override; Filter& parent_; Http::ConnectionPool::Instance& conn_pool_; @@ -158,7 +158,7 @@ class Filter : Logger::Loggable, public Http::StreamDecoderF Http::StreamEncoder* request_encoder_{}; Optional deferred_reset_reason_; Buffer::InstancePtr buffered_request_body_; - Upstream::HostDescriptionPtr upstream_host_; + Upstream::HostDescriptionConstSharedPtr upstream_host_; bool calling_encode_headers_ : 1; bool upstream_canary_ : 1; @@ -182,10 +182,10 @@ class Filter : Logger::Loggable, public Http::StreamDecoderF Http::AccessLog::ResponseFlag streamResetReasonToResponseFlag(Http::StreamResetReason reset_reason); - static const std::string& upstreamZone(Upstream::HostDescriptionPtr upstream_host); + static const std::string& upstreamZone(Upstream::HostDescriptionConstSharedPtr upstream_host); void chargeUpstreamCode(const Http::HeaderMap& response_headers, - Upstream::HostDescriptionPtr upstream_host); - void chargeUpstreamCode(Http::Code code, Upstream::HostDescriptionPtr upstream_host); + Upstream::HostDescriptionConstSharedPtr upstream_host); + void chargeUpstreamCode(Http::Code code, Upstream::HostDescriptionConstSharedPtr upstream_host); void cleanup(); virtual RetryStatePtr createRetryState(const RetryPolicy& policy, Http::HeaderMap& request_headers, @@ -211,9 +211,9 @@ class Filter : Logger::Loggable, public Http::StreamDecoderF FilterConfig& config_; Http::StreamDecoderFilterCallbacks* callbacks_{}; - RoutePtr route_; + RouteConstSharedPtr route_; const RouteEntry* route_entry_{}; - Upstream::ClusterInfoPtr cluster_; + Upstream::ClusterInfoConstSharedPtr cluster_; std::string alt_stat_prefix_; const VirtualCluster* request_vcluster_; Event::TimerPtr response_timeout_; diff --git a/source/common/runtime/runtime_impl.cc b/source/common/runtime/runtime_impl.cc index bfa5cae5fb6d0..3d1bd4055748d 100644 --- a/source/common/runtime/runtime_impl.cc +++ b/source/common/runtime/runtime_impl.cc @@ -140,9 +140,9 @@ RuntimeStats LoaderImpl::generateStats(Stats::Store& store) { void LoaderImpl::onSymlinkSwap() { current_snapshot_.reset(new SnapshotImpl(root_path_, override_path_, stats_, generator_)); - ThreadLocal::ThreadLocalObjectPtr ptr_copy = current_snapshot_; + ThreadLocal::ThreadLocalObjectSharedPtr ptr_copy = current_snapshot_; tls_.set(tls_slot_, [ptr_copy](Event::Dispatcher&) - -> ThreadLocal::ThreadLocalObjectPtr { return ptr_copy; }); + -> ThreadLocal::ThreadLocalObjectSharedPtr { return ptr_copy; }); } Snapshot& LoaderImpl::snapshot() { return tls_.getTyped(tls_slot_); } diff --git a/source/common/ssl/connection_impl.cc b/source/common/ssl/connection_impl.cc index bdf71dc0e9d25..fa569a37b44ab 100644 --- a/source/common/ssl/connection_impl.cc +++ b/source/common/ssl/connection_impl.cc @@ -11,8 +11,8 @@ namespace Ssl { ConnectionImpl::ConnectionImpl(Event::DispatcherImpl& dispatcher, int fd, - Network::Address::InstancePtr remote_address, - Network::Address::InstancePtr local_address, Context& ctx, + Network::Address::InstanceConstSharedPtr remote_address, + Network::Address::InstanceConstSharedPtr local_address, Context& ctx, InitialState state) : Network::ConnectionImpl(dispatcher, fd, remote_address, local_address), ctx_(dynamic_cast(ctx)), ssl_(ctx_.newSsl()) { @@ -236,7 +236,7 @@ std::string ConnectionImpl::uriSanPeerCertificate() { } ClientConnectionImpl::ClientConnectionImpl(Event::DispatcherImpl& dispatcher, Context& ctx, - Network::Address::InstancePtr address) + Network::Address::InstanceConstSharedPtr address) : ConnectionImpl(dispatcher, address->socket(Network::Address::SocketType::Stream), address, null_local_address_, ctx, InitialState::Client) {} diff --git a/source/common/ssl/connection_impl.h b/source/common/ssl/connection_impl.h index 30c37aafa383c..4d4926e25166c 100644 --- a/source/common/ssl/connection_impl.h +++ b/source/common/ssl/connection_impl.h @@ -11,8 +11,9 @@ class ConnectionImpl : public Network::ConnectionImpl, public Connection { enum class InitialState { Client, Server }; ConnectionImpl(Event::DispatcherImpl& dispatcher, int fd, - Network::Address::InstancePtr remote_address, - Network::Address::InstancePtr local_address, Context& ctx, InitialState state); + Network::Address::InstanceConstSharedPtr remote_address, + Network::Address::InstanceConstSharedPtr local_address, Context& ctx, + InitialState state); ~ConnectionImpl(); // Network::Connection @@ -41,7 +42,7 @@ class ConnectionImpl : public Network::ConnectionImpl, public Connection { class ClientConnectionImpl final : public ConnectionImpl, public Network::ClientConnection { public: ClientConnectionImpl(Event::DispatcherImpl& dispatcher, Context& ctx, - Network::Address::InstancePtr address); + Network::Address::InstanceConstSharedPtr address); // Network::ClientConnection void connect() override; diff --git a/source/common/stats/stats_impl.h b/source/common/stats/stats_impl.h index 93e538f147455..3f4571c2eebd8 100644 --- a/source/common/stats/stats_impl.h +++ b/source/common/stats/stats_impl.h @@ -211,8 +211,8 @@ class IsolatedStoreImpl : public Store { Timer& timer(const std::string& name) override { return timers_.get(name); } // Stats::Store - std::list counters() const override { return counters_.toList(); } - std::list gauges() const override { return gauges_.toList(); } + std::list counters() const override { return counters_.toList(); } + std::list gauges() const override { return gauges_.toList(); } ScopePtr createScope(const std::string& name) override { return ScopePtr{new ScopeImpl(*this, name)}; } diff --git a/source/common/stats/statsd.cc b/source/common/stats/statsd.cc index 405ee09c28391..ef16e9e196b49 100644 --- a/source/common/stats/statsd.cc +++ b/source/common/stats/statsd.cc @@ -13,7 +13,7 @@ namespace Stats { namespace Statsd { Writer::Writer(uint32_t port) { - Network::Address::InstancePtr address(new Network::Address::Ipv4Instance(port)); + Network::Address::InstanceConstSharedPtr address(new Network::Address::Ipv4Instance(port)); fd_ = address->socket(Network::Address::SocketType::Datagram); ASSERT(fd_ != -1); @@ -70,9 +70,10 @@ TcpStatsdSink::TcpStatsdSink(const LocalInfo::LocalInfo& local_info, fmt::format("TCP statsd requires setting --service-cluster and --service-node")); } - tls.set(tls_slot_, [this](Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectPtr { - return ThreadLocal::ThreadLocalObjectPtr{new TlsSink(*this, dispatcher)}; - }); + tls.set(tls_slot_, + [this](Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectSharedPtr { + return ThreadLocal::ThreadLocalObjectSharedPtr{new TlsSink(*this, dispatcher)}; + }); } TcpStatsdSink::TlsSink::TlsSink(TcpStatsdSink& parent, Event::Dispatcher& dispatcher) diff --git a/source/common/stats/thread_local_store.cc b/source/common/stats/thread_local_store.cc index 9a3dd1f8ea675..20d25ab135263 100644 --- a/source/common/stats/thread_local_store.cc +++ b/source/common/stats/thread_local_store.cc @@ -12,9 +12,9 @@ ThreadLocalStoreImpl::~ThreadLocalStoreImpl() { ASSERT(scopes_.empty()); } -std::list ThreadLocalStoreImpl::counters() const { +std::list ThreadLocalStoreImpl::counters() const { // Handle de-dup due to overlapping scopes. - std::list ret; + std::list ret; std::unordered_set names; std::unique_lock lock(lock_); for (ScopeImpl* scope : scopes_) { @@ -35,9 +35,9 @@ ScopePtr ThreadLocalStoreImpl::createScope(const std::string& name) { return std::move(new_scope); } -std::list ThreadLocalStoreImpl::gauges() const { +std::list ThreadLocalStoreImpl::gauges() const { // Handle de-dup due to overlapping scopes. - std::list ret; + std::list ret; std::unordered_set names; std::unique_lock lock(lock_); for (ScopeImpl* scope : scopes_) { @@ -56,8 +56,8 @@ void ThreadLocalStoreImpl::initializeThreading(Event::Dispatcher& main_thread_di main_thread_dispatcher_ = &main_thread_dispatcher; tls_ = &tls; tls_slot_ = tls_->allocateSlot(); - tls_->set(tls_slot_, [](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectPtr { - return ThreadLocal::ThreadLocalObjectPtr{new TlsCache()}; + tls_->set(tls_slot_, [](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectSharedPtr { + return ThreadLocal::ThreadLocalObjectSharedPtr{new TlsCache()}; }); } @@ -110,7 +110,7 @@ Counter& ThreadLocalStoreImpl::ScopeImpl::counter(const std::string& name) { // We now try to acquire a *reference* to the TLS cache shared pointer. This might remain null // if we don't have TLS initialized currently. The de-referenced pointer might be null if there // is no cache entry. - CounterPtr* tls_ref = nullptr; + CounterSharedPtr* tls_ref = nullptr; if (!parent_.shutting_down_ && parent_.tls_) { tls_ref = &parent_.tls_->getTyped(parent_.tls_slot_) .scope_cache_[this] @@ -125,7 +125,7 @@ Counter& ThreadLocalStoreImpl::ScopeImpl::counter(const std::string& name) { // We must now look in the central store so we must be locked. We grab a reference to the // central store location. It might contain nothing. In this case, we allocate a new stat. std::unique_lock lock(parent_.lock_); - CounterPtr& central_ref = central_cache_.counters_[final_name]; + CounterSharedPtr& central_ref = central_cache_.counters_[final_name]; if (!central_ref) { SafeAllocData alloc = parent_.safeAlloc(final_name); central_ref.reset(new CounterImpl(alloc.data_, alloc.free_)); @@ -160,7 +160,7 @@ Gauge& ThreadLocalStoreImpl::ScopeImpl::gauge(const std::string& name) { // See comments in counter(). There is no super clean way (via templates or otherwise) to // share this code so I'm leaving it largely duplicated for now. std::string final_name = prefix_ + name; - GaugePtr* tls_ref = nullptr; + GaugeSharedPtr* tls_ref = nullptr; if (!parent_.shutting_down_ && parent_.tls_) { tls_ref = &parent_.tls_->getTyped(parent_.tls_slot_).scope_cache_[this].gauges_[final_name]; @@ -171,7 +171,7 @@ Gauge& ThreadLocalStoreImpl::ScopeImpl::gauge(const std::string& name) { } std::unique_lock lock(parent_.lock_); - GaugePtr& central_ref = central_cache_.gauges_[final_name]; + GaugeSharedPtr& central_ref = central_cache_.gauges_[final_name]; if (!central_ref) { SafeAllocData alloc = parent_.safeAlloc(final_name); central_ref.reset(new GaugeImpl(alloc.data_, alloc.free_)); @@ -188,7 +188,7 @@ Timer& ThreadLocalStoreImpl::ScopeImpl::timer(const std::string& name) { // See comments in counter(). There is no super clean way (via templates or otherwise) to // share this code so I'm leaving it largely duplicated for now. std::string final_name = prefix_ + name; - TimerPtr* tls_ref = nullptr; + TimerSharedPtr* tls_ref = nullptr; if (!parent_.shutting_down_ && parent_.tls_) { tls_ref = &parent_.tls_->getTyped(parent_.tls_slot_).scope_cache_[this].timers_[final_name]; @@ -199,7 +199,7 @@ Timer& ThreadLocalStoreImpl::ScopeImpl::timer(const std::string& name) { } std::unique_lock lock(parent_.lock_); - TimerPtr& central_ref = central_cache_.timers_[final_name]; + TimerSharedPtr& central_ref = central_cache_.timers_[final_name]; if (!central_ref) { central_ref.reset(new TimerImpl(final_name, parent_)); } diff --git a/source/common/stats/thread_local_store.h b/source/common/stats/thread_local_store.h index 6d2d7e2564cb7..22498e5821c7f 100644 --- a/source/common/stats/thread_local_store.h +++ b/source/common/stats/thread_local_store.h @@ -52,9 +52,9 @@ class ThreadLocalStoreImpl : public StoreRoot { Timer& timer(const std::string& name) override { return default_scope_->timer(name); } // Stats::Store - std::list counters() const override; + std::list counters() const override; ScopePtr createScope(const std::string& name) override; - std::list gauges() const override; + std::list gauges() const override; // Stats::StoreRoot void addSink(Sink& sink) override { timer_sinks_.push_back(sink); } @@ -64,9 +64,9 @@ class ThreadLocalStoreImpl : public StoreRoot { private: struct TlsCacheEntry { - std::unordered_map counters_; - std::unordered_map gauges_; - std::unordered_map timers_; + std::unordered_map counters_; + std::unordered_map gauges_; + std::unordered_map timers_; }; struct ScopeImpl : public Scope { diff --git a/source/common/thread_local/thread_local_impl.cc b/source/common/thread_local/thread_local_impl.cc index d3b44913fbd4e..0e886e50dd84f 100644 --- a/source/common/thread_local/thread_local_impl.cc +++ b/source/common/thread_local/thread_local_impl.cc @@ -13,7 +13,7 @@ std::list> InstanceImpl::registered_th InstanceImpl::~InstanceImpl() { reset(); } -ThreadLocalObjectPtr InstanceImpl::get(uint32_t index) { +ThreadLocalObjectSharedPtr InstanceImpl::get(uint32_t index) { ASSERT(thread_local_data_.data_.size() > index); return thread_local_data_.data_[index]; } @@ -49,7 +49,7 @@ void InstanceImpl::set(uint32_t index, InitializeCb cb) { setThreadLocal(index, cb(*main_thread_dispatcher_)); } -void InstanceImpl::setThreadLocal(uint32_t index, ThreadLocalObjectPtr object) { +void InstanceImpl::setThreadLocal(uint32_t index, ThreadLocalObjectSharedPtr object) { if (thread_local_data_.data_.size() <= index) { thread_local_data_.data_.resize(index + 1); } diff --git a/source/common/thread_local/thread_local_impl.h b/source/common/thread_local/thread_local_impl.h index 314021a80ea25..dbe2544e37667 100644 --- a/source/common/thread_local/thread_local_impl.h +++ b/source/common/thread_local/thread_local_impl.h @@ -16,7 +16,7 @@ class InstanceImpl : Logger::Loggable, public Instance { // Server::ThreadLocal uint32_t allocateSlot() override { return next_slot_id_++; } - ThreadLocalObjectPtr get(uint32_t index) override; + ThreadLocalObjectSharedPtr get(uint32_t index) override; void registerThread(Event::Dispatcher& dispatcher, bool main_thread) override; void runOnAllThreads(Event::PostCb cb) override; void set(uint32_t index, InitializeCb cb) override; @@ -24,11 +24,11 @@ class InstanceImpl : Logger::Loggable, public Instance { private: struct ThreadLocalData { - std::vector data_; + std::vector data_; }; void reset(); - static void setThreadLocal(uint32_t index, ThreadLocalObjectPtr object); + static void setThreadLocal(uint32_t index, ThreadLocalObjectSharedPtr object); static std::atomic next_slot_id_; static thread_local ThreadLocalData thread_local_data_; diff --git a/source/common/tracing/http_tracer_impl.cc b/source/common/tracing/http_tracer_impl.cc index 94fd1925d9abf..1c2f2d83bb786 100644 --- a/source/common/tracing/http_tracer_impl.cc +++ b/source/common/tracing/http_tracer_impl.cc @@ -236,13 +236,15 @@ LightStepDriver::LightStepDriver(const Json::Object& config, fmt::format("{} collector cluster must support http2 for gRPC calls", cluster_->name())); } - tls_.set(tls_slot_, [this](Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectPtr { - lightstep::Tracer tracer(lightstep::NewUserDefinedTransportLightStepTracer( - *options_, std::bind(&LightStepRecorder::NewInstance, std::ref(*this), std::ref(dispatcher), - std::placeholders::_1))); - - return ThreadLocal::ThreadLocalObjectPtr{new TlsLightStepTracer(std::move(tracer), *this)}; - }); + tls_.set(tls_slot_, + [this](Event::Dispatcher& dispatcher) -> ThreadLocal::ThreadLocalObjectSharedPtr { + lightstep::Tracer tracer(lightstep::NewUserDefinedTransportLightStepTracer( + *options_, std::bind(&LightStepRecorder::NewInstance, std::ref(*this), + std::ref(dispatcher), std::placeholders::_1))); + + return ThreadLocal::ThreadLocalObjectSharedPtr{ + new TlsLightStepTracer(std::move(tracer), *this)}; + }); } SpanPtr LightStepDriver::startSpan(Http::HeaderMap& request_headers, diff --git a/source/common/tracing/http_tracer_impl.h b/source/common/tracing/http_tracer_impl.h index 6777079402c08..114960083ad48 100644 --- a/source/common/tracing/http_tracer_impl.h +++ b/source/common/tracing/http_tracer_impl.h @@ -113,7 +113,7 @@ class LightStepDriver : public Driver { SystemTime start_time) override; Upstream::ClusterManager& clusterManager() { return cm_; } - Upstream::ClusterInfoPtr cluster() { return cluster_; } + Upstream::ClusterInfoConstSharedPtr cluster() { return cluster_; } Runtime::Loader& runtime() { return runtime_; } LightstepTracerStats& tracerStats() { return tracer_stats_; } @@ -128,7 +128,7 @@ class LightStepDriver : public Driver { }; Upstream::ClusterManager& cm_; - Upstream::ClusterInfoPtr cluster_; + Upstream::ClusterInfoConstSharedPtr cluster_; LightstepTracerStats tracer_stats_; ThreadLocal::Instance& tls_; Runtime::Loader& runtime_; diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index fc9d61d8767e8..7f06329b84c6d 100644 --- a/source/common/upstream/cluster_manager_impl.cc +++ b/source/common/upstream/cluster_manager_impl.cc @@ -188,8 +188,8 @@ ClusterManagerImpl::ClusterManagerImpl(const Json::Object& config, ClusterManage tls.set(thread_local_slot_, [this, local_cluster_name](Event::Dispatcher& dispatcher) - -> ThreadLocal::ThreadLocalObjectPtr { - return ThreadLocal::ThreadLocalObjectPtr{ + -> ThreadLocal::ThreadLocalObjectSharedPtr { + return ThreadLocal::ThreadLocalObjectSharedPtr{ new ThreadLocalClusterManagerImpl(*this, dispatcher, local_cluster_name)}; }); @@ -215,7 +215,7 @@ void ClusterManagerImpl::postInitializeCluster(Cluster& cluster) { return; } - postThreadLocalClusterUpdate(cluster, cluster.hosts(), std::vector{}); + postThreadLocalClusterUpdate(cluster, cluster.hosts(), std::vector{}); } bool ClusterManagerImpl::addOrUpdatePrimaryCluster(const Json::Object& new_config) { @@ -234,7 +234,7 @@ bool ClusterManagerImpl::addOrUpdatePrimaryCluster(const Json::Object& new_confi } loadCluster(new_config, true); - ClusterInfoPtr new_cluster = primary_clusters_.at(cluster_name).cluster_->info(); + ClusterInfoConstSharedPtr new_cluster = primary_clusters_.at(cluster_name).cluster_->info(); tls_.runOnAllThreads([this, new_cluster]() -> void { ThreadLocalClusterManagerImpl& cluster_manager = tls_.getTyped(thread_local_slot_); @@ -280,12 +280,13 @@ void ClusterManagerImpl::loadCluster(const Json::Object& cluster, bool added_via } const Cluster& primary_cluster_reference = *new_cluster; - new_cluster->addMemberUpdateCb([&primary_cluster_reference, this]( - const std::vector& hosts_added, const std::vector& hosts_removed) { - // This fires when a cluster is about to have an updated member set. We need to send this - // out to all of the thread local configurations. - postThreadLocalClusterUpdate(primary_cluster_reference, hosts_added, hosts_removed); - }); + new_cluster->addMemberUpdateCb( + [&primary_cluster_reference, this](const std::vector& hosts_added, + const std::vector& hosts_removed) { + // This fires when a cluster is about to have an updated member set. We need to send this + // out to all of the thread local configurations. + postThreadLocalClusterUpdate(primary_cluster_reference, hosts_added, hosts_removed); + }); // emplace() will do nothing if the key already exists. Always erase first. size_t num_erased = primary_clusters_.erase(primary_cluster_reference.info()->name()); @@ -328,16 +329,17 @@ ClusterManagerImpl::httpConnPoolForCluster(const std::string& cluster, ResourceP return entry->second->connPool(priority, context); } -void ClusterManagerImpl::postThreadLocalClusterUpdate(const Cluster& primary_cluster, - const std::vector& hosts_added, - const std::vector& hosts_removed) { +void ClusterManagerImpl::postThreadLocalClusterUpdate( + const Cluster& primary_cluster, const std::vector& hosts_added, + const std::vector& hosts_removed) { const std::string& name = primary_cluster.info()->name(); - ConstHostVectorPtr hosts_copy(new std::vector(primary_cluster.hosts())); - ConstHostVectorPtr healthy_hosts_copy(new std::vector(primary_cluster.healthyHosts())); - ConstHostListsPtr hosts_per_zone_copy( - new std::vector>(primary_cluster.hostsPerZone())); - ConstHostListsPtr healthy_hosts_per_zone_copy( - new std::vector>(primary_cluster.healthyHostsPerZone())); + HostVectorConstSharedPtr hosts_copy(new std::vector(primary_cluster.hosts())); + HostVectorConstSharedPtr healthy_hosts_copy( + new std::vector(primary_cluster.healthyHosts())); + HostListsConstSharedPtr hosts_per_zone_copy( + new std::vector>(primary_cluster.hostsPerZone())); + HostListsConstSharedPtr healthy_hosts_per_zone_copy( + new std::vector>(primary_cluster.healthyHostsPerZone())); tls_.runOnAllThreads([this, name, hosts_copy, healthy_hosts_copy, hosts_per_zone_copy, healthy_hosts_per_zone_copy, hosts_added, hosts_removed]() -> void { @@ -356,7 +358,7 @@ Host::CreateConnectionData ClusterManagerImpl::tcpConnForCluster(const std::stri throw EnvoyException(fmt::format("unknown cluster '{}'", cluster)); } - ConstHostPtr logical_host = entry->second->lb_->chooseHost(nullptr); + HostConstSharedPtr logical_host = entry->second->lb_->chooseHost(nullptr); if (logical_host) { return logical_host->createConnection(cluster_manager.thread_local_dispatcher_); } else { @@ -408,8 +410,8 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::~ThreadLocalClusterManagerImp } void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools( - const std::vector& hosts) { - for (const HostPtr& host : hosts) { + const std::vector& hosts) { + for (const HostSharedPtr& host : hosts) { auto container = host_http_conn_pool_map_.find(host); if (container != host_http_conn_pool_map_.end()) { drainConnPools(host, container->second); @@ -418,7 +420,7 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools( } void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools( - HostPtr old_host, ConnPoolsContainer& container) { + HostSharedPtr old_host, ConnPoolsContainer& container) { for (const Http::ConnectionPool::InstancePtr& pool : container.pools_) { if (pool) { container.drains_remaining_++; @@ -445,9 +447,9 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::drainConnPools( } void ClusterManagerImpl::ThreadLocalClusterManagerImpl::updateClusterMembership( - const std::string& name, ConstHostVectorPtr hosts, ConstHostVectorPtr healthy_hosts, - ConstHostListsPtr hosts_per_zone, ConstHostListsPtr healthy_hosts_per_zone, - const std::vector& hosts_added, const std::vector& hosts_removed, + const std::string& name, HostVectorConstSharedPtr hosts, HostVectorConstSharedPtr healthy_hosts, + HostListsConstSharedPtr hosts_per_zone, HostListsConstSharedPtr healthy_hosts_per_zone, + const std::vector& hosts_added, const std::vector& hosts_removed, ThreadLocal::Instance& tls, uint32_t thead_local_slot) { ThreadLocalClusterManagerImpl& config = @@ -466,7 +468,7 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::shutdown() { } ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::ClusterEntry( - ThreadLocalClusterManagerImpl& parent, ClusterInfoPtr cluster) + ThreadLocalClusterManagerImpl& parent, ClusterInfoConstSharedPtr cluster) : parent_(parent), cluster_info_(cluster), http_async_client_(*cluster, parent.parent_.stats_, parent.thread_local_dispatcher_, parent.parent_.local_info_, parent.parent_, parent.parent_.runtime_, @@ -496,13 +498,13 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::ClusterEntry( } } - host_set_.addMemberUpdateCb( - [this](const std::vector&, const std::vector& hosts_removed) -> void { - // We need to go through and purge any connection pools for hosts that got deleted. - // Even if two hosts actually point to the same address this will be safe, since if a - // host is readded it will be a different physical HostPtr. - parent_.drainConnPools(hosts_removed); - }); + host_set_.addMemberUpdateCb([this](const std::vector&, + const std::vector& hosts_removed) -> void { + // We need to go through and purge any connection pools for hosts that got deleted. + // Even if two hosts actually point to the same address this will be safe, since if a + // host is readded it will be a different physical HostSharedPtr. + parent_.drainConnPools(hosts_removed); + }); } ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::~ClusterEntry() { @@ -518,7 +520,7 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::~ClusterEntry() Http::ConnectionPool::Instance* ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::connPool( ResourcePriority priority, LoadBalancerContext* context) { - ConstHostPtr host = lb_->chooseHost(context); + HostConstSharedPtr host = lb_->chooseHost(context); if (!host) { cluster_info_->stats().upstream_cx_none_healthy_.inc(); return nullptr; @@ -535,7 +537,7 @@ ClusterManagerImpl::ThreadLocalClusterManagerImpl::ClusterEntry::connPool( } Http::ConnectionPool::InstancePtr -ProdClusterManagerFactory::allocateConnPool(Event::Dispatcher& dispatcher, ConstHostPtr host, +ProdClusterManagerFactory::allocateConnPool(Event::Dispatcher& dispatcher, HostConstSharedPtr host, ResourcePriority priority) { if ((host->cluster().features() & ClusterInfo::Features::HTTP2) && runtime_.snapshot().featureEnabled("upstream.use_http2", 100)) { @@ -550,7 +552,7 @@ ProdClusterManagerFactory::allocateConnPool(Event::Dispatcher& dispatcher, Const ClusterPtr ProdClusterManagerFactory::clusterFromJson(const Json::Object& cluster, ClusterManager& cm, const Optional& sds_config, - Outlier::EventLoggerPtr outlier_event_logger) { + Outlier::EventLoggerSharedPtr outlier_event_logger) { return ClusterImplBase::create(cluster, cm, stats_, tls_, dns_resolver_, ssl_context_manager_, runtime_, random_, primary_dispatcher_, sds_config, local_info_, outlier_event_logger); diff --git a/source/common/upstream/cluster_manager_impl.h b/source/common/upstream/cluster_manager_impl.h index fe744d42bf15c..9b95b93632698 100644 --- a/source/common/upstream/cluster_manager_impl.h +++ b/source/common/upstream/cluster_manager_impl.h @@ -30,11 +30,11 @@ class ProdClusterManagerFactory : public ClusterManagerFactory { // Upstream::ClusterManagerFactory Http::ConnectionPool::InstancePtr allocateConnPool(Event::Dispatcher& dispatcher, - ConstHostPtr host, + HostConstSharedPtr host, ResourcePriority priority) override; ClusterPtr clusterFromJson(const Json::Object& cluster, ClusterManager& cm, const Optional& sds_config, - Outlier::EventLoggerPtr outlier_event_logger) override; + Outlier::EventLoggerSharedPtr outlier_event_logger) override; CdsApiPtr createCds(const Json::Object& config, ClusterManager& cm) override; private: @@ -148,7 +148,7 @@ class ClusterManagerImpl : public ClusterManager { }; struct ClusterEntry : public ThreadLocalCluster { - ClusterEntry(ThreadLocalClusterManagerImpl& parent, ClusterInfoPtr cluster); + ClusterEntry(ThreadLocalClusterManagerImpl& parent, ClusterInfoConstSharedPtr cluster); ~ClusterEntry(); Http::ConnectionPool::Instance* connPool(ResourcePriority priority, @@ -156,13 +156,13 @@ class ClusterManagerImpl : public ClusterManager { // Upstream::ThreadLocalCluster const HostSet& hostSet() override { return host_set_; } - ClusterInfoPtr info() override { return cluster_info_; } + ClusterInfoConstSharedPtr info() override { return cluster_info_; } LoadBalancer& loadBalancer() override { return *lb_; } ThreadLocalClusterManagerImpl& parent_; HostSetImpl host_set_; LoadBalancerPtr lb_; - ClusterInfoPtr cluster_info_; + ClusterInfoConstSharedPtr cluster_info_; Http::AsyncClientImpl http_async_client_; }; @@ -171,14 +171,14 @@ class ClusterManagerImpl : public ClusterManager { ThreadLocalClusterManagerImpl(ClusterManagerImpl& parent, Event::Dispatcher& dispatcher, const Optional& local_cluster_name); ~ThreadLocalClusterManagerImpl(); - void drainConnPools(const std::vector& hosts); - void drainConnPools(HostPtr old_host, ConnPoolsContainer& container); - static void updateClusterMembership(const std::string& name, ConstHostVectorPtr hosts, - ConstHostVectorPtr healthy_hosts, - ConstHostListsPtr hosts_per_zone, - ConstHostListsPtr healthy_hosts_per_zone, - const std::vector& hosts_added, - const std::vector& hosts_removed, + void drainConnPools(const std::vector& hosts); + void drainConnPools(HostSharedPtr old_host, ConnPoolsContainer& container); + static void updateClusterMembership(const std::string& name, HostVectorConstSharedPtr hosts, + HostVectorConstSharedPtr healthy_hosts, + HostListsConstSharedPtr hosts_per_zone, + HostListsConstSharedPtr healthy_hosts_per_zone, + const std::vector& hosts_added, + const std::vector& hosts_removed, ThreadLocal::Instance& tls, uint32_t thread_local_slot); // ThreadLocal::ThreadLocalObject @@ -187,7 +187,7 @@ class ClusterManagerImpl : public ClusterManager { ClusterManagerImpl& parent_; Event::Dispatcher& thread_local_dispatcher_; std::unordered_map thread_local_clusters_; - std::unordered_map host_http_conn_pool_map_; + std::unordered_map host_http_conn_pool_map_; const HostSet* local_host_set_{}; }; @@ -204,8 +204,8 @@ class ClusterManagerImpl : public ClusterManager { void loadCluster(const Json::Object& cluster, bool added_via_api); void postInitializeCluster(Cluster& cluster); void postThreadLocalClusterUpdate(const Cluster& primary_cluster, - const std::vector& hosts_added, - const std::vector& hosts_removed); + const std::vector& hosts_added, + const std::vector& hosts_removed); ClusterManagerFactory& factory_; Runtime::Loader& runtime_; @@ -215,7 +215,7 @@ class ClusterManagerImpl : public ClusterManager { uint32_t thread_local_slot_; std::unordered_map primary_clusters_; Optional sds_config_; - Outlier::EventLoggerPtr outlier_event_logger_; + Outlier::EventLoggerSharedPtr outlier_event_logger_; const LocalInfo::LocalInfo& local_info_; CdsApiPtr cds_api_; ClusterManagerStats cm_stats_; diff --git a/source/common/upstream/health_checker_impl.cc b/source/common/upstream/health_checker_impl.cc index 6674fc748e994..942ff1b87063f 100644 --- a/source/common/upstream/health_checker_impl.cc +++ b/source/common/upstream/health_checker_impl.cc @@ -32,9 +32,9 @@ HealthCheckerImplBase::HealthCheckerImplBase(const Cluster& cluster, const Json: stats_(generateStats(cluster.info()->statsScope())), runtime_(runtime), random_(random), interval_(config.getInteger("interval_ms")), interval_jitter_(config.getInteger("interval_jitter_ms", 0)) { - cluster_.addMemberUpdateCb( - [this](const std::vector& hosts_added, const std::vector& hosts_removed) - -> void { onClusterMemberUpdate(hosts_added, hosts_removed); }); + cluster_.addMemberUpdateCb([this](const std::vector& hosts_added, + const std::vector& hosts_removed) + -> void { onClusterMemberUpdate(hosts_added, hosts_removed); }); } void HealthCheckerImplBase::decHealthy() { @@ -85,7 +85,7 @@ void HealthCheckerImplBase::refreshHealthyStat() { stats_.healthy_.set(local_process_healthy_); } -void HealthCheckerImplBase::runCallbacks(HostPtr host, bool changed_state) { +void HealthCheckerImplBase::runCallbacks(HostSharedPtr host, bool changed_state) { // When a parent process shuts down, it will kill all of the active health checking sessions, // which will decrement the healthy count and the healthy stat in the parent. If the child is // stable and does not update, the healthy stat will be wrong. This routine is called any time @@ -98,7 +98,7 @@ void HealthCheckerImplBase::runCallbacks(HostPtr host, bool changed_state) { } HealthCheckerImplBase::ActiveHealthCheckSession::ActiveHealthCheckSession( - HealthCheckerImplBase& parent, HostPtr host) + HealthCheckerImplBase& parent, HostSharedPtr host) : parent_(parent), host_(host), interval_timer_(parent.dispatcher_.createTimer([this]() -> void { onInterval(); })), timeout_timer_(parent.dispatcher_.createTimer([this]() -> void { onTimeout(); })) { @@ -168,13 +168,13 @@ HttpHealthCheckerImpl::HttpHealthCheckerImpl(const Cluster& cluster, const Json: } } -void HttpHealthCheckerImpl::onClusterMemberUpdate(const std::vector& hosts_added, - const std::vector& hosts_removed) { - for (const HostPtr& host : hosts_added) { +void HttpHealthCheckerImpl::onClusterMemberUpdate(const std::vector& hosts_added, + const std::vector& hosts_removed) { + for (const HostSharedPtr& host : hosts_added) { active_sessions_[host].reset(new HttpActiveHealthCheckSession(*this, host)); } - for (const HostPtr& host : hosts_removed) { + for (const HostSharedPtr& host : hosts_removed) { auto session_iter = active_sessions_.find(host); ASSERT(active_sessions_.end() != session_iter); active_sessions_.erase(session_iter); @@ -182,13 +182,13 @@ void HttpHealthCheckerImpl::onClusterMemberUpdate(const std::vector& ho } void HttpHealthCheckerImpl::start() { - for (const HostPtr& host : cluster_.hosts()) { + for (const HostSharedPtr& host : cluster_.hosts()) { active_sessions_[host].reset(new HttpActiveHealthCheckSession(*this, host)); } } HttpHealthCheckerImpl::HttpActiveHealthCheckSession::HttpActiveHealthCheckSession( - HttpHealthCheckerImpl& parent, HostPtr host) + HttpHealthCheckerImpl& parent, HostSharedPtr host) : ActiveHealthCheckSession(parent, host), parent_(parent) { onInterval(); } @@ -355,13 +355,13 @@ TcpHealthCheckerImpl::TcpHealthCheckerImpl(const Cluster& cluster, const Json::O send_bytes_(TcpHealthCheckMatcher::loadJsonBytes(config.getObjectArray("send"))), receive_bytes_(TcpHealthCheckMatcher::loadJsonBytes(config.getObjectArray("receive"))) {} -void TcpHealthCheckerImpl::onClusterMemberUpdate(const std::vector& hosts_added, - const std::vector& hosts_removed) { - for (const HostPtr& host : hosts_added) { +void TcpHealthCheckerImpl::onClusterMemberUpdate(const std::vector& hosts_added, + const std::vector& hosts_removed) { + for (const HostSharedPtr& host : hosts_added) { active_sessions_[host].reset(new TcpActiveHealthCheckSession(*this, host)); } - for (const HostPtr& host : hosts_removed) { + for (const HostSharedPtr& host : hosts_removed) { auto session_iter = active_sessions_.find(host); ASSERT(active_sessions_.end() != session_iter); active_sessions_.erase(session_iter); @@ -369,7 +369,7 @@ void TcpHealthCheckerImpl::onClusterMemberUpdate(const std::vector& hos } void TcpHealthCheckerImpl::start() { - for (const HostPtr& host : cluster_.hosts()) { + for (const HostSharedPtr& host : cluster_.hosts()) { active_sessions_[host].reset(new TcpActiveHealthCheckSession(*this, host)); } } diff --git a/source/common/upstream/health_checker_impl.h b/source/common/upstream/health_checker_impl.h index c6e4b2f814a0b..2aefa2b6579d2 100644 --- a/source/common/upstream/health_checker_impl.h +++ b/source/common/upstream/health_checker_impl.h @@ -45,7 +45,7 @@ class HealthCheckerImplBase : public HealthChecker, protected Logger::Loggable& hosts_added, - const std::vector& hosts_removed) PURE; + virtual void onClusterMemberUpdate(const std::vector& hosts_added, + const std::vector& hosts_removed) PURE; const Cluster& cluster_; Event::Dispatcher& dispatcher_; @@ -86,7 +86,7 @@ class HealthCheckerImplBase : public HealthChecker, protected Logger::Loggable& hosts_added, - const std::vector& hosts_removed) override; + void onClusterMemberUpdate(const std::vector& hosts_added, + const std::vector& hosts_removed) override; const std::string path_; - std::unordered_map active_sessions_; + std::unordered_map active_sessions_; Optional service_name_; }; @@ -251,7 +251,7 @@ class TcpHealthCheckerImpl : public HealthCheckerImplBase { }; struct TcpActiveHealthCheckSession : public ActiveHealthCheckSession { - TcpActiveHealthCheckSession(TcpHealthCheckerImpl& parent, HostPtr host) + TcpActiveHealthCheckSession(TcpHealthCheckerImpl& parent, HostSharedPtr host) : ActiveHealthCheckSession(parent, host), parent_(parent) { onInterval(); } @@ -274,12 +274,12 @@ class TcpHealthCheckerImpl : public HealthCheckerImplBase { typedef std::unique_ptr TcpActiveHealthCheckSessionPtr; // HealthChecker - void onClusterMemberUpdate(const std::vector& hosts_added, - const std::vector& hosts_removed) override; + void onClusterMemberUpdate(const std::vector& hosts_added, + const std::vector& hosts_removed) override; const TcpHealthCheckMatcher::MatchSegments send_bytes_; const TcpHealthCheckMatcher::MatchSegments receive_bytes_; - std::unordered_map active_sessions_; + std::unordered_map active_sessions_; }; } // Upstream diff --git a/source/common/upstream/load_balancer_impl.cc b/source/common/upstream/load_balancer_impl.cc index 65b7f128973c6..4b6835540bdd1 100644 --- a/source/common/upstream/load_balancer_impl.cc +++ b/source/common/upstream/load_balancer_impl.cc @@ -18,10 +18,11 @@ LoadBalancerBase::LoadBalancerBase(const HostSet& host_set, const HostSet* local : stats_(stats), runtime_(runtime), random_(random), host_set_(host_set), local_host_set_(local_host_set) { if (local_host_set_) { - host_set_.addMemberUpdateCb([this](const std::vector&, const std::vector&) - -> void { regenerateZoneRoutingStructures(); }); + host_set_.addMemberUpdateCb( + [this](const std::vector&, const std::vector&) + -> void { regenerateZoneRoutingStructures(); }); local_host_set_->addMemberUpdateCb( - [this](const std::vector&, const std::vector&) + [this](const std::vector&, const std::vector&) -> void { regenerateZoneRoutingStructures(); }); } } @@ -131,7 +132,7 @@ bool LoadBalancerUtility::isGlobalPanic(const HostSet& host_set, ClusterStats& s } void LoadBalancerBase::calculateZonePercentage( - const std::vector>& hosts_per_zone, uint64_t* ret) { + const std::vector>& hosts_per_zone, uint64_t* ret) { uint64_t total_hosts = 0; for (const auto& zone_hosts : hosts_per_zone) { total_hosts += zone_hosts.size(); @@ -145,7 +146,7 @@ void LoadBalancerBase::calculateZonePercentage( } } -const std::vector& LoadBalancerBase::tryChooseLocalZoneHosts() { +const std::vector& LoadBalancerBase::tryChooseLocalZoneHosts() { ASSERT(zone_routing_state_ != ZoneRoutingState::NoZoneRouting); // At this point it's guaranteed to be at least 2 zones. @@ -193,7 +194,7 @@ const std::vector& LoadBalancerBase::tryChooseLocalZoneHosts() { return host_set_.healthyHostsPerZone()[i]; } -const std::vector& LoadBalancerBase::hostsToUse() { +const std::vector& LoadBalancerBase::hostsToUse() { ASSERT(host_set_.healthyHosts().size() <= host_set_.hosts().size()); if (host_set_.hosts().empty() || @@ -218,8 +219,8 @@ const std::vector& LoadBalancerBase::hostsToUse() { return tryChooseLocalZoneHosts(); } -ConstHostPtr RoundRobinLoadBalancer::chooseHost(const LoadBalancerContext*) { - const std::vector& hosts_to_use = hostsToUse(); +HostConstSharedPtr RoundRobinLoadBalancer::chooseHost(const LoadBalancerContext*) { + const std::vector& hosts_to_use = hostsToUse(); if (hosts_to_use.empty()) { return nullptr; } @@ -232,22 +233,22 @@ LeastRequestLoadBalancer::LeastRequestLoadBalancer(const HostSet& host_set, ClusterStats& stats, Runtime::Loader& runtime, Runtime::RandomGenerator& random) : LoadBalancerBase(host_set, local_host_set, stats, runtime, random) { - host_set.addMemberUpdateCb( - [this](const std::vector&, const std::vector& hosts_removed) -> void { - if (last_host_) { - for (const HostPtr& host : hosts_removed) { - if (host == last_host_) { - hits_left_ = 0; - last_host_.reset(); - - break; - } - } + host_set.addMemberUpdateCb([this](const std::vector&, + const std::vector& hosts_removed) -> void { + if (last_host_) { + for (const HostSharedPtr& host : hosts_removed) { + if (host == last_host_) { + hits_left_ = 0; + last_host_.reset(); + + break; } - }); + } + } + }); } -ConstHostPtr LeastRequestLoadBalancer::chooseHost(const LoadBalancerContext*) { +HostConstSharedPtr LeastRequestLoadBalancer::chooseHost(const LoadBalancerContext*) { bool is_weight_imbalanced = stats_.max_host_weight_.value() != 1; bool is_weight_enabled = runtime_.snapshot().getInteger("upstream.weight_enabled", 1UL) != 0; @@ -261,7 +262,7 @@ ConstHostPtr LeastRequestLoadBalancer::chooseHost(const LoadBalancerContext*) { last_host_.reset(); } - const std::vector& hosts_to_use = hostsToUse(); + const std::vector& hosts_to_use = hostsToUse(); if (hosts_to_use.empty()) { return nullptr; } @@ -273,8 +274,8 @@ ConstHostPtr LeastRequestLoadBalancer::chooseHost(const LoadBalancerContext*) { return last_host_; } else { - HostPtr host1 = hosts_to_use[random_.random() % hosts_to_use.size()]; - HostPtr host2 = hosts_to_use[random_.random() % hosts_to_use.size()]; + HostSharedPtr host1 = hosts_to_use[random_.random() % hosts_to_use.size()]; + HostSharedPtr host2 = hosts_to_use[random_.random() % hosts_to_use.size()]; if (host1->stats().rq_active_.value() < host2->stats().rq_active_.value()) { return host1; } else { @@ -283,8 +284,8 @@ ConstHostPtr LeastRequestLoadBalancer::chooseHost(const LoadBalancerContext*) { } } -ConstHostPtr RandomLoadBalancer::chooseHost(const LoadBalancerContext*) { - const std::vector& hosts_to_use = hostsToUse(); +HostConstSharedPtr RandomLoadBalancer::chooseHost(const LoadBalancerContext*) { + const std::vector& hosts_to_use = hostsToUse(); if (hosts_to_use.empty()) { return nullptr; } diff --git a/source/common/upstream/load_balancer_impl.h b/source/common/upstream/load_balancer_impl.h index 17362d62fc198..c1c4140821b4e 100644 --- a/source/common/upstream/load_balancer_impl.h +++ b/source/common/upstream/load_balancer_impl.h @@ -30,7 +30,7 @@ class LoadBalancerBase { /** * Pick the host list to use (healthy or all depending on how many in the set are not healthy). */ - const std::vector& hostsToUse(); + const std::vector& hostsToUse(); ClusterStats& stats_; Runtime::Loader& runtime_; @@ -48,14 +48,14 @@ class LoadBalancerBase { /** * Try to select upstream hosts from the same zone. */ - const std::vector& tryChooseLocalZoneHosts(); + const std::vector& tryChooseLocalZoneHosts(); /** * @return (number of hosts in a given zone)/(total number of hosts) in ret param. * The result is stored as integer number and scaled by 10000 multiplier for better precision. * Caller is responsible for allocation/de-allocation of ret. */ - void calculateZonePercentage(const std::vector>& hosts_per_zone, + void calculateZonePercentage(const std::vector>& hosts_per_zone, uint64_t* ret); /** @@ -82,7 +82,7 @@ class RoundRobinLoadBalancer : public LoadBalancer, LoadBalancerBase { : LoadBalancerBase(host_set, local_host_set_, stats, runtime, random) {} // Upstream::LoadBalancer - ConstHostPtr chooseHost(const LoadBalancerContext* context) override; + HostConstSharedPtr chooseHost(const LoadBalancerContext* context) override; private: size_t rr_index_{}; @@ -108,10 +108,10 @@ class LeastRequestLoadBalancer : public LoadBalancer, LoadBalancerBase { Runtime::RandomGenerator& random); // Upstream::LoadBalancer - ConstHostPtr chooseHost(const LoadBalancerContext* context) override; + HostConstSharedPtr chooseHost(const LoadBalancerContext* context) override; private: - HostPtr last_host_; + HostSharedPtr last_host_; uint32_t hits_left_{}; }; @@ -125,7 +125,7 @@ class RandomLoadBalancer : public LoadBalancer, LoadBalancerBase { : LoadBalancerBase(host_set, local_host_set, stats, runtime, random) {} // Upstream::LoadBalancer - ConstHostPtr chooseHost(const LoadBalancerContext* context) override; + HostConstSharedPtr chooseHost(const LoadBalancerContext* context) override; }; } // Upstream diff --git a/source/common/upstream/logical_dns_cluster.cc b/source/common/upstream/logical_dns_cluster.cc index ec53f0cf67f65..401178d6ec056 100644 --- a/source/common/upstream/logical_dns_cluster.cc +++ b/source/common/upstream/logical_dns_cluster.cc @@ -26,8 +26,8 @@ LogicalDnsCluster::LogicalDnsCluster(const Json::Object& config, Runtime::Loader // This must come before startResolve(), since the resolve callback relies on // tls_slot_ being initialized. - tls.set(tls_slot_, [](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectPtr { - return ThreadLocal::ThreadLocalObjectPtr{new PerThreadCurrentHostData()}; + tls.set(tls_slot_, [](Event::Dispatcher&) -> ThreadLocal::ThreadLocalObjectSharedPtr { + return ThreadLocal::ThreadLocalObjectSharedPtr{new PerThreadCurrentHostData()}; }); startResolve(); @@ -45,8 +45,8 @@ void LogicalDnsCluster::startResolve() { info_->stats().update_attempt_.inc(); active_dns_query_ = dns_resolver_.resolve( - dns_address, - [this, dns_address](std::list&& address_list) -> void { + dns_address, [this, dns_address]( + std::list&& address_list) -> void { active_dns_query_ = nullptr; log_debug("async DNS resolution complete for {}", dns_address); info_->stats().update_success_.inc(); @@ -54,7 +54,7 @@ void LogicalDnsCluster::startResolve() { if (!address_list.empty()) { // TODO(mattklein123): IPv6 support as well as moving port handling into the DNS // interface. - Network::Address::InstancePtr new_address( + Network::Address::InstanceConstSharedPtr new_address( new Network::Address::Ipv4Instance(address_list.front()->ip()->addressAsString(), Network::Utility::portFromTcpUrl(dns_url_))); if (!current_resolved_address_ || !(*new_address == *current_resolved_address_)) { @@ -73,7 +73,7 @@ void LogicalDnsCluster::startResolve() { // want to do better again later. logical_host_.reset(new LogicalHost( info_, hostname_, Network::Utility::resolveUrl("tcp://0.0.0.0:0"), *this)); - HostVectorPtr new_hosts(new std::vector()); + HostVectorSharedPtr new_hosts(new std::vector()); new_hosts->emplace_back(logical_host_); updateHosts(new_hosts, createHealthyHostList(*new_hosts), empty_host_lists_, empty_host_lists_, *new_hosts, {}); @@ -96,7 +96,7 @@ LogicalDnsCluster::LogicalHost::createConnection(Event::Dispatcher& dispatcher) parent_.tls_.getTyped(parent_.tls_slot_); ASSERT(data.current_resolved_address_); return {HostImpl::createConnection(dispatcher, *parent_.info_, data.current_resolved_address_), - HostDescriptionPtr{ + HostDescriptionConstSharedPtr{ new RealHostDescription(data.current_resolved_address_, shared_from_this())}}; } diff --git a/source/common/upstream/logical_dns_cluster.h b/source/common/upstream/logical_dns_cluster.h index ed1a51b7485c2..7f60889d709f0 100644 --- a/source/common/upstream/logical_dns_cluster.h +++ b/source/common/upstream/logical_dns_cluster.h @@ -42,8 +42,8 @@ class LogicalDnsCluster : public ClusterImplBase { private: struct LogicalHost : public HostImpl { - LogicalHost(ClusterInfoPtr cluster, const std::string& hostname, - Network::Address::InstancePtr address, LogicalDnsCluster& parent) + LogicalHost(ClusterInfoConstSharedPtr cluster, const std::string& hostname, + Network::Address::InstanceConstSharedPtr address, LogicalDnsCluster& parent) : HostImpl(cluster, hostname, address, false, 1, ""), parent_(parent) {} // Upstream::Host @@ -53,7 +53,8 @@ class LogicalDnsCluster : public ClusterImplBase { }; struct RealHostDescription : public HostDescription { - RealHostDescription(Network::Address::InstancePtr address, ConstHostPtr logical_host) + RealHostDescription(Network::Address::InstanceConstSharedPtr address, + HostConstSharedPtr logical_host) : address_(address), logical_host_(logical_host) {} // Upstream:HostDescription @@ -64,18 +65,18 @@ class LogicalDnsCluster : public ClusterImplBase { } const HostStats& stats() const override { return logical_host_->stats(); } const std::string& hostname() const override { return logical_host_->hostname(); } - Network::Address::InstancePtr address() const override { return address_; } + Network::Address::InstanceConstSharedPtr address() const override { return address_; } const std::string& zone() const override { return EMPTY_STRING; } - Network::Address::InstancePtr address_; - ConstHostPtr logical_host_; + Network::Address::InstanceConstSharedPtr address_; + HostConstSharedPtr logical_host_; }; struct PerThreadCurrentHostData : public ThreadLocal::ThreadLocalObject { // ThreadLocal::ThreadLocalObject void shutdown() override {} - Network::Address::InstancePtr current_resolved_address_; + Network::Address::InstanceConstSharedPtr current_resolved_address_; }; void startResolve(); @@ -90,8 +91,8 @@ class LogicalDnsCluster : public ClusterImplBase { Event::TimerPtr resolve_timer_; std::string dns_url_; std::string hostname_; - Network::Address::InstancePtr current_resolved_address_; - HostPtr logical_host_; + Network::Address::InstanceConstSharedPtr current_resolved_address_; + HostSharedPtr logical_host_; Network::ActiveDnsQuery* active_dns_query_{}; }; diff --git a/source/common/upstream/outlier_detection_impl.cc b/source/common/upstream/outlier_detection_impl.cc index 13bc0b06fc780..4d32e9edc2120 100644 --- a/source/common/upstream/outlier_detection_impl.cc +++ b/source/common/upstream/outlier_detection_impl.cc @@ -9,11 +9,11 @@ namespace Upstream { namespace Outlier { -DetectorPtr DetectorImplFactory::createForCluster(Cluster& cluster, - const Json::Object& cluster_config, - Event::Dispatcher& dispatcher, - Runtime::Loader& runtime, - EventLoggerPtr event_logger) { +DetectorSharedPtr DetectorImplFactory::createForCluster(Cluster& cluster, + const Json::Object& cluster_config, + Event::Dispatcher& dispatcher, + Runtime::Loader& runtime, + EventLoggerSharedPtr event_logger) { if (cluster_config.hasObject("outlier_detection")) { return DetectorImpl::create(cluster, *cluster_config.getObject("outlier_detection"), dispatcher, runtime, ProdSystemTimeSource::instance_, event_logger); @@ -62,7 +62,7 @@ DetectorConfig::DetectorConfig(const Json::Object& json_config) DetectorImpl::DetectorImpl(const Cluster& cluster, const Json::Object& json_config, Event::Dispatcher& dispatcher, Runtime::Loader& runtime, - SystemTimeSource& time_source, EventLoggerPtr event_logger) + SystemTimeSource& time_source, EventLoggerSharedPtr event_logger) : config_(json_config), dispatcher_(dispatcher), runtime_(runtime), time_source_(time_source), stats_(generateStats(cluster.info()->statsScope())), interval_timer_(dispatcher.createTimer([this]() -> void { onIntervalTimer(); })), @@ -80,7 +80,7 @@ DetectorImpl::~DetectorImpl() { std::shared_ptr DetectorImpl::create(const Cluster& cluster, const Json::Object& json_config, Event::Dispatcher& dispatcher, Runtime::Loader& runtime, - SystemTimeSource& time_source, EventLoggerPtr event_logger) { + SystemTimeSource& time_source, EventLoggerSharedPtr event_logger) { std::shared_ptr detector( new DetectorImpl(cluster, json_config, dispatcher, runtime, time_source, event_logger)); detector->initialize(cluster); @@ -88,17 +88,17 @@ DetectorImpl::create(const Cluster& cluster, const Json::Object& json_config, } void DetectorImpl::initialize(const Cluster& cluster) { - for (HostPtr host : cluster.hosts()) { + for (HostSharedPtr host : cluster.hosts()) { addHostSink(host); } - cluster.addMemberUpdateCb([this](const std::vector& hosts_added, - const std::vector& hosts_removed) -> void { - for (HostPtr host : hosts_added) { + cluster.addMemberUpdateCb([this](const std::vector& hosts_added, + const std::vector& hosts_removed) -> void { + for (HostSharedPtr host : hosts_added) { addHostSink(host); } - for (HostPtr host : hosts_removed) { + for (HostSharedPtr host : hosts_removed) { ASSERT(host_sinks_.count(host) == 1); if (host->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)) { ASSERT(stats_.ejections_active_.value() > 0); @@ -112,7 +112,7 @@ void DetectorImpl::initialize(const Cluster& cluster) { armIntervalTimer(); } -void DetectorImpl::addHostSink(HostPtr host) { +void DetectorImpl::addHostSink(HostSharedPtr host) { ASSERT(host_sinks_.count(host) == 0); DetectorHostSinkImpl* sink = new DetectorHostSinkImpl(shared_from_this(), host); host_sinks_[host] = sink; @@ -124,7 +124,8 @@ void DetectorImpl::armIntervalTimer() { runtime_.snapshot().getInteger("outlier_detection.interval_ms", config_.intervalMs()))); } -void DetectorImpl::checkHostForUneject(HostPtr host, DetectorHostSinkImpl* sink, SystemTime now) { +void DetectorImpl::checkHostForUneject(HostSharedPtr host, DetectorHostSinkImpl* sink, + SystemTime now) { if (!host->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)) { return; } @@ -145,7 +146,7 @@ void DetectorImpl::checkHostForUneject(HostPtr host, DetectorHostSinkImpl* sink, } } -void DetectorImpl::ejectHost(HostPtr host, EjectionType type) { +void DetectorImpl::ejectHost(HostSharedPtr host, EjectionType type) { uint64_t max_ejection_percent = std::min( 100, runtime_.snapshot().getInteger("outlier_detection.max_ejection_percent", config_.maxEjectionPercent())); @@ -172,7 +173,7 @@ DetectionStats DetectorImpl::generateStats(Stats::Scope& scope) { POOL_GAUGE_PREFIX(scope, prefix))}; } -void DetectorImpl::onConsecutive5xx(HostPtr host) { +void DetectorImpl::onConsecutive5xx(HostSharedPtr host) { // This event will come from all threads, so we synchronize with a post to the main thread. // NOTE: Unfortunately consecutive 5xx is complicated from a threading perspective because // we catch consecutive 5xx on worker threads and then post back to the main thread. @@ -192,7 +193,7 @@ void DetectorImpl::onConsecutive5xx(HostPtr host) { }); } -void DetectorImpl::onConsecutive5xxWorker(HostPtr host) { +void DetectorImpl::onConsecutive5xxWorker(HostSharedPtr host) { // This comes in cross thread. There is a chance that the host has already been removed from // the set. If so, just ignore it. if (host_sinks_.count(host) == 0) { @@ -216,13 +217,13 @@ void DetectorImpl::onIntervalTimer() { armIntervalTimer(); } -void DetectorImpl::runCallbacks(HostPtr host) { +void DetectorImpl::runCallbacks(HostSharedPtr host) { for (ChangeStateCb cb : callbacks_) { cb(host); } } -void EventLoggerImpl::logEject(HostDescriptionPtr host, EjectionType type) { +void EventLoggerImpl::logEject(HostDescriptionConstSharedPtr host, EjectionType type) { // TODO(mattklein123): Log friendly host name (e.g., instance ID or DNS name). // clang-format off static const std::string json = @@ -243,7 +244,7 @@ void EventLoggerImpl::logEject(HostDescriptionPtr host, EjectionType type) { host->outlierDetector().numEjections())); } -void EventLoggerImpl::logUneject(HostDescriptionPtr host) { +void EventLoggerImpl::logUneject(HostDescriptionConstSharedPtr host) { // TODO(mattklein123): Log friendly host name (e.g., instance ID or DNS name). // clang-format off static const std::string json = diff --git a/source/common/upstream/outlier_detection_impl.h b/source/common/upstream/outlier_detection_impl.h index b1147f4834ed3..898217dc700a1 100644 --- a/source/common/upstream/outlier_detection_impl.h +++ b/source/common/upstream/outlier_detection_impl.h @@ -32,9 +32,9 @@ class DetectorHostSinkNullImpl : public DetectorHostSink { */ class DetectorImplFactory { public: - static DetectorPtr createForCluster(Cluster& cluster, const Json::Object& cluster_config, - Event::Dispatcher& dispatcher, Runtime::Loader& runtime, - EventLoggerPtr event_logger); + static DetectorSharedPtr createForCluster(Cluster& cluster, const Json::Object& cluster_config, + Event::Dispatcher& dispatcher, Runtime::Loader& runtime, + EventLoggerSharedPtr event_logger); }; class DetectorImpl; @@ -44,7 +44,7 @@ class DetectorImpl; */ class DetectorHostSinkImpl : public DetectorHostSink { public: - DetectorHostSinkImpl(std::shared_ptr detector, HostPtr host) + DetectorHostSinkImpl(std::shared_ptr detector, HostSharedPtr host) : detector_(detector), host_(host) {} void eject(SystemTime ejection_time); @@ -114,10 +114,11 @@ class DetectorImpl : public Detector, public std::enable_shared_from_this create(const Cluster& cluster, const Json::Object& json_config, Event::Dispatcher& dispatcher, - Runtime::Loader& runtime, SystemTimeSource& time_source, EventLoggerPtr event_logger); + Runtime::Loader& runtime, SystemTimeSource& time_source, + EventLoggerSharedPtr event_logger); ~DetectorImpl(); - void onConsecutive5xx(HostPtr host); + void onConsecutive5xx(HostSharedPtr host); Runtime::Loader& runtime() { return runtime_; } DetectorConfig& config() { return config_; } @@ -127,17 +128,17 @@ class DetectorImpl : public Detector, public std::enable_shared_from_this callbacks_; - std::unordered_map host_sinks_; - EventLoggerPtr event_logger_; + std::unordered_map host_sinks_; + EventLoggerSharedPtr event_logger_; }; class EventLoggerImpl : public EventLogger { @@ -157,14 +158,14 @@ class EventLoggerImpl : public EventLogger { : file_(log_manager.createAccessLog(file_name)), time_source_(time_source) {} // Upstream::Outlier::EventLogger - void logEject(HostDescriptionPtr host, EjectionType type) override; - void logUneject(HostDescriptionPtr host) override; + void logEject(HostDescriptionConstSharedPtr host, EjectionType type) override; + void logUneject(HostDescriptionConstSharedPtr host) override; private: std::string typeToString(EjectionType type); int secsSinceLastAction(const Optional& lastActionTime, SystemTime now); - Filesystem::FilePtr file_; + Filesystem::FileSharedPtr file_; SystemTimeSource& time_source_; }; diff --git a/source/common/upstream/ring_hash_lb.cc b/source/common/upstream/ring_hash_lb.cc index f63dddfa281a3..9a0d8c1688120 100644 --- a/source/common/upstream/ring_hash_lb.cc +++ b/source/common/upstream/ring_hash_lb.cc @@ -9,13 +9,13 @@ RingHashLoadBalancer::RingHashLoadBalancer(HostSet& host_set, ClusterStats& stat Runtime::Loader& runtime, Runtime::RandomGenerator& random) : host_set_(host_set), stats_(stats), runtime_(runtime), random_(random) { - host_set_.addMemberUpdateCb([this](const std::vector&, const std::vector&) - -> void { refresh(); }); + host_set_.addMemberUpdateCb([this](const std::vector&, + const std::vector&) -> void { refresh(); }); refresh(); } -ConstHostPtr RingHashLoadBalancer::chooseHost(const LoadBalancerContext* context) { +HostConstSharedPtr RingHashLoadBalancer::chooseHost(const LoadBalancerContext* context) { if (LoadBalancerUtility::isGlobalPanic(host_set_, stats_, runtime_)) { return all_hosts_ring_.chooseHost(context, random_); } else { @@ -23,8 +23,8 @@ ConstHostPtr RingHashLoadBalancer::chooseHost(const LoadBalancerContext* context } } -ConstHostPtr RingHashLoadBalancer::Ring::chooseHost(const LoadBalancerContext* context, - Runtime::RandomGenerator& random) { +HostConstSharedPtr RingHashLoadBalancer::Ring::chooseHost(const LoadBalancerContext* context, + Runtime::RandomGenerator& random) { if (ring_.empty()) { return nullptr; } @@ -71,7 +71,7 @@ ConstHostPtr RingHashLoadBalancer::Ring::chooseHost(const LoadBalancerContext* c } void RingHashLoadBalancer::Ring::create(Runtime::Loader& runtime, - const std::vector& hosts) { + const std::vector& hosts) { log_trace("ring hash: building ring"); ring_.clear(); if (hosts.empty()) { diff --git a/source/common/upstream/ring_hash_lb.h b/source/common/upstream/ring_hash_lb.h index bb0c632c43da9..c19e4f0b755b4 100644 --- a/source/common/upstream/ring_hash_lb.h +++ b/source/common/upstream/ring_hash_lb.h @@ -22,17 +22,18 @@ class RingHashLoadBalancer : public LoadBalancer, Logger::Loggable& hosts); + HostConstSharedPtr chooseHost(const LoadBalancerContext* context, + Runtime::RandomGenerator& random); + void create(Runtime::Loader& runtime, const std::vector& hosts); std::vector ring_; }; diff --git a/source/common/upstream/sds.cc b/source/common/upstream/sds.cc index 86f4bd1c694aa..d1acec598ea7e 100644 --- a/source/common/upstream/sds.cc +++ b/source/common/upstream/sds.cc @@ -20,7 +20,7 @@ SdsClusterImpl::SdsClusterImpl(const Json::Object& config, Runtime::Loader& runt void SdsClusterImpl::parseResponse(const Http::Message& response) { Json::ObjectPtr json = Json::Factory::LoadFromString(response.bodyAsString()); json->validateSchema(Json::Schema::SDS_SCHEMA); - std::vector new_hosts; + std::vector new_hosts; for (const Json::ObjectPtr& host : json->getObjectArray("hosts")) { bool canary = false; uint32_t weight = 1; @@ -31,25 +31,25 @@ void SdsClusterImpl::parseResponse(const Http::Message& response) { zone = host->getObject("tags")->getString("az", zone); } - new_hosts.emplace_back( - new HostImpl(info_, "", Network::Address::InstancePtr{new Network::Address::Ipv4Instance( - host->getString("ip_address"), host->getInteger("port"))}, - canary, weight, zone)); + new_hosts.emplace_back(new HostImpl( + info_, "", Network::Address::InstanceConstSharedPtr{new Network::Address::Ipv4Instance( + host->getString("ip_address"), host->getInteger("port"))}, + canary, weight, zone)); } - HostVectorPtr current_hosts_copy(new std::vector(hosts())); - std::vector hosts_added; - std::vector hosts_removed; + HostVectorSharedPtr current_hosts_copy(new std::vector(hosts())); + std::vector hosts_added; + std::vector hosts_removed; if (updateDynamicHostList(new_hosts, *current_hosts_copy, hosts_added, hosts_removed, health_checker_ != nullptr)) { log_debug("sds hosts changed for cluster: {} ({})", info_->name(), hosts().size()); - HostListsPtr per_zone(new std::vector>()); + HostListsSharedPtr per_zone(new std::vector>()); // If local zone name is not defined then skip populating per zone hosts. if (!local_info_.zoneName().empty()) { - std::map> hosts_per_zone; + std::map> hosts_per_zone; - for (HostPtr host : *current_hosts_copy) { + for (HostSharedPtr host : *current_hosts_copy) { hosts_per_zone[host->zone()].push_back(host); } @@ -71,7 +71,7 @@ void SdsClusterImpl::parseResponse(const Http::Message& response) { if (initialize_callback_ && health_checker_ && pending_health_checks_ == 0) { pending_health_checks_ = hosts().size(); ASSERT(pending_health_checks_ > 0); - health_checker_->addHostCheckCompleteCb([this](HostPtr, bool) -> void { + health_checker_->addHostCheckCompleteCb([this](HostSharedPtr, bool) -> void { if (pending_health_checks_ > 0 && --pending_health_checks_ == 0) { initialize_callback_(); initialize_callback_ = nullptr; diff --git a/source/common/upstream/upstream_impl.cc b/source/common/upstream/upstream_impl.cc index 88c1ef5b89151..551fd0b89e608 100644 --- a/source/common/upstream/upstream_impl.cc +++ b/source/common/upstream/upstream_impl.cc @@ -27,9 +27,9 @@ Host::CreateConnectionData HostImpl::createConnection(Event::Dispatcher& dispatc return {createConnection(dispatcher, *cluster_, address_), shared_from_this()}; } -Network::ClientConnectionPtr HostImpl::createConnection(Event::Dispatcher& dispatcher, - const ClusterInfo& cluster, - Network::Address::InstancePtr address) { +Network::ClientConnectionPtr +HostImpl::createConnection(Event::Dispatcher& dispatcher, const ClusterInfo& cluster, + Network::Address::InstanceConstSharedPtr address) { Network::ClientConnectionPtr connection = cluster.sslContext() ? dispatcher.createSslClientConnection(*cluster.sslContext(), address) : dispatcher.createClientConnection(address); @@ -47,8 +47,8 @@ ClusterStats ClusterInfoImpl::generateStats(Stats::Scope& scope) { return {ALL_CLUSTER_STATS(POOL_COUNTER(scope), POOL_GAUGE(scope), POOL_TIMER(scope))}; } -void HostSetImpl::runUpdateCallbacks(const std::vector& hosts_added, - const std::vector& hosts_removed) { +void HostSetImpl::runUpdateCallbacks(const std::vector& hosts_added, + const std::vector& hosts_removed) { for (MemberUpdateCb& callback : callbacks_) { callback(hosts_added, hosts_removed); } @@ -87,7 +87,8 @@ ClusterInfoImpl::ClusterInfoImpl(const Json::Object& config, Runtime::Loader& ru } } -const ConstHostListsPtr ClusterImplBase::empty_host_lists_{new std::vector>()}; +const HostListsConstSharedPtr ClusterImplBase::empty_host_lists_{ + new std::vector>()}; ClusterPtr ClusterImplBase::create(const Json::Object& cluster, ClusterManager& cm, Stats::Store& stats, ThreadLocal::Instance& tls, @@ -97,7 +98,7 @@ ClusterPtr ClusterImplBase::create(const Json::Object& cluster, ClusterManager& Event::Dispatcher& dispatcher, const Optional& sds_config, const LocalInfo::LocalInfo& local_info, - Outlier::EventLoggerPtr outlier_event_logger) { + Outlier::EventLoggerSharedPtr outlier_event_logger) { cluster.validateSchema(Json::Schema::CLUSTER_SCHEMA); @@ -145,8 +146,9 @@ ClusterImplBase::ClusterImplBase(const Json::Object& config, Runtime::Loader& ru Stats::Store& stats, Ssl::ContextManager& ssl_context_manager) : runtime_(runtime), info_(new ClusterInfoImpl(config, runtime, stats, ssl_context_manager)) {} -ConstHostVectorPtr ClusterImplBase::createHealthyHostList(const std::vector& hosts) { - HostVectorPtr healthy_list(new std::vector()); +HostVectorConstSharedPtr +ClusterImplBase::createHealthyHostList(const std::vector& hosts) { + HostVectorSharedPtr healthy_list(new std::vector()); for (const auto& host : hosts) { if (host->healthy()) { healthy_list->emplace_back(host); @@ -156,12 +158,12 @@ ConstHostVectorPtr ClusterImplBase::createHealthyHostList(const std::vector>& hosts) { - HostListsPtr healthy_list(new std::vector>()); +HostListsConstSharedPtr +ClusterImplBase::createHealthyHostLists(const std::vector>& hosts) { + HostListsSharedPtr healthy_list(new std::vector>()); for (const auto& hosts_zone : hosts) { - std::vector current_zone_hosts; + std::vector current_zone_hosts; for (const auto& host : hosts_zone) { if (host->healthy()) { current_zone_hosts.emplace_back(host); @@ -195,8 +197,8 @@ ResourceManager& ClusterInfoImpl::resourceManager(ResourcePriority priority) con return *resource_managers_.managers_[enumToInt(priority)]; } -void ClusterImplBase::runUpdateCallbacks(const std::vector& hosts_added, - const std::vector& hosts_removed) { +void ClusterImplBase::runUpdateCallbacks(const std::vector& hosts_added, + const std::vector& hosts_removed) { if (!hosts_added.empty() || !hosts_removed.empty()) { info_->stats().membership_change_.inc(); } @@ -210,7 +212,7 @@ void ClusterImplBase::setHealthChecker(HealthCheckerPtr&& health_checker) { ASSERT(!health_checker_); health_checker_ = std::move(health_checker); health_checker_->start(); - health_checker_->addHostCheckCompleteCb([this](HostPtr, bool changed_state) -> void { + health_checker_->addHostCheckCompleteCb([this](HostSharedPtr, bool changed_state) -> void { // If we get a health check completion that resulted in a state change, signal to // update the host sets on all threads. if (changed_state) { @@ -219,18 +221,19 @@ void ClusterImplBase::setHealthChecker(HealthCheckerPtr&& health_checker) { }); } -void ClusterImplBase::setOutlierDetector(Outlier::DetectorPtr outlier_detector) { +void ClusterImplBase::setOutlierDetector(Outlier::DetectorSharedPtr outlier_detector) { if (!outlier_detector) { return; } outlier_detector_ = std::move(outlier_detector); - outlier_detector_->addChangedStateCb([this](HostPtr) -> void { reloadHealthyHosts(); }); + outlier_detector_->addChangedStateCb([this](HostSharedPtr) -> void { reloadHealthyHosts(); }); } void ClusterImplBase::reloadHealthyHosts() { - ConstHostVectorPtr hosts_copy(new std::vector(hosts())); - ConstHostListsPtr hosts_per_zone_copy(new std::vector>(hostsPerZone())); + HostVectorConstSharedPtr hosts_copy(new std::vector(hosts())); + HostListsConstSharedPtr hosts_per_zone_copy( + new std::vector>(hostsPerZone())); updateHosts(hosts_copy, createHealthyHostList(hosts()), hosts_per_zone_copy, createHealthyHostLists(hostsPerZone()), {}, {}); } @@ -266,9 +269,9 @@ StaticClusterImpl::StaticClusterImpl(const Json::Object& config, Runtime::Loader Stats::Store& stats, Ssl::ContextManager& ssl_context_manager) : ClusterImplBase(config, runtime, stats, ssl_context_manager) { std::vector hosts_json = config.getObjectArray("hosts"); - HostVectorPtr new_hosts(new std::vector()); + HostVectorSharedPtr new_hosts(new std::vector()); for (Json::ObjectPtr& host : hosts_json) { - new_hosts->emplace_back(HostPtr{new HostImpl( + new_hosts->emplace_back(HostSharedPtr{new HostImpl( info_, "", Network::Utility::resolveUrl(host->getString("url")), false, 1, "")}); } @@ -276,10 +279,10 @@ StaticClusterImpl::StaticClusterImpl(const Json::Object& config, Runtime::Loader {}, {}); } -bool BaseDynamicClusterImpl::updateDynamicHostList(const std::vector& new_hosts, - std::vector& current_hosts, - std::vector& hosts_added, - std::vector& hosts_removed, +bool BaseDynamicClusterImpl::updateDynamicHostList(const std::vector& new_hosts, + std::vector& current_hosts, + std::vector& hosts_added, + std::vector& hosts_removed, bool depend_on_hc) { uint64_t max_host_weight = 1; @@ -289,8 +292,8 @@ bool BaseDynamicClusterImpl::updateDynamicHostList(const std::vector& n // duplicates here. It's possible for DNS to return the same address multiple times, and a bad // SDS implementation could do the same thing. std::unordered_set host_addresses; - std::vector final_hosts; - for (HostPtr host : new_hosts) { + std::vector final_hosts; + for (HostSharedPtr host : new_hosts) { if (host_addresses.count(host->address()->asString())) { continue; } @@ -378,12 +381,12 @@ StrictDnsClusterImpl::StrictDnsClusterImpl(const Json::Object& config, Runtime:: } } -void StrictDnsClusterImpl::updateAllHosts(const std::vector& hosts_added, - const std::vector& hosts_removed) { +void StrictDnsClusterImpl::updateAllHosts(const std::vector& hosts_added, + const std::vector& hosts_removed) { // At this point we know that we are different so make a new host list and notify. - HostVectorPtr new_hosts(new std::vector()); + HostVectorSharedPtr new_hosts(new std::vector()); for (const ResolveTargetPtr& target : resolve_targets_) { - for (const HostPtr& host : target->hosts_) { + for (const HostSharedPtr& host : target->hosts_) { new_hosts->emplace_back(host); } } @@ -410,25 +413,26 @@ void StrictDnsClusterImpl::ResolveTarget::startResolve() { parent_.info_->stats().update_attempt_.inc(); active_query_ = parent_.dns_resolver_.resolve( - dns_address_, [this](std::list&& address_list) -> void { + dns_address_, + [this](std::list&& address_list) -> void { active_query_ = nullptr; log_debug("async DNS resolution complete for {}", dns_address_); parent_.info_->stats().update_success_.inc(); - std::vector new_hosts; - for (Network::Address::InstancePtr address : address_list) { + std::vector new_hosts; + for (Network::Address::InstanceConstSharedPtr address : address_list) { // TODO(mattklein123): Currently the DNS interface does not consider port. We need to make // a new address that has port in it. We need to both support IPv6 as well as potentially // move port handling into the DNS interface itself, which would work better for SRV. - new_hosts.emplace_back( - new HostImpl(parent_.info_, dns_address_, - Network::Address::InstancePtr{new Network::Address::Ipv4Instance( - address->ip()->addressAsString(), port_)}, - false, 1, "")); + new_hosts.emplace_back(new HostImpl( + parent_.info_, dns_address_, + Network::Address::InstanceConstSharedPtr{ + new Network::Address::Ipv4Instance(address->ip()->addressAsString(), port_)}, + false, 1, "")); } - std::vector hosts_added; - std::vector hosts_removed; + std::vector hosts_added; + std::vector hosts_removed; if (parent_.updateDynamicHostList(new_hosts, hosts_, hosts_added, hosts_removed, false)) { log_debug("DNS hosts have changed for {}", dns_address_); parent_.updateAllHosts(hosts_added, hosts_removed); diff --git a/source/common/upstream/upstream_impl.h b/source/common/upstream/upstream_impl.h index 057a086e1bb43..05ae8c246113f 100644 --- a/source/common/upstream/upstream_impl.h +++ b/source/common/upstream/upstream_impl.h @@ -25,8 +25,9 @@ namespace Upstream { */ class HostDescriptionImpl : virtual public HostDescription { public: - HostDescriptionImpl(ClusterInfoPtr cluster, const std::string& hostname, - Network::Address::InstancePtr address, bool canary, const std::string& zone) + HostDescriptionImpl(ClusterInfoConstSharedPtr cluster, const std::string& hostname, + Network::Address::InstanceConstSharedPtr address, bool canary, + const std::string& zone) : cluster_(cluster), hostname_(hostname), address_(address), canary_(canary), zone_(zone), stats_{ALL_HOST_STATS(POOL_COUNTER(stats_store_), POOL_GAUGE(stats_store_))} {} @@ -42,13 +43,13 @@ class HostDescriptionImpl : virtual public HostDescription { } const HostStats& stats() const override { return stats_; } const std::string& hostname() const override { return hostname_; } - Network::Address::InstancePtr address() const override { return address_; } + Network::Address::InstanceConstSharedPtr address() const override { return address_; } const std::string& zone() const override { return zone_; } protected: - ClusterInfoPtr cluster_; + ClusterInfoConstSharedPtr cluster_; const std::string hostname_; - Network::Address::InstancePtr address_; + Network::Address::InstanceConstSharedPtr address_; const bool canary_; const std::string zone_; Stats::IsolatedStoreImpl stats_store_; @@ -66,17 +67,17 @@ class HostImpl : public HostDescriptionImpl, public Host, public std::enable_shared_from_this { public: - HostImpl(ClusterInfoPtr cluster, const std::string& hostname, - Network::Address::InstancePtr address, bool canary, uint32_t initial_weight, + HostImpl(ClusterInfoConstSharedPtr cluster, const std::string& hostname, + Network::Address::InstanceConstSharedPtr address, bool canary, uint32_t initial_weight, const std::string& zone) : HostDescriptionImpl(cluster, hostname, address, canary, zone) { weight(initial_weight); } // Upstream::Host - std::list counters() const override { return stats_store_.counters(); } + std::list counters() const override { return stats_store_.counters(); } CreateConnectionData createConnection(Event::Dispatcher& dispatcher) const override; - std::list gauges() const override { return stats_store_.gauges(); } + std::list gauges() const override { return stats_store_.gauges(); } void healthFlagClear(HealthFlag flag) override { health_flags_ &= ~enumToInt(flag); } bool healthFlagGet(HealthFlag flag) const override { return health_flags_ & enumToInt(flag); } void healthFlagSet(HealthFlag flag) override { health_flags_ |= enumToInt(flag); } @@ -88,19 +89,19 @@ class HostImpl : public HostDescriptionImpl, void weight(uint32_t new_weight) override; protected: - static Network::ClientConnectionPtr createConnection(Event::Dispatcher& dispatcher, - const ClusterInfo& cluster, - Network::Address::InstancePtr address); + static Network::ClientConnectionPtr + createConnection(Event::Dispatcher& dispatcher, const ClusterInfo& cluster, + Network::Address::InstanceConstSharedPtr address); private: std::atomic health_flags_{}; std::atomic weight_; }; -typedef std::shared_ptr> HostVectorPtr; -typedef std::shared_ptr> ConstHostVectorPtr; -typedef std::shared_ptr>> HostListsPtr; -typedef std::shared_ptr>> ConstHostListsPtr; +typedef std::shared_ptr> HostVectorSharedPtr; +typedef std::shared_ptr> HostVectorConstSharedPtr; +typedef std::shared_ptr>> HostListsSharedPtr; +typedef std::shared_ptr>> HostListsConstSharedPtr; /** * Base class for all clusters as well as thread local host sets. @@ -108,14 +109,15 @@ typedef std::shared_ptr>> ConstHostListsP class HostSetImpl : public virtual HostSet { public: HostSetImpl() - : hosts_(new std::vector()), healthy_hosts_(new std::vector()), - hosts_per_zone_(new std::vector>()), - healthy_hosts_per_zone_(new std::vector>()) {} - - void updateHosts(ConstHostVectorPtr hosts, ConstHostVectorPtr healthy_hosts, - ConstHostListsPtr hosts_per_zone, ConstHostListsPtr healthy_hosts_per_zone, - const std::vector& hosts_added, - const std::vector& hosts_removed) { + : hosts_(new std::vector()), healthy_hosts_(new std::vector()), + hosts_per_zone_(new std::vector>()), + healthy_hosts_per_zone_(new std::vector>()) {} + + void updateHosts(HostVectorConstSharedPtr hosts, HostVectorConstSharedPtr healthy_hosts, + HostListsConstSharedPtr hosts_per_zone, + HostListsConstSharedPtr healthy_hosts_per_zone, + const std::vector& hosts_added, + const std::vector& hosts_removed) { hosts_ = hosts; healthy_hosts_ = healthy_hosts; hosts_per_zone_ = hosts_per_zone; @@ -124,25 +126,25 @@ class HostSetImpl : public virtual HostSet { } // Upstream::HostSet - const std::vector& hosts() const override { return *hosts_; } - const std::vector& healthyHosts() const override { return *healthy_hosts_; } - const std::vector>& hostsPerZone() const override { + const std::vector& hosts() const override { return *hosts_; } + const std::vector& healthyHosts() const override { return *healthy_hosts_; } + const std::vector>& hostsPerZone() const override { return *hosts_per_zone_; } - const std::vector>& healthyHostsPerZone() const override { + const std::vector>& healthyHostsPerZone() const override { return *healthy_hosts_per_zone_; } void addMemberUpdateCb(MemberUpdateCb callback) const override; protected: - virtual void runUpdateCallbacks(const std::vector& hosts_added, - const std::vector& hosts_removed); + virtual void runUpdateCallbacks(const std::vector& hosts_added, + const std::vector& hosts_removed); private: - ConstHostVectorPtr hosts_; - ConstHostVectorPtr healthy_hosts_; - ConstHostListsPtr hosts_per_zone_; - ConstHostListsPtr healthy_hosts_per_zone_; + HostVectorConstSharedPtr hosts_; + HostVectorConstSharedPtr healthy_hosts_; + HostListsConstSharedPtr hosts_per_zone_; + HostListsConstSharedPtr healthy_hosts_per_zone_; mutable std::list callbacks_; }; @@ -217,7 +219,7 @@ class ClusterImplBase : public Cluster, Runtime::RandomGenerator& random, Event::Dispatcher& dispatcher, const Optional& sds_config, const LocalInfo::LocalInfo& local_info, - Outlier::EventLoggerPtr outlier_event_logger); + Outlier::EventLoggerSharedPtr outlier_event_logger); /** * Optionally set the health checker for the primary cluster. This is done after cluster @@ -230,27 +232,29 @@ class ClusterImplBase : public Cluster, * Optionally set the outlier detector for the primary cluster. Done for the same reason as * documented in setHealthChecker(). */ - void setOutlierDetector(Outlier::DetectorPtr outlier_detector); + void setOutlierDetector(Outlier::DetectorSharedPtr outlier_detector); // Upstream::Cluster - ClusterInfoPtr info() const override { return info_; } + ClusterInfoConstSharedPtr info() const override { return info_; } protected: ClusterImplBase(const Json::Object& config, Runtime::Loader& runtime, Stats::Store& stats, Ssl::ContextManager& ssl_context_manager); - static ConstHostVectorPtr createHealthyHostList(const std::vector& hosts); - static ConstHostListsPtr createHealthyHostLists(const std::vector>& hosts); - void runUpdateCallbacks(const std::vector& hosts_added, - const std::vector& hosts_removed) override; + static HostVectorConstSharedPtr createHealthyHostList(const std::vector& hosts); + static HostListsConstSharedPtr + createHealthyHostLists(const std::vector>& hosts); + void runUpdateCallbacks(const std::vector& hosts_added, + const std::vector& hosts_removed) override; - static const ConstHostListsPtr empty_host_lists_; + static const HostListsConstSharedPtr empty_host_lists_; Runtime::Loader& runtime_; - ClusterInfoPtr info_; // This cluster info stores the stats scope so it must be initialized first - // and destroyed last. + ClusterInfoConstSharedPtr + info_; // This cluster info stores the stats scope so it must be initialized first + // and destroyed last. HealthCheckerPtr health_checker_; - Outlier::DetectorPtr outlier_detector_; + Outlier::DetectorSharedPtr outlier_detector_; private: void reloadHealthyHosts(); @@ -288,9 +292,10 @@ class BaseDynamicClusterImpl : public ClusterImplBase { protected: using ClusterImplBase::ClusterImplBase; - bool updateDynamicHostList(const std::vector& new_hosts, - std::vector& current_hosts, std::vector& hosts_added, - std::vector& hosts_removed, bool depend_on_hc); + bool updateDynamicHostList(const std::vector& new_hosts, + std::vector& current_hosts, + std::vector& hosts_added, + std::vector& hosts_removed, bool depend_on_hc); std::function initialize_callback_; // Set once the first resolve completes. @@ -323,13 +328,13 @@ class StrictDnsClusterImpl : public BaseDynamicClusterImpl { std::string dns_address_; uint32_t port_; Event::TimerPtr resolve_timer_; - std::vector hosts_; + std::vector hosts_; }; typedef std::unique_ptr ResolveTargetPtr; - void updateAllHosts(const std::vector& hosts_added, - const std::vector& hosts_removed); + void updateAllHosts(const std::vector& hosts_added, + const std::vector& hosts_removed); Network::DnsResolver& dns_resolver_; std::list resolve_targets_; diff --git a/source/server/config/http/buffer.cc b/source/server/config/http/buffer.cc index 76fe32e29fe1d..6c7ac338d0127 100644 --- a/source/server/config/http/buffer.cc +++ b/source/server/config/http/buffer.cc @@ -17,12 +17,13 @@ HttpFilterFactoryCb BufferFilterConfig::tryCreateFilterFactory(HttpFilterType ty json_config.validateSchema(Json::Schema::BUFFER_HTTP_FILTER_SCHEMA); - Http::BufferFilterConfigPtr config(new Http::BufferFilterConfig{ + Http::BufferFilterConfigConstSharedPtr config(new Http::BufferFilterConfig{ Http::BufferFilter::generateStats(stats_prefix, server.stats()), static_cast(json_config.getInteger("max_request_bytes")), std::chrono::seconds(json_config.getInteger("max_request_time_s"))}); return [config](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{new Http::BufferFilter(config)}); + callbacks.addStreamDecoderFilter( + Http::StreamDecoderFilterSharedPtr{new Http::BufferFilter(config)}); }; } diff --git a/source/server/config/http/dynamo.cc b/source/server/config/http/dynamo.cc index 101aa504a5294..45a88d892edba 100644 --- a/source/server/config/http/dynamo.cc +++ b/source/server/config/http/dynamo.cc @@ -15,7 +15,7 @@ HttpFilterFactoryCb DynamoFilterConfig::tryCreateFilterFactory(HttpFilterType ty } return [&server, stat_prefix](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamFilter(Http::StreamFilterPtr{ + callbacks.addStreamFilter(Http::StreamFilterSharedPtr{ new Dynamo::DynamoFilter(server.runtime(), stat_prefix, server.stats())}); }; } diff --git a/source/server/config/http/fault.cc b/source/server/config/http/fault.cc index de4938ce56db9..6cda18d19de99 100644 --- a/source/server/config/http/fault.cc +++ b/source/server/config/http/fault.cc @@ -15,10 +15,11 @@ HttpFilterFactoryCb FaultFilterConfig::tryCreateFilterFactory(HttpFilterType typ return nullptr; } - Http::FaultFilterConfigPtr config( + Http::FaultFilterConfigSharedPtr config( new Http::FaultFilterConfig(json_config, server.runtime(), stats_prefix, server.stats())); return [config](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{new Http::FaultFilter(config)}); + callbacks.addStreamDecoderFilter( + Http::StreamDecoderFilterSharedPtr{new Http::FaultFilter(config)}); }; } diff --git a/source/server/config/http/grpc_http1_bridge.cc b/source/server/config/http/grpc_http1_bridge.cc index b17d6eff8f020..ed3748d4dd0ea 100644 --- a/source/server/config/http/grpc_http1_bridge.cc +++ b/source/server/config/http/grpc_http1_bridge.cc @@ -16,7 +16,7 @@ HttpFilterFactoryCb GrpcHttp1BridgeFilterConfig::tryCreateFilterFactory(HttpFilt return [&server](Http::FilterChainFactoryCallbacks& callbacks) -> void { callbacks.addStreamFilter( - Http::StreamFilterPtr{new Grpc::Http1BridgeFilter(server.clusterManager())}); + Http::StreamFilterSharedPtr{new Grpc::Http1BridgeFilter(server.clusterManager())}); }; } diff --git a/source/server/config/http/ratelimit.cc b/source/server/config/http/ratelimit.cc index 20e21d34344e4..267c60fcefc09 100644 --- a/source/server/config/http/ratelimit.cc +++ b/source/server/config/http/ratelimit.cc @@ -14,10 +14,10 @@ HttpFilterFactoryCb RateLimitFilterConfig::tryCreateFilterFactory(HttpFilterType return nullptr; } - Http::RateLimit::FilterConfigPtr filter_config(new Http::RateLimit::FilterConfig( + Http::RateLimit::FilterConfigSharedPtr filter_config(new Http::RateLimit::FilterConfig( config, server.localInfo(), server.stats(), server.runtime(), server.clusterManager())); return [filter_config, &server](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{new Http::RateLimit::Filter( + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{new Http::RateLimit::Filter( filter_config, server.rateLimitClient(std::chrono::milliseconds(20)))}); }; } diff --git a/source/server/config/http/router.cc b/source/server/config/http/router.cc index 3805437b8c130..6d00c42a0a016 100644 --- a/source/server/config/http/router.cc +++ b/source/server/config/http/router.cc @@ -18,7 +18,7 @@ HttpFilterFactoryCb RouterFilterConfig::tryCreateFilterFactory(HttpFilterType ty json_config.validateSchema(Json::Schema::ROUTER_HTTP_FILTER_SCHEMA); - Router::FilterConfigPtr config(new Router::FilterConfig( + Router::FilterConfigSharedPtr config(new Router::FilterConfig( stat_prefix, server.localInfo(), server.stats(), server.clusterManager(), server.runtime(), server.random(), Router::ShadowWriterPtr{new Router::ShadowWriterImpl(server.clusterManager())}, diff --git a/source/server/config/network/client_ssl_auth.cc b/source/server/config/network/client_ssl_auth.cc index ff8941b1566c2..92ff2c651ebb0 100644 --- a/source/server/config/network/client_ssl_auth.cc +++ b/source/server/config/network/client_ssl_auth.cc @@ -16,12 +16,12 @@ ClientSslAuthConfigFactory::tryCreateFilterFactory(NetworkFilterType type, const return nullptr; } - Filter::Auth::ClientSsl::ConfigPtr config(Filter::Auth::ClientSsl::Config::create( + Filter::Auth::ClientSsl::ConfigSharedPtr config(Filter::Auth::ClientSsl::Config::create( json_config, server.threadLocal(), server.clusterManager(), server.dispatcher(), server.stats(), server.random())); return [config](Network::FilterManager& filter_manager) -> void { filter_manager.addReadFilter( - Network::ReadFilterPtr{new Filter::Auth::ClientSsl::Instance(config)}); + Network::ReadFilterSharedPtr{new Filter::Auth::ClientSsl::Instance(config)}); }; } diff --git a/source/server/config/network/echo.cc b/source/server/config/network/echo.cc index 6d8a1d57fecc3..50fa6675ff8aa 100644 --- a/source/server/config/network/echo.cc +++ b/source/server/config/network/echo.cc @@ -19,7 +19,7 @@ class EchoConfigFactory : public NetworkFilterConfigFactory { } return [](Network::FilterManager& filter_manager) - -> void { filter_manager.addReadFilter(Network::ReadFilterPtr{new Filter::Echo()}); }; + -> void { filter_manager.addReadFilter(Network::ReadFilterSharedPtr{new Filter::Echo()}); }; } }; diff --git a/source/server/config/network/http_connection_manager.cc b/source/server/config/network/http_connection_manager.cc index 81428bcd15743..6a9cbf3e36870 100644 --- a/source/server/config/network/http_connection_manager.cc +++ b/source/server/config/network/http_connection_manager.cc @@ -28,7 +28,7 @@ NetworkFilterFactoryCb HttpConnectionManagerFilterConfigFactory::tryCreateFilter std::shared_ptr http_config( new HttpConnectionManagerConfig(config, server)); return [http_config, &server](Network::FilterManager& filter_manager) mutable -> void { - filter_manager.addReadFilter(Network::ReadFilterPtr{ + filter_manager.addReadFilter(Network::ReadFilterSharedPtr{ new Http::ConnectionManagerImpl(*http_config, server.drainManager(), server.random(), server.httpTracer(), server.runtime())}); }; @@ -96,8 +96,9 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig(const Json::Object& con if (config.hasObject("access_log")) { for (Json::ObjectPtr& access_log : config.getObjectArray("access_log")) { - Http::AccessLog::InstancePtr current_access_log = Http::AccessLog::InstanceImpl::fromJson( - *access_log, server.runtime(), server.accessLogManager()); + Http::AccessLog::InstanceSharedPtr current_access_log = + Http::AccessLog::InstanceImpl::fromJson(*access_log, server.runtime(), + server.accessLogManager()); access_logs_.push_back(current_access_log); } } diff --git a/source/server/config/network/http_connection_manager.h b/source/server/config/network/http_connection_manager.h index cf357e125bcd4..bf29eed3b5e47 100644 --- a/source/server/config/network/http_connection_manager.h +++ b/source/server/config/network/http_connection_manager.h @@ -72,7 +72,9 @@ class HttpConnectionManagerConfig : Logger::Loggable, void createFilterChain(Http::FilterChainFactoryCallbacks& callbacks) override; // Http::ConnectionManagerConfig - const std::list& accessLogs() override { return access_logs_; } + const std::list& accessLogs() override { + return access_logs_; + } Http::ServerConnectionPtr createCodec(Network::Connection& connection, const Buffer::Instance& data, Http::ServerConnectionCallbacks& callbacks) override; @@ -110,7 +112,7 @@ class HttpConnectionManagerConfig : Logger::Loggable, Server::Instance& server_; std::list filter_factories_; - std::list access_logs_; + std::list access_logs_; const std::string stats_prefix_; Http::ConnectionManagerStats stats_; Http::ConnectionManagerTracingStats tracing_stats_; diff --git a/source/server/config/network/mongo_proxy.cc b/source/server/config/network/mongo_proxy.cc index 10e4e048ca3d0..fd4aa2f691f96 100644 --- a/source/server/config/network/mongo_proxy.cc +++ b/source/server/config/network/mongo_proxy.cc @@ -19,14 +19,14 @@ NetworkFilterFactoryCb MongoProxyFilterConfigFactory::tryCreateFilterFactory( config.validateSchema(Json::Schema::MONGO_PROXY_NETWORK_FILTER_SCHEMA); std::string stat_prefix = "mongo." + config.getString("stat_prefix") + "."; - Mongo::AccessLogPtr access_log; + Mongo::AccessLogSharedPtr access_log; if (config.hasObject("access_log")) { access_log.reset( new Mongo::AccessLog(config.getString("access_log"), server.accessLogManager())); } return [stat_prefix, &server, access_log](Network::FilterManager& filter_manager) -> void { - filter_manager.addFilter(Network::FilterPtr{ + filter_manager.addFilter(Network::FilterSharedPtr{ new Mongo::ProdProxyFilter(stat_prefix, server.stats(), server.runtime(), access_log)}); }; } diff --git a/source/server/config/network/ratelimit.cc b/source/server/config/network/ratelimit.cc index 1b42c6378ed29..d321eb8ced3c7 100644 --- a/source/server/config/network/ratelimit.cc +++ b/source/server/config/network/ratelimit.cc @@ -15,10 +15,10 @@ RateLimitConfigFactory::tryCreateFilterFactory(NetworkFilterType type, const std return nullptr; } - RateLimit::TcpFilter::ConfigPtr config( + RateLimit::TcpFilter::ConfigSharedPtr config( new RateLimit::TcpFilter::Config(json_config, server.stats(), server.runtime())); return [config, &server](Network::FilterManager& filter_manager) -> void { - filter_manager.addReadFilter(Network::ReadFilterPtr{new RateLimit::TcpFilter::Instance( + filter_manager.addReadFilter(Network::ReadFilterSharedPtr{new RateLimit::TcpFilter::Instance( config, server.rateLimitClient(Optional()))}); }; } diff --git a/source/server/config/network/redis_proxy.cc b/source/server/config/network/redis_proxy.cc index 3f8935c80061a..65579019006e2 100644 --- a/source/server/config/network/redis_proxy.cc +++ b/source/server/config/network/redis_proxy.cc @@ -20,7 +20,7 @@ NetworkFilterFactoryCb RedisProxyFilterConfigFactory::tryCreateFilterFactory( Redis::ConnPool::ClientFactoryImpl::instance_, server.threadLocal())); return [conn_pool](Network::FilterManager& filter_manager) -> void { Redis::DecoderFactoryImpl factory; - filter_manager.addReadFilter(Network::ReadFilterPtr{ + filter_manager.addReadFilter(Network::ReadFilterSharedPtr{ new Redis::ProxyFilter(factory, Redis::EncoderPtr{new Redis::EncoderImpl()}, *conn_pool)}); }; } diff --git a/source/server/config/network/tcp_proxy.cc b/source/server/config/network/tcp_proxy.cc index 211de865e66f3..2c9df978a8c80 100644 --- a/source/server/config/network/tcp_proxy.cc +++ b/source/server/config/network/tcp_proxy.cc @@ -16,11 +16,11 @@ NetworkFilterFactoryCb TcpProxyConfigFactory::tryCreateFilterFactory(NetworkFilt return nullptr; } - Filter::TcpProxyConfigPtr filter_config( + Filter::TcpProxyConfigSharedPtr filter_config( new Filter::TcpProxyConfig(config, server.clusterManager(), server.stats())); return [filter_config, &server](Network::FilterManager& filter_manager) -> void { filter_manager.addReadFilter( - Network::ReadFilterPtr{new Filter::TcpProxy(filter_config, server.clusterManager())}); + Network::ReadFilterSharedPtr{new Filter::TcpProxy(filter_config, server.clusterManager())}); }; } diff --git a/source/server/configuration_impl.h b/source/server/configuration_impl.h index 99c1c7ec27466..f3159697cd1e8 100644 --- a/source/server/configuration_impl.h +++ b/source/server/configuration_impl.h @@ -91,7 +91,7 @@ class MainImpl : Logger::Loggable, public Main { // Server::Configuration::Listener Network::FilterChainFactory& filterChainFactory() override { return *this; } - Network::Address::InstancePtr address() override { return address_; } + Network::Address::InstanceConstSharedPtr address() override { return address_; } bool bindToPort() override { return bind_to_port_; } Ssl::ServerContext* sslContext() override { return ssl_context_.get(); } bool useProxyProto() override { return use_proxy_proto_; } @@ -104,7 +104,7 @@ class MainImpl : Logger::Loggable, public Main { private: MainImpl& parent_; - Network::Address::InstancePtr address_; + Network::Address::InstanceConstSharedPtr address_; bool bind_to_port_{}; Stats::ScopePtr scope_; Ssl::ServerContextPtr ssl_context_; @@ -157,10 +157,10 @@ class InitialImpl : public Initial { struct AdminImpl : public Admin { // Server::Configuration::Initial::Admin const std::string& accessLogPath() override { return access_log_path_; } - Network::Address::InstancePtr address() override { return address_; } + Network::Address::InstanceConstSharedPtr address() override { return address_; } std::string access_log_path_; - Network::Address::InstancePtr address_; + Network::Address::InstanceConstSharedPtr address_; }; struct RuntimeImpl : public Runtime { diff --git a/source/server/connection_handler_impl.cc b/source/server/connection_handler_impl.cc index 2c823a8387c0a..9a4cb11b8ec1f 100644 --- a/source/server/connection_handler_impl.cc +++ b/source/server/connection_handler_impl.cc @@ -84,7 +84,7 @@ ConnectionHandlerImpl::findListenerByAddress(const Network::Address::Instance& a // However, linear performance might be adequate since the number of listeners is small. auto listener = std::find_if( listeners_.begin(), listeners_.end(), - [&address](const std::pair& p) { + [&address](const std::pair& p) { return p.first->type() == Network::Address::Type::Ip && *(p.first) == address; }); @@ -97,7 +97,7 @@ ConnectionHandlerImpl::findListenerByAddress(const Network::Address::Instance& a // TODO(wattli): consolidate with previous search for more efficiency. listener = std::find_if( listeners_.begin(), listeners_.end(), - [&address](const std::pair& p) { + [&address](const std::pair& p) { return p.first->type() == Network::Address::Type::Ip && p.first->ip()->port() == address.ip()->port() && p.first->ip()->isAnyAddress(); }); diff --git a/source/server/connection_handler_impl.h b/source/server/connection_handler_impl.h index 14fc8591b1079..34570cf5ed3a4 100644 --- a/source/server/connection_handler_impl.h +++ b/source/server/connection_handler_impl.h @@ -137,7 +137,7 @@ class ConnectionHandlerImpl : public Network::ConnectionHandler, NonCopyable { spdlog::logger& logger_; Api::ApiPtr api_; Event::DispatcherPtr dispatcher_; - std::list> listeners_; + std::list> listeners_; std::list connections_; std::atomic num_connections_{}; Stats::Counter& watchdog_miss_counter_; diff --git a/source/server/http/admin.cc b/source/server/http/admin.cc index bb06f442a5b83..4e6c0d0cb2aa6 100644 --- a/source/server/http/admin.cc +++ b/source/server/http/admin.cc @@ -125,11 +125,11 @@ Http::Code AdminImpl::handlerClusters(const std::string&, Buffer::Instance& resp for (auto& host : cluster.second.get().hosts()) { std::map all_stats; - for (Stats::CounterPtr counter : host->counters()) { + for (Stats::CounterSharedPtr counter : host->counters()) { all_stats[counter->name()] = counter->value(); } - for (Stats::GaugePtr gauge : host->gauges()) { + for (Stats::GaugeSharedPtr gauge : host->gauges()) { all_stats[gauge->name()] = gauge->value(); } @@ -215,7 +215,7 @@ Http::Code AdminImpl::handlerLogging(const std::string& url, Buffer::Instance& r } Http::Code AdminImpl::handlerResetCounters(const std::string&, Buffer::Instance& response) { - for (Stats::CounterPtr counter : server_.stats().counters()) { + for (Stats::CounterSharedPtr counter : server_.stats().counters()) { counter->reset(); } @@ -237,11 +237,11 @@ Http::Code AdminImpl::handlerStats(const std::string&, Buffer::Instance& respons // We currently don't support timers locally (only via statsd) so just group all the counters // and gauges together, alpha sort them, and spit them out. std::map all_stats; - for (Stats::CounterPtr counter : server_.stats().counters()) { + for (Stats::CounterSharedPtr counter : server_.stats().counters()) { all_stats.emplace(counter->name(), counter->value()); } - for (Stats::GaugePtr gauge : server_.stats().gauges()) { + for (Stats::GaugeSharedPtr gauge : server_.stats().gauges()) { all_stats.emplace(gauge->name(), gauge->value()); } @@ -295,8 +295,8 @@ void AdminFilter::onComplete() { AdminImpl::NullRouteConfigProvider::NullRouteConfigProvider() : config_(new Router::NullConfigImpl()) {} -AdminImpl::AdminImpl(const std::string& access_log_path, Network::Address::InstancePtr address, - Server::Instance& server) +AdminImpl::AdminImpl(const std::string& access_log_path, + Network::Address::InstanceConstSharedPtr address, Server::Instance& server) : server_(server), socket_(new Network::TcpListenSocket(address, true)), stats_(Http::ConnectionManagerImpl::generateStats("http.admin.", server_.stats())), tracing_stats_(Http::ConnectionManagerImpl::generateTracingStats("http.admin.tracing.", @@ -330,13 +330,13 @@ Http::ServerConnectionPtr AdminImpl::createCodec(Network::Connection& connection } bool AdminImpl::createFilterChain(Network::Connection& connection) { - connection.addReadFilter(Network::ReadFilterPtr{new Http::ConnectionManagerImpl( + connection.addReadFilter(Network::ReadFilterSharedPtr{new Http::ConnectionManagerImpl( *this, server_.drainManager(), server_.random(), server_.httpTracer(), server_.runtime())}); return true; } void AdminImpl::createFilterChain(Http::FilterChainFactoryCallbacks& callbacks) { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{new AdminFilter(*this)}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{new AdminFilter(*this)}); } Http::Code AdminImpl::runCallback(const std::string& path, Buffer::Instance& response) { diff --git a/source/server/http/admin.h b/source/server/http/admin.h index 6e56a907ebdd3..d3dba3cf4488d 100644 --- a/source/server/http/admin.h +++ b/source/server/http/admin.h @@ -22,7 +22,7 @@ class AdminImpl : public Admin, public Http::ConnectionManagerConfig, Logger::Loggable { public: - AdminImpl(const std::string& access_log_path, Network::Address::InstancePtr address, + AdminImpl(const std::string& access_log_path, Network::Address::InstanceConstSharedPtr address, Server::Instance& server); Http::Code runCallback(const std::string& path, Buffer::Instance& response); @@ -41,7 +41,9 @@ class AdminImpl : public Admin, void createFilterChain(Http::FilterChainFactoryCallbacks& callbacks) override; // Http::ConnectionManagerConfig - const std::list& accessLogs() override { return access_logs_; } + const std::list& accessLogs() override { + return access_logs_; + } Http::ServerConnectionPtr createCodec(Network::Connection& connection, const Buffer::Instance& data, Http::ServerConnectionCallbacks& callbacks) override; @@ -80,9 +82,9 @@ class AdminImpl : public Admin, NullRouteConfigProvider(); // Router::RouteConfigProvider - Router::ConfigPtr config() override { return config_; } + Router::ConfigConstSharedPtr config() override { return config_; } - Router::ConfigPtr config_; + Router::ConfigConstSharedPtr config_; }; /** @@ -110,7 +112,7 @@ class AdminImpl : public Admin, Http::Code handlerQuitQuitQuit(const std::string& url, Buffer::Instance& response); Server::Instance& server_; - std::list access_logs_; + std::list access_logs_; Network::ListenSocketPtr socket_; Http::ConnectionManagerStats stats_; Http::ConnectionManagerTracingStats tracing_stats_; diff --git a/source/server/http/health_check.cc b/source/server/http/health_check.cc index d6aef1068f493..14fc1fdd818f9 100644 --- a/source/server/http/health_check.cc +++ b/source/server/http/health_check.cc @@ -39,7 +39,7 @@ HttpFilterFactoryCb HealthCheckFilterConfig::tryCreateFilterFactory(HttpFilterTy throw EnvoyException("cache_time_ms must not be set when path_through_mode is disabled"); } - HealthCheckCacheManagerPtr cache_manager; + HealthCheckCacheManagerSharedPtr cache_manager; if (cache_time_ms > 0) { cache_manager.reset( new HealthCheckCacheManager(server.dispatcher(), std::chrono::milliseconds(cache_time_ms))); @@ -47,7 +47,7 @@ HttpFilterFactoryCb HealthCheckFilterConfig::tryCreateFilterFactory(HttpFilterTy return [&server, pass_through_mode, cache_manager, hc_endpoint]( Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamFilter(Http::StreamFilterPtr{ + callbacks.addStreamFilter(Http::StreamFilterSharedPtr{ new HealthCheckFilter(server, pass_through_mode, cache_manager, hc_endpoint)}); }; } diff --git a/source/server/http/health_check.h b/source/server/http/health_check.h index f0edc4bfebd3c..f84aac1bbfdcc 100644 --- a/source/server/http/health_check.h +++ b/source/server/http/health_check.h @@ -45,7 +45,7 @@ class HealthCheckCacheManager { std::atomic last_response_code_{}; }; -typedef std::shared_ptr HealthCheckCacheManagerPtr; +typedef std::shared_ptr HealthCheckCacheManagerSharedPtr; /** * Health check responder filter. @@ -53,7 +53,7 @@ typedef std::shared_ptr HealthCheckCacheManagerPtr; class HealthCheckFilter : public Http::StreamFilter { public: HealthCheckFilter(Server::Instance& server, bool pass_through_mode, - HealthCheckCacheManagerPtr cache_manager, const std::string& endpoint) + HealthCheckCacheManagerSharedPtr cache_manager, const std::string& endpoint) : server_(server), pass_through_mode_(pass_through_mode), cache_manager_(cache_manager), endpoint_(endpoint) {} @@ -83,6 +83,6 @@ class HealthCheckFilter : public Http::StreamFilter { bool handling_{}; bool health_check_request_{}; bool pass_through_mode_{}; - HealthCheckCacheManagerPtr cache_manager_{}; + HealthCheckCacheManagerSharedPtr cache_manager_{}; const std::string endpoint_; }; diff --git a/source/server/server.cc b/source/server/server.cc index fdacabf9dfa8b..deef64e89e372 100644 --- a/source/server/server.cc +++ b/source/server/server.cc @@ -115,7 +115,7 @@ void InstanceImpl::flushStats() { server_stats_.days_until_first_cert_expiring_.set( sslContextManager().daysUntilFirstCertExpires()); - for (Stats::CounterPtr counter : stats_store_.counters()) { + for (Stats::CounterSharedPtr counter : stats_store_.counters()) { uint64_t delta = counter->latch(); if (counter->used()) { for (const auto& sink : stat_sinks_) { @@ -124,7 +124,7 @@ void InstanceImpl::flushStats() { } } - for (Stats::GaugePtr gauge : stats_store_.gauges()) { + for (Stats::GaugeSharedPtr gauge : stats_store_.gauges()) { if (gauge->used()) { for (const auto& sink : stat_sinks_) { sink->flushGauge(gauge->name(), gauge->value()); @@ -136,7 +136,7 @@ void InstanceImpl::flushStats() { } int InstanceImpl::getListenSocketFd(const std::string& address) { - Network::Address::InstancePtr addr = Network::Utility::resolveUrl(address); + Network::Address::InstanceConstSharedPtr addr = Network::Utility::resolveUrl(address); for (const auto& entry : socket_map_) { if (entry.second->localAddress()->asString() == addr->asString()) { return entry.second->fd(); diff --git a/test/common/filter/auth/client_ssl_test.cc b/test/common/filter/auth/client_ssl_test.cc index 59d6f1cf0039e..9af3d2b58dd50 100644 --- a/test/common/filter/auth/client_ssl_test.cc +++ b/test/common/filter/auth/client_ssl_test.cc @@ -72,7 +72,7 @@ class ClientSslAuthFilterTest : public testing::Test { Upstream::MockClusterManager cm_; Event::MockDispatcher dispatcher_; Http::MockAsyncClientRequest request_; - ConfigPtr config_; + ConfigSharedPtr config_; NiceMock filter_callbacks_; std::unique_ptr instance_; Event::MockTimer* interval_timer_; diff --git a/test/common/filter/ratelimit_test.cc b/test/common/filter/ratelimit_test.cc index b173d68f90ff7..83b3de5e17306 100644 --- a/test/common/filter/ratelimit_test.cc +++ b/test/common/filter/ratelimit_test.cc @@ -44,14 +44,14 @@ class RateLimitFilterTest : public testing::Test { } ~RateLimitFilterTest() { - for (Stats::GaugePtr gauge : stats_store_.gauges()) { + for (Stats::GaugeSharedPtr gauge : stats_store_.gauges()) { EXPECT_EQ(0U, gauge->value()); } } Stats::IsolatedStoreImpl stats_store_; NiceMock runtime_; - ConfigPtr config_; + ConfigSharedPtr config_; MockClient* client_; std::unique_ptr filter_; NiceMock filter_callbacks_; diff --git a/test/common/filter/tcp_proxy_test.cc b/test/common/filter/tcp_proxy_test.cc index 7dc5ddb2db5ca..ad1d779e1fd53 100644 --- a/test/common/filter/tcp_proxy_test.cc +++ b/test/common/filter/tcp_proxy_test.cc @@ -332,11 +332,11 @@ class TcpProxyTest : public testing::Test { filter_->onNewConnection()); } - TcpProxyConfigPtr config_; + TcpProxyConfigSharedPtr config_; NiceMock filter_callbacks_; NiceMock cluster_manager_; NiceMock* upstream_connection_{}; - Network::ReadFilterPtr upstream_read_filter_; + Network::ReadFilterSharedPtr upstream_read_filter_; NiceMock* connect_timer_{}; std::unique_ptr filter_; NiceMock runtime_; @@ -484,7 +484,7 @@ class TcpProxyRoutingTest : public testing::Test { filter_->initializeReadFilterCallbacks(filter_callbacks_); } - TcpProxyConfigPtr config_; + TcpProxyConfigSharedPtr config_; NiceMock connection_; NiceMock filter_callbacks_; NiceMock cluster_manager_; diff --git a/test/common/http/access_log/access_log_impl_test.cc b/test/common/http/access_log/access_log_impl_test.cc index 43a1c7164441c..62251547985a1 100644 --- a/test/common/http/access_log/access_log_impl_test.cc +++ b/test/common/http/access_log/access_log_impl_test.cc @@ -48,8 +48,10 @@ class TestRequestInfo : public RequestInfo { return response_flags_ & response_flag; } void setResponseFlag(ResponseFlag response_flag) override { response_flags_ |= response_flag; } - void onUpstreamHostSelected(Upstream::HostDescriptionPtr host) override { upstream_host_ = host; } - Upstream::HostDescriptionPtr upstreamHost() const override { return upstream_host_; } + void onUpstreamHostSelected(Upstream::HostDescriptionConstSharedPtr host) override { + upstream_host_ = host; + } + Upstream::HostDescriptionConstSharedPtr upstreamHost() const override { return upstream_host_; } bool healthCheck() const override { return hc_request_; } void healthCheck(bool is_hc) { hc_request_ = is_hc; } @@ -58,7 +60,7 @@ class TestRequestInfo : public RequestInfo { Optional response_code_; uint64_t response_flags_{}; uint64_t duration_{3}; - Upstream::HostDescriptionPtr upstream_host_{}; + Upstream::HostDescriptionConstSharedPtr upstream_host_{}; bool hc_request_{}; }; @@ -86,7 +88,7 @@ TEST_F(AccessLogImplTest, LogMoreData) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); request_info_.response_flags_ = ResponseFlag::UpstreamConnectionFailure; @@ -109,7 +111,7 @@ TEST_F(AccessLogImplTest, EnvoyUpstreamServiceTime) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); response_headers_.addViaCopy(Http::Headers::get().EnvoyUpstreamServiceTime, "999"); @@ -128,7 +130,7 @@ TEST_F(AccessLogImplTest, NoFilter) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); log->log(&request_headers_, &response_headers_, request_info_); @@ -149,7 +151,7 @@ TEST_F(AccessLogImplTest, UpstreamHost) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); log->log(&request_headers_, &response_headers_, request_info_); @@ -171,7 +173,7 @@ TEST_F(AccessLogImplTest, WithFilterMiss) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)).Times(0); log->log(&request_headers_, &response_headers_, request_info_); @@ -194,7 +196,7 @@ TEST_F(AccessLogImplTest, WithFilterHit) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)).Times(3); log->log(&request_headers_, &response_headers_, request_info_); @@ -216,7 +218,7 @@ TEST_F(AccessLogImplTest, RuntimeFilter) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); // Value is taken from random generator. EXPECT_CALL(runtime_.snapshot_, featureEnabled("access_log.test_key", 0)).WillOnce(Return(true)); @@ -248,7 +250,7 @@ TEST_F(AccessLogImplTest, PathRewrite) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); EXPECT_CALL(*file_, write(_)); log->log(&request_headers_, &response_headers_, request_info_); @@ -266,7 +268,7 @@ TEST_F(AccessLogImplTest, healthCheckTrue) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); TestHeaderMapImpl header_map{}; request_info_.hc_request_ = true; @@ -284,7 +286,7 @@ TEST_F(AccessLogImplTest, healthCheckFalse) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); TestHeaderMapImpl header_map{}; EXPECT_CALL(*file_, write(_)); @@ -310,7 +312,7 @@ TEST_F(AccessLogImplTest, requestTracing) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); { TestHeaderMapImpl forced_header{{"x-request-id", force_tracing_guid}}; @@ -459,7 +461,7 @@ TEST_F(AccessLogImplTest, andFilter) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); request_info_.response_code_.value(500); { @@ -490,7 +492,7 @@ TEST_F(AccessLogImplTest, orFilter) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); request_info_.response_code_.value(500); { @@ -524,7 +526,7 @@ TEST_F(AccessLogImplTest, multipleOperators) { )EOF"; Json::ObjectPtr loader = Json::Factory::LoadFromString(json); - InstancePtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); + InstanceSharedPtr log = InstanceImpl::fromJson(*loader, runtime_, log_manager_); request_info_.response_code_.value(500); { diff --git a/test/common/http/codec_client_test.cc b/test/common/http/codec_client_test.cc index 47bd2256e27b5..1b0cfef578ae1 100644 --- a/test/common/http/codec_client_test.cc +++ b/test/common/http/codec_client_test.cc @@ -31,7 +31,8 @@ class CodecClientTest : public testing::Test { EXPECT_CALL(*connection_, addConnectionCallbacks(_)).WillOnce(SaveArgAddress(&connection_cb_)); EXPECT_CALL(*connection_, connect()); EXPECT_CALL(*connection_, addReadFilter(_)) - .WillOnce(Invoke([this](Network::ReadFilterPtr filter) -> void { filter_ = filter; })); + .WillOnce( + Invoke([this](Network::ReadFilterSharedPtr filter) -> void { filter_ = filter; })); codec_ = new Http::MockClientConnection(); @@ -46,9 +47,9 @@ class CodecClientTest : public testing::Test { Http::MockClientConnection* codec_; std::unique_ptr client_; Network::ConnectionCallbacks* connection_cb_; - Network::ReadFilterPtr filter_; + Network::ReadFilterSharedPtr filter_; std::shared_ptr cluster_{new NiceMock()}; - Upstream::HostDescriptionPtr host_{new Upstream::HostDescriptionImpl( + Upstream::HostDescriptionConstSharedPtr host_{new Upstream::HostDescriptionImpl( cluster_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, "")}; }; diff --git a/test/common/http/common.h b/test/common/http/common.h index e017db7057be9..8bbbaa28a5600 100644 --- a/test/common/http/common.h +++ b/test/common/http/common.h @@ -15,7 +15,7 @@ class CodecClientForTest : public Http::CodecClient { typedef std::function DestroyCb; CodecClientForTest(Network::ClientConnectionPtr&& connection, Http::ClientConnection* codec, - DestroyCb destroy_cb, Upstream::HostDescriptionPtr host) + DestroyCb destroy_cb, Upstream::HostDescriptionConstSharedPtr host) : CodecClient(CodecClient::Type::HTTP1, std::move(connection), host), destroy_cb_(destroy_cb) { codec_.reset(codec); @@ -36,14 +36,15 @@ class CodecClientForTest : public Http::CodecClient { * Mock callbacks used for conn pool testing. */ struct ConnPoolCallbacks : public Http::ConnectionPool::Callbacks { - void onPoolReady(Http::StreamEncoder& encoder, Upstream::HostDescriptionPtr host) override { + void onPoolReady(Http::StreamEncoder& encoder, + Upstream::HostDescriptionConstSharedPtr host) override { outer_encoder_ = &encoder; host_ = host; pool_ready_.ready(); } void onPoolFailure(Http::ConnectionPool::PoolFailureReason, - Upstream::HostDescriptionPtr host) override { + Upstream::HostDescriptionConstSharedPtr host) override { host_ = host; pool_failure_.ready(); } @@ -51,7 +52,7 @@ struct ConnPoolCallbacks : public Http::ConnectionPool::Callbacks { ReadyWatcher pool_failure_; ReadyWatcher pool_ready_; Http::StreamEncoder* outer_encoder_{}; - Upstream::HostDescriptionPtr host_; + Upstream::HostDescriptionConstSharedPtr host_; }; /** diff --git a/test/common/http/conn_manager_impl_test.cc b/test/common/http/conn_manager_impl_test.cc index f3dbb893dc8b5..118d7186fc73f 100644 --- a/test/common/http/conn_manager_impl_test.cc +++ b/test/common/http/conn_manager_impl_test.cc @@ -38,14 +38,14 @@ class HttpConnectionManagerImplTest : public Test, public ConnectionManagerConfi public: struct RouteConfigProvider : public Router::RouteConfigProvider { // Router::RouteConfigProvider - Router::ConfigPtr config() override { return route_config_; } + Router::ConfigConstSharedPtr config() override { return route_config_; } std::shared_ptr route_config_{new NiceMock()}; }; HttpConnectionManagerImplTest() : access_log_path_("dummy_path"), - access_logs_{Http::AccessLog::InstancePtr{new Http::AccessLog::InstanceImpl( + access_logs_{Http::AccessLog::InstanceSharedPtr{new Http::AccessLog::InstanceImpl( access_log_path_, {}, AccessLog::AccessLogFormatUtils::defaultAccessLogFormatter(), log_manager_)}}, codec_(new NiceMock()), @@ -75,7 +75,9 @@ class HttpConnectionManagerImplTest : public Test, public ConnectionManagerConfi } // Http::ConnectionManagerConfig - const std::list& accessLogs() override { return access_logs_; } + const std::list& accessLogs() override { + return access_logs_; + } ServerConnectionPtr createCodec(Network::Connection&, const Buffer::Instance&, ServerConnectionCallbacks&) override { return ServerConnectionPtr{codec_}; @@ -101,7 +103,7 @@ class HttpConnectionManagerImplTest : public Test, public ConnectionManagerConfi Event::MockDispatcher dispatcher_; NiceMock<::AccessLog::MockAccessLogManager> log_manager_; std::string access_log_path_; - std::list access_logs_; + std::list access_logs_; Stats::IsolatedStoreImpl fake_stats_; NiceMock filter_callbacks_; Http::MockServerConnection* codec_; @@ -422,7 +424,7 @@ TEST_F(HttpConnectionManagerImplTest, DrainClose) { Http::MockStreamDecoderFilter* filter = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{filter}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{filter}); })); EXPECT_CALL(*filter, decodeHeaders(_, true)) @@ -467,7 +469,7 @@ TEST_F(HttpConnectionManagerImplTest, ResponseBeforeRequestComplete) { Http::MockStreamDecoderFilter* filter = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{filter}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{filter}); })); EXPECT_CALL(*filter, decodeHeaders(_, false)) @@ -505,7 +507,7 @@ TEST_F(HttpConnectionManagerImplTest, ResponseStartBeforeRequestComplete) { Http::MockStreamDecoderFilter* filter = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{filter}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{filter}); })); EXPECT_CALL(*filter, decodeHeaders(_, false)) @@ -554,7 +556,7 @@ TEST_F(HttpConnectionManagerImplTest, DownstreamDisconnect) { Http::MockStreamDecoderFilter* filter = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{filter}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{filter}); })); NiceMock encoder; @@ -580,7 +582,7 @@ TEST_F(HttpConnectionManagerImplTest, DownstreamProtocolError) { Http::MockStreamDecoderFilter* filter = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{filter}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{filter}); })); // A protocol exception should result in reset of the streams followed by a local close. @@ -626,7 +628,7 @@ TEST_F(HttpConnectionManagerImplTest, IdleTimeout) { Http::MockStreamDecoderFilter* filter = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{filter}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{filter}); })); NiceMock encoder; @@ -675,8 +677,8 @@ TEST_F(HttpConnectionManagerImplTest, IntermediateBufferingEarlyResponse) { Http::MockStreamDecoderFilter* decoder_filter2 = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter1}); - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter2}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter1}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter2}); })); EXPECT_CALL(*decoder_filter1, decodeHeaders(_, false)) @@ -722,9 +724,9 @@ TEST_F(HttpConnectionManagerImplTest, DoubleBuffering) { Http::MockStreamDecoderFilter* decoder_filter3 = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter1}); - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter2}); - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter3}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter1}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter2}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter3}); })); EXPECT_CALL(*decoder_filter1, decodeHeaders(_, false)) @@ -773,8 +775,8 @@ TEST_F(HttpConnectionManagerImplTest, ZeroByteDataFiltering) { Http::MockStreamDecoderFilter* decoder_filter2 = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter1}); - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter2}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter1}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter2}); })); EXPECT_CALL(*decoder_filter1, decodeHeaders(_, false)) @@ -820,11 +822,11 @@ TEST_F(HttpConnectionManagerImplTest, MultipleFilters) { Http::MockStreamEncoderFilter* encoder_filter2 = new NiceMock(); EXPECT_CALL(filter_factory_, createFilterChain(_)) .WillOnce(Invoke([&](Http::FilterChainFactoryCallbacks& callbacks) -> void { - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter1}); - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter2}); - callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterPtr{decoder_filter3}); - callbacks.addStreamEncoderFilter(Http::StreamEncoderFilterPtr{encoder_filter1}); - callbacks.addStreamEncoderFilter(Http::StreamEncoderFilterPtr{encoder_filter2}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter1}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter2}); + callbacks.addStreamDecoderFilter(Http::StreamDecoderFilterSharedPtr{decoder_filter3}); + callbacks.addStreamEncoderFilter(Http::StreamEncoderFilterSharedPtr{encoder_filter1}); + callbacks.addStreamEncoderFilter(Http::StreamEncoderFilterSharedPtr{encoder_filter2}); })); // Test route caching. diff --git a/test/common/http/filter/fault_filter_test.cc b/test/common/http/filter/fault_filter_test.cc index 2c321f18ea697..0070c2e9bdb03 100644 --- a/test/common/http/filter/fault_filter_test.cc +++ b/test/common/http/filter/fault_filter_test.cc @@ -99,7 +99,7 @@ class FaultFilterTest : public testing::Test { EXPECT_CALL(*timer_, disableTimer()); } - FaultFilterConfigPtr config_; + FaultFilterConfigSharedPtr config_; std::unique_ptr filter_; NiceMock filter_callbacks_; TestHeaderMapImpl request_headers_; diff --git a/test/common/http/filter/ratelimit_test.cc b/test/common/http/filter/ratelimit_test.cc index f13d366a2097d..65087143dcfcb 100644 --- a/test/common/http/filter/ratelimit_test.cc +++ b/test/common/http/filter/ratelimit_test.cc @@ -56,7 +56,7 @@ class HttpRateLimitFilterTest : public testing::Test { } )EOF"; - FilterConfigPtr config_; + FilterConfigSharedPtr config_; ::RateLimit::MockClient* client_; std::unique_ptr filter_; NiceMock filter_callbacks_; diff --git a/test/common/http/http1/conn_pool_test.cc b/test/common/http/http1/conn_pool_test.cc index be56219bfe5eb..c14d9ad14068f 100644 --- a/test/common/http/http1/conn_pool_test.cc +++ b/test/common/http/http1/conn_pool_test.cc @@ -29,10 +29,11 @@ namespace Http1 { */ class ConnPoolImplForTest : public ConnPoolImpl { public: - ConnPoolImplForTest(Event::MockDispatcher& dispatcher, Upstream::ClusterInfoPtr cluster) + ConnPoolImplForTest(Event::MockDispatcher& dispatcher, + Upstream::ClusterInfoConstSharedPtr cluster) : ConnPoolImpl( dispatcher, - Upstream::HostPtr{new Upstream::HostImpl( + Upstream::HostSharedPtr{new Upstream::HostImpl( cluster, "", Network::Utility::resolveUrl("tcp://127.0.0.1:9000"), false, 1, "")}, Upstream::ResourcePriority::Default), mock_dispatcher_(dispatcher) {} @@ -98,7 +99,7 @@ class Http1ConnPoolImplTest : public testing::Test { ~Http1ConnPoolImplTest() { // Make sure all gauges are 0. - for (Stats::GaugePtr gauge : cluster_->stats_store_.gauges()) { + for (Stats::GaugeSharedPtr gauge : cluster_->stats_store_.gauges()) { EXPECT_EQ(0U, gauge->value()); } } diff --git a/test/common/http/http2/conn_pool_test.cc b/test/common/http/http2/conn_pool_test.cc index 9f7d5e674146d..ee37dfcaa6e67 100644 --- a/test/common/http/http2/conn_pool_test.cc +++ b/test/common/http/http2/conn_pool_test.cc @@ -54,7 +54,7 @@ class Http2ConnPoolImplTest : public testing::Test { ~Http2ConnPoolImplTest() { // Make sure all gauges are 0. - for (Stats::GaugePtr gauge : cluster_->stats_store_.gauges()) { + for (Stats::GaugeSharedPtr gauge : cluster_->stats_store_.gauges()) { EXPECT_EQ(0U, gauge->value()); } } @@ -87,7 +87,7 @@ class Http2ConnPoolImplTest : public testing::Test { NiceMock dispatcher_; std::shared_ptr cluster_{new NiceMock()}; - Upstream::HostPtr host_{new Upstream::HostImpl( + Upstream::HostSharedPtr host_{new Upstream::HostImpl( cluster_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}; TestConnPoolImpl pool_; std::vector test_clients_; diff --git a/test/common/mongo/bson_impl_test.cc b/test/common/mongo/bson_impl_test.cc index 80161b5780bc7..dfcf49faaa789 100644 --- a/test/common/mongo/bson_impl_test.cc +++ b/test/common/mongo/bson_impl_test.cc @@ -4,13 +4,13 @@ namespace Bson { TEST(BsonImplTest, BadCast) { - DocumentPtr doc = DocumentImpl::create()->addString("hello", "world"); + DocumentSharedPtr doc = DocumentImpl::create()->addString("hello", "world"); EXPECT_THROW(doc->values().front()->asDouble(), EnvoyException); } TEST(BsonImplTest, Equal) { - DocumentPtr doc1 = DocumentImpl::create(); - DocumentPtr doc2 = DocumentImpl::create()->addString("hello", "world"); + DocumentSharedPtr doc1 = DocumentImpl::create(); + DocumentSharedPtr doc2 = DocumentImpl::create()->addString("hello", "world"); EXPECT_FALSE(*doc1 == *doc2); doc1->addDouble("hello", 2.0); diff --git a/test/common/mongo/proxy_test.cc b/test/common/mongo/proxy_test.cc index ac02b313d8219..a3c86b7cec089 100644 --- a/test/common/mongo/proxy_test.cc +++ b/test/common/mongo/proxy_test.cc @@ -64,7 +64,7 @@ class MongoProxyFilterTest : public testing::Test { NiceMock runtime_; Event::MockDispatcher dispatcher_; std::shared_ptr file_{new NiceMock()}; - AccessLogPtr access_log_; + AccessLogSharedPtr access_log_; std::unique_ptr filter_; NiceMock read_filter_callbacks_; ::AccessLog::MockAccessLogManager log_manager_; diff --git a/test/common/network/address_impl_test.cc b/test/common/network/address_impl_test.cc index cfa29239dc44a..cbe99d8238fca 100644 --- a/test/common/network/address_impl_test.cc +++ b/test/common/network/address_impl_test.cc @@ -11,7 +11,7 @@ namespace Network { namespace Address { namespace { -bool addressesEqual(const InstancePtr& a, const Instance& b) { +bool addressesEqual(const InstanceConstSharedPtr& a, const Instance& b) { if (a == nullptr || a->type() != Type::Ip || b.type() != Type::Ip) { return false; } else { diff --git a/test/common/network/cidr_range_test.cc b/test/common/network/cidr_range_test.cc index 500b79d388535..8aa7dfb8eddac 100644 --- a/test/common/network/cidr_range_test.cc +++ b/test/common/network/cidr_range_test.cc @@ -60,10 +60,10 @@ TEST(TruncateIpAddressAndLength, Various) { }; test_cases.size(); for (const auto& kv : test_cases) { - InstancePtr inPtr = parseInternetAddress(kv.first.first); + InstanceConstSharedPtr inPtr = parseInternetAddress(kv.first.first); EXPECT_TRUE(inPtr != nullptr) << kv.first.first; int length_io = kv.first.second; - InstancePtr outPtr = CidrRange::truncateIpAddressAndLength(inPtr, &length_io); + InstanceConstSharedPtr outPtr = CidrRange::truncateIpAddressAndLength(inPtr, &length_io); if (kv.second.second == -1) { EXPECT_EQ(outPtr, nullptr) << outPtr->asString() << "\n" << kv; EXPECT_EQ(length_io, -1) << kv; @@ -75,8 +75,8 @@ TEST(TruncateIpAddressAndLength, Various) { } } -TEST(Ipv4CidrRangeTest, InstancePtrAndLengthCtor) { - InstancePtr ptr = parseInternetAddress("1.2.3.5"); +TEST(Ipv4CidrRangeTest, InstanceConstSharedPtrAndLengthCtor) { + InstanceConstSharedPtr ptr = parseInternetAddress("1.2.3.5"); CidrRange rng(CidrRange::create(ptr, 31)); // Copy ctor. EXPECT_TRUE(rng.isValid()); EXPECT_EQ(rng.length(), 31); @@ -155,8 +155,8 @@ TEST(Ipv4CidrRangeTest, BigRange) { EXPECT_FALSE(rng.isInRange(parseInternetAddress("11.0.0.0"))); } -TEST(Ipv6CidrRange, InstancePtrAndLengthCtor) { - InstancePtr ptr = parseInternetAddress("abcd::0345"); +TEST(Ipv6CidrRange, InstanceConstSharedPtrAndLengthCtor) { + InstanceConstSharedPtr ptr = parseInternetAddress("abcd::0345"); CidrRange rng(CidrRange::create(ptr, 127)); // Copy ctor. EXPECT_TRUE(rng.isValid()); EXPECT_EQ(rng.length(), 127); diff --git a/test/common/network/dns_impl_test.cc b/test/common/network/dns_impl_test.cc index 9cb974aab128f..4ced34d2e9c11 100644 --- a/test/common/network/dns_impl_test.cc +++ b/test/common/network/dns_impl_test.cc @@ -31,7 +31,7 @@ class TestDnsServerQuery { public: TestDnsServerQuery(ConnectionPtr connection, const HostMap& hosts) : connection_(std::move(connection)), hosts_(hosts) { - connection_->addReadFilter(Network::ReadFilterPtr{new ReadFilter(*this)}); + connection_->addReadFilter(Network::ReadFilterSharedPtr{new ReadFilter(*this)}); } ~TestDnsServerQuery() { connection_->close(ConnectionCloseType::NoFlush); } @@ -218,7 +218,8 @@ class DnsImplTest : public testing::Test { DnsResolverPtr resolver_; }; -static bool hasAddress(const std::list& results, const std::string& address) { +static bool hasAddress(const std::list& results, + const std::string& address) { for (auto result : results) { if (result->ip()->addressAsString() == address) { return true; @@ -232,10 +233,11 @@ static bool hasAddress(const std::list& results, const std // development, where segfaults were encountered due to callback invocations on // destruction. TEST_F(DnsImplTest, DestructPending) { - EXPECT_NE(nullptr, resolver_->resolve("", [&](std::list&& results) -> void { - FAIL(); - UNREFERENCED_PARAMETER(results); - })); + EXPECT_NE(nullptr, resolver_->resolve( + "", [&](std::list&& results) -> void { + FAIL(); + UNREFERENCED_PARAMETER(results); + })); // Also validate that pending events are around to exercise the resource // reclamation path. EXPECT_GT(peer_->events().size(), 0U); @@ -245,17 +247,19 @@ TEST_F(DnsImplTest, DestructPending) { // to TestDnsServer, but localhost should resolve via the hosts file with no // asynchronous behavior or network events. TEST_F(DnsImplTest, LocalLookup) { - std::list address_list; - EXPECT_NE(nullptr, resolver_->resolve("", [&](std::list&& results) -> void { - address_list = results; - dispatcher_.exit(); - })); + std::list address_list; + EXPECT_NE(nullptr, resolver_->resolve( + "", [&](std::list&& results) -> void { + address_list = results; + dispatcher_.exit(); + })); dispatcher_.run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(address_list.empty()); - EXPECT_EQ(nullptr, resolver_->resolve("localhost", [&](std::list&& results) - -> void { address_list = results; })); + EXPECT_EQ(nullptr, resolver_->resolve("localhost", + [&](std::list&& results) + -> void { address_list = results; })); EXPECT_TRUE(hasAddress(address_list, "127.0.0.1")); } @@ -263,21 +267,23 @@ TEST_F(DnsImplTest, LocalLookup) { // network event handling in DnsResolverImpl. TEST_F(DnsImplTest, RemoteAsyncLookup) { server_->addHosts("some.good.domain", {"201.134.56.7"}); - std::list address_list; - EXPECT_NE(nullptr, resolver_->resolve("some.bad.domain", - [&](std::list&& results) -> void { - address_list = results; - dispatcher_.exit(); - })); + std::list address_list; + EXPECT_NE(nullptr, + resolver_->resolve("some.bad.domain", + [&](std::list&& results) -> void { + address_list = results; + dispatcher_.exit(); + })); dispatcher_.run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(address_list.empty()); - EXPECT_NE(nullptr, resolver_->resolve("some.good.domain", - [&](std::list&& results) -> void { - address_list = results; - dispatcher_.exit(); - })); + EXPECT_NE(nullptr, + resolver_->resolve("some.good.domain", + [&](std::list&& results) -> void { + address_list = results; + dispatcher_.exit(); + })); dispatcher_.run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(hasAddress(address_list, "201.134.56.7")); @@ -286,12 +292,13 @@ TEST_F(DnsImplTest, RemoteAsyncLookup) { // Validate that multiple A records are correctly passed to the callback. TEST_F(DnsImplTest, MultiARecordLookup) { server_->addHosts("some.good.domain", {"201.134.56.7", "123.4.5.6", "6.5.4.3"}); - std::list address_list; - EXPECT_NE(nullptr, resolver_->resolve("some.good.domain", - [&](std::list&& results) -> void { - address_list = results; - dispatcher_.exit(); - })); + std::list address_list; + EXPECT_NE(nullptr, + resolver_->resolve("some.good.domain", + [&](std::list&& results) -> void { + address_list = results; + dispatcher_.exit(); + })); dispatcher_.run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(hasAddress(address_list, "201.134.56.7")); @@ -303,15 +310,16 @@ TEST_F(DnsImplTest, MultiARecordLookup) { TEST_F(DnsImplTest, Cancel) { server_->addHosts("some.good.domain", {"201.134.56.7"}); - ActiveDnsQuery* query = resolver_->resolve("some.domain", [](std::list && ) - -> void { FAIL(); }); + ActiveDnsQuery* query = resolver_->resolve( + "some.domain", [](std::list && ) -> void { FAIL(); }); - std::list address_list; - EXPECT_NE(nullptr, resolver_->resolve("some.good.domain", - [&](std::list&& results) -> void { - address_list = results; - dispatcher_.exit(); - })); + std::list address_list; + EXPECT_NE(nullptr, + resolver_->resolve("some.good.domain", + [&](std::list&& results) -> void { + address_list = results; + dispatcher_.exit(); + })); ASSERT_NE(nullptr, query); query->cancel(); @@ -328,12 +336,13 @@ class DnsImplZeroTimeoutTest : public DnsImplTest { // Validate that timeouts result in an empty callback. TEST_F(DnsImplZeroTimeoutTest, Timeout) { server_->addHosts("some.good.domain", {"201.134.56.7"}); - std::list address_list; - EXPECT_NE(nullptr, resolver_->resolve("some.good.domain", - [&](std::list&& results) -> void { - address_list = results; - dispatcher_.exit(); - })); + std::list address_list; + EXPECT_NE(nullptr, + resolver_->resolve("some.good.domain", + [&](std::list&& results) -> void { + address_list = results; + dispatcher_.exit(); + })); dispatcher_.run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(address_list.empty()); diff --git a/test/common/network/filter_manager_impl_test.cc b/test/common/network/filter_manager_impl_test.cc index 7d8c6ac1f6032..d43a51f0e4cf3 100644 --- a/test/common/network/filter_manager_impl_test.cc +++ b/test/common/network/filter_manager_impl_test.cc @@ -49,11 +49,11 @@ TEST_F(NetworkFilterManagerTest, All) { NiceMock connection; FilterManagerImpl manager(connection, *this); - manager.addReadFilter(ReadFilterPtr{read_filter}); - manager.addWriteFilter(WriteFilterPtr{write_filter}); - manager.addFilter(FilterPtr{filter}); + manager.addReadFilter(ReadFilterSharedPtr{read_filter}); + manager.addWriteFilter(WriteFilterSharedPtr{write_filter}); + manager.addFilter(FilterSharedPtr{filter}); - read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionPtr{host_description}); + read_filter->callbacks_->upstreamHost(Upstream::HostDescriptionConstSharedPtr{host_description}); EXPECT_EQ(read_filter->callbacks_->upstreamHost(), filter->callbacks_->upstreamHost()); EXPECT_CALL(*read_filter, onNewConnection()).WillOnce(Return(FilterStatus::StopIteration)); @@ -111,10 +111,10 @@ TEST_F(NetworkFilterManagerTest, RateLimitAndTcpProxy) { Json::ObjectPtr rl_config_loader = Json::Factory::LoadFromString(rl_json); - RateLimit::TcpFilter::ConfigPtr rl_config( + RateLimit::TcpFilter::ConfigSharedPtr rl_config( new RateLimit::TcpFilter::Config(*rl_config_loader, stats_store, runtime)); RateLimit::MockClient* rl_client = new RateLimit::MockClient(); - manager.addReadFilter(ReadFilterPtr{ + manager.addReadFilter(ReadFilterSharedPtr{ new RateLimit::TcpFilter::Instance(rl_config, RateLimit::ClientPtr{rl_client})}); std::string tcp_proxy_json = R"EOF( @@ -131,9 +131,9 @@ TEST_F(NetworkFilterManagerTest, RateLimitAndTcpProxy) { )EOF"; Json::ObjectPtr tcp_proxy_config_loader = Json::Factory::LoadFromString(tcp_proxy_json); - ::Filter::TcpProxyConfigPtr tcp_proxy_config( + ::Filter::TcpProxyConfigSharedPtr tcp_proxy_config( new ::Filter::TcpProxyConfig(*tcp_proxy_config_loader, cm, stats_store)); - manager.addReadFilter(ReadFilterPtr{new ::Filter::TcpProxy(tcp_proxy_config, cm)}); + manager.addReadFilter(ReadFilterSharedPtr{new ::Filter::TcpProxy(tcp_proxy_config, cm)}); RateLimit::RequestCallbacks* request_callbacks{}; EXPECT_CALL(*rl_client, limit(_, "foo", testing::ContainerEq(std::vector{ diff --git a/test/common/network/listener_impl_test.cc b/test/common/network/listener_impl_test.cc index ed978c759e94f..fb9d8d8c7bee7 100644 --- a/test/common/network/listener_impl_test.cc +++ b/test/common/network/listener_impl_test.cc @@ -54,16 +54,17 @@ class TestListenerImpl : public ListenerImpl { const Network::ListenerOptions& listener_options) : ListenerImpl(conn_handler, dispatcher, socket, cb, stats_store, listener_options) { ON_CALL(*this, newConnection(_, _, _)) - .WillByDefault(Invoke( - [this](int fd, Address::InstancePtr remote_address, Address::InstancePtr local_address) - -> void { ListenerImpl::newConnection(fd, remote_address, local_address); } + .WillByDefault(Invoke([this](int fd, Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address) -> void { + ListenerImpl::newConnection(fd, remote_address, local_address); + } - )); + )); } - MOCK_METHOD1(getOriginalDst, Address::InstancePtr(int fd)); - MOCK_METHOD3(newConnection, void(int fd, Address::InstancePtr remote_address, - Address::InstancePtr local_address)); + MOCK_METHOD1(getOriginalDst, Address::InstanceConstSharedPtr(int fd)); + MOCK_METHOD3(newConnection, void(int fd, Address::InstanceConstSharedPtr remote_address, + Address::InstanceConstSharedPtr local_address)); }; TEST(ListenerImplTest, NormalRedirect) { @@ -88,7 +89,7 @@ TEST(ListenerImplTest, NormalRedirect) { dispatcher.createClientConnection(Utility::resolveUrl("tcp://127.0.0.1:10000")); client_connection->connect(); - Address::InstancePtr alt_address(new Address::Ipv4Instance("127.0.0.1", 10001)); + Address::InstanceConstSharedPtr alt_address(new Address::Ipv4Instance("127.0.0.1", 10001)); EXPECT_CALL(listener, getOriginalDst(_)).WillRepeatedly(Return(alt_address)); EXPECT_CALL(connection_handler, findListenerByAddress(Eq(ByRef(*alt_address)))) .WillRepeatedly(Return(&listenerDst)); @@ -128,7 +129,7 @@ TEST(ListenerImplTest, FallbackToWildcardListener) { dispatcher.createClientConnection(Utility::resolveUrl("tcp://127.0.0.1:10000")); client_connection->connect(); - Address::InstancePtr alt_address(new Address::Ipv4Instance("127.0.0.1", 10001)); + Address::InstanceConstSharedPtr alt_address(new Address::Ipv4Instance("127.0.0.1", 10001)); EXPECT_CALL(listener, getOriginalDst(_)).WillRepeatedly(Return(alt_address)); EXPECT_CALL(connection_handler, findListenerByAddress(Eq(ByRef(*alt_address)))) .WillRepeatedly(Return(&listenerDst)); @@ -167,7 +168,7 @@ TEST(ListenerImplTest, UseActualDst) { dispatcher.createClientConnection(Utility::resolveUrl("tcp://127.0.0.1:10000")); client_connection->connect(); - Address::InstancePtr alt_address(new Address::Ipv4Instance("127.0.0.1", 10001)); + Address::InstanceConstSharedPtr alt_address(new Address::Ipv4Instance("127.0.0.1", 10001)); EXPECT_CALL(listener, getOriginalDst(_)).WillRepeatedly(Return(alt_address)); EXPECT_CALL(connection_handler, findListenerByAddress(Eq(ByRef(*alt_address)))) .WillRepeatedly(Return(&listener)); diff --git a/test/common/network/utility_test.cc b/test/common/network/utility_test.cc index 50bf62c60fc01..dd284c2d5d4ff 100644 --- a/test/common/network/utility_test.cc +++ b/test/common/network/utility_test.cc @@ -142,7 +142,7 @@ TEST(NetworkUtility, loopbackAddress) { TEST(NetworkUtility, AnyAddress) { { - Address::InstancePtr any = Utility::getIpv4AnyAddress(); + Address::InstanceConstSharedPtr any = Utility::getIpv4AnyAddress(); ASSERT_TRUE(any != nullptr); EXPECT_EQ(any->type(), Address::Type::Ip); EXPECT_EQ(any->ip()->version(), Address::IpVersion::v4); @@ -150,7 +150,7 @@ TEST(NetworkUtility, AnyAddress) { EXPECT_EQ(any, Utility::getIpv4AnyAddress()); } { - Address::InstancePtr any = Utility::getIpv6AnyAddress(); + Address::InstanceConstSharedPtr any = Utility::getIpv6AnyAddress(); ASSERT_TRUE(any != nullptr); EXPECT_EQ(any->type(), Address::Type::Ip); EXPECT_EQ(any->ip()->version(), Address::IpVersion::v6); diff --git a/test/common/redis/conn_pool_impl_test.cc b/test/common/redis/conn_pool_impl_test.cc index 78babc2afa11d..9a0351b996f5e 100644 --- a/test/common/redis/conn_pool_impl_test.cc +++ b/test/common/redis/conn_pool_impl_test.cc @@ -45,7 +45,7 @@ class RedisClientImplTest : public testing::Test, public DecoderFactory { MockDecoder* decoder_{new MockDecoder()}; DecoderCallbacks* callbacks_{}; NiceMock* upstream_connection_{}; - Network::ReadFilterPtr upstream_read_filter_; + Network::ReadFilterSharedPtr upstream_read_filter_; ClientPtr client_; }; @@ -165,11 +165,11 @@ TEST(RedisClientFactoryImplTest, Basic) { class RedisConnPoolImplTest : public testing::Test, public ClientFactory { public: // Redis::ConnPool::ClientFactory - ClientPtr create(Upstream::ConstHostPtr host, Event::Dispatcher& dispatcher) override { + ClientPtr create(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher) override { return ClientPtr{create_(host, dispatcher)}; } - MOCK_METHOD2(create_, Client*(Upstream::ConstHostPtr host, Event::Dispatcher& dispatcher)); + MOCK_METHOD2(create_, Client*(Upstream::HostConstSharedPtr host, Event::Dispatcher& dispatcher)); const std::string cluster_name_{"foo"}; NiceMock cm_; @@ -186,10 +186,11 @@ TEST_F(RedisConnPoolImplTest, Basic) { MockClient* client = new NiceMock(); EXPECT_CALL(cm_.thread_local_cluster_.lb_, chooseHost(_)) - .WillOnce(Invoke([&](const Upstream::LoadBalancerContext* context) -> Upstream::ConstHostPtr { - EXPECT_EQ(context->hashKey().value(), std::hash()("foo")); - return cm_.thread_local_cluster_.lb_.host_; - })); + .WillOnce( + Invoke([&](const Upstream::LoadBalancerContext* context) -> Upstream::HostConstSharedPtr { + EXPECT_EQ(context->hashKey().value(), std::hash()("foo")); + return cm_.thread_local_cluster_.lb_.host_; + })); EXPECT_CALL(*this, create_(_, _)).WillOnce(Return(client)); EXPECT_CALL(*client, makeRequest(Ref(value), Ref(callbacks))).WillOnce(Return(&active_request)); ActiveRequest* request = conn_pool_.makeRequest("foo", value, callbacks); diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index d9564fba7e90b..51b5272cfff18 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -581,18 +581,18 @@ TEST(RouterMatcherTest, HashPolicy) { { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); - Router::RoutePtr route = config.route(headers, 0); + Router::RouteConstSharedPtr route = config.route(headers, 0); EXPECT_FALSE(route->routeEntry()->hashPolicy()->generateHash(headers).valid()); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/foo", "GET"); headers.addViaCopy("foo_header", "bar"); - Router::RoutePtr route = config.route(headers, 0); + Router::RouteConstSharedPtr route = config.route(headers, 0); EXPECT_TRUE(route->routeEntry()->hashPolicy()->generateHash(headers).valid()); } { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET"); - Router::RoutePtr route = config.route(headers, 0); + Router::RouteConstSharedPtr route = config.route(headers, 0); EXPECT_EQ(nullptr, route->routeEntry()->hashPolicy()); } } @@ -637,7 +637,7 @@ TEST(RouteMatcherTest, ClusterHeader) { { Http::TestHeaderMapImpl headers = genHeaders("www.lyft.com", "/bar", "GET"); headers.addViaCopy("some_header", "some_cluster"); - Router::RoutePtr route = config.route(headers, 0); + Router::RouteConstSharedPtr route = config.route(headers, 0); EXPECT_EQ("some_cluster", route->routeEntry()->clusterName()); // Make sure things forward and don't crash. diff --git a/test/common/router/rds_impl_test.cc b/test/common/router/rds_impl_test.cc index f8a76ed0f4797..64a28eee7c56b 100644 --- a/test/common/router/rds_impl_test.cc +++ b/test/common/router/rds_impl_test.cc @@ -163,7 +163,7 @@ TEST_F(RdsImplTest, Basic) { interval_timer_->callback_(); // Load the config and verified shared count. - ConfigPtr config = rds_->config(); + ConfigConstSharedPtr config = rds_->config(); EXPECT_EQ(2, config.use_count()); // Third request. diff --git a/test/common/router/router_test.cc b/test/common/router/router_test.cc index 1c430af37584b..8b092ec1b4131 100644 --- a/test/common/router/router_test.cc +++ b/test/common/router/router_test.cc @@ -75,7 +75,8 @@ class RouterTest : public testing::Test { TestFilter router_; Event::MockTimer* response_timeout_{}; Event::MockTimer* per_try_timeout_{}; - Network::Address::InstancePtr host_address_{Network::Utility::resolveUrl("tcp://10.0.0.5:9211")}; + Network::Address::InstanceConstSharedPtr host_address_{ + Network::Utility::resolveUrl("tcp://10.0.0.5:9211")}; }; TEST_F(RouterTest, RouteNotFound) { @@ -122,7 +123,7 @@ TEST_F(RouterTest, PoolFailureWithPriority) { EXPECT_CALL(callbacks_.request_info_, setResponseFlag(Http::AccessLog::ResponseFlag::UpstreamConnectionFailure)); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); Http::TestHeaderMapImpl headers; @@ -248,7 +249,7 @@ TEST_F(RouterTest, UpstreamTimeout) { return nullptr; })); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); expectResponseTimerCreate(); @@ -287,7 +288,7 @@ TEST_F(RouterTest, UpstreamTimeoutWithAltResponse) { return nullptr; })); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); expectResponseTimerCreate(); @@ -325,7 +326,7 @@ TEST_F(RouterTest, UpstreamPerTryTimeout) { return nullptr; })); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); expectResponseTimerCreate(); @@ -368,7 +369,7 @@ TEST_F(RouterTest, RetryRequestNotComplete) { EXPECT_CALL(callbacks_.request_info_, setResponseFlag(Http::AccessLog::ResponseFlag::UpstreamRemoteReset)); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); Http::TestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}}; @@ -393,7 +394,7 @@ TEST_F(RouterTest, RetryNoneHealthy) { expectResponseTimerCreate(); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); Http::TestHeaderMapImpl headers{{"x-envoy-retry-on", "5xx"}, {"x-envoy-internal", "true"}}; @@ -1002,7 +1003,7 @@ TEST_F(RouterTest, AutoHostRewriteEnabled) { })); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); EXPECT_CALL(callbacks_.route_->route_entry_, autoHostRewrite()).WillOnce(Return(true)); router_.decodeHeaders(incoming_headers, true); @@ -1036,7 +1037,7 @@ TEST_F(RouterTest, AutoHostRewriteDisabled) { })); EXPECT_CALL(callbacks_.request_info_, onUpstreamHostSelected(_)) - .WillOnce(Invoke([&](const Upstream::HostDescriptionPtr host) + .WillOnce(Invoke([&](const Upstream::HostDescriptionConstSharedPtr host) -> void { EXPECT_EQ(host_address_, host->address()); })); EXPECT_CALL(callbacks_.route_->route_entry_, autoHostRewrite()).WillOnce(Return(false)); router_.decodeHeaders(incoming_headers, true); diff --git a/test/common/stats/statsd_test.cc b/test/common/stats/statsd_test.cc index 97f2bad4879b3..2dba212c119da 100644 --- a/test/common/stats/statsd_test.cc +++ b/test/common/stats/statsd_test.cc @@ -33,7 +33,7 @@ TEST_F(TcpStatsdSinkTest, All) { Upstream::MockHost::MockCreateConnectionData conn_info; conn_info.connection_ = connection; conn_info.host_.reset( - new Upstream::HostImpl(Upstream::ClusterInfoPtr{new Upstream::MockClusterInfo}, "", + new Upstream::HostImpl(Upstream::ClusterInfoConstSharedPtr{new Upstream::MockClusterInfo}, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")); EXPECT_CALL(cluster_manager_, tcpConnForCluster_("statsd")).WillOnce(Return(conn_info)); diff --git a/test/common/stats/thread_local_store_test.cc b/test/common/stats/thread_local_store_test.cc index 04bf17330cd84..cf23074872e62 100644 --- a/test/common/stats/thread_local_store_test.cc +++ b/test/common/stats/thread_local_store_test.cc @@ -67,7 +67,7 @@ class StatsThreadLocalStoreTest : public testing::Test, public RawStatDataAlloca store_->addSink(sink_); } - CounterPtr findCounter(const std::string& name) { + CounterSharedPtr findCounter(const std::string& name) { for (auto counter : store_->counters()) { if (counter->name() == name) { return counter; @@ -76,7 +76,7 @@ class StatsThreadLocalStoreTest : public testing::Test, public RawStatDataAlloca return nullptr; } - GaugePtr findGauge(const std::string& name) { + GaugeSharedPtr findGauge(const std::string& name) { for (auto gauge : store_->gauges()) { if (gauge->name() == name) { return gauge; @@ -205,7 +205,7 @@ TEST_F(StatsThreadLocalStoreTest, ScopeDelete) { EXPECT_CALL(*this, alloc(_)); scope1->counter("c1"); EXPECT_EQ(2UL, store_->counters().size()); - CounterPtr c1 = store_->counters().front(); + CounterSharedPtr c1 = store_->counters().front(); EXPECT_EQ("scope1.c1", c1->name()); EXPECT_CALL(main_thread_dispatcher_, post(_)); diff --git a/test/common/upstream/cluster_manager_impl_test.cc b/test/common/upstream/cluster_manager_impl_test.cc index 73d989601bbc4..584e15aa48a93 100644 --- a/test/common/upstream/cluster_manager_impl_test.cc +++ b/test/common/upstream/cluster_manager_impl_test.cc @@ -35,21 +35,21 @@ class TestClusterManagerFactory : public ClusterManagerFactory { ON_CALL(*this, clusterFromJson_(_, _, _, _)) .WillByDefault(Invoke([&](const Json::Object& cluster, ClusterManager& cm, const Optional& sds_config, - Outlier::EventLoggerPtr outlier_event_logger) -> Cluster* { + Outlier::EventLoggerSharedPtr outlier_event_logger) -> Cluster* { return ClusterImplBase::create(cluster, cm, stats_, tls_, dns_resolver_, ssl_context_manager_, runtime_, random_, dispatcher_, sds_config, local_info_, outlier_event_logger).release(); })); } - Http::ConnectionPool::InstancePtr allocateConnPool(Event::Dispatcher&, ConstHostPtr host, + Http::ConnectionPool::InstancePtr allocateConnPool(Event::Dispatcher&, HostConstSharedPtr host, ResourcePriority) override { return Http::ConnectionPool::InstancePtr{allocateConnPool_(host)}; } ClusterPtr clusterFromJson(const Json::Object& cluster, ClusterManager& cm, const Optional& sds_config, - Outlier::EventLoggerPtr outlier_event_logger) override { + Outlier::EventLoggerSharedPtr outlier_event_logger) override { return ClusterPtr{clusterFromJson_(cluster, cm, sds_config, outlier_event_logger)}; } @@ -57,10 +57,10 @@ class TestClusterManagerFactory : public ClusterManagerFactory { return CdsApiPtr{createCds_()}; } - MOCK_METHOD1(allocateConnPool_, Http::ConnectionPool::Instance*(ConstHostPtr host)); + MOCK_METHOD1(allocateConnPool_, Http::ConnectionPool::Instance*(HostConstSharedPtr host)); MOCK_METHOD4(clusterFromJson_, Cluster*(const Json::Object& cluster, ClusterManager& cm, const Optional& sds_config, - Outlier::EventLoggerPtr outlier_event_logger)); + Outlier::EventLoggerSharedPtr outlier_event_logger)); MOCK_METHOD0(createCds_, CdsApi*()); Stats::IsolatedStoreImpl stats_; @@ -537,7 +537,7 @@ TEST_F(ClusterManagerImplTest, DynamicAddRemove) { loader_api = Json::Factory::LoadFromString(json_api_3); MockCluster* cluster2 = new NiceMock(); - cluster2->hosts_ = {HostPtr{new HostImpl( + cluster2->hosts_ = {HostSharedPtr{new HostImpl( cluster2->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(factory_, clusterFromJson_(_, _, _, _)).WillOnce(Return(cluster2)); EXPECT_CALL(*cluster2, initializePhase()).Times(0); diff --git a/test/common/upstream/health_checker_impl_test.cc b/test/common/upstream/health_checker_impl_test.cc index 1d6405f1eadfc..a32f297b4d659 100644 --- a/test/common/upstream/health_checker_impl_test.cc +++ b/test/common/upstream/health_checker_impl_test.cc @@ -66,7 +66,7 @@ class HttpHealthCheckerImplTest : public testing::Test { Json::ObjectPtr config = Json::Factory::LoadFromString(json); health_checker_.reset( new TestHttpHealthCheckerImpl(*cluster_, *config, dispatcher_, runtime_, random_)); - health_checker_->addHostCheckCompleteCb([this](HostPtr host, bool changed_state) + health_checker_->addHostCheckCompleteCb([this](HostSharedPtr host, bool changed_state) -> void { onHostStatus(host, changed_state); }); } @@ -87,7 +87,7 @@ class HttpHealthCheckerImplTest : public testing::Test { Json::ObjectPtr config = Json::Factory::LoadFromString(json); health_checker_.reset( new TestHttpHealthCheckerImpl(*cluster_, *config, dispatcher_, runtime_, random_)); - health_checker_->addHostCheckCompleteCb([this](HostPtr host, bool changed_state) + health_checker_->addHostCheckCompleteCb([this](HostSharedPtr host, bool changed_state) -> void { onHostStatus(host, changed_state); }); } @@ -148,7 +148,7 @@ class HttpHealthCheckerImplTest : public testing::Test { } } - MOCK_METHOD2(onHostStatus, void(HostPtr host, bool changed_state)); + MOCK_METHOD2(onHostStatus, void(HostSharedPtr host, bool changed_state)); std::shared_ptr cluster_; NiceMock dispatcher_; @@ -162,7 +162,7 @@ TEST_F(HttpHealthCheckerImplTest, Success) { setupNoServiceValidationHC(); EXPECT_CALL(*this, onHostStatus(_, false)).Times(1); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->info_->stats().upstream_cx_total_.inc(); expectSessionCreate(); @@ -184,7 +184,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessServiceCheck) { EXPECT_CALL(*this, onHostStatus(_, false)).Times(1); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->info_->stats().upstream_cx_total_.inc(); expectSessionCreate(); @@ -207,7 +207,7 @@ TEST_F(HttpHealthCheckerImplTest, ServiceDoesNotMatchFail) { EXPECT_CALL(*this, onHostStatus(_, true)).Times(1); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->info_->stats().upstream_cx_total_.inc(); expectSessionCreate(); @@ -231,7 +231,7 @@ TEST_F(HttpHealthCheckerImplTest, ServiceNotPresentInResponseFail) { EXPECT_CALL(*this, onHostStatus(_, true)).Times(1); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->info_->stats().upstream_cx_total_.inc(); expectSessionCreate(); @@ -254,7 +254,7 @@ TEST_F(HttpHealthCheckerImplTest, ServiceCheckRuntimeOff) { EXPECT_CALL(*this, onHostStatus(_, false)).Times(1); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->info_->stats().upstream_cx_total_.inc(); expectSessionCreate(); @@ -274,7 +274,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessStartFailedFailFirstServiceCheck) { setupNoServiceValidationHC(); EXPECT_CALL(runtime_.snapshot_, featureEnabled("health_check.verify_cluster", 100)) .WillRepeatedly(Return(true)); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->hosts_[0]->healthFlagSet(Host::HealthFlag::FAILED_ACTIVE_HC); expectSessionCreate(); @@ -306,7 +306,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessNoTraffic) { setupNoServiceValidationHC(); EXPECT_CALL(*this, onHostStatus(_, false)).Times(1); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; expectSessionCreate(); expectStreamCreate(0); @@ -319,7 +319,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessNoTraffic) { TEST_F(HttpHealthCheckerImplTest, SuccessStartFailedSuccessFirst) { setupNoServiceValidationHC(); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->hosts_[0]->healthFlagSet(Host::HealthFlag::FAILED_ACTIVE_HC); expectSessionCreate(); @@ -337,7 +337,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessStartFailedSuccessFirst) { TEST_F(HttpHealthCheckerImplTest, SuccessStartFailedFailFirst) { setupNoServiceValidationHC(); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->hosts_[0]->healthFlagSet(Host::HealthFlag::FAILED_ACTIVE_HC); expectSessionCreate(); @@ -366,7 +366,7 @@ TEST_F(HttpHealthCheckerImplTest, SuccessStartFailedFailFirst) { TEST_F(HttpHealthCheckerImplTest, HttpFail) { setupNoServiceValidationHC(); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; expectSessionCreate(); expectStreamCreate(0); @@ -395,7 +395,7 @@ TEST_F(HttpHealthCheckerImplTest, Disconnect) { setupNoServiceValidationHC(); EXPECT_CALL(*this, onHostStatus(_, false)).Times(1); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; expectSessionCreate(); expectStreamCreate(0); @@ -416,7 +416,7 @@ TEST_F(HttpHealthCheckerImplTest, Disconnect) { TEST_F(HttpHealthCheckerImplTest, Timeout) { setupNoServiceValidationHC(); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; expectSessionCreate(); expectStreamCreate(0); @@ -443,11 +443,11 @@ TEST_F(HttpHealthCheckerImplTest, DynamicAddAndRemove) { expectSessionCreate(); expectStreamCreate(0); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->runCallbacks({cluster_->hosts_.back()}, {}); - std::vector removed{cluster_->hosts_.back()}; + std::vector removed{cluster_->hosts_.back()}; cluster_->hosts_.clear(); EXPECT_CALL(*test_sessions_[0]->client_connection_, close(_)); cluster_->runCallbacks({}, removed); @@ -457,7 +457,7 @@ TEST_F(HttpHealthCheckerImplTest, ConnectionClose) { setupNoServiceValidationHC(); EXPECT_CALL(*this, onHostStatus(_, false)); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; expectSessionCreate(); expectStreamCreate(0); @@ -476,7 +476,7 @@ TEST_F(HttpHealthCheckerImplTest, RemoteCloseBetweenChecks) { setupNoServiceValidationHC(); EXPECT_CALL(*this, onHostStatus(_, false)).Times(2); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; expectSessionCreate(); expectStreamCreate(0); @@ -622,13 +622,13 @@ class TcpHealthCheckerImplTest : public testing::Test { Network::MockClientConnection* connection_{}; Event::MockTimer* timeout_timer_{}; Event::MockTimer* interval_timer_{}; - Network::ReadFilterPtr read_filter_; + Network::ReadFilterSharedPtr read_filter_; NiceMock runtime_; NiceMock random_; }; TEST_F(TcpHealthCheckerImplTest, Success) { - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; expectSessionCreate(); expectClientCreate(); @@ -646,7 +646,7 @@ TEST_F(TcpHealthCheckerImplTest, Timeout) { expectSessionCreate(); expectClientCreate(); - cluster_->hosts_ = {HostPtr{new HostImpl( + cluster_->hosts_ = {HostSharedPtr{new HostImpl( cluster_->info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; cluster_->runCallbacks({cluster_->hosts_.back()}, {}); @@ -672,7 +672,7 @@ TEST_F(TcpHealthCheckerImplTest, Timeout) { expectClientCreate(); interval_timer_->callback_(); - std::vector removed{cluster_->hosts_.back()}; + std::vector removed{cluster_->hosts_.back()}; cluster_->hosts_.clear(); EXPECT_CALL(*connection_, close(_)); cluster_->runCallbacks({}, removed); diff --git a/test/common/upstream/host_utility_test.cc b/test/common/upstream/host_utility_test.cc index b8cc486918587..e17d7d6016abd 100644 --- a/test/common/upstream/host_utility_test.cc +++ b/test/common/upstream/host_utility_test.cc @@ -7,7 +7,7 @@ namespace Upstream { TEST(HostUtilityTest, All) { - ClusterInfoPtr cluster{new MockClusterInfo()}; + ClusterInfoConstSharedPtr cluster{new MockClusterInfo()}; HostImpl host(cluster, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, ""); EXPECT_EQ("healthy", HostUtility::healthFlagsToString(host)); diff --git a/test/common/upstream/load_balancer_impl_test.cc b/test/common/upstream/load_balancer_impl_test.cc index 9745e98ace792..3ed1ed52e7334 100644 --- a/test/common/upstream/load_balancer_impl_test.cc +++ b/test/common/upstream/load_balancer_impl_test.cc @@ -10,9 +10,10 @@ using testing::Return; namespace Upstream { -static HostPtr newTestHost(Upstream::ClusterInfoPtr cluster, const std::string& url, - uint32_t weight = 1) { - return HostPtr{new HostImpl(cluster, "", Network::Utility::resolveUrl(url), false, weight, "")}; +static HostSharedPtr newTestHost(Upstream::ClusterInfoConstSharedPtr cluster, + const std::string& url, uint32_t weight = 1) { + return HostSharedPtr{ + new HostImpl(cluster, "", Network::Utility::resolveUrl(url), false, weight, "")}; } class RoundRobinLoadBalancerTest : public testing::Test { @@ -36,7 +37,7 @@ class RoundRobinLoadBalancerTest : public testing::Test { ClusterStats stats_; std::shared_ptr local_cluster_hosts_; std::shared_ptr lb_; - std::vector empty_host_vector_; + std::vector empty_host_vector_; }; TEST_F(RoundRobinLoadBalancerTest, NoHosts) { @@ -88,14 +89,14 @@ TEST_F(RoundRobinLoadBalancerTest, MaxUnhealthyPanic) { TEST_F(RoundRobinLoadBalancerTest, ZoneAwareSmallCluster) { init(true); - HostVectorPtr hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:82")})); - HostListsPtr hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}})); + HostVectorSharedPtr hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:82")})); + HostListsSharedPtr hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}})); cluster_.hosts_ = *hosts; cluster_.healthy_hosts_ = *hosts; @@ -127,17 +128,17 @@ TEST_F(RoundRobinLoadBalancerTest, ZoneAwareSmallCluster) { TEST_F(RoundRobinLoadBalancerTest, NoZoneAwareDifferentZoneSize) { init(true); - HostVectorPtr hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:82")})); - HostListsPtr upstream_hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}})); - HostListsPtr local_hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}})); + HostVectorSharedPtr hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:82")})); + HostListsSharedPtr upstream_hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}})); + HostListsSharedPtr local_hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}})); cluster_.healthy_hosts_ = *hosts; cluster_.hosts_ = *hosts; @@ -156,14 +157,14 @@ TEST_F(RoundRobinLoadBalancerTest, NoZoneAwareDifferentZoneSize) { TEST_F(RoundRobinLoadBalancerTest, ZoneAwareRoutingLargeZoneSwitchOnOff) { init(true); - HostVectorPtr hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:82")})); - HostListsPtr hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}})); + HostVectorSharedPtr hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:82")})); + HostListsSharedPtr hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}})); EXPECT_CALL(runtime_.snapshot_, getInteger("upstream.healthy_panic_threshold", 50)) .WillRepeatedly(Return(50)); @@ -192,28 +193,28 @@ TEST_F(RoundRobinLoadBalancerTest, ZoneAwareRoutingLargeZoneSwitchOnOff) { TEST_F(RoundRobinLoadBalancerTest, ZoneAwareRoutingSmallZone) { init(true); - HostVectorPtr upstream_hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:82"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:83"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:84")})); - HostVectorPtr local_hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:0"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:1"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:2")})); - - HostListsPtr upstream_hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:83"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:84")}})); - - HostListsPtr local_hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:0")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:1")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:2")}})); + HostVectorSharedPtr upstream_hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:81"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:82"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:83"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:84")})); + HostVectorSharedPtr local_hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:0"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:1"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:2")})); + + HostListsSharedPtr upstream_hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:82")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:83"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:84")}})); + + HostListsSharedPtr local_hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:0")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:1")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:2")}})); EXPECT_CALL(runtime_.snapshot_, getInteger("upstream.healthy_panic_threshold", 50)) .WillRepeatedly(Return(50)); @@ -243,15 +244,15 @@ TEST_F(RoundRobinLoadBalancerTest, LowPrecisionForDistribution) { init(true); // upstream_hosts and local_hosts do not matter, zone aware routing is based on per zone hosts. - HostVectorPtr upstream_hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80")})); + HostVectorSharedPtr upstream_hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80")})); cluster_.healthy_hosts_ = *upstream_hosts; cluster_.hosts_ = *upstream_hosts; - HostVectorPtr local_hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:0")})); + HostVectorSharedPtr local_hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:0")})); - HostListsPtr upstream_hosts_per_zone(new std::vector>()); - HostListsPtr local_hosts_per_zone(new std::vector>()); + HostListsSharedPtr upstream_hosts_per_zone(new std::vector>()); + HostListsSharedPtr local_hosts_per_zone(new std::vector>()); EXPECT_CALL(runtime_.snapshot_, getInteger("upstream.healthy_panic_threshold", 50)) .WillRepeatedly(Return(50)); @@ -264,8 +265,8 @@ TEST_F(RoundRobinLoadBalancerTest, LowPrecisionForDistribution) { // situation. // Reuse the same host in all of the structures below to reduce time test takes and this does not // impact load balancing logic. - HostPtr host = newTestHost(cluster_.info_, "tcp://127.0.0.1:80"); - std::vector current(45000); + HostSharedPtr host = newTestHost(cluster_.info_, "tcp://127.0.0.1:80"); + std::vector current(45000); for (int i = 0; i < 45000; ++i) { current[i] = host; @@ -304,10 +305,10 @@ TEST_F(RoundRobinLoadBalancerTest, LowPrecisionForDistribution) { TEST_F(RoundRobinLoadBalancerTest, NoZoneAwareRoutingOneZone) { init(true); - HostVectorPtr hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80")})); - HostListsPtr hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}})); + HostVectorSharedPtr hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80")})); + HostListsSharedPtr hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}})); cluster_.healthy_hosts_ = *hosts; cluster_.hosts_ = *hosts; @@ -319,13 +320,13 @@ TEST_F(RoundRobinLoadBalancerTest, NoZoneAwareRoutingOneZone) { TEST_F(RoundRobinLoadBalancerTest, NoZoneAwareRoutingNotHealthy) { init(true); - HostVectorPtr hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.2:80")})); - HostListsPtr hosts_per_zone( - new std::vector>({{}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.2:80")}})); + HostVectorSharedPtr hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.2:80")})); + HostListsSharedPtr hosts_per_zone(new std::vector>( + {{}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.2:80")}})); cluster_.healthy_hosts_ = *hosts; cluster_.hosts_ = *hosts; @@ -340,15 +341,15 @@ TEST_F(RoundRobinLoadBalancerTest, NoZoneAwareRoutingNotHealthy) { TEST_F(RoundRobinLoadBalancerTest, NoZoneAwareRoutingLocalEmpty) { init(true); - HostVectorPtr upstream_hosts( - new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), - newTestHost(cluster_.info_, "tcp://127.0.0.1:81")})); - HostVectorPtr local_hosts(new std::vector({}, {})); + HostVectorSharedPtr upstream_hosts( + new std::vector({newTestHost(cluster_.info_, "tcp://127.0.0.1:80"), + newTestHost(cluster_.info_, "tcp://127.0.0.1:81")})); + HostVectorSharedPtr local_hosts(new std::vector({}, {})); - HostListsPtr upstream_hosts_per_zone( - new std::vector>({{newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, - {newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}})); - HostListsPtr local_hosts_per_zone(new std::vector>({{}, {}})); + HostListsSharedPtr upstream_hosts_per_zone(new std::vector>( + {{newTestHost(cluster_.info_, "tcp://127.0.0.1:80")}, + {newTestHost(cluster_.info_, "tcp://127.0.0.1:81")}})); + HostListsSharedPtr local_hosts_per_zone(new std::vector>({{}, {}})); EXPECT_CALL(runtime_.snapshot_, getInteger("upstream.healthy_panic_threshold", 50)) .WillOnce(Return(50)); @@ -400,7 +401,7 @@ TEST_F(LeastRequestLoadBalancerTest, SingleHost) { EXPECT_EQ(cluster_.healthy_hosts_[0], lb_.chooseHost(nullptr)); } - std::vector empty; + std::vector empty; { cluster_.runCallbacks(empty, empty); EXPECT_CALL(random_, random()).WillOnce(Return(2)); @@ -408,7 +409,7 @@ TEST_F(LeastRequestLoadBalancerTest, SingleHost) { } { - std::vector remove_hosts; + std::vector remove_hosts; remove_hosts.push_back(cluster_.hosts_[0]); cluster_.runCallbacks(empty, remove_hosts); EXPECT_CALL(random_, random()).Times(0); @@ -515,8 +516,8 @@ TEST_F(LeastRequestLoadBalancerTest, WeightImbalanceCallbacks) { EXPECT_EQ(cluster_.healthy_hosts_[1], lb_.chooseHost(nullptr)); // Same host stays as we have to hit it 3 times, but we remove it and fire callback. - std::vector empty; - std::vector hosts_removed; + std::vector empty; + std::vector hosts_removed; hosts_removed.push_back(cluster_.hosts_[1]); cluster_.hosts_.erase(cluster_.hosts_.begin() + 1); cluster_.healthy_hosts_.erase(cluster_.healthy_hosts_.begin() + 1); diff --git a/test/common/upstream/load_balancer_simulation_test.cc b/test/common/upstream/load_balancer_simulation_test.cc index 4d71e1bcbdc14..34c7905e5e2d5 100644 --- a/test/common/upstream/load_balancer_simulation_test.cc +++ b/test/common/upstream/load_balancer_simulation_test.cc @@ -11,9 +11,11 @@ using testing::Return; namespace Upstream { -static HostPtr newTestHost(Upstream::ClusterInfoPtr cluster, const std::string& url, - uint32_t weight = 1, const std::string& zone = "") { - return HostPtr{new HostImpl(cluster, "", Network::Utility::resolveUrl(url), false, weight, zone)}; +static HostSharedPtr newTestHost(Upstream::ClusterInfoConstSharedPtr cluster, + const std::string& url, uint32_t weight = 1, + const std::string& zone = "") { + return HostSharedPtr{ + new HostImpl(cluster, "", Network::Utility::resolveUrl(url), false, weight, zone)}; } /** @@ -44,22 +46,22 @@ class DISABLED_SimulationTest : public testing::Test { // TODO(mattklein123): make load balancer per originating cluster host. RandomLoadBalancer lb(cluster_, local_host_set_, stats_, runtime_, random_); - HostListsPtr upstream_per_zone_hosts = generateHostsPerZone(healthy_destination_cluster); - HostListsPtr local_per_zone_hosts = generateHostsPerZone(originating_cluster); + HostListsSharedPtr upstream_per_zone_hosts = generateHostsPerZone(healthy_destination_cluster); + HostListsSharedPtr local_per_zone_hosts = generateHostsPerZone(originating_cluster); - HostVectorPtr originating_hosts = generateHostList(originating_cluster); - HostVectorPtr healthy_destination = generateHostList(healthy_destination_cluster); + HostVectorSharedPtr originating_hosts = generateHostList(originating_cluster); + HostVectorSharedPtr healthy_destination = generateHostList(healthy_destination_cluster); cluster_.healthy_hosts_ = *healthy_destination; - HostVectorPtr all_destination = generateHostList(all_destination_cluster); + HostVectorSharedPtr all_destination = generateHostList(all_destination_cluster); cluster_.hosts_ = *all_destination; std::map hits; for (uint32_t i = 0; i < total_number_of_requests; ++i) { - HostPtr from_host = selectOriginatingHost(*originating_hosts); + HostSharedPtr from_host = selectOriginatingHost(*originating_hosts); uint32_t from_zone = atoi(from_host->zone().c_str()); // Populate host set for upstream cluster. - HostListsPtr per_zone_upstream(new std::vector>()); + HostListsSharedPtr per_zone_upstream(new std::vector>()); per_zone_upstream->push_back((*upstream_per_zone_hosts)[from_zone]); for (size_t zone = 0; zone < upstream_per_zone_hosts->size(); ++zone) { if (zone == from_zone) { @@ -72,7 +74,7 @@ class DISABLED_SimulationTest : public testing::Test { cluster_.healthy_hosts_per_zone_ = *per_zone_upstream; // Populate host set for originating cluster. - HostListsPtr per_zone_local(new std::vector>()); + HostListsSharedPtr per_zone_local(new std::vector>()); per_zone_local->push_back((*local_per_zone_hosts)[from_zone]); for (size_t zone = 0; zone < local_per_zone_hosts->size(); ++zone) { if (zone == from_zone) { @@ -84,7 +86,7 @@ class DISABLED_SimulationTest : public testing::Test { local_host_set_->updateHosts(originating_hosts, originating_hosts, per_zone_local, per_zone_local, empty_vector_, empty_vector_); - ConstHostPtr selected = lb.chooseHost(nullptr); + HostConstSharedPtr selected = lb.chooseHost(nullptr); hits[selected->address()->asString()]++; } @@ -96,7 +98,7 @@ class DISABLED_SimulationTest : public testing::Test { } } - HostPtr selectOriginatingHost(const std::vector& hosts) { + HostSharedPtr selectOriginatingHost(const std::vector& hosts) { // Originating cluster should have roughly the same per host request distribution. return hosts[random_.random() % hosts.size()]; } @@ -105,8 +107,8 @@ class DISABLED_SimulationTest : public testing::Test { * Generate list of hosts based on number of hosts in the given zone. * @param hosts number of hosts per zone. */ - HostVectorPtr generateHostList(const std::vector& hosts) { - HostVectorPtr ret(new std::vector()); + HostVectorSharedPtr generateHostList(const std::vector& hosts) { + HostVectorSharedPtr ret(new std::vector()); for (size_t i = 0; i < hosts.size(); ++i) { const std::string zone = std::to_string(i); for (uint32_t j = 0; j < hosts[i]; ++j) { @@ -122,11 +124,11 @@ class DISABLED_SimulationTest : public testing::Test { * Generate hosts by zone. * @param hosts number of hosts per zone. */ - HostListsPtr generateHostsPerZone(const std::vector& hosts) { - HostListsPtr ret(new std::vector>()); + HostListsSharedPtr generateHostsPerZone(const std::vector& hosts) { + HostListsSharedPtr ret(new std::vector>()); for (size_t i = 0; i < hosts.size(); ++i) { const std::string zone = std::to_string(i); - std::vector zone_hosts; + std::vector zone_hosts; for (uint32_t j = 0; j < hosts[i]; ++j) { const std::string url = fmt::format("tcp://host.{}.{}:80", i, j); @@ -140,7 +142,7 @@ class DISABLED_SimulationTest : public testing::Test { }; const uint32_t total_number_of_requests = 1000000; - std::vector empty_vector_; + std::vector empty_vector_; HostSetImpl* local_host_set_; NiceMock cluster_; diff --git a/test/common/upstream/logical_dns_cluster_test.cc b/test/common/upstream/logical_dns_cluster_test.cc index 649efa8d32898..9daada7138225 100644 --- a/test/common/upstream/logical_dns_cluster_test.cc +++ b/test/common/upstream/logical_dns_cluster_test.cc @@ -21,8 +21,9 @@ class LogicalDnsClusterTest : public testing::Test { resolve_timer_ = new Event::MockTimer(&dispatcher_); cluster_.reset(new LogicalDnsCluster(*config, runtime_, stats_store_, ssl_context_manager_, dns_resolver_, tls_, dispatcher_)); - cluster_->addMemberUpdateCb([&](const std::vector&, const std::vector&) - -> void { membership_updated_.ready(); }); + cluster_->addMemberUpdateCb( + [&](const std::vector&, const std::vector&) + -> void { membership_updated_.ready(); }); cluster_->setInitializedCb([&]() -> void { initialized_.ready(); }); } @@ -117,7 +118,7 @@ TEST_F(LogicalDnsClusterTest, Basic) { EXPECT_EQ(0UL, cluster_->hostsPerZone().size()); EXPECT_EQ(0UL, cluster_->healthyHostsPerZone().size()); EXPECT_EQ(cluster_->hosts()[0], cluster_->healthyHosts()[0]); - HostPtr logical_host = cluster_->hosts()[0]; + HostSharedPtr logical_host = cluster_->hosts()[0]; EXPECT_CALL(dispatcher_, createClientConnection_( PointeesEq(Network::Utility::resolveUrl("tcp://127.0.0.1:443")))) diff --git a/test/common/upstream/outlier_detection_impl_test.cc b/test/common/upstream/outlier_detection_impl_test.cc index 812e5d63b1e9d..de6630f390866 100644 --- a/test/common/upstream/outlier_detection_impl_test.cc +++ b/test/common/upstream/outlier_detection_impl_test.cc @@ -45,7 +45,7 @@ TEST(OutlierDetectorImplFactoryTest, Detector) { class CallbackChecker { public: - MOCK_METHOD1(check, void(HostPtr host)); + MOCK_METHOD1(check, void(HostSharedPtr host)); }; class OutlierDetectorImplTest : public testing::Test { @@ -90,12 +90,12 @@ TEST_F(OutlierDetectorImplTest, DetectorStaticConfig) { TEST_F(OutlierDetectorImplTest, DestroyWithActive) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); @@ -120,12 +120,12 @@ TEST_F(OutlierDetectorImplTest, DestroyWithActive) { TEST_F(OutlierDetectorImplTest, DestroyHostInUse) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); detector.reset(); @@ -138,14 +138,14 @@ TEST_F(OutlierDetectorImplTest, DestroyHostInUse) { TEST_F(OutlierDetectorImplTest, BasicFlow) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); - cluster_.hosts_.push_back(HostPtr{new HostImpl( + cluster_.hosts_.push_back(HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:81"), false, 1, "")}); cluster_.runCallbacks({cluster_.hosts_[1]}, {}); @@ -195,12 +195,12 @@ TEST_F(OutlierDetectorImplTest, BasicFlow) { TEST_F(OutlierDetectorImplTest, RemoveWhileEjected) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); @@ -218,7 +218,7 @@ TEST_F(OutlierDetectorImplTest, RemoveWhileEjected) { EXPECT_EQ(1UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); - std::vector old_hosts = std::move(cluster_.hosts_); + std::vector old_hosts = std::move(cluster_.hosts_); cluster_.runCallbacks({}, old_hosts); EXPECT_EQ(0UL, cluster_.info_->stats_store_.gauge("outlier_detection.ejections_active").value()); @@ -232,14 +232,14 @@ TEST_F(OutlierDetectorImplTest, RemoveWhileEjected) { TEST_F(OutlierDetectorImplTest, Overflow) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); cluster_.hosts_ = { - HostPtr{new HostImpl(cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), - false, 1, "")}, - HostPtr{new HostImpl(cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:81"), - false, 1, "")}}; + HostSharedPtr{new HostImpl(cluster_.info_, "", + Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}, + HostSharedPtr{new HostImpl( + cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:81"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); ON_CALL(runtime_.snapshot_, getInteger("outlier_detection.max_ejection_percent", _)) .WillByDefault(Return(1)); @@ -272,12 +272,12 @@ TEST_F(OutlierDetectorImplTest, Overflow) { TEST_F(OutlierDetectorImplTest, NotEnforcing) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); @@ -297,12 +297,12 @@ TEST_F(OutlierDetectorImplTest, NotEnforcing) { TEST_F(OutlierDetectorImplTest, CrossThreadRemoveRace) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); @@ -314,7 +314,7 @@ TEST_F(OutlierDetectorImplTest, CrossThreadRemoveRace) { cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); // Remove before the cross thread event comes in. - std::vector old_hosts = std::move(cluster_.hosts_); + std::vector old_hosts = std::move(cluster_.hosts_); cluster_.runCallbacks({}, old_hosts); post_cb(); @@ -323,12 +323,12 @@ TEST_F(OutlierDetectorImplTest, CrossThreadRemoveRace) { TEST_F(OutlierDetectorImplTest, CrossThreadDestroyRace) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); @@ -350,12 +350,12 @@ TEST_F(OutlierDetectorImplTest, CrossThreadDestroyRace) { TEST_F(OutlierDetectorImplTest, CrossThreadFailRace) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); @@ -383,12 +383,12 @@ TEST_F(OutlierDetectorImplTest, CrossThreadFailRace) { TEST_F(OutlierDetectorImplTest, Consecutive5xxAlreadyEjected) { EXPECT_CALL(cluster_, addMemberUpdateCb(_)); - cluster_.hosts_ = {HostPtr{new HostImpl( + cluster_.hosts_ = {HostSharedPtr{new HostImpl( cluster_.info_, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, 1, "")}}; EXPECT_CALL(*interval_timer_, enableTimer(std::chrono::milliseconds(10000))); std::shared_ptr detector( DetectorImpl::create(cluster_, *loader_, dispatcher_, runtime_, time_source_, event_logger_)); - detector->addChangedStateCb([&](HostPtr host) -> void { checker_.check(host); }); + detector->addChangedStateCb([&](HostSharedPtr host) -> void { checker_.check(host); }); // Cause a consecutive 5xx error. cluster_.hosts_[0]->outlierDetector().putHttpResponseCode(503); diff --git a/test/common/upstream/ring_hash_lb_test.cc b/test/common/upstream/ring_hash_lb_test.cc index b3593731c7619..f8d7a17469393 100644 --- a/test/common/upstream/ring_hash_lb_test.cc +++ b/test/common/upstream/ring_hash_lb_test.cc @@ -11,8 +11,9 @@ using testing::Return; namespace Upstream { -static HostPtr newTestHost(Upstream::ClusterInfoPtr cluster, const std::string& url) { - return HostPtr{new HostImpl(cluster, "", Network::Utility::resolveUrl(url), false, 1, "")}; +static HostSharedPtr newTestHost(Upstream::ClusterInfoConstSharedPtr cluster, + const std::string& url) { + return HostSharedPtr{new HostImpl(cluster, "", Network::Utility::resolveUrl(url), false, 1, "")}; } class TestLoadBalancerContext : public LoadBalancerContext { diff --git a/test/common/upstream/sds_test.cc b/test/common/upstream/sds_test.cc index da861bd4738d1..4affe41a0003f 100644 --- a/test/common/upstream/sds_test.cc +++ b/test/common/upstream/sds_test.cc @@ -42,8 +42,8 @@ class SdsTest : public testing::Test { EXPECT_EQ(Cluster::InitializePhase::Secondary, cluster_->initializePhase()); } - HostPtr findHost(const std::string& address) { - for (HostPtr host : cluster_->hosts()) { + HostSharedPtr findHost(const std::string& address) { + for (HostSharedPtr host : cluster_->hosts()) { if (host->address()->ip()->addressAsString() == address) { return host; } @@ -54,7 +54,7 @@ class SdsTest : public testing::Test { uint64_t numHealthy() { uint64_t healthy = 0; - for (HostPtr host : cluster_->hosts()) { + for (HostSharedPtr host : cluster_->hosts()) { if (host->healthy()) { healthy++; } @@ -115,8 +115,9 @@ TEST_F(SdsTest, NoHealthChecker) { cluster_->initialize(); EXPECT_CALL(membership_updated_, ready()).Times(3); - cluster_->addMemberUpdateCb([&](const std::vector&, const std::vector&) - -> void { membership_updated_.ready(); }); + cluster_->addMemberUpdateCb( + [&](const std::vector&, const std::vector&) + -> void { membership_updated_.ready(); }); cluster_->setInitializedCb([&]() -> void { membership_updated_.ready(); }); Http::MessagePtr message(new Http::ResponseMessageImpl( @@ -137,7 +138,7 @@ TEST_F(SdsTest, NoHealthChecker) { // Hosts in SDS and static clusters should have empty hostname EXPECT_EQ("", cluster_->hosts()[0]->hostname()); - HostPtr canary_host = findHost("10.0.16.43"); + HostSharedPtr canary_host = findHost("10.0.16.43"); EXPECT_TRUE(canary_host->canary()); EXPECT_EQ("us-east-1d", canary_host->zone()); EXPECT_EQ(40U, canary_host->weight()); diff --git a/test/common/upstream/upstream_impl_test.cc b/test/common/upstream/upstream_impl_test.cc index 653187f7af1a7..8631e8c44c027 100644 --- a/test/common/upstream/upstream_impl_test.cc +++ b/test/common/upstream/upstream_impl_test.cc @@ -20,9 +20,9 @@ using testing::NiceMock; namespace Upstream { -static std::list hostListToAddresses(const std::vector& hosts) { +static std::list hostListToAddresses(const std::vector& hosts) { std::list addresses; - for (const HostPtr& host : hosts) { + for (const HostSharedPtr& host : hosts) { addresses.push_back(host->address()->asString()); } @@ -144,8 +144,9 @@ TEST(StrictDnsClusterImplTest, Basic) { EXPECT_FALSE(cluster.info()->maintenanceMode()); ReadyWatcher membership_updated; - cluster.addMemberUpdateCb([&](const std::vector&, const std::vector&) - -> void { membership_updated.ready(); }); + cluster.addMemberUpdateCb( + [&](const std::vector&, const std::vector&) + -> void { membership_updated.ready(); }); resolver1.expectResolve(dns_resolver); EXPECT_CALL(*resolver1.timer_, enableTimer(std::chrono::milliseconds(4000))); @@ -188,7 +189,7 @@ TEST(StrictDnsClusterImplTest, Basic) { EXPECT_EQ(0UL, cluster.hostsPerZone().size()); EXPECT_EQ(0UL, cluster.healthyHostsPerZone().size()); - for (const HostPtr& host : cluster.hosts()) { + for (const HostSharedPtr& host : cluster.hosts()) { EXPECT_EQ(cluster.info().get(), &host->cluster()); } @@ -310,7 +311,7 @@ TEST(StaticClusterImplTest, OutlierDetector) { Outlier::MockDetector* detector = new Outlier::MockDetector(); EXPECT_CALL(*detector, addChangedStateCb(_)); - cluster.setOutlierDetector(Outlier::DetectorPtr{detector}); + cluster.setOutlierDetector(Outlier::DetectorSharedPtr{detector}); EXPECT_EQ(2UL, cluster.healthyHosts().size()); EXPECT_EQ(2UL, cluster.info()->stats().membership_healthy_.value()); @@ -350,7 +351,7 @@ TEST(StaticClusterImplTest, HealthyStat) { StaticClusterImpl cluster(*config, runtime, stats, ssl_context_manager); Outlier::MockDetector* outlier_detector = new NiceMock(); - cluster.setOutlierDetector(Outlier::DetectorPtr{outlier_detector}); + cluster.setOutlierDetector(Outlier::DetectorSharedPtr{outlier_detector}); MockHealthChecker* health_checker = new NiceMock(); cluster.setHealthChecker(HealthCheckerPtr{health_checker}); diff --git a/test/integration/fake_upstream.cc b/test/integration/fake_upstream.cc index bf6bf9d2e045e..45566d4290b6a 100644 --- a/test/integration/fake_upstream.cc +++ b/test/integration/fake_upstream.cc @@ -123,7 +123,7 @@ FakeHttpConnection::FakeHttpConnection(Network::Connection& connection, Stats::S ASSERT(type == Type::HTTP2); } - connection.addReadFilter(Network::ReadFilterPtr{new ReadFilter(*this)}); + connection.addReadFilter(Network::ReadFilterSharedPtr{new ReadFilter(*this)}); } void FakeConnectionBase::close() { diff --git a/test/integration/fake_upstream.h b/test/integration/fake_upstream.h index 6da734536811e..f0ee54dc41268 100644 --- a/test/integration/fake_upstream.h +++ b/test/integration/fake_upstream.h @@ -123,7 +123,7 @@ typedef std::unique_ptr FakeHttpConnectionPtr; class FakeRawConnection : Logger::Loggable, public FakeConnectionBase { public: FakeRawConnection(Network::Connection& connection) : FakeConnectionBase(connection) { - connection.addReadFilter(Network::ReadFilterPtr{new ReadFilter(*this)}); + connection.addReadFilter(Network::ReadFilterSharedPtr{new ReadFilter(*this)}); } void waitForData(uint64_t num_bytes); diff --git a/test/integration/integration.cc b/test/integration/integration.cc index e4d8416e8cdd3..a386f0037a389 100644 --- a/test/integration/integration.cc +++ b/test/integration/integration.cc @@ -81,10 +81,9 @@ void IntegrationStreamDecoder::onResetStream(Http::StreamResetReason) { } } -IntegrationCodecClient::IntegrationCodecClient(Event::Dispatcher& dispatcher, - Network::ClientConnectionPtr&& conn, - Upstream::HostDescriptionPtr host_description, - CodecClient::Type type) +IntegrationCodecClient::IntegrationCodecClient( + Event::Dispatcher& dispatcher, Network::ClientConnectionPtr&& conn, + Upstream::HostDescriptionConstSharedPtr host_description, CodecClient::Type type) : CodecClientProd(type, std::move(conn), host_description), callbacks_(*this), codec_callbacks_(*this) { connection_->addConnectionCallbacks(callbacks_); @@ -237,7 +236,7 @@ IntegrationCodecClientPtr BaseIntegrationTest::makeHttpConnection(Network::ClientConnectionPtr&& conn, Http::CodecClient::Type type) { std::shared_ptr cluster{new NiceMock()}; - Upstream::HostDescriptionPtr host_description{new Upstream::HostDescriptionImpl( + Upstream::HostDescriptionConstSharedPtr host_description{new Upstream::HostDescriptionImpl( cluster, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, "")}; return IntegrationCodecClientPtr{ new IntegrationCodecClient(*dispatcher_, std::move(conn), host_description, type)}; diff --git a/test/integration/integration.h b/test/integration/integration.h index 800b9b875b422..20f4998b0ddb7 100644 --- a/test/integration/integration.h +++ b/test/integration/integration.h @@ -50,7 +50,7 @@ typedef std::unique_ptr IntegrationStreamDecoderPtr; class IntegrationCodecClient : public Http::CodecClientProd { public: IntegrationCodecClient(Event::Dispatcher& dispatcher, Network::ClientConnectionPtr&& conn, - Upstream::HostDescriptionPtr host_description, + Upstream::HostDescriptionConstSharedPtr host_description, Http::CodecClient::Type type); void makeHeaderOnlyRequest(const Http::HeaderMap& headers, IntegrationStreamDecoder& response); diff --git a/test/integration/server.h b/test/integration/server.h index fc61ca2e4690a..8d6762b85d0d6 100644 --- a/test/integration/server.h +++ b/test/integration/server.h @@ -74,11 +74,11 @@ class TestIsolatedStoreImpl : public StoreRoot { } // Stats::Store - std::list counters() const override { + std::list counters() const override { std::unique_lock lock(lock_); return store_.counters(); } - std::list gauges() const override { + std::list gauges() const override { std::unique_lock lock(lock_); return store_.gauges(); } diff --git a/test/integration/utility.cc b/test/integration/utility.cc index fc88eb8a059b2..7aca598300f6b 100644 --- a/test/integration/utility.cc +++ b/test/integration/utility.cc @@ -48,7 +48,7 @@ IntegrationUtil::makeSingleRequest(uint32_t port, const std::string& method, con Api::Impl api(std::chrono::milliseconds(9000)); Event::DispatcherPtr dispatcher(api.allocateDispatcher()); std::shared_ptr cluster{new NiceMock()}; - Upstream::HostDescriptionPtr host_description{new Upstream::HostDescriptionImpl( + Upstream::HostDescriptionConstSharedPtr host_description{new Upstream::HostDescriptionImpl( cluster, "", Network::Utility::resolveUrl("tcp://127.0.0.1:80"), false, "")}; Http::CodecClientProd client(type, dispatcher->createClientConnection(Network::Utility::resolveUrl( @@ -79,7 +79,7 @@ RawConnectionDriver::RawConnectionDriver(uint32_t port, Buffer::Instance& initia dispatcher_ = api_->allocateDispatcher(); client_ = dispatcher_->createClientConnection( Network::Utility::resolveUrl(fmt::format("tcp://127.0.0.1:{}", port))); - client_->addReadFilter(Network::ReadFilterPtr{new ForwardingFilter(*this, data_callback)}); + client_->addReadFilter(Network::ReadFilterSharedPtr{new ForwardingFilter(*this, data_callback)}); client_->write(initial_data); client_->connect(); } diff --git a/test/mocks/access_log/mocks.h b/test/mocks/access_log/mocks.h index 970b21fa1178c..850daadb1f95c 100644 --- a/test/mocks/access_log/mocks.h +++ b/test/mocks/access_log/mocks.h @@ -13,7 +13,7 @@ class MockAccessLogManager : public AccessLogManager { // AccessLog::AccessLogManager MOCK_METHOD0(reopen, void()); - MOCK_METHOD1(createAccessLog, Filesystem::FilePtr(const std::string& file_name)); + MOCK_METHOD1(createAccessLog, Filesystem::FileSharedPtr(const std::string& file_name)); std::shared_ptr file_{new testing::NiceMock()}; }; diff --git a/test/mocks/api/mocks.h b/test/mocks/api/mocks.h index c6eaef7b37cc9..3a8f3b8e4de2d 100644 --- a/test/mocks/api/mocks.h +++ b/test/mocks/api/mocks.h @@ -18,8 +18,8 @@ class MockApi : public Api { MOCK_METHOD0(allocateDispatcher_, Event::Dispatcher*()); MOCK_METHOD4(createFile, - Filesystem::FilePtr(const std::string& path, Event::Dispatcher& dispatcher, - Thread::BasicLockable& lock, Stats::Store& stats_store)); + Filesystem::FileSharedPtr(const std::string& path, Event::Dispatcher& dispatcher, + Thread::BasicLockable& lock, Stats::Store& stats_store)); MOCK_METHOD1(fileExists, bool(const std::string& path)); MOCK_METHOD1(fileReadToEnd, std::string(const std::string& path)); diff --git a/test/mocks/event/mocks.h b/test/mocks/event/mocks.h index 2b3c352b8838e..3f517aa8e742d 100644 --- a/test/mocks/event/mocks.h +++ b/test/mocks/event/mocks.h @@ -19,13 +19,13 @@ class MockDispatcher : public Dispatcher { ~MockDispatcher(); Network::ClientConnectionPtr - createClientConnection(Network::Address::InstancePtr address) override { + createClientConnection(Network::Address::InstanceConstSharedPtr address) override { return Network::ClientConnectionPtr{createClientConnection_(address)}; } Network::ClientConnectionPtr createSslClientConnection(Ssl::ClientContext& ssl_ctx, - Network::Address::InstancePtr address) override { + Network::Address::InstanceConstSharedPtr address) override { return Network::ClientConnectionPtr{createSslClientConnection_(ssl_ctx, address)}; } @@ -74,10 +74,10 @@ class MockDispatcher : public Dispatcher { // Event::Dispatcher MOCK_METHOD0(clearDeferredDeleteList, void()); MOCK_METHOD1(createClientConnection_, - Network::ClientConnection*(Network::Address::InstancePtr address)); + Network::ClientConnection*(Network::Address::InstanceConstSharedPtr address)); MOCK_METHOD2(createSslClientConnection_, Network::ClientConnection*(Ssl::ClientContext& ssl_ctx, - Network::Address::InstancePtr address)); + Network::Address::InstanceConstSharedPtr address)); MOCK_METHOD0(createDnsResolver_, Network::DnsResolver*()); MOCK_METHOD4(createFileEvent_, FileEvent*(int fd, FileReadyCb cb, FileTriggerType trigger, uint32_t events)); diff --git a/test/mocks/http/mocks.h b/test/mocks/http/mocks.h index 3e98b3011c61b..f750ff0bd7eb7 100644 --- a/test/mocks/http/mocks.h +++ b/test/mocks/http/mocks.h @@ -35,7 +35,7 @@ class MockRequestInfo : public RequestInfo { // Http::AccessLog::RequestInfo MOCK_METHOD1(setResponseFlag, void(ResponseFlag response_flag)); - MOCK_METHOD1(onUpstreamHostSelected, void(Upstream::HostDescriptionPtr host)); + MOCK_METHOD1(onUpstreamHostSelected, void(Upstream::HostDescriptionConstSharedPtr host)); MOCK_CONST_METHOD0(startTime, SystemTime()); MOCK_CONST_METHOD0(bytesReceived, uint64_t()); MOCK_CONST_METHOD0(protocol, Protocol()); @@ -44,7 +44,7 @@ class MockRequestInfo : public RequestInfo { MOCK_CONST_METHOD0(bytesSent, uint64_t()); MOCK_CONST_METHOD0(duration, std::chrono::milliseconds()); MOCK_CONST_METHOD1(getResponseFlag, bool(Http::AccessLog::ResponseFlag)); - MOCK_CONST_METHOD0(upstreamHost, Upstream::HostDescriptionPtr()); + MOCK_CONST_METHOD0(upstreamHost, Upstream::HostDescriptionConstSharedPtr()); MOCK_CONST_METHOD0(healthCheck, bool()); MOCK_METHOD1(healthCheck, void(bool is_hc)); @@ -65,7 +65,7 @@ class MockConnectionManagerConfig : public ConnectionManagerConfig { return ServerConnectionPtr{createCodec_(connection, instance, callbacks)}; } - MOCK_METHOD0(accessLogs, const std::list&()); + MOCK_METHOD0(accessLogs, const std::list&()); MOCK_METHOD3(createCodec_, ServerConnection*(Network::Connection&, const Buffer::Instance&, ServerConnectionCallbacks&)); MOCK_METHOD0(dateProvider, DateProvider&()); @@ -215,7 +215,7 @@ class MockStreamDecoderFilterCallbacks : public StreamDecoderFilterCallbacks, MOCK_METHOD0(ssl, Ssl::Connection*()); MOCK_METHOD0(dispatcher, Event::Dispatcher&()); MOCK_METHOD0(resetStream, void()); - MOCK_METHOD0(route, Router::RoutePtr()); + MOCK_METHOD0(route, Router::RouteConstSharedPtr()); MOCK_METHOD0(streamId, uint64_t()); MOCK_METHOD0(requestInfo, Http::AccessLog::RequestInfo&()); MOCK_METHOD0(downstreamAddress, const std::string&()); @@ -245,7 +245,7 @@ class MockStreamEncoderFilterCallbacks : public StreamEncoderFilterCallbacks, MOCK_METHOD0(ssl, Ssl::Connection*()); MOCK_METHOD0(dispatcher, Event::Dispatcher&()); MOCK_METHOD0(resetStream, void()); - MOCK_METHOD0(route, Router::RoutePtr()); + MOCK_METHOD0(route, Router::RouteConstSharedPtr()); MOCK_METHOD0(streamId, uint64_t()); MOCK_METHOD0(requestInfo, Http::AccessLog::RequestInfo&()); MOCK_METHOD0(downstreamAddress, const std::string&()); @@ -347,10 +347,10 @@ class MockFilterChainFactoryCallbacks : public Http::FilterChainFactoryCallbacks MockFilterChainFactoryCallbacks(); ~MockFilterChainFactoryCallbacks(); - MOCK_METHOD1(addStreamDecoderFilter, void(Http::StreamDecoderFilterPtr filter)); - MOCK_METHOD1(addStreamEncoderFilter, void(Http::StreamEncoderFilterPtr filter)); - MOCK_METHOD1(addStreamFilter, void(Http::StreamFilterPtr filter)); - MOCK_METHOD1(addAccessLogHandler, void(Http::AccessLog::InstancePtr handler)); + MOCK_METHOD1(addStreamDecoderFilter, void(Http::StreamDecoderFilterSharedPtr filter)); + MOCK_METHOD1(addStreamEncoderFilter, void(Http::StreamEncoderFilterSharedPtr filter)); + MOCK_METHOD1(addStreamFilter, void(Http::StreamFilterSharedPtr filter)); + MOCK_METHOD1(addAccessLogHandler, void(Http::AccessLog::InstanceSharedPtr handler)); }; } // Http diff --git a/test/mocks/local_info/mocks.h b/test/mocks/local_info/mocks.h index 53e02fe2fef48..bc9678e23c6b9 100644 --- a/test/mocks/local_info/mocks.h +++ b/test/mocks/local_info/mocks.h @@ -9,12 +9,12 @@ class MockLocalInfo : public LocalInfo { MockLocalInfo(); ~MockLocalInfo(); - MOCK_CONST_METHOD0(address, Network::Address::InstancePtr()); + MOCK_CONST_METHOD0(address, Network::Address::InstanceConstSharedPtr()); MOCK_CONST_METHOD0(zoneName, std::string&()); MOCK_CONST_METHOD0(clusterName, std::string&()); MOCK_CONST_METHOD0(nodeName, std::string&()); - Network::Address::InstancePtr address_; + Network::Address::InstanceConstSharedPtr address_; std::string zone_name_{"zone_name"}; std::string cluster_name_{"cluster_name"}; std::string node_name_{"node_name"}; diff --git a/test/mocks/network/mocks.h b/test/mocks/network/mocks.h index bd030b12002f5..ae8d23b0997b0 100644 --- a/test/mocks/network/mocks.h +++ b/test/mocks/network/mocks.h @@ -28,7 +28,7 @@ class MockConnectionBase { testing::NiceMock dispatcher_; std::list callbacks_; uint64_t id_{next_id_++}; - Address::InstancePtr remote_address_; + Address::InstanceConstSharedPtr remote_address_; bool read_enabled_{true}; Connection::State state_{Connection::State::Open}; }; @@ -40,9 +40,9 @@ class MockConnection : public Connection, public MockConnectionBase { // Network::Connection MOCK_METHOD1(addConnectionCallbacks, void(ConnectionCallbacks& cb)); - MOCK_METHOD1(addWriteFilter, void(WriteFilterPtr filter)); - MOCK_METHOD1(addFilter, void(FilterPtr filter)); - MOCK_METHOD1(addReadFilter, void(ReadFilterPtr filter)); + MOCK_METHOD1(addWriteFilter, void(WriteFilterSharedPtr filter)); + MOCK_METHOD1(addFilter, void(FilterSharedPtr filter)); + MOCK_METHOD1(addReadFilter, void(ReadFilterSharedPtr filter)); MOCK_METHOD1(close, void(ConnectionCloseType type)); MOCK_METHOD0(dispatcher, Event::Dispatcher&()); MOCK_METHOD0(id, uint64_t()); @@ -72,9 +72,9 @@ class MockClientConnection : public ClientConnection, public MockConnectionBase // Network::Connection MOCK_METHOD1(addConnectionCallbacks, void(ConnectionCallbacks& cb)); - MOCK_METHOD1(addWriteFilter, void(WriteFilterPtr filter)); - MOCK_METHOD1(addFilter, void(FilterPtr filter)); - MOCK_METHOD1(addReadFilter, void(ReadFilterPtr filter)); + MOCK_METHOD1(addWriteFilter, void(WriteFilterSharedPtr filter)); + MOCK_METHOD1(addFilter, void(FilterSharedPtr filter)); + MOCK_METHOD1(addReadFilter, void(ReadFilterSharedPtr filter)); MOCK_METHOD1(close, void(ConnectionCloseType type)); MOCK_METHOD0(dispatcher, Event::Dispatcher&()); MOCK_METHOD0(id, uint64_t()); @@ -123,11 +123,11 @@ class MockReadFilterCallbacks : public ReadFilterCallbacks { MOCK_METHOD0(connection, Connection&()); MOCK_METHOD0(continueReading, void()); - MOCK_METHOD0(upstreamHost, Upstream::HostDescriptionPtr()); - MOCK_METHOD1(upstreamHost, void(Upstream::HostDescriptionPtr host)); + MOCK_METHOD0(upstreamHost, Upstream::HostDescriptionConstSharedPtr()); + MOCK_METHOD1(upstreamHost, void(Upstream::HostDescriptionConstSharedPtr host)); testing::NiceMock connection_; - Upstream::HostDescriptionPtr host_; + Upstream::HostDescriptionConstSharedPtr host_; }; class MockReadFilter : public ReadFilter { @@ -194,11 +194,11 @@ class MockListenSocket : public ListenSocket { MockListenSocket(); ~MockListenSocket(); - MOCK_METHOD0(localAddress, Address::InstancePtr()); + MOCK_METHOD0(localAddress, Address::InstanceConstSharedPtr()); MOCK_METHOD0(fd, int()); MOCK_METHOD0(close, void()); - Address::InstancePtr local_address_; + Address::InstanceConstSharedPtr local_address_; }; class MockListener : public Listener { diff --git a/test/mocks/router/mocks.h b/test/mocks/router/mocks.h index 9e2ff57b9899b..6455306f5eb0b 100644 --- a/test/mocks/router/mocks.h +++ b/test/mocks/router/mocks.h @@ -176,7 +176,7 @@ class MockConfig : public Config { ~MockConfig(); // Router::Config - MOCK_CONST_METHOD2(route, RoutePtr(const Http::HeaderMap&, uint64_t random_value)); + MOCK_CONST_METHOD2(route, RouteConstSharedPtr(const Http::HeaderMap&, uint64_t random_value)); MOCK_CONST_METHOD0(internalOnlyHeaders, const std::list&()); MOCK_CONST_METHOD0(responseHeadersToAdd, const std::list>&()); diff --git a/test/mocks/stats/mocks.h b/test/mocks/stats/mocks.h index 61578d3a4e575..e7c58ac78e192 100644 --- a/test/mocks/stats/mocks.h +++ b/test/mocks/stats/mocks.h @@ -66,10 +66,10 @@ class MockStore : public Store { MOCK_METHOD2(deliverHistogramToSinks, void(const std::string& name, uint64_t value)); MOCK_METHOD2(deliverTimingToSinks, void(const std::string&, std::chrono::milliseconds)); MOCK_METHOD1(counter, Counter&(const std::string&)); - MOCK_CONST_METHOD0(counters, std::list()); + MOCK_CONST_METHOD0(counters, std::list()); MOCK_METHOD1(createScope_, Scope*(const std::string& name)); MOCK_METHOD1(gauge, Gauge&(const std::string&)); - MOCK_CONST_METHOD0(gauges, std::list()); + MOCK_CONST_METHOD0(gauges, std::list()); MOCK_METHOD1(timer, Timer&(const std::string& name)); testing::NiceMock counter_; diff --git a/test/mocks/thread_local/mocks.h b/test/mocks/thread_local/mocks.h index cb54b4863882d..9a5eea06c6e6b 100644 --- a/test/mocks/thread_local/mocks.h +++ b/test/mocks/thread_local/mocks.h @@ -13,14 +13,14 @@ class MockInstance : public Instance { // Server::ThreadLocal MOCK_METHOD0(allocateSlot, uint32_t()); - MOCK_METHOD1(get, ThreadLocalObjectPtr(uint32_t index)); + MOCK_METHOD1(get, ThreadLocalObjectSharedPtr(uint32_t index)); MOCK_METHOD2(registerThread, void(Event::Dispatcher& dispatcher, bool main_thread)); MOCK_METHOD1(runOnAllThreads, void(Event::PostCb cb)); MOCK_METHOD2(set, void(uint32_t index, InitializeCb cb)); MOCK_METHOD0(shutdownThread, void()); uint32_t allocateSlot_() { return current_slot_++; } - ThreadLocalObjectPtr get_(uint32_t index) { return data_[index]; } + ThreadLocalObjectSharedPtr get_(uint32_t index) { return data_[index]; } void runOnAllThreads_(Event::PostCb cb) { cb(); } void set_(uint32_t index, InitializeCb cb) { data_[index] = cb(dispatcher_); } void shutdownThread_() { @@ -31,7 +31,7 @@ class MockInstance : public Instance { testing::NiceMock dispatcher_; uint32_t current_slot_{}; - std::unordered_map data_; + std::unordered_map data_; }; } // ThreadLocal diff --git a/test/mocks/upstream/host.h b/test/mocks/upstream/host.h index 62629d202434e..6387e623e7fa9 100644 --- a/test/mocks/upstream/host.h +++ b/test/mocks/upstream/host.h @@ -26,8 +26,8 @@ class MockEventLogger : public EventLogger { MockEventLogger(); ~MockEventLogger(); - MOCK_METHOD2(logEject, void(HostDescriptionPtr host, EjectionType type)); - MOCK_METHOD1(logUneject, void(HostDescriptionPtr host)); + MOCK_METHOD2(logEject, void(HostDescriptionConstSharedPtr host, EjectionType type)); + MOCK_METHOD1(logUneject, void(HostDescriptionConstSharedPtr host)); }; class MockDetector : public Detector { @@ -35,7 +35,7 @@ class MockDetector : public Detector { MockDetector(); ~MockDetector(); - void runCallbacks(HostPtr host) { + void runCallbacks(HostSharedPtr host) { for (ChangeStateCb cb : callbacks_) { cb(host); } @@ -53,7 +53,7 @@ class MockHostDescription : public HostDescription { MockHostDescription(); ~MockHostDescription(); - MOCK_CONST_METHOD0(address, Network::Address::InstancePtr()); + MOCK_CONST_METHOD0(address, Network::Address::InstanceConstSharedPtr()); MOCK_CONST_METHOD0(canary, bool()); MOCK_CONST_METHOD0(cluster, const ClusterInfo&()); MOCK_CONST_METHOD0(outlierDetector, Outlier::DetectorHostSink&()); @@ -62,7 +62,7 @@ class MockHostDescription : public HostDescription { MOCK_CONST_METHOD0(zone, const std::string&()); std::string hostname_; - Network::Address::InstancePtr address_; + Network::Address::InstanceConstSharedPtr address_; testing::NiceMock outlier_detector_; testing::NiceMock cluster_; Stats::IsolatedStoreImpl stats_store_; @@ -73,7 +73,7 @@ class MockHost : public Host { public: struct MockCreateConnectionData { Network::ClientConnection* connection_{}; - ConstHostPtr host_; + HostConstSharedPtr host_; }; MockHost(); @@ -88,12 +88,12 @@ class MockHost : public Host { setOutlierDetector_(outlier_detector); } - MOCK_CONST_METHOD0(address, Network::Address::InstancePtr()); + MOCK_CONST_METHOD0(address, Network::Address::InstanceConstSharedPtr()); MOCK_CONST_METHOD0(canary, bool()); MOCK_CONST_METHOD0(cluster, const ClusterInfo&()); - MOCK_CONST_METHOD0(counters, std::list()); + MOCK_CONST_METHOD0(counters, std::list()); MOCK_CONST_METHOD1(createConnection_, MockCreateConnectionData(Event::Dispatcher& dispatcher)); - MOCK_CONST_METHOD0(gauges, std::list()); + MOCK_CONST_METHOD0(gauges, std::list()); MOCK_METHOD1(healthFlagClear, void(HealthFlag flag)); MOCK_CONST_METHOD1(healthFlagGet, bool(HealthFlag flag)); MOCK_METHOD1(healthFlagSet, void(HealthFlag flag)); diff --git a/test/mocks/upstream/mocks.h b/test/mocks/upstream/mocks.h index fc30289986bd9..f9b83cb04860c 100644 --- a/test/mocks/upstream/mocks.h +++ b/test/mocks/upstream/mocks.h @@ -22,7 +22,8 @@ class MockCluster : public Cluster { MockCluster(); ~MockCluster(); - void runCallbacks(const std::vector added, const std::vector removed) { + void runCallbacks(const std::vector added, + const std::vector removed) { for (MemberUpdateCb cb : callbacks_) { cb(added, removed); } @@ -30,21 +31,21 @@ class MockCluster : public Cluster { // Upstream::HostSet MOCK_CONST_METHOD1(addMemberUpdateCb, void(MemberUpdateCb callback)); - MOCK_CONST_METHOD0(hosts, const std::vector&()); - MOCK_CONST_METHOD0(healthyHosts, const std::vector&()); - MOCK_CONST_METHOD0(hostsPerZone, const std::vector>&()); - MOCK_CONST_METHOD0(healthyHostsPerZone, const std::vector>&()); + MOCK_CONST_METHOD0(hosts, const std::vector&()); + MOCK_CONST_METHOD0(healthyHosts, const std::vector&()); + MOCK_CONST_METHOD0(hostsPerZone, const std::vector>&()); + MOCK_CONST_METHOD0(healthyHostsPerZone, const std::vector>&()); // Upstream::Cluster - MOCK_CONST_METHOD0(info, ClusterInfoPtr()); + MOCK_CONST_METHOD0(info, ClusterInfoConstSharedPtr()); MOCK_METHOD0(initialize, void()); MOCK_CONST_METHOD0(initializePhase, InitializePhase()); MOCK_METHOD1(setInitializedCb, void(std::function)); - std::vector hosts_; - std::vector healthy_hosts_; - std::vector> hosts_per_zone_; - std::vector> healthy_hosts_per_zone_; + std::vector hosts_; + std::vector healthy_hosts_; + std::vector> hosts_per_zone_; + std::vector> healthy_hosts_per_zone_; std::list callbacks_; std::shared_ptr info_{new NiceMock()}; std::function initialize_callback_; @@ -56,7 +57,7 @@ class MockLoadBalancer : public LoadBalancer { ~MockLoadBalancer(); // Upstream::LoadBalancer - MOCK_METHOD1(chooseHost, ConstHostPtr(const LoadBalancerContext* context)); + MOCK_METHOD1(chooseHost, HostConstSharedPtr(const LoadBalancerContext* context)); std::shared_ptr host_{new MockHost()}; }; @@ -68,7 +69,7 @@ class MockThreadLocalCluster : public ThreadLocalCluster { // Upstream::ThreadLocalCluster MOCK_METHOD0(hostSet, const HostSet&()); - MOCK_METHOD0(info, ClusterInfoPtr()); + MOCK_METHOD0(info, ClusterInfoConstSharedPtr()); MOCK_METHOD0(loadBalancer, LoadBalancer&()); NiceMock cluster_; @@ -112,7 +113,7 @@ class MockHealthChecker : public HealthChecker { MOCK_METHOD1(addHostCheckCompleteCb, void(HostStatusCb callback)); MOCK_METHOD0(start, void()); - void runCallbacks(Upstream::HostPtr host, bool changed_state) { + void runCallbacks(Upstream::HostSharedPtr host, bool changed_state) { for (auto callback : callbacks_) { callback(host, changed_state); } diff --git a/test/server/connection_handler_test.cc b/test/server/connection_handler_test.cc index b1704d2dfb370..f47c252445c0c 100644 --- a/test/server/connection_handler_test.cc +++ b/test/server/connection_handler_test.cc @@ -91,7 +91,8 @@ TEST_F(ConnectionHandlerTest, FindListenerByAddress) { Network::MockFilterChainFactory factory; Network::MockConnectionHandler connection_handler; Network::MockListenSocket socket; - Network::Address::InstancePtr alt_address(new Network::Address::Ipv4Instance("127.0.0.1", 10001)); + Network::Address::InstanceConstSharedPtr alt_address( + new Network::Address::Ipv4Instance("127.0.0.1", 10001)); EXPECT_CALL(socket, localAddress()).WillRepeatedly(Return(alt_address)); Network::Listener* listener = new Network::MockListener(); @@ -110,8 +111,9 @@ TEST_F(ConnectionHandlerTest, FindListenerByAddress) { EXPECT_EQ(listener, handler.findListenerByAddress(ByRef(*alt_address))); Network::MockListenSocket socket2; - Network::Address::InstancePtr alt_address2(new Network::Address::Ipv4Instance("0.0.0.0", 10001)); - Network::Address::InstancePtr alt_address3( + Network::Address::InstanceConstSharedPtr alt_address2( + new Network::Address::Ipv4Instance("0.0.0.0", 10001)); + Network::Address::InstanceConstSharedPtr alt_address3( new Network::Address::Ipv4Instance("127.0.0.2", 10001)); EXPECT_CALL(socket2, localAddress()).WillRepeatedly(Return(alt_address2)); diff --git a/test/server/http/health_check_test.cc b/test/server/http/health_check_test.cc index 3a53e9702178a..43bcea213fd24 100644 --- a/test/server/http/health_check_test.cc +++ b/test/server/http/health_check_test.cc @@ -34,7 +34,7 @@ class HealthCheckFilterTest : public testing::Test { NiceMock server_; Event::MockTimer* cache_timer_{}; Event::MockDispatcher dispatcher_; - HealthCheckCacheManagerPtr cache_manager_; + HealthCheckCacheManagerSharedPtr cache_manager_; std::unique_ptr filter_; NiceMock callbacks_; Http::TestHeaderMapImpl request_headers_; diff --git a/test/test_common/utility.cc b/test/test_common/utility.cc index 45c620314cb26..79afc12a2dbf5 100644 --- a/test/test_common/utility.cc +++ b/test/test_common/utility.cc @@ -45,9 +45,9 @@ std::string TestUtility::bufferToString(const Buffer::Instance& buffer) { return output; } -std::list +std::list TestUtility::makeDnsResponse(const std::list& addresses) { - std::list ret; + std::list ret; for (auto address : addresses) { ret.emplace_back(new Network::Address::Ipv4Instance(address)); } diff --git a/test/test_common/utility.h b/test/test_common/utility.h index bdedad71dcb4d..ea8e5c626ba92 100644 --- a/test/test_common/utility.h +++ b/test/test_common/utility.h @@ -25,7 +25,7 @@ class TestUtility { * Convert a string list of IP addresses into a list of network addresses usable for DNS * response testing. */ - static std::list + static std::list makeDnsResponse(const std::list& addresses); };