diff --git a/.github/workflows/mobile-compile_time_options.yml b/.github/workflows/mobile-compile_time_options.yml index a3a541fb6499..b03ceb2983c2 100644 --- a/.github/workflows/mobile-compile_time_options.yml +++ b/.github/workflows/mobile-compile_time_options.yml @@ -46,6 +46,36 @@ jobs: --define=envoy_full_protos=disabled \ --test_env=ENVOY_IP_TEST_VERSIONS=v4only \ //test/common/integration:client_integration_test + cc_build_no_exceptions: + needs: env + permissions: + contents: read + packages: read + name: cc_test_no_yaml + runs-on: ubuntu-20.04 + timeout-minutes: 120 + container: + image: ${{ needs.env.outputs.build_image_ubuntu }} + steps: + - uses: actions/checkout@v4 + - name: Add safe directory + run: git config --global --add safe.directory /__w/envoy/envoy + - name: 'Running C++ build with exceptions disabled' + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + # Envoy Mobile build which verifies that the build configuration where YAML is disabled. + run: | + cd mobile + ./bazelw build \ + --config=mobile-remote-ci \ + --define=admin_html=disabled \ + --define=admin_functionality=disabled \ + --define envoy_exceptions=disabled \ + --define envoy_mobile_listener=disabled \ + --define=envoy_yaml=disabled \ + --copt=-fno-unwind-tables \ + --copt=-fno-exceptions \ + //test/performance:test_binary_size cc_test: needs: env diff --git a/envoy/common/BUILD b/envoy/common/BUILD index fb37784cbdf3..f32828da2aa8 100644 --- a/envoy/common/BUILD +++ b/envoy/common/BUILD @@ -29,6 +29,9 @@ envoy_basic_cc_library( hdrs = [ "exception.h", ], + deps = [ + "//source/common/common:assert_lib", + ], ) envoy_basic_cc_library( diff --git a/envoy/common/exception.h b/envoy/common/exception.h index a5fe1c8d53d7..e9381057a5a0 100644 --- a/envoy/common/exception.h +++ b/envoy/common/exception.h @@ -3,7 +3,24 @@ #include #include +#include "source/common/common/assert.h" + namespace Envoy { + +// This is a workaround to allow an exceptionless Envoy Mobile build while we +// have not finished plumbing Satus/StatusOr<> based error handling, so +// hard-failing instead. See +// (https://github.com/envoyproxy/envoy-mobile/issues/176) +// for example error handling PRs. +// TODO(alyssawilk) finish up error handling and remove this. +#ifdef ENVOY_DISABLE_EXCEPTIONS +#define throwEnvoyExceptionOrPanic(x) PANIC(x) +#define throwExceptionOrPanic(x, y) PANIC(y) +#else +#define throwEnvoyExceptionOrPanic(x) throw EnvoyException(x) +#define throwExceptionOrPanic(y, x) throw y(x) +#endif + /** * Base class for all envoy exceptions. */ @@ -16,7 +33,7 @@ class EnvoyException : public std::runtime_error { { \ const absl::Status status = status_fn; \ if (!status.ok()) { \ - throw EnvoyException(std::string(status.message())); \ + throwEnvoyExceptionOrPanic(std::string(status.message())); \ } \ } @@ -25,10 +42,17 @@ class EnvoyException : public std::runtime_error { // // The completely unnecessary throw action argument is just so 'throw' appears // at the call site, so format checks about use of exceptions are triggered. +#ifdef ENVOY_DISABLE_EXCEPTIONS +#define THROW_IF_STATUS_NOT_OK(variable, throw_action) \ + if (!variable.status().ok()) { \ + PANIC(std::string(variable.status().message())); \ + } +#else #define THROW_IF_STATUS_NOT_OK(variable, throw_action) \ if (!variable.status().ok()) { \ throw_action EnvoyException(std::string(variable.status().message())); \ } +#endif #define RETURN_IF_STATUS_NOT_OK(variable) \ if (!variable.status().ok()) { \ diff --git a/source/common/access_log/access_log_manager_impl.cc b/source/common/access_log/access_log_manager_impl.cc index ba3486ca545f..27e289359d73 100644 --- a/source/common/access_log/access_log_manager_impl.cc +++ b/source/common/access_log/access_log_manager_impl.cc @@ -54,8 +54,8 @@ AccessLogFileImpl::AccessLogFileImpl(Filesystem::FilePtr&& file, Event::Dispatch flush_timer_->enableTimer(flush_interval_msec_); auto open_result = open(); if (!open_result.return_value_) { - throw EnvoyException(fmt::format("unable to open file '{}': {}", file_->path(), - open_result.err_->getErrorDetails())); + throwEnvoyExceptionOrPanic(fmt::format("unable to open file '{}': {}", file_->path(), + open_result.err_->getErrorDetails())); } } diff --git a/source/common/common/regex.cc b/source/common/common/regex.cc index 0281d658988d..086de371b7b3 100644 --- a/source/common/common/regex.cc +++ b/source/common/common/regex.cc @@ -17,7 +17,7 @@ CompiledGoogleReMatcher::CompiledGoogleReMatcher(const std::string& regex, bool do_program_size_check) : regex_(regex, re2::RE2::Quiet) { if (!regex_.ok()) { - throw EnvoyException(regex_.error()); + throwEnvoyExceptionOrPanic(regex_.error()); } if (do_program_size_check && Runtime::isRuntimeInitialized()) { @@ -25,10 +25,11 @@ CompiledGoogleReMatcher::CompiledGoogleReMatcher(const std::string& regex, const uint32_t max_program_size_error_level = Runtime::getInteger("re2.max_program_size.error_level", 100); if (regex_program_size > max_program_size_error_level) { - throw EnvoyException(fmt::format("regex '{}' RE2 program size of {} > max program size of " - "{} set for the error level threshold. Increase " - "configured max program size if necessary.", - regex, regex_program_size, max_program_size_error_level)); + throwEnvoyExceptionOrPanic( + fmt::format("regex '{}' RE2 program size of {} > max program size of " + "{} set for the error level threshold. Increase " + "configured max program size if necessary.", + regex, regex_program_size, max_program_size_error_level)); } const uint32_t max_program_size_warn_level = @@ -52,9 +53,10 @@ CompiledGoogleReMatcher::CompiledGoogleReMatcher( const uint32_t max_program_size = PROTOBUF_GET_WRAPPED_OR_DEFAULT(config.google_re2(), max_program_size, 100); if (regex_program_size > max_program_size) { - throw EnvoyException(fmt::format("regex '{}' RE2 program size of {} > max program size of " - "{}. Increase configured max program size if necessary.", - config.regex(), regex_program_size, max_program_size)); + throwEnvoyExceptionOrPanic( + fmt::format("regex '{}' RE2 program size of {} > max program size of " + "{}. Increase configured max program size if necessary.", + config.regex(), regex_program_size, max_program_size)); } } } diff --git a/source/common/common/utility.cc b/source/common/common/utility.cc index 3c425812fa4e..144d57f69a12 100644 --- a/source/common/common/utility.cc +++ b/source/common/common/utility.cc @@ -408,7 +408,7 @@ std::string StringUtil::removeTokens(absl::string_view source, absl::string_view uint32_t StringUtil::itoa(char* out, size_t buffer_size, uint64_t i) { // The maximum size required for an unsigned 64-bit integer is 21 chars (including null). if (buffer_size < 21) { - throw std::invalid_argument("itoa buffer too small"); + throwExceptionOrPanic(std::invalid_argument, "itoa buffer too small"); } char* current = out; @@ -651,7 +651,7 @@ InlineString::InlineString(const char* str, size_t size) : size_(size) { } void ExceptionUtil::throwEnvoyException(const std::string& message) { - throw EnvoyException(message); + throwEnvoyExceptionOrPanic(message); } } // namespace Envoy diff --git a/source/common/config/datasource.cc b/source/common/config/datasource.cc index e43c733a9284..cf7af0e0f71c 100644 --- a/source/common/config/datasource.cc +++ b/source/common/config/datasource.cc @@ -23,15 +23,16 @@ std::string read(const envoy::config::core::v3::DataSource& source, bool allow_e case envoy::config::core::v3::DataSource::SpecifierCase::kFilename: if (max_size > 0) { if (!api.fileSystem().fileExists(source.filename())) { - throw EnvoyException(fmt::format("file {} does not exist", source.filename())); + throwEnvoyExceptionOrPanic(fmt::format("file {} does not exist", source.filename())); } const ssize_t size = api.fileSystem().fileSize(source.filename()); if (size < 0) { - throw EnvoyException(absl::StrCat("cannot determine size of file ", source.filename())); + throwEnvoyExceptionOrPanic( + absl::StrCat("cannot determine size of file ", source.filename())); } if (static_cast(size) > max_size) { - throw EnvoyException(fmt::format("file {} size is {} bytes; maximum is {}", - source.filename(), size, max_size)); + throwEnvoyExceptionOrPanic(fmt::format("file {} size is {} bytes; maximum is {}", + source.filename(), size, max_size)); } } file_or_error = api.fileSystem().fileReadToEnd(source.filename()); @@ -47,7 +48,7 @@ std::string read(const envoy::config::core::v3::DataSource& source, bool allow_e case envoy::config::core::v3::DataSource::SpecifierCase::kEnvironmentVariable: { const char* environment_variable = std::getenv(source.environment_variable().c_str()); if (environment_variable == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Environment variable doesn't exist: {}", source.environment_variable())); } data = environment_variable; @@ -55,12 +56,12 @@ std::string read(const envoy::config::core::v3::DataSource& source, bool allow_e } default: if (!allow_empty) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Unexpected DataSource::specifier_case(): {}", source.specifier_case())); } } if (!allow_empty && data.empty()) { - throw EnvoyException("DataSource cannot be empty"); + throwEnvoyExceptionOrPanic("DataSource cannot be empty"); } return data; } diff --git a/source/common/config/subscription_factory_impl.cc b/source/common/config/subscription_factory_impl.cc index 21ff380a9745..c06588a1300e 100644 --- a/source/common/config/subscription_factory_impl.cc +++ b/source/common/config/subscription_factory_impl.cc @@ -67,11 +67,11 @@ SubscriptionPtr SubscriptionFactoryImpl::subscriptionFromConfigSource( switch (api_config_source.api_type()) { PANIC_ON_PROTO_ENUM_SENTINEL_VALUES; case envoy::config::core::v3::ApiConfigSource::AGGREGATED_GRPC: - throw EnvoyException("Unsupported config source AGGREGATED_GRPC"); + throwEnvoyExceptionOrPanic("Unsupported config source AGGREGATED_GRPC"); case envoy::config::core::v3::ApiConfigSource::AGGREGATED_DELTA_GRPC: - throw EnvoyException("Unsupported config source AGGREGATED_DELTA_GRPC"); + throwEnvoyExceptionOrPanic("Unsupported config source AGGREGATED_DELTA_GRPC"); case envoy::config::core::v3::ApiConfigSource::DEPRECATED_AND_UNAVAILABLE_DO_NOT_USE: - throw EnvoyException( + throwEnvoyExceptionOrPanic( "REST_LEGACY no longer a supported ApiConfigSource. " "Please specify an explicit supported api_type in the following config:\n" + config.DebugString()); @@ -86,7 +86,7 @@ SubscriptionPtr SubscriptionFactoryImpl::subscriptionFromConfigSource( break; } if (subscription_type.empty()) { - throw EnvoyException("Invalid API config source API type"); + throwEnvoyExceptionOrPanic("Invalid API config source API type"); } break; } @@ -95,13 +95,13 @@ SubscriptionPtr SubscriptionFactoryImpl::subscriptionFromConfigSource( break; } default: - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Missing config source specifier in envoy::config::core::v3::ConfigSource"); } ConfigSubscriptionFactory* factory = Registry::FactoryRegistry::getFactory(subscription_type); if (factory == nullptr) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "Didn't find a registered config subscription factory implementation for name: '{}'", subscription_type)); } @@ -113,7 +113,7 @@ SubscriptionPtr createFromFactoryOrThrow(ConfigSubscriptionFactory::Subscription ConfigSubscriptionFactory* factory = Registry::FactoryRegistry::getFactory(subscription_type); if (factory == nullptr) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "Didn't find a registered config subscription factory implementation for name: '{}'", subscription_type)); } @@ -153,7 +153,7 @@ SubscriptionPtr SubscriptionFactoryImpl::collectionSubscriptionFromUrl( } case xds::core::v3::ResourceLocator::XDSTP: { if (resource_type != collection_locator.resource_type()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("xdstp:// type does not match {} in {}", resource_type, Config::XdsResourceIdentifier::encodeUrl(collection_locator))); } @@ -179,8 +179,8 @@ SubscriptionPtr SubscriptionFactoryImpl::collectionSubscriptionFromUrl( "envoy.config_subscription.aggregated_grpc_collection"); } default: - throw EnvoyException(fmt::format("Unknown xdstp:// transport API type in {}", - api_config_source.DebugString())); + throwEnvoyExceptionOrPanic(fmt::format("Unknown xdstp:// transport API type in {}", + api_config_source.DebugString())); } } case envoy::config::core::v3::ConfigSource::ConfigSourceSpecifierCase::kAds: { @@ -191,14 +191,15 @@ SubscriptionPtr SubscriptionFactoryImpl::collectionSubscriptionFromUrl( return createFromFactoryOrThrow(data, "envoy.config_subscription.ads_collection"); } default: - throw EnvoyException("Missing or not supported config source specifier in " - "envoy::config::core::v3::ConfigSource for a collection. Only ADS and " - "gRPC in delta-xDS mode are supported."); + throwEnvoyExceptionOrPanic( + "Missing or not supported config source specifier in " + "envoy::config::core::v3::ConfigSource for a collection. Only ADS and " + "gRPC in delta-xDS mode are supported."); } } default: // TODO(htuch): Implement HTTP semantics for collection ResourceLocators. - throw EnvoyException("Unsupported code path"); + throwEnvoyExceptionOrPanic("Unsupported code path"); } } diff --git a/source/common/config/utility.cc b/source/common/config/utility.cc index ac770ddf66d4..c1db95c678e7 100644 --- a/source/common/config/utility.cc +++ b/source/common/config/utility.cc @@ -33,11 +33,11 @@ Upstream::ClusterConstOptRef Utility::checkCluster(absl::string_view error_prefi bool allow_added_via_api) { const auto cluster = cm.clusters().getCluster(cluster_name); if (!cluster.has_value()) { - throw EnvoyException(fmt::format("{}: unknown cluster '{}'", error_prefix, cluster_name)); + throwEnvoyExceptionOrPanic(fmt::format("{}: unknown cluster '{}'", error_prefix, cluster_name)); } if (!allow_added_via_api && cluster->get().info()->addedViaApi()) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "{}: invalid cluster '{}': currently only static (non-CDS) clusters are supported", error_prefix, cluster_name)); } @@ -55,7 +55,7 @@ Utility::checkClusterAndLocalInfo(absl::string_view error_prefix, absl::string_v void Utility::checkLocalInfo(absl::string_view error_prefix, const LocalInfo::LocalInfo& local_info) { if (local_info.clusterName().empty() || local_info.nodeName().empty()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("{}: node 'id' and 'cluster' are required. Set it either in 'node' config or " "via --service-node and --service-cluster options.", error_prefix, local_info.node().DebugString())); @@ -66,7 +66,7 @@ void Utility::checkFilesystemSubscriptionBackingPath(const std::string& path, Ap // TODO(junr03): the file might be deleted between this check and the // watch addition. if (!api.fileSystem().fileExists(path)) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "paths must refer to an existing path in the system: '{}' does not exist", path)); } } @@ -84,32 +84,32 @@ void checkApiConfigSourceNames(const envoy::config::core::v3::ApiConfigSource& a api_config_source.api_type() == envoy::config::core::v3::ApiConfigSource::DELTA_GRPC); if (api_config_source.cluster_names().empty() && api_config_source.grpc_services().empty()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("API configs must have either a gRPC service or a cluster name defined: {}", api_config_source.DebugString())); } if (is_grpc) { if (!api_config_source.cluster_names().empty()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("{}::(DELTA_)GRPC must not have a cluster name specified: {}", api_config_source.GetTypeName(), api_config_source.DebugString())); } if (api_config_source.grpc_services().size() > 1) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("{}::(DELTA_)GRPC must have a single gRPC service specified: {}", api_config_source.GetTypeName(), api_config_source.DebugString())); } } else { if (!api_config_source.grpc_services().empty()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("{}, if not a gRPC type, must not have a gRPC service specified: {}", api_config_source.GetTypeName(), api_config_source.DebugString())); } if (api_config_source.cluster_names().size() != 1) { - throw EnvoyException(fmt::format("{} must have a singleton cluster name specified: {}", - api_config_source.GetTypeName(), - api_config_source.DebugString())); + throwEnvoyExceptionOrPanic(fmt::format("{} must have a singleton cluster name specified: {}", + api_config_source.GetTypeName(), + api_config_source.DebugString())); } } } @@ -120,9 +120,10 @@ void Utility::validateClusterName(const Upstream::ClusterManager::ClusterSet& pr const std::string& config_source) { const auto& it = primary_clusters.find(cluster_name); if (it == primary_clusters.end()) { - throw EnvoyException(fmt::format("{} must have a statically defined non-EDS cluster: '{}' does " - "not exist, was added via api, or is an EDS cluster", - config_source, cluster_name)); + throwEnvoyExceptionOrPanic( + fmt::format("{} must have a statically defined non-EDS cluster: '{}' does " + "not exist, was added via api, or is an EDS cluster", + config_source, cluster_name)); } } @@ -179,7 +180,7 @@ Utility::getGrpcControlPlane(const envoy::config::core::v3::ApiConfigSource& api std::chrono::milliseconds Utility::apiConfigSourceRefreshDelay( const envoy::config::core::v3::ApiConfigSource& api_config_source) { if (!api_config_source.has_refresh_delay()) { - throw EnvoyException("refresh_delay is required for REST API configuration sources"); + throwEnvoyExceptionOrPanic("refresh_delay is required for REST API configuration sources"); } return std::chrono::milliseconds( @@ -238,8 +239,9 @@ Grpc::AsyncClientFactoryPtr Utility::factoryForGrpcApiConfigSource( if (api_config_source.api_type() != envoy::config::core::v3::ApiConfigSource::GRPC && api_config_source.api_type() != envoy::config::core::v3::ApiConfigSource::DELTA_GRPC) { - throw EnvoyException(fmt::format("{} type must be gRPC: {}", api_config_source.GetTypeName(), - api_config_source.DebugString())); + throwEnvoyExceptionOrPanic(fmt::format("{} type must be gRPC: {}", + api_config_source.GetTypeName(), + api_config_source.DebugString())); } envoy::config::core::v3::GrpcService grpc_service; @@ -273,7 +275,7 @@ void Utility::translateOpaqueConfig(const ProtobufWkt::Any& typed_config, #ifdef ENVOY_ENABLE_YAML MessageUtil::jsonConvert(typed_struct.value(), validation_visitor, out_proto); #else - throw EnvoyException("Attempting to use JSON typed structs with JSON compiled out"); + IS_ENVOY_BUG("Attempting to use JSON typed structs with JSON compiled out"); #endif } } else if (type == legacy_typed_struct_type) { @@ -289,7 +291,7 @@ void Utility::translateOpaqueConfig(const ProtobufWkt::Any& typed_config, MessageUtil::jsonConvert(typed_struct.value(), validation_visitor, out_proto); #else UNREFERENCED_PARAMETER(validation_visitor); - throw EnvoyException("Attempting to use legacy JSON structs with JSON compiled out"); + IS_ENVOY_BUG("Attempting to use legacy JSON structs with JSON compiled out"); #endif } } // out_proto is expecting Struct, unpack directly @@ -301,7 +303,7 @@ void Utility::translateOpaqueConfig(const ProtobufWkt::Any& typed_config, MessageUtil::unpackTo(typed_config, struct_config); MessageUtil::jsonConvert(struct_config, validation_visitor, out_proto); #else - throw EnvoyException("Attempting to use JSON structs with JSON compiled out"); + IS_ENVOY_BUG("Attempting to use JSON structs with JSON compiled out"); #endif } } @@ -318,7 +320,7 @@ JitteredExponentialBackOffStrategyPtr Utility::buildJitteredExponentialBackOffSt PROTOBUF_GET_MS_OR_DEFAULT(backoff.value(), max_interval, base_interval_ms * 10); if (max_interval_ms < base_interval_ms) { - throw EnvoyException("max_interval must be greater than or equal to the base_interval"); + throwEnvoyExceptionOrPanic("max_interval must be greater than or equal to the base_interval"); } return std::make_unique(base_interval_ms, max_interval_ms, random); @@ -326,13 +328,13 @@ JitteredExponentialBackOffStrategyPtr Utility::buildJitteredExponentialBackOffSt // default_base_interval_ms must be greater than zero if (default_base_interval_ms == 0) { - throw EnvoyException("default_base_interval_ms must be greater than zero"); + throwEnvoyExceptionOrPanic("default_base_interval_ms must be greater than zero"); } // default maximum interval is specified if (default_max_interval_ms != absl::nullopt) { if (default_max_interval_ms.value() < default_base_interval_ms) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "default_max_interval_ms must be greater than or equal to the default_base_interval_ms"); } return std::make_unique( diff --git a/source/common/config/xds_resource.cc b/source/common/config/xds_resource.cc index dfd98b8ecac3..28fa4c4ace3b 100644 --- a/source/common/config/xds_resource.cc +++ b/source/common/config/xds_resource.cc @@ -104,6 +104,10 @@ std::string XdsResourceIdentifier::encodeUrl(const xds::core::v3::ResourceLocato namespace { +void throwDecodeExceptionOrPanic(std::string message) { + throwExceptionOrPanic(XdsResourceIdentifier::DecodeException, message); +} + void decodePath(absl::string_view path, std::string* resource_type, std::string& id) { // This is guaranteed by Http::Utility::extractHostPathFromUrn. ASSERT(absl::StartsWith(path, "/")); @@ -112,8 +116,7 @@ void decodePath(absl::string_view path, std::string* resource_type, std::string& if (resource_type != nullptr) { *resource_type = std::string(path_components[0]); if (resource_type->empty()) { - throw XdsResourceIdentifier::DecodeException( - fmt::format("Resource type missing from {}", path)); + throwDecodeExceptionOrPanic(fmt::format("Resource type missing from {}", path)); } id_it = std::next(id_it); } @@ -140,8 +143,7 @@ void decodeFragment( } else if (absl::StartsWith(fragment_component, "entry=")) { directives.Add()->set_entry(PercentEncoding::decode(fragment_component.substr(6))); } else { - throw XdsResourceIdentifier::DecodeException( - fmt::format("Unknown fragment component {}", fragment_component)); + throwDecodeExceptionOrPanic(fmt::format("Unknown fragment component {}", fragment_component)); ; } } @@ -151,8 +153,7 @@ void decodeFragment( xds::core::v3::ResourceName XdsResourceIdentifier::decodeUrn(absl::string_view resource_urn) { if (!hasXdsTpScheme(resource_urn)) { - throw XdsResourceIdentifier::DecodeException( - fmt::format("{} does not have an xdstp: scheme", resource_urn)); + throwDecodeExceptionOrPanic(fmt::format("{} does not have an xdstp: scheme", resource_urn)); } absl::string_view host, path; Http::Utility::extractHostPathFromUri(resource_urn, host, path); @@ -187,7 +188,8 @@ xds::core::v3::ResourceLocator XdsResourceIdentifier::decodeUrl(absl::string_vie decodePath(path, nullptr, *decoded_resource_locator.mutable_id()); return decoded_resource_locator; } else { - throw XdsResourceIdentifier::DecodeException( + throwExceptionOrPanic( + XdsResourceIdentifier::DecodeException, fmt::format("{} does not have a xdstp:, http: or file: scheme", resource_url)); } decoded_resource_locator.set_authority(PercentEncoding::decode(host)); diff --git a/source/common/filesystem/inotify/watcher_impl.cc b/source/common/filesystem/inotify/watcher_impl.cc index c7a3db2cd23a..864da79f5b59 100644 --- a/source/common/filesystem/inotify/watcher_impl.cc +++ b/source/common/filesystem/inotify/watcher_impl.cc @@ -42,7 +42,7 @@ void WatcherImpl::addWatch(absl::string_view path, uint32_t events, OnChangedCb const uint32_t watch_mask = IN_MODIFY | IN_MOVED_TO; int watch_fd = inotify_add_watch(inotify_fd_, std::string(result.directory_).c_str(), watch_mask); if (watch_fd == -1) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("unable to add filesystem watch for file {}: {}", path, errorDetails(errno))); } diff --git a/source/common/filesystem/kqueue/watcher_impl.cc b/source/common/filesystem/kqueue/watcher_impl.cc index 11b396c9789d..200c08dc8104 100644 --- a/source/common/filesystem/kqueue/watcher_impl.cc +++ b/source/common/filesystem/kqueue/watcher_impl.cc @@ -35,7 +35,7 @@ WatcherImpl::~WatcherImpl() { void WatcherImpl::addWatch(absl::string_view path, uint32_t events, Watcher::OnChangedCb cb) { FileWatchPtr watch = addWatch(path, events, cb, false); if (watch == nullptr) { - throw EnvoyException(absl::StrCat("invalid watch path ", path)); + throwEnvoyExceptionOrPanic(absl::StrCat("invalid watch path ", path)); } } @@ -73,7 +73,7 @@ WatcherImpl::FileWatchPtr WatcherImpl::addWatch(absl::string_view path, uint32_t reinterpret_cast(watch_fd)); if (kevent(queue_, &event, 1, nullptr, 0, nullptr) == -1 || event.flags & EV_ERROR) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("unable to add filesystem watch for file {}: {}", path, errorDetails(errno))); } diff --git a/source/common/filesystem/posix/directory_iterator_impl.cc b/source/common/filesystem/posix/directory_iterator_impl.cc index a50514d991dc..f5d7fcba1cc4 100644 --- a/source/common/filesystem/posix/directory_iterator_impl.cc +++ b/source/common/filesystem/posix/directory_iterator_impl.cc @@ -28,7 +28,7 @@ void DirectoryIteratorImpl::openDirectory() { DIR* temp_dir = ::opendir(directory_path_.c_str()); dir_ = temp_dir; if (!dir_) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("unable to open directory {}: {}", directory_path_, errorDetails(errno))); } } @@ -37,7 +37,7 @@ void DirectoryIteratorImpl::nextEntry() { errno = 0; dirent* entry = ::readdir(dir_); if (entry == nullptr && errno != 0) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("unable to iterate directory {}: {}", directory_path_, errorDetails(errno))); } @@ -65,7 +65,7 @@ DirectoryEntry DirectoryIteratorImpl::makeEntry(absl::string_view filename) cons // TODO: throwing an exception here makes this dangerous to use in worker threads, // and in general since it's not clear to the user of Directory that an exception // may be thrown. Perhaps make this return StatusOr and handle failures gracefully. - throw EnvoyException(fmt::format("unable to stat file: '{}' ({})", full_path, errno)); + throwEnvoyExceptionOrPanic(fmt::format("unable to stat file: '{}' ({})", full_path, errno)); } else if (S_ISDIR(stat_buf.st_mode)) { return DirectoryEntry{std::string{filename}, FileType::Directory, absl::nullopt}; } else if (S_ISREG(stat_buf.st_mode)) { diff --git a/source/common/filter/config_discovery_impl.cc b/source/common/filter/config_discovery_impl.cc index e9ce25cd6e86..74ef9a8cf096 100644 --- a/source/common/filter/config_discovery_impl.cc +++ b/source/common/filter/config_discovery_impl.cc @@ -252,9 +252,10 @@ void FilterConfigProviderManagerImplBase::validateProtoConfigDefaultFactory( const bool null_default_factory, const std::string& filter_config_name, absl::string_view type_url) const { if (null_default_factory) { - throw EnvoyException(fmt::format("Error: cannot find filter factory {} for default filter " - "configuration with type URL {}.", - filter_config_name, type_url)); + throwEnvoyExceptionOrPanic( + fmt::format("Error: cannot find filter factory {} for default filter " + "configuration with type URL {}.", + filter_config_name, type_url)); } } diff --git a/source/common/filter/config_discovery_impl.h b/source/common/filter/config_discovery_impl.h index 60f53060fb40..6f34058a17c0 100644 --- a/source/common/filter/config_discovery_impl.h +++ b/source/common/filter/config_discovery_impl.h @@ -127,7 +127,7 @@ class DynamicFilterConfigProviderImpl : public DynamicFilterConfigProviderImplBa if (default_configuration_) { auto status = onConfigUpdate(*default_configuration_, "", nullptr); if (!status.ok()) { - throw EnvoyException(std::string(status.message())); + throwEnvoyExceptionOrPanic(std::string(status.message())); } } } diff --git a/source/common/formatter/http_specific_formatter.cc b/source/common/formatter/http_specific_formatter.cc index c86194ccd9cf..c68638d8eb6a 100644 --- a/source/common/formatter/http_specific_formatter.cc +++ b/source/common/formatter/http_specific_formatter.cc @@ -201,7 +201,8 @@ GrpcStatusFormatter::Format GrpcStatusFormatter::parseFormat(absl::string_view f return GrpcStatusFormatter::Number; } - throw EnvoyException("GrpcStatusFormatter only supports CAMEL_STRING, SNAKE_STRING or NUMBER."); + throwEnvoyExceptionOrPanic( + "GrpcStatusFormatter only supports CAMEL_STRING, SNAKE_STRING or NUMBER."); } GrpcStatusFormatter::GrpcStatusFormatter(const std::string& main_header, diff --git a/source/common/formatter/stream_info_formatter.cc b/source/common/formatter/stream_info_formatter.cc index ac305351c6c2..1bc5ff5d6e9d 100644 --- a/source/common/formatter/stream_info_formatter.cc +++ b/source/common/formatter/stream_info_formatter.cc @@ -140,7 +140,7 @@ FilterStateFormatter::create(const std::string& format, const absl::optional>(formatter); if (!factory) { - throw EnvoyException(absl::StrCat("Formatter not found: ", formatter.name())); + throwEnvoyExceptionOrPanic(absl::StrCat("Formatter not found: ", formatter.name())); } auto typed_config = Envoy::Config::Utility::translateAnyToFactoryConfig( formatter.typed_config(), context.messageValidationVisitor(), *factory); auto parser = factory->createCommandParserFromProto(*typed_config, context); if (!parser) { - throw EnvoyException(absl::StrCat("Failed to create command parser: ", formatter.name())); + throwEnvoyExceptionOrPanic( + absl::StrCat("Failed to create command parser: ", formatter.name())); } commands.push_back(std::move(parser)); } diff --git a/source/common/formatter/substitution_format_utility.cc b/source/common/formatter/substitution_format_utility.cc index baaf382896bf..82a906d3ed3d 100644 --- a/source/common/formatter/substitution_format_utility.cc +++ b/source/common/formatter/substitution_format_utility.cc @@ -16,15 +16,15 @@ void CommandSyntaxChecker::verifySyntax(CommandSyntaxFlags flags, const std::str const std::string& subcommand, const absl::optional& length) { if ((flags == COMMAND_ONLY) && ((subcommand.length() != 0) || length.has_value())) { - throw EnvoyException(fmt::format("{} does not take any parameters or length", command)); + throwEnvoyExceptionOrPanic(fmt::format("{} does not take any parameters or length", command)); } if ((flags & PARAMS_REQUIRED).any() && (subcommand.length() == 0)) { - throw EnvoyException(fmt::format("{} requires parameters", command)); + throwEnvoyExceptionOrPanic(fmt::format("{} requires parameters", command)); } if ((flags & LENGTH_ALLOWED).none() && length.has_value()) { - throw EnvoyException(fmt::format("{} does not allow length to be specified.", command)); + throwEnvoyExceptionOrPanic(fmt::format("{} does not allow length to be specified.", command)); } } @@ -93,7 +93,7 @@ void SubstitutionFormatUtils::parseSubcommandHeaders(const std::string& subcomma alternative_header = ""; parseSubcommand(subcommand, '?', main_header, alternative_header, subs); if (!subs.empty()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( // Header format rules support only one alternative header. // docs/root/configuration/observability/access_log/access_log.rst#format-rules absl::StrCat("More than 1 alternative header specified in token: ", subcommand)); @@ -102,7 +102,8 @@ void SubstitutionFormatUtils::parseSubcommandHeaders(const std::string& subcomma // The main and alternative header should not contain invalid characters {NUL, LR, CF}. if (!Envoy::Http::validHeaderString(main_header) || !Envoy::Http::validHeaderString(alternative_header)) { - throw EnvoyException("Invalid header configuration. Format string contains null or newline."); + throwEnvoyExceptionOrPanic( + "Invalid header configuration. Format string contains null or newline."); } } diff --git a/source/common/formatter/substitution_formatter.h b/source/common/formatter/substitution_formatter.h index 02dce31b9668..7f2361c397e2 100644 --- a/source/common/formatter/substitution_formatter.h +++ b/source/common/formatter/substitution_formatter.h @@ -106,7 +106,7 @@ class SubstitutionFormatParser { std::smatch m; const std::string search_space = std::string(format.substr(pos)); if (!std::regex_search(search_space, m, command_w_args_regex)) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Incorrect configuration: {}. Couldn't find valid command at position {}", format, pos)); } @@ -121,7 +121,7 @@ class SubstitutionFormatParser { if (m.str(3).length() != 0) { size_t length_value; if (!absl::SimpleAtoi(m.str(3), &length_value)) { - throw EnvoyException(absl::StrCat("Length must be an integer, given: ", m.str(3))); + throwEnvoyExceptionOrPanic(absl::StrCat("Length must be an integer, given: ", m.str(3))); } max_length = length_value; } @@ -317,7 +317,7 @@ template class StructFormatterBase { output->emplace(pair.first, toFormatNumberValue(pair.second.number_value())); break; default: - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Only string values, nested structs, list values and number values are " "supported in structured access log format."); } @@ -346,7 +346,7 @@ template class StructFormatterBase { break; default: - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Only string values, nested structs, list values and number values are " "supported in structured access log format."); } diff --git a/source/common/grpc/async_client_manager_impl.cc b/source/common/grpc/async_client_manager_impl.cc index e741ec56383d..c4c7a825aa1e 100644 --- a/source/common/grpc/async_client_manager_impl.cc +++ b/source/common/grpc/async_client_manager_impl.cc @@ -84,7 +84,7 @@ GoogleAsyncClientFactoryImpl::GoogleAsyncClientFactoryImpl( UNREFERENCED_PARAMETER(config_); UNREFERENCED_PARAMETER(api_); UNREFERENCED_PARAMETER(stat_names_); - throw EnvoyException("Google C++ gRPC client is not linked"); + throwEnvoyExceptionOrPanic("Google C++ gRPC client is not linked"); #else ASSERT(google_tls_slot_ != nullptr); #endif @@ -94,7 +94,7 @@ GoogleAsyncClientFactoryImpl::GoogleAsyncClientFactoryImpl( for (const auto& header : config.initial_metadata()) { // Validate key if (!validateGrpcHeaderChars(header.key())) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Illegal characters in gRPC initial metadata header key: {}.", header.key())); } @@ -102,7 +102,7 @@ GoogleAsyncClientFactoryImpl::GoogleAsyncClientFactoryImpl( // Binary base64 encoded - handled by the GRPC library if (!::absl::EndsWith(header.key(), "-bin") && !validateGrpcCompatibleAsciiHeaderValue(header.value())) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "Illegal ASCII value for gRPC initial metadata header key: {}.", header.key())); } } diff --git a/source/common/grpc/google_grpc_utils.cc b/source/common/grpc/google_grpc_utils.cc index fbe891306692..3cf19326244d 100644 --- a/source/common/grpc/google_grpc_utils.cc +++ b/source/common/grpc/google_grpc_utils.cc @@ -38,8 +38,8 @@ getGoogleGrpcChannelCredentials(const envoy::config::core::v3::GrpcService& grpc google_grpc_credentials_factory_name); } if (credentials_factory == nullptr) { - throw EnvoyException(absl::StrCat("Unknown google grpc credentials factory: ", - google_grpc_credentials_factory_name)); + throwEnvoyExceptionOrPanic(absl::StrCat("Unknown google grpc credentials factory: ", + google_grpc_credentials_factory_name)); } return credentials_factory->getChannelCredentials(grpc_service, api); } diff --git a/source/common/http/match_delegate/config.cc b/source/common/http/match_delegate/config.cc index 88f8391e7ceb..5b8cac5a1bc3 100644 --- a/source/common/http/match_delegate/config.cc +++ b/source/common/http/match_delegate/config.cc @@ -300,8 +300,8 @@ Envoy::Http::FilterFactoryCb MatchDelegateConfig::createFilterFactoryFromProtoTy if (!validation_visitor.errors().empty()) { // TODO(snowp): Output all violations. - throw EnvoyException(fmt::format("requirement violation while creating match tree: {}", - validation_visitor.errors()[0])); + throwEnvoyExceptionOrPanic(fmt::format("requirement violation while creating match tree: {}", + validation_visitor.errors()[0])); } Matcher::MatchTreeSharedPtr match_tree = nullptr; diff --git a/source/common/http/utility.cc b/source/common/http/utility.cc index ecb5a83a8234..4d1a5718e16b 100644 --- a/source/common/http/utility.cc +++ b/source/common/http/utility.cc @@ -122,15 +122,16 @@ void validateCustomSettingsParameters( switch (it.identifier().value()) { case http2::adapter::ENABLE_PUSH: if (it.value().value() == 1) { - throw EnvoyException("server push is not supported by Envoy and can not be enabled via a " - "SETTINGS parameter."); + throwEnvoyExceptionOrPanic( + "server push is not supported by Envoy and can not be enabled via a " + "SETTINGS parameter."); } break; case http2::adapter::ENABLE_CONNECT_PROTOCOL: // An exception is made for `allow_connect` which can't be checked for presence due to the // use of a primitive type (bool). - throw EnvoyException("the \"allow_connect\" SETTINGS parameter must only be configured " - "through the named field"); + throwEnvoyExceptionOrPanic("the \"allow_connect\" SETTINGS parameter must only be configured " + "through the named field"); case http2::adapter::HEADER_TABLE_SIZE: if (options.has_hpack_table_size()) { parameter_collisions.push_back("hpack_table_size"); @@ -153,12 +154,12 @@ void validateCustomSettingsParameters( } if (!custom_parameter_collisions.empty()) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "inconsistent HTTP/2 custom SETTINGS parameter(s) detected; identifiers = {{{}}}", absl::StrJoin(custom_parameter_collisions, ","))); } if (!parameter_collisions.empty()) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "the {{{}}} HTTP/2 SETTINGS parameter(s) can not be configured through both named and " "custom parameters", absl::StrJoin(parameter_collisions, ","))); @@ -1420,7 +1421,7 @@ void Utility::validateCoreRetryPolicy(const envoy::config::core::v3::RetryPolicy PROTOBUF_GET_MS_OR_DEFAULT(core_back_off, max_interval, base_interval_ms * 10); if (max_interval_ms < base_interval_ms) { - throw EnvoyException("max_interval must be greater than or equal to the base_interval"); + throwEnvoyExceptionOrPanic("max_interval must be greater than or equal to the base_interval"); } } } diff --git a/source/common/json/json_internal.cc b/source/common/json/json_internal.cc index 23d77f5307ef..e7de7479247d 100644 --- a/source/common/json/json_internal.cc +++ b/source/common/json/json_internal.cc @@ -25,6 +25,7 @@ namespace Json { namespace Nlohmann { namespace { + /** * Internal representation of Object. */ @@ -133,9 +134,11 @@ class Field : public Object { bool isType(Type type) const { return type == type_; } void checkType(Type type) const { if (!isType(type)) { - throw Exception(fmt::format( - "JSON field from line {} accessed with type '{}' does not match actual type '{}'.", - line_number_start_, typeAsString(type), typeAsString(type_))); + throwExceptionOrPanic( + Exception, + fmt::format( + "JSON field from line {} accessed with type '{}' does not match actual type '{}'.", + line_number_start_, typeAsString(type), typeAsString(type_))); } } @@ -188,8 +191,9 @@ class ObjectHandler : public nlohmann::json_sax { } bool number_unsigned(uint64_t value) override { if (value > static_cast(std::numeric_limits::max())) { - throw Exception(fmt::format("JSON value from line {} is larger than int64_t (not supported)", - line_number_)); + throwExceptionOrPanic( + Exception, fmt::format("JSON value from line {} is larger than int64_t (not supported)", + line_number_)); } return handleValueEvent(Field::createValue(static_cast(value))); } @@ -411,8 +415,9 @@ bool Field::getBoolean(const std::string& name) const { checkType(Type::Object); auto value_itr = value_.object_value_.find(name); if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Boolean)) { - throw Exception(fmt::format("key '{}' missing or not a boolean from lines {}-{}", name, - line_number_start_, line_number_end_)); + throwExceptionOrPanic(Exception, + fmt::format("key '{}' missing or not a boolean from lines {}-{}", name, + line_number_start_, line_number_end_)); } return value_itr->second->booleanValue(); } @@ -430,8 +435,9 @@ double Field::getDouble(const std::string& name) const { checkType(Type::Object); auto value_itr = value_.object_value_.find(name); if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Double)) { - throw Exception(fmt::format("key '{}' missing or not a double from lines {}-{}", name, - line_number_start_, line_number_end_)); + throwExceptionOrPanic(Exception, + fmt::format("key '{}' missing or not a double from lines {}-{}", name, + line_number_start_, line_number_end_)); } return value_itr->second->doubleValue(); } @@ -449,8 +455,9 @@ int64_t Field::getInteger(const std::string& name) const { checkType(Type::Object); auto value_itr = value_.object_value_.find(name); if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::Integer)) { - throw Exception(fmt::format("key '{}' missing or not an integer from lines {}-{}", name, - line_number_start_, line_number_end_)); + throwExceptionOrPanic(Exception, + fmt::format("key '{}' missing or not an integer from lines {}-{}", name, + line_number_start_, line_number_end_)); } return value_itr->second->integerValue(); } @@ -467,7 +474,7 @@ int64_t Field::getInteger(const std::string& name, int64_t default_value) const ObjectSharedPtr Field::getObject(const std::string& name, bool allow_empty) const { auto result = getObjectNoThrow(name, allow_empty); if (!result.ok()) { - throw Exception(std::string(result.status().message())); + throwExceptionOrPanic(Exception, std::string(result.status().message())); } return result.value(); @@ -500,8 +507,9 @@ std::vector Field::getObjectArray(const std::string& name, if (allow_empty && value_itr == value_.object_value_.end()) { return {}; } - throw Exception(fmt::format("key '{}' missing or not an array from lines {}-{}", name, - line_number_start_, line_number_end_)); + throwExceptionOrPanic(Exception, + fmt::format("key '{}' missing or not an array from lines {}-{}", name, + line_number_start_, line_number_end_)); } std::vector array_value = value_itr->second->arrayValue(); @@ -512,8 +520,9 @@ std::string Field::getString(const std::string& name) const { checkType(Type::Object); auto value_itr = value_.object_value_.find(name); if (value_itr == value_.object_value_.end() || !value_itr->second->isType(Type::String)) { - throw Exception(fmt::format("key '{}' missing or not a string from lines {}-{}", name, - line_number_start_, line_number_end_)); + throwExceptionOrPanic(Exception, + fmt::format("key '{}' missing or not a string from lines {}-{}", name, + line_number_start_, line_number_end_)); } return value_itr->second->stringValue(); } @@ -535,16 +544,18 @@ std::vector Field::getStringArray(const std::string& name, bool all if (allow_empty && value_itr == value_.object_value_.end()) { return string_array; } - throw Exception(fmt::format("key '{}' missing or not an array from lines {}-{}", name, - line_number_start_, line_number_end_)); + throwExceptionOrPanic(Exception, + fmt::format("key '{}' missing or not an array from lines {}-{}", name, + line_number_start_, line_number_end_)); } std::vector array = value_itr->second->arrayValue(); string_array.reserve(array.size()); for (const auto& element : array) { if (!element->isType(Type::String)) { - throw Exception(fmt::format("JSON array '{}' from line {} does not contain all strings", name, - line_number_start_)); + throwExceptionOrPanic(Exception, + fmt::format("JSON array '{}' from line {} does not contain all strings", + name, line_number_start_)); } string_array.push_back(element->stringValue()); } @@ -568,7 +579,8 @@ bool Field::empty() const { } else if (isType(Type::Array)) { return value_.array_value_.empty(); } else { - throw Exception( + throwExceptionOrPanic( + Exception, fmt::format("Json does not support empty() on types other than array and object")); } } @@ -589,7 +601,9 @@ void Field::iterate(const ObjectCallback& callback) const { } } -void Field::validateSchema(const std::string&) const { throw Exception("not implemented"); } +void Field::validateSchema(const std::string&) const { + throwExceptionOrPanic(Exception, "not implemented"); +} bool ObjectHandler::start_object(std::size_t) { FieldSharedPtr object = Field::createObject(); @@ -723,7 +737,7 @@ absl::StatusOr Factory::loadFromStringNoThrow(const std::string ObjectSharedPtr Factory::loadFromString(const std::string& json) { auto result = loadFromStringNoThrow(json); if (!result.ok()) { - throw Exception(std::string(result.status().message())); + throwExceptionOrPanic(Exception, std::string(result.status().message())); } return result.value(); @@ -752,7 +766,7 @@ FieldSharedPtr loadFromProtobufValueInternal(const ProtobufWkt::Value& protobuf_ case ProtobufWkt::Value::kStructValue: return loadFromProtobufStructInternal(protobuf_value.struct_value()); default: - throw Exception("Protobuf value case not implemented"); + throwExceptionOrPanic(Exception, "Protobuf value case not implemented"); } } diff --git a/source/common/matcher/field_matcher.h b/source/common/matcher/field_matcher.h index e27c1aa444e8..ddda93d0513c 100644 --- a/source/common/matcher/field_matcher.h +++ b/source/common/matcher/field_matcher.h @@ -150,7 +150,7 @@ class SingleFieldMatcher : public FieldMatcher, Logger::LoggabledataInputType()) == supported_input_types.end()) { std::string supported_types = absl::StrJoin(supported_input_types.begin(), supported_input_types.end(), ", "); - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Unsupported data input type: ", data_input_->dataInputType(), ". The matcher supports input type: ", supported_types)); } diff --git a/source/common/matcher/map_matcher.h b/source/common/matcher/map_matcher.h index 4cb50e542f99..1e2c73bfd60c 100644 --- a/source/common/matcher/map_matcher.h +++ b/source/common/matcher/map_matcher.h @@ -20,7 +20,7 @@ class MapMatcher : public MatchTree, Logger::LoggabledataInputType(); if (input_type != DefaultMatchingDataType) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Unsupported data input type: ", input_type, ", currently only string type is supported in map matcher")); } diff --git a/source/common/network/address_impl.cc b/source/common/network/address_impl.cc index b165c2bcec9d..553e5e646b63 100644 --- a/source/common/network/address_impl.cc +++ b/source/common/network/address_impl.cc @@ -34,7 +34,7 @@ const SocketInterface* sockInterfaceOrDefault(const SocketInterface* sock_interf void throwOnError(absl::Status status) { if (!status.ok()) { - throw EnvoyException(status.ToString()); + throwEnvoyExceptionOrPanic(status.ToString()); } } @@ -151,7 +151,7 @@ Ipv4Instance::Ipv4Instance(const std::string& address, uint32_t port, ip_.ipv4_.address_.sin_port = htons(port); int rc = inet_pton(AF_INET, address.c_str(), &ip_.ipv4_.address_.sin_addr); if (1 != rc) { - throw EnvoyException(fmt::format("invalid ipv4 address '{}'", address)); + throwEnvoyExceptionOrPanic(fmt::format("invalid ipv4 address '{}'", address)); } friendly_name_ = absl::StrCat(address, ":", port); @@ -296,7 +296,7 @@ Ipv6Instance::Ipv6Instance(const std::string& address, uint32_t port, addr_in.sin6_port = htons(port); if (!address.empty()) { if (1 != inet_pton(AF_INET6, address.c_str(), &addr_in.sin6_addr)) { - throw EnvoyException(fmt::format("invalid ipv6 address '{}'", address)); + throwEnvoyExceptionOrPanic(fmt::format("invalid ipv6 address '{}'", address)); } } else { addr_in.sin6_addr = in6addr_any; @@ -344,7 +344,7 @@ PipeInstance::PipeInstance(const sockaddr_un* address, socklen_t ss_len, mode_t : InstanceBase(Type::Pipe, sockInterfaceOrDefault(sock_interface)) { if (address->sun_path[0] == '\0') { #if !defined(__linux__) - throw EnvoyException("Abstract AF_UNIX sockets are only supported on linux."); + throwEnvoyExceptionOrPanic("Abstract AF_UNIX sockets are only supported on linux."); #endif RELEASE_ASSERT(static_cast(ss_len) >= offsetof(struct sockaddr_un, sun_path) + 1, ""); @@ -359,7 +359,7 @@ PipeInstance::PipeInstance(const std::string& pipe_path, mode_t mode, const SocketInterface* sock_interface) : InstanceBase(Type::Pipe, sockInterfaceOrDefault(sock_interface)) { if (pipe_path.size() >= sizeof(pipe_.address_.sun_path)) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Path \"{}\" exceeds maximum UNIX domain socket path size of {}.", pipe_path, sizeof(pipe_.address_.sun_path))); } @@ -372,10 +372,10 @@ PipeInstance::PipeInstance(const std::string& pipe_path, mode_t mode, // be null terminated. The friendly name is the address path with embedded nulls replaced with // '@' for consistency with the first character. #if !defined(__linux__) - throw EnvoyException("Abstract AF_UNIX sockets are only supported on linux."); + throwEnvoyExceptionOrPanic("Abstract AF_UNIX sockets are only supported on linux."); #endif if (mode != 0) { - throw EnvoyException("Cannot set mode for Abstract AF_UNIX sockets"); + throwEnvoyExceptionOrPanic("Cannot set mode for Abstract AF_UNIX sockets"); } pipe_.abstract_namespace_ = true; pipe_.address_length_ = pipe_path.size(); @@ -389,7 +389,7 @@ PipeInstance::PipeInstance(const std::string& pipe_path, mode_t mode, } else { // Throw an error if the pipe path has an embedded null character. if (pipe_path.size() != strlen(pipe_path.c_str())) { - throw EnvoyException("UNIX domain socket pathname contains embedded null characters"); + throwEnvoyExceptionOrPanic("UNIX domain socket pathname contains embedded null characters"); } StringUtil::strlcpy(&pipe_.address_.sun_path[0], pipe_path.c_str(), sizeof(pipe_.address_.sun_path)); diff --git a/source/common/network/cidr_range.cc b/source/common/network/cidr_range.cc index eabc4c88ceb5..917fdd6707b6 100644 --- a/source/common/network/cidr_range.cc +++ b/source/common/network/cidr_range.cc @@ -201,7 +201,7 @@ IpList::IpList(const Protobuf::RepeatedPtrField/<# mask bits>)", entry.address_prefix(), entry.prefix_len().value())); } diff --git a/source/common/network/io_socket_handle_impl.cc b/source/common/network/io_socket_handle_impl.cc index 792e05f7db42..e34f067089b4 100644 --- a/source/common/network/io_socket_handle_impl.cc +++ b/source/common/network/io_socket_handle_impl.cc @@ -542,8 +542,8 @@ Address::InstanceConstSharedPtr IoSocketHandleImpl::localAddress() { Api::SysCallIntResult result = os_sys_calls.getsockname(fd_, reinterpret_cast(&ss), &ss_len); if (result.return_value_ != 0) { - throw EnvoyException(fmt::format("getsockname failed for '{}': ({}) {}", fd_, result.errno_, - errorDetails(result.errno_))); + throwEnvoyExceptionOrPanic(fmt::format("getsockname failed for '{}': ({}) {}", fd_, + result.errno_, errorDetails(result.errno_))); } return Address::addressFromSockAddrOrThrow(ss, ss_len, socket_v6only_); } @@ -556,7 +556,7 @@ Address::InstanceConstSharedPtr IoSocketHandleImpl::peerAddress() { Api::SysCallIntResult result = os_sys_calls.getpeername(fd_, reinterpret_cast(&ss), &ss_len); if (result.return_value_ != 0) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("getpeername failed for '{}': {}", fd_, errorDetails(result.errno_))); } @@ -569,7 +569,7 @@ Address::InstanceConstSharedPtr IoSocketHandleImpl::peerAddress() { ss_len = sizeof(ss); result = os_sys_calls.getsockname(fd_, reinterpret_cast(&ss), &ss_len); if (result.return_value_ != 0) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("getsockname failed for '{}': {}", fd_, errorDetails(result.errno_))); } } diff --git a/source/common/network/listen_socket_impl.cc b/source/common/network/listen_socket_impl.cc index c24f024ad34c..20f42e36f359 100644 --- a/source/common/network/listen_socket_impl.cc +++ b/source/common/network/listen_socket_impl.cc @@ -24,10 +24,14 @@ Api::SysCallIntResult ListenSocketImpl::bind(Network::Address::InstanceConstShar const Api::SysCallIntResult result = SocketImpl::bind(connection_info_provider_->localAddress()); if (SOCKET_FAILURE(result.return_value_)) { close(); - throw SocketBindException(fmt::format("cannot bind '{}': {}", - connection_info_provider_->localAddress()->asString(), - errorDetails(result.errno_)), - result.errno_); + const std::string error = + fmt::format("cannot bind '{}': {}", connection_info_provider_->localAddress()->asString(), + errorDetails(result.errno_)); +#ifdef ENVOY_DISABLE_EXCEPTIONS + PANIC(error); +#else + throw SocketBindException(error, result.errno_); +#endif } return {0, 0}; } @@ -35,7 +39,7 @@ Api::SysCallIntResult ListenSocketImpl::bind(Network::Address::InstanceConstShar void ListenSocketImpl::setListenSocketOptions(const Network::Socket::OptionsSharedPtr& options) { if (!Network::Socket::applyOptions(options, *this, envoy::config::core::v3::SocketOption::STATE_PREBIND)) { - throw SocketOptionException("ListenSocket: Setting socket options failed"); + throwExceptionOrPanic(SocketOptionException, "ListenSocket: Setting socket options failed"); } } diff --git a/source/common/network/resolver_impl.cc b/source/common/network/resolver_impl.cc index 02effebc873d..bd51bcfd2272 100644 --- a/source/common/network/resolver_impl.cc +++ b/source/common/network/resolver_impl.cc @@ -31,8 +31,8 @@ class IpResolver : public Resolver { case envoy::config::core::v3::SocketAddress::PortSpecifierCase::kNamedPort: break; } - throw EnvoyException(fmt::format("IP resolver can't handle port specifier type {}", - socket_address.port_specifier_case())); + throwEnvoyExceptionOrPanic(fmt::format("IP resolver can't handle port specifier type {}", + socket_address.port_specifier_case())); } std::string name() const override { return Config::AddressResolverNames::get().IP; } @@ -46,7 +46,7 @@ REGISTER_FACTORY(IpResolver, Resolver); InstanceConstSharedPtr resolveProtoAddress(const envoy::config::core::v3::Address& address) { switch (address.address_case()) { case envoy::config::core::v3::Address::AddressCase::ADDRESS_NOT_SET: - throw EnvoyException("Address must be set: " + address.DebugString()); + throwEnvoyExceptionOrPanic("Address must be set: " + address.DebugString()); case envoy::config::core::v3::Address::AddressCase::kSocketAddress: return resolveProtoSocketAddress(address.socket_address()); case envoy::config::core::v3::Address::AddressCase::kPipe: @@ -63,7 +63,7 @@ InstanceConstSharedPtr resolveProtoAddress(const envoy::config::core::v3::Addres break; } } - throw EnvoyException("Failed to resolve address:" + address.DebugString()); + throwEnvoyExceptionOrPanic("Failed to resolve address:" + address.DebugString()); } InstanceConstSharedPtr @@ -77,7 +77,7 @@ resolveProtoSocketAddress(const envoy::config::core::v3::SocketAddress& socket_a resolver = Registry::FactoryRegistry::getFactory(resolver_name); } if (resolver == nullptr) { - throw EnvoyException(fmt::format("Unknown address resolver: {}", resolver_name)); + throwEnvoyExceptionOrPanic(fmt::format("Unknown address resolver: {}", resolver_name)); } return resolver->resolve(socket_address); } diff --git a/source/common/network/socket_impl.cc b/source/common/network/socket_impl.cc index 3d96d964e93a..14d9d2c781e8 100644 --- a/source/common/network/socket_impl.cc +++ b/source/common/network/socket_impl.cc @@ -68,9 +68,9 @@ Api::SysCallIntResult SocketImpl::bind(Network::Address::InstanceConstSharedPtr if (pipe->mode() != 0 && !abstract_namespace && bind_result.return_value_ == 0) { auto set_permissions = Api::OsSysCallsSingleton::get().chmod(pipe_sa->sun_path, pipe->mode()); if (set_permissions.return_value_ != 0) { - throw EnvoyException(fmt::format("Failed to create socket with mode {}: {}", - std::to_string(pipe->mode()), - errorDetails(set_permissions.errno_))); + throwEnvoyExceptionOrPanic(fmt::format("Failed to create socket with mode {}: {}", + std::to_string(pipe->mode()), + errorDetails(set_permissions.errno_))); } } return bind_result; diff --git a/source/common/network/utility.cc b/source/common/network/utility.cc index c2f0b08385e1..6e9f3188d244 100644 --- a/source/common/network/utility.cc +++ b/source/common/network/utility.cc @@ -57,7 +57,7 @@ Address::InstanceConstSharedPtr Utility::resolveUrl(const std::string& url) { } else if (urlIsUnixScheme(url)) { return std::make_shared(url.substr(UNIX_SCHEME.size())); } else { - throw EnvoyException(absl::StrCat("unknown protocol scheme: ", url)); + throwEnvoyExceptionOrPanic(absl::StrCat("unknown protocol scheme: ", url)); } } @@ -223,7 +223,7 @@ Address::InstanceConstSharedPtr Utility::copyInternetAddressAndPort(const Addres } void Utility::throwWithMalformedIp(absl::string_view ip_address) { - throw EnvoyException(absl::StrCat("malformed IP address: ", ip_address)); + throwEnvoyExceptionOrPanic(absl::StrCat("malformed IP address: ", ip_address)); } // TODO(hennna): Currently getLocalAddress does not support choosing between @@ -443,7 +443,7 @@ void Utility::parsePortRangeList(absl::string_view string, std::list& } if (s.empty() || (min > 65535) || (max > 65535) || ss.fail() || !ss.eof()) { - throw EnvoyException(fmt::format("invalid port number or range '{}'", s_string)); + throwEnvoyExceptionOrPanic(fmt::format("invalid port number or range '{}'", s_string)); } list.emplace_back(PortRange(min, max)); diff --git a/source/common/protobuf/message_validator_impl.cc b/source/common/protobuf/message_validator_impl.cc index 7908f688d3ac..15cebb197654 100644 --- a/source/common/protobuf/message_validator_impl.cc +++ b/source/common/protobuf/message_validator_impl.cc @@ -20,7 +20,8 @@ void onDeprecatedFieldCommon(absl::string_view description, bool soft_deprecatio if (soft_deprecation) { ENVOY_LOG_MISC(warn, "Deprecated field: {}", absl::StrCat(description, deprecation_error)); } else { - throw DeprecatedProtoFieldException(absl::StrCat(description, deprecation_error)); + throwExceptionOrPanic(DeprecatedProtoFieldException, + absl::StrCat(description, deprecation_error)); } } } // namespace @@ -75,8 +76,8 @@ void WarningValidationVisitorImpl::onWorkInProgress(absl::string_view descriptio } void StrictValidationVisitorImpl::onUnknownField(absl::string_view description) { - throw UnknownProtoFieldException( - absl::StrCat("Protobuf message (", description, ") has unknown fields")); + throwExceptionOrPanic(UnknownProtoFieldException, + absl::StrCat("Protobuf message (", description, ") has unknown fields")); } void StrictValidationVisitorImpl::onDeprecatedField(absl::string_view description, diff --git a/source/common/protobuf/utility.cc b/source/common/protobuf/utility.cc index f6c98b44e5ab..7765a0d0dc81 100644 --- a/source/common/protobuf/utility.cc +++ b/source/common/protobuf/utility.cc @@ -114,26 +114,26 @@ uint64_t fractionalPercentDenominatorToInt( } // namespace ProtobufPercentHelper -MissingFieldException::MissingFieldException(const std::string& field_name, - const Protobuf::Message& message) - : EnvoyException( - fmt::format("Field '{}' is missing in: {}", field_name, message.DebugString())) {} - -ProtoValidationException::ProtoValidationException(const std::string& validation_error, - const Protobuf::Message& message) - : EnvoyException(fmt::format("Proto constraint validation failed ({}): {}", validation_error, - message.DebugString())) { +MissingFieldException::MissingFieldException(const std::string& message) + : EnvoyException(message) {} + +ProtoValidationException::ProtoValidationException(const std::string& message) + : EnvoyException(message) { ENVOY_LOG_MISC(debug, "Proto validation error; throwing {}", what()); } void ProtoExceptionUtil::throwMissingFieldException(const std::string& field_name, const Protobuf::Message& message) { - throw MissingFieldException(field_name, message); + std::string error = + fmt::format("Field '{}' is missing in: {}", field_name, message.DebugString()); + throwExceptionOrPanic(MissingFieldException, error); } void ProtoExceptionUtil::throwProtoValidationException(const std::string& validation_error, const Protobuf::Message& message) { - throw ProtoValidationException(validation_error, message); + std::string error = fmt::format("Proto constraint validation failed ({}): {}", validation_error, + message.DebugString()); + throwExceptionOrPanic(ProtoValidationException, error); } size_t MessageUtil::hash(const Protobuf::Message& message) { @@ -350,12 +350,12 @@ void MessageUtil::packFrom(ProtobufWkt::Any& any_message, const Protobuf::Messag void MessageUtil::unpackTo(const ProtobufWkt::Any& any_message, Protobuf::Message& message) { #if defined(ENVOY_ENABLE_FULL_PROTOS) if (!any_message.UnpackTo(&message)) { - throw EnvoyException(fmt::format("Unable to unpack as {}: {}", - message.GetDescriptor()->full_name(), - any_message.DebugString())); + throwEnvoyExceptionOrPanic(fmt::format("Unable to unpack as {}: {}", + message.GetDescriptor()->full_name(), + any_message.DebugString())); #else if (!message.ParseFromString(any_message.value())) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Unable to unpack as {}: {}", message.GetTypeName(), any_message.type_url())); #endif } @@ -605,7 +605,7 @@ void MessageUtil::wireCast(const Protobuf::Message& src, Protobuf::Message& dst) // This should should generally succeed, but if there are malformed UTF-8 strings in a message, // this can fail. if (!dst.ParseFromString(src.SerializeAsString())) { - throw EnvoyException("Unable to deserialize during wireCast()"); + throwEnvoyExceptionOrPanic("Unable to deserialize during wireCast()"); } } @@ -728,7 +728,7 @@ absl::Status validateDurationNoThrow(const ProtobufWkt::Duration& duration, void validateDuration(const ProtobufWkt::Duration& duration, int64_t max_seconds_value) { const auto result = validateDurationNoThrow(duration, max_seconds_value); if (!result.ok()) { - throw DurationUtil::OutOfRangeException(std::string(result.message())); + throwExceptionOrPanic(DurationUtil::OutOfRangeException, std::string(result.message())); } } diff --git a/source/common/protobuf/utility.h b/source/common/protobuf/utility.h index 2a016d4529c1..3eeeeabdc330 100644 --- a/source/common/protobuf/utility.h +++ b/source/common/protobuf/utility.h @@ -135,7 +135,7 @@ namespace Envoy { class MissingFieldException : public EnvoyException { public: - MissingFieldException(const std::string& field_name, const Protobuf::Message& message); + MissingFieldException(const std::string& message); }; class TypeUtil { @@ -205,7 +205,7 @@ class RepeatedPtrUtil { class ProtoValidationException : public EnvoyException { public: - ProtoValidationException(const std::string& validation_error, const Protobuf::Message& message); + ProtoValidationException(const std::string& message); }; /** diff --git a/source/common/protobuf/visitor.cc b/source/common/protobuf/visitor.cc index 38e0231dc7a7..1d544a693833 100644 --- a/source/common/protobuf/visitor.cc +++ b/source/common/protobuf/visitor.cc @@ -43,7 +43,8 @@ void traverseMessageWorker(ConstProtoVisitor& visitor, const Protobuf::Message& traverseMessageWorker(visitor, *inner_message, parents, true, recurse_into_any); return; } else if (!target_type_url.empty()) { - throw EnvoyException(fmt::format("Invalid type_url '{}' during traversal", target_type_url)); + throwEnvoyExceptionOrPanic( + fmt::format("Invalid type_url '{}' during traversal", target_type_url)); } } Protobuf::ReflectableMessage reflectable_message = createReflectableMessage(message); diff --git a/source/common/protobuf/visitor_helper.h b/source/common/protobuf/visitor_helper.h index 187648dcf970..c9e16c264491 100644 --- a/source/common/protobuf/visitor_helper.h +++ b/source/common/protobuf/visitor_helper.h @@ -24,7 +24,7 @@ convertTypedStruct(const Protobuf::Message& message) { MessageUtil::jsonConvert(typed_struct->value(), ProtobufMessage::getNullValidationVisitor(), *inner_message); #else - throw EnvoyException("JSON and YAML support compiled out."); + throwEnvoyExceptionOrPanic("JSON and YAML support compiled out."); #endif } return {std::move(inner_message), target_type_url}; diff --git a/source/common/quic/quic_transport_socket_factory.cc b/source/common/quic/quic_transport_socket_factory.cc index b038c0eb2b0d..9b23710852c2 100644 --- a/source/common/quic/quic_transport_socket_factory.cc +++ b/source/common/quic/quic_transport_socket_factory.cc @@ -24,7 +24,7 @@ QuicServerTransportSocketConfigFactory::createTransportSocketFactory( quic_transport.downstream_tls_context(), context); // TODO(RyanTheOptimist): support TLS client authentication. if (server_config->requireClientCertificate()) { - throw EnvoyException("TLS Client Authentication is not supported over QUIC"); + throwEnvoyExceptionOrPanic("TLS Client Authentication is not supported over QUIC"); } auto factory = std::make_unique( diff --git a/source/common/router/config_impl.cc b/source/common/router/config_impl.cc index 7ca8f9edfb95..5f57bf18ac59 100644 --- a/source/common/router/config_impl.cc +++ b/source/common/router/config_impl.cc @@ -110,7 +110,7 @@ RouteEntryImplBaseConstSharedPtr createAndValidateRoute( break; // throw the error below. } if (!route) { - throw EnvoyException("Invalid route config"); + throwEnvoyExceptionOrPanic("Invalid route config"); } if (validation_clusters.has_value()) { @@ -119,7 +119,7 @@ RouteEntryImplBaseConstSharedPtr createAndValidateRoute( if (!shadow_policy->cluster().empty()) { ASSERT(shadow_policy->clusterHeader().get().empty()); if (!validation_clusters->hasCluster(shadow_policy->cluster())) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("route: unknown shadow cluster '{}'", shadow_policy->cluster())); } } @@ -151,9 +151,9 @@ class RouteActionValidationVisitor const envoy::config::route::v3::WeightedCluster::ClusterWeight& validateWeightedClusterSpecifier( const envoy::config::route::v3::WeightedCluster::ClusterWeight& cluster) { if (!cluster.name().empty() && !cluster.cluster_header().empty()) { - throw EnvoyException("Only one of name or cluster_header can be specified"); + throwEnvoyExceptionOrPanic("Only one of name or cluster_header can be specified"); } else if (cluster.name().empty() && cluster.cluster_header().empty()) { - throw EnvoyException("At least one of name or cluster_header need to be specified"); + throwEnvoyExceptionOrPanic("At least one of name or cluster_header need to be specified"); } return cluster; } @@ -195,7 +195,7 @@ getClusterSpecifierPluginByTheProto(const envoy::config::route::v3::ClusterSpeci if (plugin.is_optional()) { return std::make_shared(); } - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Didn't find a registered implementation for '{}' with type URL: '{}'", plugin.extension().name(), Envoy::Config::Utility::getFactoryType(plugin.extension().typed_config()))); @@ -312,7 +312,7 @@ RetryPolicyImpl::RetryPolicyImpl(const envoy::config::route::v3::RetryPolicy& re } if ((*max_interval_).count() < (*base_interval_).count()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "retry_policy.max_interval must greater than or equal to the base_interval"); } } @@ -400,13 +400,13 @@ absl::flat_hash_set InternalRedirectPolicyImpl::buildRedirectRespons void validateMirrorClusterSpecifier( const envoy::config::route::v3::RouteAction::RequestMirrorPolicy& config) { if (!config.cluster().empty() && !config.cluster_header().empty()) { - throw EnvoyException(fmt::format("Only one of cluster '{}' or cluster_header '{}' " - "in request mirror policy can be specified", - config.cluster(), config.cluster_header())); + throwEnvoyExceptionOrPanic(fmt::format("Only one of cluster '{}' or cluster_header '{}' " + "in request mirror policy can be specified", + config.cluster(), config.cluster_header())); } else if (config.cluster().empty() && config.cluster_header().empty()) { // For shadow policies with `cluster_header_`, we only verify that this field is not // empty because the cluster name is not set yet at config time. - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Exactly one of cluster or cluster_header in request mirror policy need to be specified"); } } @@ -582,7 +582,7 @@ RouteEntryImplBase::RouteEntryImplBase(const CommonVirtualHostSharedPtr& vhost, weighted_clusters.emplace_back(std::move(cluster_entry)); total_weight += weighted_clusters.back()->clusterWeight(); if (total_weight > std::numeric_limits::max()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("The sum of weights of all weighted clusters of route {} exceeds {}", route_name_, std::numeric_limits::max())); } @@ -590,7 +590,7 @@ RouteEntryImplBase::RouteEntryImplBase(const CommonVirtualHostSharedPtr& vhost, // Reject the config if the total_weight of all clusters is 0. if (total_weight == 0) { - throw EnvoyException("Sum of weights in the weighted_cluster must be greater than 0."); + throwEnvoyExceptionOrPanic("Sum of weights in the weighted_cluster must be greater than 0."); } weighted_clusters_config_ = @@ -644,7 +644,7 @@ RouteEntryImplBase::RouteEntryImplBase(const CommonVirtualHostSharedPtr& vhost, Envoy::Http::LowerCaseString(upgrade_config.upgrade_type()).get(), enabled)) .second; if (!success) { - throw EnvoyException(absl::StrCat("Duplicate upgrade ", upgrade_config.upgrade_type())); + throwEnvoyExceptionOrPanic(absl::StrCat("Duplicate upgrade ", upgrade_config.upgrade_type())); } if (absl::EqualsIgnoreCase(upgrade_config.upgrade_type(), Http::Headers::get().MethodValues.Connect) || @@ -653,8 +653,8 @@ RouteEntryImplBase::RouteEntryImplBase(const CommonVirtualHostSharedPtr& vhost, Http::Headers::get().UpgradeValues.ConnectUdp))) { connect_config_ = std::make_unique(upgrade_config.connect_config()); } else if (upgrade_config.has_connect_config()) { - throw EnvoyException(absl::StrCat("Non-CONNECT upgrade type ", upgrade_config.upgrade_type(), - " has ConnectConfig")); + throwEnvoyExceptionOrPanic(absl::StrCat("Non-CONNECT upgrade type ", + upgrade_config.upgrade_type(), " has ConnectConfig")); } } @@ -672,12 +672,12 @@ RouteEntryImplBase::RouteEntryImplBase(const CommonVirtualHostSharedPtr& vhost, } if (num_rewrite_polices > 1) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Specify only one of prefix_rewrite, regex_rewrite or path_rewrite_policy"); } if (!prefix_rewrite_.empty() && path_matcher_ != nullptr) { - throw EnvoyException("Cannot use prefix_rewrite with matcher extension"); + throwEnvoyExceptionOrPanic("Cannot use prefix_rewrite with matcher extension"); } if (route.route().has_regex_rewrite()) { @@ -689,7 +689,7 @@ RouteEntryImplBase::RouteEntryImplBase(const CommonVirtualHostSharedPtr& vhost, if (path_rewriter_ != nullptr) { absl::Status compatible_status = path_rewriter_->isCompatiblePathMatcher(path_matcher_); if (!compatible_status.ok()) { - throw EnvoyException(std::string(compatible_status.message())); + throwEnvoyExceptionOrPanic(std::string(compatible_status.message())); } } @@ -1162,7 +1162,7 @@ RouteEntryImplBase::buildPathRewriter(envoy::config::route::v3::Route route, absl::StatusOr rewriter = factory.createPathRewriter(*config); if (!rewriter.ok()) { - throw EnvoyException(std::string(rewriter.status().message())); + throwEnvoyExceptionOrPanic(std::string(rewriter.status().message())); } return rewriter.value(); @@ -1183,7 +1183,7 @@ RouteEntryImplBase::buildPathMatcher(envoy::config::route::v3::Route route, absl::StatusOr matcher = factory.createPathMatcher(*config); if (!matcher.ok()) { - throw EnvoyException(std::string(matcher.status().message())); + throwEnvoyExceptionOrPanic(std::string(matcher.status().message())); } return matcher.value(); @@ -1345,14 +1345,14 @@ void RouteEntryImplBase::validateClusters( // route tables. This would enable the all CDS with static route table case. if (!cluster_name_.empty()) { if (!cluster_info_maps.hasCluster(cluster_name_)) { - throw EnvoyException(fmt::format("route: unknown cluster '{}'", cluster_name_)); + throwEnvoyExceptionOrPanic(fmt::format("route: unknown cluster '{}'", cluster_name_)); } } else if (weighted_clusters_config_ != nullptr) { for (const WeightedClusterEntrySharedPtr& cluster : weighted_clusters_config_->weighted_clusters_) { if (!cluster->clusterName().empty()) { if (!cluster_info_maps.hasCluster(cluster->clusterName())) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("route: unknown weighted cluster '{}'", cluster->clusterName())); } } @@ -1360,7 +1360,7 @@ void RouteEntryImplBase::validateClusters( // not empty because the cluster name is not set yet at config time (hence the validation // here). else if (cluster->clusterHeaderName().get().empty()) { - throw EnvoyException("route: unknown weighted cluster with no cluster_header field"); + throwEnvoyExceptionOrPanic("route: unknown weighted cluster with no cluster_header field"); } } } @@ -1702,7 +1702,7 @@ CommonVirtualHostImpl::CommonVirtualHostImpl( } if (virtual_host.has_matcher() && !virtual_host.routes().empty()) { - throw EnvoyException("cannot set both matcher and routes on virtual host"); + throwEnvoyExceptionOrPanic("cannot set both matcher and routes on virtual host"); } if (!virtual_host.virtual_clusters().empty()) { @@ -1734,7 +1734,7 @@ CommonVirtualHostImpl::VirtualClusterEntry::VirtualClusterEntry( VirtualClusterBase(virtual_cluster.name(), stat_name_storage_.statName(), scope.scopeFromStatName(stat_name_storage_.statName()), stat_names) { if (virtual_cluster.headers().empty()) { - throw EnvoyException("virtual clusters must define 'headers'"); + throwEnvoyExceptionOrPanic("virtual clusters must define 'headers'"); } ASSERT(!virtual_cluster.headers().empty()); @@ -1814,8 +1814,9 @@ VirtualHostImpl::VirtualHostImpl( if (!validation_visitor.errors().empty()) { // TODO(snowp): Output all violations. - throw EnvoyException(fmt::format("requirement violation while creating route match tree: {}", - validation_visitor.errors()[0])); + throwEnvoyExceptionOrPanic( + fmt::format("requirement violation while creating route match tree: {}", + validation_visitor.errors()[0])); } } else { for (const auto& route : virtual_host.routes()) { @@ -1962,8 +1963,8 @@ RouteMatcher::RouteMatcher(const envoy::config::route::v3::RouteConfiguration& r bool duplicate_found = false; if ("*" == domain) { if (default_virtual_host_) { - throw EnvoyException(fmt::format("Only a single wildcard domain is permitted in route {}", - route_config.name())); + throwEnvoyExceptionOrPanic(fmt::format( + "Only a single wildcard domain is permitted in route {}", route_config.name())); } default_virtual_host_ = virtual_host; } else if (!domain.empty() && '*' == domain[0]) { @@ -1978,9 +1979,10 @@ RouteMatcher::RouteMatcher(const envoy::config::route::v3::RouteConfiguration& r duplicate_found = !virtual_hosts_.emplace(domain, virtual_host).second; } if (duplicate_found) { - throw EnvoyException(fmt::format("Only unique values for domains are permitted. Duplicate " - "entry of domain {} in route {}", - domain, route_config.name())); + throwEnvoyExceptionOrPanic( + fmt::format("Only unique values for domains are permitted. Duplicate " + "entry of domain {} in route {}", + domain, route_config.name())); } } } @@ -2115,7 +2117,7 @@ ClusterSpecifierPluginSharedPtr CommonConfigImpl::clusterSpecifierPlugin(absl::string_view provider) const { auto iter = cluster_specifier_plugins_.find(provider); if (iter == cluster_specifier_plugins_.end() || iter->second == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Unknown cluster specifier plugin name: {} is used in the route", provider)); } return iter->second; @@ -2172,7 +2174,7 @@ RouteSpecificFilterConfigConstSharedPtr PerFilterConfigs::createRouteSpecificFil name, Envoy::Config::Utility::getFactoryType(typed_config)); return nullptr; } else { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Didn't find a registered implementation for '{}' with type URL: '{}'", name, Envoy::Config::Utility::getFactoryType(typed_config))); } @@ -2189,7 +2191,7 @@ RouteSpecificFilterConfigConstSharedPtr PerFilterConfigs::createRouteSpecificFil "optional, so ignore it.", name); } else { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "The filter {} doesn't support virtual host or route specific configurations", name)); } } @@ -2240,7 +2242,7 @@ PerFilterConfigs::PerFilterConfigs( // If the field `config` is not configured, we treat it as configuration error. if (!filter_config.has_config()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Empty route/virtual host per filter configuration for {} filter", name)); } diff --git a/source/common/router/config_utility.cc b/source/common/router/config_utility.cc index 04f603c63a7e..2493bab40e91 100644 --- a/source/common/router/config_utility.cc +++ b/source/common/router/config_utility.cc @@ -116,8 +116,8 @@ std::string ConfigUtility::parseDirectResponseBody(const envoy::config::route::v const std::string string_body = Envoy::Config::DataSource::read(body, true, api, max_body_size_bytes); if (string_body.length() > max_body_size_bytes) { - throw EnvoyException(fmt::format("response body size is {} bytes; maximum is {}", - string_body.length(), max_body_size_bytes)); + throwEnvoyExceptionOrPanic(fmt::format("response body size is {} bytes; maximum is {}", + string_body.length(), max_body_size_bytes)); } return string_body; } diff --git a/source/common/router/header_parser.cc b/source/common/router/header_parser.cc index bc48fe67f506..1801bcec4896 100644 --- a/source/common/router/header_parser.cc +++ b/source/common/router/header_parser.cc @@ -35,7 +35,7 @@ parseHttpHeaderFormatter(const envoy::config::core::v3::HeaderValue& header_valu // Host is disallowed as it created confusing and inconsistent behaviors for // HTTP/1 and HTTP/2. It could arguably be allowed on the response path. if (!Http::HeaderUtility::isModifiableHeader(key)) { - throw EnvoyException(":-prefixed or host headers may not be modified"); + throwEnvoyExceptionOrPanic(":-prefixed or host headers may not be modified"); } // UPSTREAM_METADATA and DYNAMIC_METADATA must be translated from JSON ["a", "b"] format to colon @@ -58,7 +58,7 @@ HeadersToAddEntry::HeadersToAddEntry(const HeaderValueOption& header_value_optio if (header_value_option.has_append()) { // 'append' is set and ensure the 'append_action' value is equal to the default value. if (header_value_option.append_action() != HeaderValueOption::APPEND_IF_EXISTS_OR_ADD) { - throw EnvoyException("Both append and append_action are set and it's not allowed"); + throwEnvoyExceptionOrPanic("Both append and append_action are set and it's not allowed"); } append_action_ = header_value_option.append().value() @@ -112,7 +112,7 @@ HeaderParser::configure(const Protobuf::RepeatedPtrField& hea // request finalization assume their existence and they are needed for well-formedness in most // cases. if (!Http::HeaderUtility::isRemovableHeader(header)) { - throw EnvoyException(":-prefixed or host headers may not be removed"); + throwEnvoyExceptionOrPanic(":-prefixed or host headers may not be removed"); } header_parser->headers_to_remove_.emplace_back(header); } diff --git a/source/common/router/router_ratelimit.cc b/source/common/router/router_ratelimit.cc index 03c5b9a86ba1..b53943de89f4 100644 --- a/source/common/router/router_ratelimit.cc +++ b/source/common/router/router_ratelimit.cc @@ -334,7 +334,7 @@ RateLimitPolicyEntryImpl::RateLimitPolicyEntryImpl( if (producer) { actions_.emplace_back(std::move(producer)); } else { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Rate limit descriptor extension failed: ", action.extension().name())); } break; @@ -348,7 +348,7 @@ RateLimitPolicyEntryImpl::RateLimitPolicyEntryImpl( new QueryParameterValueMatchAction(action.query_parameter_value_match())); break; case envoy::config::route::v3::RateLimit::Action::ActionSpecifierCase::ACTION_SPECIFIER_NOT_SET: - throw EnvoyException("invalid config"); + throwEnvoyExceptionOrPanic("invalid config"); } } if (config.has_limit()) { @@ -359,7 +359,7 @@ RateLimitPolicyEntryImpl::RateLimitPolicyEntryImpl( break; case envoy::config::route::v3::RateLimit_Override::OverrideSpecifierCase:: OVERRIDE_SPECIFIER_NOT_SET: - throw EnvoyException("invalid config"); + throwEnvoyExceptionOrPanic("invalid config"); } } } diff --git a/source/common/router/scoped_config_impl.cc b/source/common/router/scoped_config_impl.cc index 45a16d9c4c46..80e2a33d8c32 100644 --- a/source/common/router/scoped_config_impl.cc +++ b/source/common/router/scoped_config_impl.cc @@ -18,6 +18,10 @@ bool ScopeKey::operator==(const ScopeKey& other) const { return this->hash() == other.hash(); } +void throwProtoValidationExceptionOrPanic(std::string message) { + throwExceptionOrPanic(ProtoValidationException, message); +} + HeaderValueExtractorImpl::HeaderValueExtractorImpl( ScopedRoutes::ScopeKeyBuilder::FragmentBuilder&& config) : FragmentBuilderBase(std::move(config)), @@ -29,14 +33,12 @@ HeaderValueExtractorImpl::HeaderValueExtractorImpl( ScopedRoutes::ScopeKeyBuilder::FragmentBuilder::HeaderValueExtractor::kIndex) { if (header_value_extractor_config_.index() != 0 && header_value_extractor_config_.element_separator().empty()) { - throw ProtoValidationException("Index > 0 for empty string element separator.", - header_value_extractor_config_); + throwProtoValidationExceptionOrPanic("Index > 0 for empty string element separator."); } } if (header_value_extractor_config_.extract_type_case() == ScopedRoutes::ScopeKeyBuilder::FragmentBuilder::HeaderValueExtractor::EXTRACT_TYPE_NOT_SET) { - throw ProtoValidationException("HeaderValueExtractor extract_type not set.", - header_value_extractor_config_); + throwProtoValidationExceptionOrPanic("HeaderValueExtractor extract_type not set."); } } diff --git a/source/common/router/scoped_rds.cc b/source/common/router/scoped_rds.cc index 18afd067cc1c..b39fbba09491 100644 --- a/source/common/router/scoped_rds.cc +++ b/source/common/router/scoped_rds.cc @@ -103,11 +103,13 @@ makeScopedRouteInfos(ProtobufTypes::ConstMessagePtrVector&& config_protos, MessageUtil::downcastAndValidate( *config_proto, factory_context.messageValidationContext().staticValidationVisitor()); if (!scoped_route_config.route_configuration_name().empty()) { - throw EnvoyException("Fetching routes via RDS (route_configuration_name) is not supported " - "with inline scoped routes."); + throwEnvoyExceptionOrPanic( + "Fetching routes via RDS (route_configuration_name) is not supported " + "with inline scoped routes."); } if (!scoped_route_config.has_route_configuration()) { - throw EnvoyException("You must specify a route_configuration with inline scoped routes."); + throwEnvoyExceptionOrPanic( + "You must specify a route_configuration with inline scoped routes."); } RouteConfigProviderPtr route_config_provider = config_provider_manager.routeConfigProviderManager().createStaticRouteConfigProvider( diff --git a/source/common/router/vhds.cc b/source/common/router/vhds.cc index 939852a50fc6..7f0139907337 100644 --- a/source/common/router/vhds.cc +++ b/source/common/router/vhds.cc @@ -43,7 +43,7 @@ VhdsSubscription::VhdsSubscription(RouteConfigUpdatePtr& config_update_info, .api_config_source() .api_type(); if (config_source != envoy::config::core::v3::ApiConfigSource::DELTA_GRPC) { - throw EnvoyException("vhds: only 'DELTA_GRPC' is supported as an api_type."); + throwEnvoyExceptionOrPanic("vhds: only 'DELTA_GRPC' is supported as an api_type."); } const auto resource_name = getResourceName(); Envoy::Config::SubscriptionOptions options; diff --git a/source/common/runtime/runtime_impl.cc b/source/common/runtime/runtime_impl.cc index 3c308b94e4f7..b8068a5d7884 100644 --- a/source/common/runtime/runtime_impl.cc +++ b/source/common/runtime/runtime_impl.cc @@ -417,11 +417,11 @@ void DiskLayer::walkDirectory(const std::string& path, const std::string& prefix ENVOY_LOG(debug, "walking directory: {}", path); if (depth > MaxWalkDepth) { - throw EnvoyException(absl::StrCat("Walk recursion depth exceeded ", MaxWalkDepth)); + throwEnvoyExceptionOrPanic(absl::StrCat("Walk recursion depth exceeded ", MaxWalkDepth)); } // Check if this is an obviously bad path. if (api.fileSystem().illegalPath(path)) { - throw EnvoyException(absl::StrCat("Invalid path: ", path)); + throwEnvoyExceptionOrPanic(absl::StrCat("Invalid path: ", path)); } Filesystem::Directory directory(path); @@ -488,7 +488,7 @@ void ProtoLayer::walkProtoValue(const ProtobufWkt::Value& v, const std::string& case ProtobufWkt::Value::KIND_NOT_SET: case ProtobufWkt::Value::kListValue: case ProtobufWkt::Value::kNullValue: - throw EnvoyException(absl::StrCat("Invalid runtime entry value for ", prefix)); + throwEnvoyExceptionOrPanic(absl::StrCat("Invalid runtime entry value for ", prefix)); break; case ProtobufWkt::Value::kStringValue: SnapshotImpl::addEntry(values_, prefix, v, ""); @@ -529,7 +529,7 @@ LoaderImpl::LoaderImpl(Event::Dispatcher& dispatcher, ThreadLocal::SlotAllocator for (const auto& layer : config_.layers()) { auto ret = layer_names.insert(layer.name()); if (!ret.second) { - throw EnvoyException(absl::StrCat("Duplicate layer name: ", layer.name())); + throwEnvoyExceptionOrPanic(absl::StrCat("Duplicate layer name: ", layer.name())); } switch (layer.layer_specifier_case()) { case envoy::config::bootstrap::v3::RuntimeLayer::LayerSpecifierCase::kStaticLayer: @@ -537,7 +537,7 @@ LoaderImpl::LoaderImpl(Event::Dispatcher& dispatcher, ThreadLocal::SlotAllocator break; case envoy::config::bootstrap::v3::RuntimeLayer::LayerSpecifierCase::kAdminLayer: if (admin_layer_ != nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Too many admin layers specified in LayeredRuntime, at most one may be specified"); } admin_layer_ = std::make_unique(layer.name(), stats_); @@ -555,7 +555,7 @@ LoaderImpl::LoaderImpl(Event::Dispatcher& dispatcher, ThreadLocal::SlotAllocator init_manager_.add(subscriptions_.back()->init_target_); break; case envoy::config::bootstrap::v3::RuntimeLayer::LayerSpecifierCase::LAYER_SPECIFIER_NOT_SET: - throw EnvoyException("layer specifier not set"); + throwEnvoyExceptionOrPanic("layer specifier not set"); } } @@ -703,7 +703,7 @@ SnapshotConstSharedPtr LoaderImpl::threadsafeSnapshot() { void LoaderImpl::mergeValues(const absl::node_hash_map& values) { if (admin_layer_ == nullptr) { - throw EnvoyException("No admin layer specified"); + throwEnvoyExceptionOrPanic("No admin layer specified"); } admin_layer_->mergeValues(values); loadNewSnapshot(); diff --git a/source/common/secret/secret_manager_impl.cc b/source/common/secret/secret_manager_impl.cc index ac7624e5d901..717f5a2555b2 100644 --- a/source/common/secret/secret_manager_impl.cc +++ b/source/common/secret/secret_manager_impl.cc @@ -34,7 +34,7 @@ void SecretManagerImpl::addStaticSecret( std::make_shared(secret.tls_certificate()); if (!static_tls_certificate_providers_.insert(std::make_pair(secret.name(), secret_provider)) .second) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Duplicate static TlsCertificate secret name ", secret.name())); } break; @@ -45,7 +45,7 @@ void SecretManagerImpl::addStaticSecret( if (!static_certificate_validation_context_providers_ .insert(std::make_pair(secret.name(), secret_provider)) .second) { - throw EnvoyException(absl::StrCat( + throwEnvoyExceptionOrPanic(absl::StrCat( "Duplicate static CertificateValidationContext secret name ", secret.name())); } break; @@ -56,7 +56,7 @@ void SecretManagerImpl::addStaticSecret( if (!static_session_ticket_keys_providers_ .insert(std::make_pair(secret.name(), secret_provider)) .second) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Duplicate static TlsSessionTicketKeys secret name ", secret.name())); } break; @@ -66,13 +66,13 @@ void SecretManagerImpl::addStaticSecret( std::make_shared(secret.generic_secret()); if (!static_generic_secret_providers_.insert(std::make_pair(secret.name(), secret_provider)) .second) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Duplicate static GenericSecret secret name ", secret.name())); } break; } default: - throw EnvoyException("Secret type not implemented"); + throwEnvoyExceptionOrPanic("Secret type not implemented"); } } diff --git a/source/common/ssl/tls_certificate_config_impl.cc b/source/common/ssl/tls_certificate_config_impl.cc index 7e96344d7f9a..0b131494b5da 100644 --- a/source/common/ssl/tls_certificate_config_impl.cc +++ b/source/common/ssl/tls_certificate_config_impl.cc @@ -17,7 +17,7 @@ std::vector readOcspStaple(const envoy::config::core::v3::DataSource& s std::string staple = Config::DataSource::read(source, true, api); if (source.specifier_case() == envoy::config::core::v3::DataSource::SpecifierCase::kInlineString) { - throw EnvoyException("OCSP staple cannot be provided via inline_string"); + throwEnvoyExceptionOrPanic("OCSP staple cannot be provided via inline_string"); } return {staple.begin(), staple.end()}; @@ -48,15 +48,15 @@ TlsCertificateConfigImpl::TlsCertificateConfigImpl( private_key_method_(nullptr) { if (config.has_pkcs12()) { if (config.has_private_key()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Certificate configuration can't have both pkcs12 and private_key")); } if (config.has_certificate_chain()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Certificate configuration can't have both pkcs12 and certificate_chain")); } if (config.has_private_key_provider()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Certificate configuration can't have both pkcs12 and private_key_provider")); } } else { @@ -67,8 +67,8 @@ TlsCertificateConfigImpl::TlsCertificateConfigImpl( .createPrivateKeyMethodProvider(config.private_key_provider(), factory_context); if (private_key_method_ == nullptr || (!private_key_method_->isAvailable() && !config.private_key_provider().fallback())) { - throw EnvoyException(fmt::format("Failed to load private key provider: {}", - config.private_key_provider().provider_name())); + throwEnvoyExceptionOrPanic(fmt::format("Failed to load private key provider: {}", + config.private_key_provider().provider_name())); } if (!private_key_method_->isAvailable()) { @@ -76,13 +76,13 @@ TlsCertificateConfigImpl::TlsCertificateConfigImpl( } } if (certificate_chain_.empty()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Failed to load incomplete certificate from {}: certificate chain not set", certificate_chain_path_)); } if (private_key_.empty() && private_key_method_ == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Failed to load incomplete private key from path: {}", private_key_path_)); } } diff --git a/source/common/stats/tag_extractor_impl.cc b/source/common/stats/tag_extractor_impl.cc index 78b220eefa0c..c48370880519 100644 --- a/source/common/stats/tag_extractor_impl.cc +++ b/source/common/stats/tag_extractor_impl.cc @@ -72,11 +72,11 @@ TagExtractorPtr TagExtractorImplBase::createTagExtractor(absl::string_view name, absl::string_view negative_match, Regex::Type re_type) { if (name.empty()) { - throw EnvoyException("tag_name cannot be empty"); + throwEnvoyExceptionOrPanic("tag_name cannot be empty"); } if (regex.empty()) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "No regex specified for tag specifier and no default regex for name: '{}'", name)); } switch (re_type) { diff --git a/source/common/stats/tag_producer_impl.cc b/source/common/stats/tag_producer_impl.cc index 4d8f5a518f88..2d4d22cc060f 100644 --- a/source/common/stats/tag_producer_impl.cc +++ b/source/common/stats/tag_producer_impl.cc @@ -34,7 +34,7 @@ TagProducerImpl::TagProducerImpl(const envoy::config::metrics::v3::StatsConfig& if (tag_specifier.regex().empty()) { if (addExtractorsMatching(name) == 0) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "No regex specified for tag specifier and no default regex for name: '{}'", name)); } } else { diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index 807a00276aa3..bf4012d6d848 100644 --- a/source/common/upstream/cluster_manager_impl.cc +++ b/source/common/upstream/cluster_manager_impl.cc @@ -413,7 +413,7 @@ ClusterManagerImpl::ClusterManagerImpl( } auto* factory = Config::Utility::getFactoryByName(name); if (!factory) { - throw EnvoyException(fmt::format("{} not found", name)); + throwEnvoyExceptionOrPanic(fmt::format("{} not found", name)); } ads_mux_ = factory->create( Config::Utility::factoryForGrpcApiConfigSource( @@ -434,7 +434,7 @@ ClusterManagerImpl::ClusterManagerImpl( auto* factory = Config::Utility::getFactoryByName(name); if (!factory) { - throw EnvoyException(fmt::format("{} not found", name)); + throwEnvoyExceptionOrPanic(fmt::format("{} not found", name)); } ads_mux_ = factory->create( Config::Utility::factoryForGrpcApiConfigSource( @@ -465,7 +465,7 @@ ClusterManagerImpl::ClusterManagerImpl( if (local_cluster_name_) { auto local_cluster = active_clusters_.find(local_cluster_name_.value()); if (local_cluster == active_clusters_.end()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("local cluster '{}' must be defined", local_cluster_name_.value())); } local_cluster_params.emplace(); @@ -854,7 +854,7 @@ ClusterManagerImpl::loadCluster(const envoy::config::cluster::v3::Cluster& clust factory_.clusterFromProto(cluster, *this, outlier_event_logger_, added_via_api); if (!new_cluster_pair_or_error.ok()) { - throw EnvoyException(std::string(new_cluster_pair_or_error.status().message())); + throwEnvoyExceptionOrPanic(std::string(new_cluster_pair_or_error.status().message())); } auto& new_cluster = new_cluster_pair_or_error->first; auto& lb = new_cluster_pair_or_error->second; @@ -864,7 +864,7 @@ ClusterManagerImpl::loadCluster(const envoy::config::cluster::v3::Cluster& clust if (!added_via_api) { if (cluster_map.find(cluster_info->name()) != cluster_map.end()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("cluster manager: duplicate cluster '{}'", cluster_info->name())); } } @@ -880,12 +880,13 @@ ClusterManagerImpl::loadCluster(const envoy::config::cluster::v3::Cluster& clust } if (cluster_provided_lb && lb == nullptr) { - throw EnvoyException(fmt::format("cluster manager: cluster provided LB specified but cluster " - "'{}' did not provide one. Check cluster documentation.", - cluster_info->name())); + throwEnvoyExceptionOrPanic( + fmt::format("cluster manager: cluster provided LB specified but cluster " + "'{}' did not provide one. Check cluster documentation.", + cluster_info->name())); } if (!cluster_provided_lb && lb != nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("cluster manager: cluster provided LB not specified but cluster " "'{}' provided one. Check cluster documentation.", cluster_info->name())); @@ -1096,10 +1097,10 @@ void ClusterManagerImpl::drainConnections(DrainConnectionsHostPredicate predicat void ClusterManagerImpl::checkActiveStaticCluster(const std::string& cluster) { const auto& it = active_clusters_.find(cluster); if (it == active_clusters_.end()) { - throw EnvoyException(fmt::format("Unknown gRPC client cluster '{}'", cluster)); + throwEnvoyExceptionOrPanic(fmt::format("Unknown gRPC client cluster '{}'", cluster)); } if (it->second->added_via_api_) { - throw EnvoyException(fmt::format("gRPC client cluster '{}' is not static", cluster)); + throwEnvoyExceptionOrPanic(fmt::format("gRPC client cluster '{}' is not static", cluster)); } } diff --git a/source/common/upstream/default_local_address_selector_factory.cc b/source/common/upstream/default_local_address_selector_factory.cc index f10dd91b4451..7dc9817b6c9f 100644 --- a/source/common/upstream/default_local_address_selector_factory.cc +++ b/source/common/upstream/default_local_address_selector_factory.cc @@ -13,14 +13,14 @@ void validate(const std::vector<::Envoy::Upstream::UpstreamLocalAddress>& upstre absl::optional cluster_name) { if (upstream_local_addresses.empty()) { - throw EnvoyException(fmt::format("{}'s upstream binding config has no valid source address.", - !(cluster_name.has_value()) - ? "Bootstrap" - : fmt::format("Cluster {}", cluster_name.value()))); + throwEnvoyExceptionOrPanic( + fmt::format("{}'s upstream binding config has no valid source address.", + !(cluster_name.has_value()) ? "Bootstrap" + : fmt::format("Cluster {}", cluster_name.value()))); } if (upstream_local_addresses.size() > 2) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "{}'s upstream binding config has more than one extra/additional source addresses. Only " "one extra/additional source can be supported in BindConfig's " "extra_source_addresses/additional_source_addresses field", @@ -42,7 +42,7 @@ void validate(const std::vector<::Envoy::Upstream::UpstreamLocalAddress>& upstre if (upstream_local_addresses[0].address_->ip()->version() == upstream_local_addresses[1].address_->ip()->version()) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "{}'s upstream binding config has two same IP version source addresses. Only two " "different IP version source addresses can be supported in BindConfig's source_address " "and extra_source_addresses/additional_source_addresses fields", diff --git a/source/common/upstream/outlier_detection_impl.cc b/source/common/upstream/outlier_detection_impl.cc index 1f8478ebc907..d74d42b83a99 100644 --- a/source/common/upstream/outlier_detection_impl.cc +++ b/source/common/upstream/outlier_detection_impl.cc @@ -293,7 +293,7 @@ DetectorImpl::create(Cluster& cluster, const envoy::config::cluster::v3::Outlier new DetectorImpl(cluster, config, dispatcher, runtime, time_source, event_logger, random)); if (detector->config().maxEjectionTimeMs() < detector->config().baseEjectionTimeMs()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "outlier detector's max_ejection_time cannot be smaller than base_ejection_time"); } detector->initialize(cluster); diff --git a/source/common/upstream/subset_lb_config.cc b/source/common/upstream/subset_lb_config.cc index 0de84d5055ba..ef3cf228ebd7 100644 --- a/source/common/upstream/subset_lb_config.cc +++ b/source/common/upstream/subset_lb_config.cc @@ -20,7 +20,8 @@ SubsetSelectorImpl::SubsetSelectorImpl( // defining fallback_keys_subset_ for a fallback policy other than KEYS_SUBSET doesn't have // any effect and it is probably a user mistake. We should let the user know about it. if (!fallback_keys_subset_.empty()) { - throw EnvoyException("fallback_keys_subset can be set only for KEYS_SUBSET fallback_policy"); + throwEnvoyExceptionOrPanic( + "fallback_keys_subset can be set only for KEYS_SUBSET fallback_policy"); } return; } @@ -29,7 +30,7 @@ SubsetSelectorImpl::SubsetSelectorImpl( // it would be the same as not defining fallback policy at all (global fallback policy would be // used) if (fallback_keys_subset_.empty()) { - throw EnvoyException("fallback_keys_subset cannot be empty"); + throwEnvoyExceptionOrPanic("fallback_keys_subset cannot be empty"); } // We allow only for a fallback to a subset of the selector keys because this is probably the @@ -38,13 +39,13 @@ SubsetSelectorImpl::SubsetSelectorImpl( // for this. if (!std::includes(selector_keys_.begin(), selector_keys_.end(), fallback_keys_subset_.begin(), fallback_keys_subset_.end())) { - throw EnvoyException("fallback_keys_subset must be a subset of selector keys"); + throwEnvoyExceptionOrPanic("fallback_keys_subset must be a subset of selector keys"); } // Enforce that the fallback_keys_subset_ set is smaller than the selector_keys_ set. Otherwise // we could end up with a infinite recursion of SubsetLoadBalancer::chooseHost(). if (selector_keys_.size() == fallback_keys_subset_.size()) { - throw EnvoyException("fallback_keys_subset cannot be equal to keys"); + throwEnvoyExceptionOrPanic("fallback_keys_subset cannot be equal to keys"); } } diff --git a/source/common/upstream/thread_aware_lb_impl.cc b/source/common/upstream/thread_aware_lb_impl.cc index a787c466a533..7c16473d9c1c 100644 --- a/source/common/upstream/thread_aware_lb_impl.cc +++ b/source/common/upstream/thread_aware_lb_impl.cc @@ -19,7 +19,7 @@ void normalizeHostWeights(const HostVector& hosts, double normalized_locality_we for (const auto& host : hosts) { sum += host->weight(); if (sum > std::numeric_limits::max()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("The sum of weights of all upstream hosts in a locality exceeds {}", std::numeric_limits::max())); } @@ -45,7 +45,7 @@ void normalizeLocalityWeights(const HostsPerLocality& hosts_per_locality, for (const auto weight : locality_weights) { sum += weight; if (sum > std::numeric_limits::max()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("The sum of weights of all localities at the same priority exceeds {}", std::numeric_limits::max())); } diff --git a/source/common/upstream/upstream_impl.cc b/source/common/upstream/upstream_impl.cc index a37052a5ea82..ae7c4629044d 100644 --- a/source/common/upstream/upstream_impl.cc +++ b/source/common/upstream/upstream_impl.cc @@ -97,15 +97,16 @@ createProtocolOptionsConfig(const std::string& name, const ProtobufWkt::Any& typ } if (factory == nullptr) { - throw EnvoyException(fmt::format("Didn't find a registered network or http filter or protocol " - "options implementation for name: '{}'", - name)); + throwEnvoyExceptionOrPanic( + fmt::format("Didn't find a registered network or http filter or protocol " + "options implementation for name: '{}'", + name)); } ProtobufTypes::MessagePtr proto_config = factory->createEmptyProtocolOptionsProto(); if (proto_config == nullptr) { - throw EnvoyException(fmt::format("filter {} does not support protocol options", name)); + throwEnvoyExceptionOrPanic(fmt::format("filter {} does not support protocol options", name)); } Envoy::Config::Utility::translateOpaqueConfig( @@ -287,10 +288,10 @@ parseBindConfig(::Envoy::OptRef bind_ if (upstream_local_addresses.size() > 1) { for (auto const& upstream_local_address : upstream_local_addresses) { if (upstream_local_address.address_ == nullptr) { - throw EnvoyException(fmt::format("{}'s upstream binding config has invalid IP addresses.", - !(cluster_name.has_value()) - ? "Bootstrap" - : fmt::format("Cluster {}", cluster_name.value()))); + throwEnvoyExceptionOrPanic(fmt::format( + "{}'s upstream binding config has invalid IP addresses.", + !(cluster_name.has_value()) ? "Bootstrap" + : fmt::format("Cluster {}", cluster_name.value()))); } } } @@ -317,7 +318,7 @@ Envoy::Upstream::UpstreamLocalAddressSelectorConstSharedPtr createUpstreamLocalA if (bind_config.has_value()) { if (bind_config->additional_source_addresses_size() > 0 && bind_config->extra_source_addresses_size() > 0) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "Can't specify both `extra_source_addresses` and `additional_source_addresses` " "in the {}'s upstream binding config", !(cluster_name.has_value()) ? "Bootstrap" @@ -327,7 +328,7 @@ Envoy::Upstream::UpstreamLocalAddressSelectorConstSharedPtr createUpstreamLocalA if (!bind_config->has_source_address() && (bind_config->extra_source_addresses_size() > 0 || bind_config->additional_source_addresses_size() > 0)) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "{}'s upstream binding config has extra/additional source addresses but no " "source_address. Extra/additional addresses cannot be specified if " "source_address is not set.", @@ -411,7 +412,7 @@ HostDescriptionImpl::HostDescriptionImpl( if (health_check_config.port_value() != 0 && dest_address->type() != Network::Address::Type::Ip) { // Setting the health check port to non-0 only works for IP-type addresses. Setting the port // for a pipe address is a misconfiguration. Throw an exception. - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Invalid host configuration: non-zero port for non-IP address")); } health_check_address_ = resolveHealthCheckAddress(health_check_config, dest_address); @@ -874,8 +875,9 @@ createOptions(const envoy::config::cluster::v3::Cluster& config, if (config.protocol_selection() == envoy::config::cluster::v3::Cluster::USE_CONFIGURED_PROTOCOL) { // Make sure multiple protocol configurations are not present if (config.has_http_protocol_options() && config.has_http2_protocol_options()) { - throw EnvoyException(fmt::format("cluster: Both HTTP1 and HTTP2 options may only be " - "configured with non-default 'protocol_selection' values")); + throwEnvoyExceptionOrPanic( + fmt::format("cluster: Both HTTP1 and HTTP2 options may only be " + "configured with non-default 'protocol_selection' values")); } } @@ -1083,15 +1085,16 @@ ClusterInfoImpl::ClusterInfoImpl( added_via_api_(added_via_api), has_configured_http_filters_(false) { #ifdef WIN32 if (set_local_interface_name_on_upstream_connections_) { - throw EnvoyException("set_local_interface_name_on_upstream_connections_ cannot be set to true " - "on Windows platforms"); + throwEnvoyExceptionOrPanic( + "set_local_interface_name_on_upstream_connections_ cannot be set to true " + "on Windows platforms"); } #endif if (config.has_max_requests_per_connection() && http_protocol_options_->common_http_protocol_options_.has_max_requests_per_connection()) { - throw EnvoyException("Only one of max_requests_per_connection from Cluster or " - "HttpProtocolOptions can be specified"); + throwEnvoyExceptionOrPanic("Only one of max_requests_per_connection from Cluster or " + "HttpProtocolOptions can be specified"); } // If load_balancing_policy is set we will use it directly, ignoring lb_policy. @@ -1103,7 +1106,7 @@ ClusterInfoImpl::ClusterInfoImpl( config, server_context.messageValidationVisitor()); if (!lb_pair.ok()) { - throw EnvoyException(std::string(lb_pair.status().message())); + throwEnvoyExceptionOrPanic(std::string(lb_pair.status().message())); } load_balancer_config_ = std::move(lb_pair->config); @@ -1143,7 +1146,7 @@ ClusterInfoImpl::ClusterInfoImpl( break; case envoy::config::cluster::v3::Cluster::CLUSTER_PROVIDED: if (config.has_lb_subset_config()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("cluster: LB policy {} cannot be combined with lb_subset_config", envoy::config::cluster::v3::Cluster::LbPolicy_Name(config.lb_policy()))); } @@ -1161,9 +1164,9 @@ ClusterInfoImpl::ClusterInfoImpl( if (config.lb_subset_config().locality_weight_aware() && !config.common_lb_config().has_locality_weighted_lb_config()) { - throw EnvoyException(fmt::format("Locality weight aware subset LB requires that a " - "locality_weighted_lb_config be set in {}", - name_)); + throwEnvoyExceptionOrPanic(fmt::format("Locality weight aware subset LB requires that a " + "locality_weighted_lb_config be set in {}", + name_)); } // Use default (1h) or configured `idle_timeout`, unless it's set to 0, indicating that no @@ -1209,7 +1212,7 @@ ClusterInfoImpl::ClusterInfoImpl( if (config.has_eds_cluster_config()) { if (config.type() != envoy::config::cluster::v3::Cluster::EDS) { - throw EnvoyException("eds_cluster_config set in a non-EDS cluster"); + throwEnvoyExceptionOrPanic("eds_cluster_config set in a non-EDS cluster"); } } @@ -1229,7 +1232,7 @@ ClusterInfoImpl::ClusterInfoImpl( if (proto_config.has_config_discovery()) { if (proto_config.has_typed_config()) { - throw EnvoyException("Only one of typed_config or config_discovery can be used"); + throwEnvoyExceptionOrPanic("Only one of typed_config or config_discovery can be used"); } ENVOY_LOG(debug, " dynamic filter name: {}", proto_config.name()); @@ -1264,7 +1267,7 @@ ClusterInfoImpl::ClusterInfoImpl( envoy::extensions::filters::http::upstream_codec::v3::UpstreamCodec::default_instance()); } if (http_filters[http_filters.size() - 1].name() != "envoy.filters.http.upstream_codec") { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("The codec filter is the only valid terminal upstream filter")); } @@ -1283,18 +1286,19 @@ void ClusterInfoImpl::configureLbPolicies(const envoy::config::cluster::v3::Clus Server::Configuration::ServerFactoryContext& context) { // Check if load_balancing_policy is set first. if (!config.has_load_balancing_policy()) { - throw EnvoyException("cluster: field load_balancing_policy need to be set"); + throwEnvoyExceptionOrPanic("cluster: field load_balancing_policy need to be set"); } if (config.has_lb_subset_config()) { - throw EnvoyException("cluster: load_balancing_policy cannot be combined with lb_subset_config"); + throwEnvoyExceptionOrPanic( + "cluster: load_balancing_policy cannot be combined with lb_subset_config"); } if (config.has_common_lb_config()) { const auto& lb_config = config.common_lb_config(); if (lb_config.has_zone_aware_lb_config() || lb_config.has_locality_weighted_lb_config() || lb_config.has_consistent_hashing_lb_config()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "cluster: load_balancing_policy cannot be combined with partial fields " "(zone_aware_lb_config, " "locality_weighted_lb_config, consistent_hashing_lb_config) of common_lb_config"); @@ -1322,9 +1326,10 @@ void ClusterInfoImpl::configureLbPolicies(const envoy::config::cluster::v3::Clus } if (load_balancer_factory_ == nullptr) { - throw EnvoyException(fmt::format("cluster: didn't find a registered load balancer factory " - "implementation for cluster: '{}' with names from [{}]", - name_, absl::StrJoin(missing_policies, ", "))); + throwEnvoyExceptionOrPanic( + fmt::format("cluster: didn't find a registered load balancer factory " + "implementation for cluster: '{}' with names from [{}]", + name_, absl::StrJoin(missing_policies, ", "))); } lb_type_ = LoadBalancerType::LoadBalancingPolicyConfig; @@ -1458,13 +1463,13 @@ ClusterImplBase::ClusterImplBase(const envoy::config::cluster::v3::Cluster& clus if ((info_->features() & ClusterInfoImpl::Features::USE_ALPN)) { if (!raw_factory_pointer->supportsAlpn()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("ALPN configured for cluster {} which has a non-ALPN transport socket: {}", cluster.name(), cluster.DebugString())); } if (!matcher_supports_alpn && !runtime_.snapshot().featureEnabled(ClusterImplBase::DoNotValidateAlpnRuntimeKey, 0)) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "ALPN configured for cluster {} which has a non-ALPN transport socket matcher: {}", cluster.name(), cluster.DebugString())); } @@ -1473,12 +1478,12 @@ ClusterImplBase::ClusterImplBase(const envoy::config::cluster::v3::Cluster& clus if (info_->features() & ClusterInfoImpl::Features::HTTP3) { #if defined(ENVOY_ENABLE_QUIC) if (!validateTransportSocketSupportsQuic(cluster.transport_socket())) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("HTTP3 requires a QuicUpstreamTransport transport socket: {} {}", cluster.name(), cluster.transport_socket().DebugString())); } #else - throw EnvoyException("HTTP3 configured but not enabled in the build."); + throwEnvoyExceptionOrPanic("HTTP3 configured but not enabled in the build."); #endif } @@ -1683,9 +1688,10 @@ ClusterImplBase::resolveProtoAddress(const envoy::config::core::v3::Address& add CATCH(EnvoyException & e, { if (info_->type() == envoy::config::cluster::v3::Cluster::STATIC || info_->type() == envoy::config::cluster::v3::Cluster::EDS) { - throw EnvoyException(fmt::format("{}. Consider setting resolver_name or setting cluster type " - "to 'STRICT_DNS' or 'LOGICAL_DNS'", - e.what())); + throwEnvoyExceptionOrPanic( + fmt::format("{}. Consider setting resolver_name or setting cluster type " + "to 'STRICT_DNS' or 'LOGICAL_DNS'", + e.what())); } throw e; }); @@ -1694,7 +1700,7 @@ ClusterImplBase::resolveProtoAddress(const envoy::config::core::v3::Address& add void ClusterImplBase::validateEndpointsForZoneAwareRouting( const envoy::config::endpoint::v3::LocalityLbEndpoints& endpoints) const { if (local_cluster_ && endpoints.priority() > 0) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Unexpected non-zero priority for local cluster '{}'.", info()->name())); } } @@ -1882,7 +1888,7 @@ ClusterInfoImpl::ResourceManagers::load(const envoy::config::cluster::v3::Cluste if (per_host_it->has_max_pending_requests() || per_host_it->has_max_requests() || per_host_it->has_max_retries() || per_host_it->has_max_connection_pools() || per_host_it->has_retry_budget()) { - throw EnvoyException("Unsupported field in per_host_thresholds"); + throwEnvoyExceptionOrPanic("Unsupported field in per_host_thresholds"); } if (per_host_it->has_max_connections()) { max_connections_per_host = per_host_it->max_connections().value(); diff --git a/source/exe/stripped_main_base.cc b/source/exe/stripped_main_base.cc index 878e72a75735..ec3903cd93e5 100644 --- a/source/exe/stripped_main_base.cc +++ b/source/exe/stripped_main_base.cc @@ -136,7 +136,7 @@ void StrippedMainBase::configureHotRestarter(Random::RandomGenerator& random_gen } if (restarter == nullptr) { - throw EnvoyException("unable to select a dynamic base id"); + throwEnvoyExceptionOrPanic("unable to select a dynamic base id"); } restarter_.swap(restarter); diff --git a/source/extensions/common/dynamic_forward_proxy/dns_cache_manager_impl.cc b/source/extensions/common/dynamic_forward_proxy/dns_cache_manager_impl.cc index 037536e02db6..8e3bdf33bde2 100644 --- a/source/extensions/common/dynamic_forward_proxy/dns_cache_manager_impl.cc +++ b/source/extensions/common/dynamic_forward_proxy/dns_cache_manager_impl.cc @@ -19,7 +19,7 @@ DnsCacheSharedPtr DnsCacheManagerImpl::getCache( const auto& existing_cache = caches_.find(config.name()); if (existing_cache != caches_.end()) { if (!Protobuf::util::MessageDifferencer::Equivalent(config, existing_cache->second.config_)) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("config specified DNS cache '{}' with different settings", config.name())); } diff --git a/source/extensions/filters/http/composite/action.cc b/source/extensions/filters/http/composite/action.cc index 40fdbe1bf45f..670fa44b5f1f 100644 --- a/source/extensions/filters/http/composite/action.cc +++ b/source/extensions/filters/http/composite/action.cc @@ -37,7 +37,7 @@ Matcher::ActionFactoryCb ExecuteFilterActionFactory::createActionFactoryCb( } if (callback == nullptr) { - throw EnvoyException("Failed to get filter factory creation function"); + throwEnvoyExceptionOrPanic("Failed to get filter factory creation function"); } return [cb = std::move(callback)]() -> Matcher::ActionPtr { diff --git a/source/extensions/filters/http/compressor/config.cc b/source/extensions/filters/http/compressor/config.cc index 3b16724a5d66..e63d7affb93b 100644 --- a/source/extensions/filters/http/compressor/config.cc +++ b/source/extensions/filters/http/compressor/config.cc @@ -19,7 +19,7 @@ Http::FilterFactoryCb CompressorFilterFactory::createFilterFactoryFromProtoTyped Registry::FactoryRegistry< Compression::Compressor::NamedCompressorLibraryConfigFactory>::getFactoryByType(type); if (config_factory == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Didn't find a registered implementation for type: '{}'", type)); } ProtobufTypes::MessagePtr message = Config::Utility::translateAnyToFactoryConfig( diff --git a/source/extensions/filters/http/decompressor/config.cc b/source/extensions/filters/http/decompressor/config.cc index e15257c7d2e3..be5db4e868b4 100644 --- a/source/extensions/filters/http/decompressor/config.cc +++ b/source/extensions/filters/http/decompressor/config.cc @@ -20,8 +20,8 @@ Http::FilterFactoryCb DecompressorFilterFactory::createFilterFactoryFromProtoTyp Compression::Decompressor::NamedDecompressorLibraryConfigFactory>:: getFactoryByType(decompressor_library_type); if (decompressor_library_factory == nullptr) { - throw EnvoyException(fmt::format("Didn't find a registered implementation for type: '{}'", - decompressor_library_type)); + throwEnvoyExceptionOrPanic(fmt::format("Didn't find a registered implementation for type: '{}'", + decompressor_library_type)); } ProtobufTypes::MessagePtr message = Config::Utility::translateAnyToFactoryConfig( proto_config.decompressor_library().typed_config(), context.messageValidationVisitor(), diff --git a/source/extensions/filters/network/http_connection_manager/config.cc b/source/extensions/filters/network/http_connection_manager/config.cc index bf9e54ad3393..cb8b23c41d83 100644 --- a/source/extensions/filters/network/http_connection_manager/config.cc +++ b/source/extensions/filters/network/http_connection_manager/config.cc @@ -173,26 +173,26 @@ createHeaderValidatorFactory([[maybe_unused]] const envoy::extensions::filters:: auto* factory = Envoy::Config::Utility::getFactory( header_validator_config); if (!factory) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Header validator extension not found: '{}'", header_validator_config.name())); } header_validator_factory = factory->createFromProto(header_validator_config.typed_config(), context.getServerFactoryContext()); if (!header_validator_factory) { - throw EnvoyException(fmt::format("Header validator extension could not be created: '{}'", - header_validator_config.name())); + throwEnvoyExceptionOrPanic(fmt::format("Header validator extension could not be created: '{}'", + header_validator_config.name())); } #else if (config.has_typed_header_validation_config()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("This Envoy binary does not support header validator extensions.: '{}'", config.typed_header_validation_config().name())); } if (Runtime::runtimeFeatureEnabled( "envoy.reloadable_features.enable_universal_header_validator")) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Header validator can not be enabled since this Envoy binary does not support it."); } #endif @@ -403,7 +403,7 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( } if (config.strip_any_host_port() && config.strip_matching_host_port()) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "Error: Only one of `strip_matching_host_port` or `strip_any_host_port` can be set.")); } @@ -440,12 +440,12 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( extension->mutable_typed_config()->PackFrom(xff_config); } else { if (use_remote_address_) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Original IP detection extensions and use_remote_address may not be mixed"); } if (xff_num_trusted_hops_ > 0) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Original IP detection extensions and xff_num_trusted_hops may not be mixed"); } } @@ -455,14 +455,14 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( auto* factory = Envoy::Config::Utility::getFactory(extension_config); if (!factory) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Original IP detection extension not found: '{}'", extension_config.name())); } auto extension = factory->createExtension(extension_config.typed_config(), context_); if (!extension) { - throw EnvoyException(fmt::format("Original IP detection extension could not be created: '{}'", - extension_config.name())); + throwEnvoyExceptionOrPanic(fmt::format( + "Original IP detection extension could not be created: '{}'", extension_config.name())); } original_ip_detection_extensions_.push_back(extension); } @@ -473,14 +473,14 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( auto* factory = Envoy::Config::Utility::getFactory(extension_config); if (!factory) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Early header mutation extension not found: '{}'", extension_config.name())); } auto extension = factory->createExtension(extension_config.typed_config(), context_); if (!extension) { - throw EnvoyException(fmt::format("Early header mutation extension could not be created: '{}'", - extension_config.name())); + throwEnvoyExceptionOrPanic(fmt::format( + "Early header mutation extension could not be created: '{}'", extension_config.name())); } early_header_mutation_extensions_.push_back(std::move(extension)); } @@ -567,12 +567,12 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( if (config.has_access_log_options()) { if (config.flush_access_log_on_new_request() /* deprecated */) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Only one of flush_access_log_on_new_request or access_log_options can be specified."); } if (config.has_access_log_flush_interval()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Only one of access_log_flush_interval or access_log_options can be specified."); } @@ -625,15 +625,15 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig( #ifdef ENVOY_ENABLE_QUIC codec_type_ = CodecType::HTTP3; if (!context_.isQuicListener()) { - throw EnvoyException("HTTP/3 codec configured on non-QUIC listener."); + throwEnvoyExceptionOrPanic("HTTP/3 codec configured on non-QUIC listener."); } #else - throw EnvoyException("HTTP3 configured but not enabled in the build."); + throwEnvoyExceptionOrPanic("HTTP3 configured but not enabled in the build."); #endif break; } if (codec_type_ != CodecType::HTTP3 && context_.isQuicListener()) { - throw EnvoyException("Non-HTTP/3 codec configured on QUIC listener."); + throwEnvoyExceptionOrPanic("Non-HTTP/3 codec configured on QUIC listener."); } Http::FilterChainHelper contexts, bssl::UniquePtr list( PEM_X509_INFO_read_bio(bio.get(), nullptr, nullptr, nullptr)); if (list == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Failed to load trusted CA certificates from ", config_->caCertPath())); } @@ -101,7 +101,7 @@ int DefaultCertValidator::initializeSslContexts(std::vector contexts, } } if (ca_cert_ == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Failed to load trusted CA certificates from ", config_->caCertPath())); } if (has_crl) { @@ -128,7 +128,7 @@ int DefaultCertValidator::initializeSslContexts(std::vector contexts, bssl::UniquePtr list( PEM_X509_INFO_read_bio(bio.get(), nullptr, nullptr, nullptr)); if (list == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Failed to load CRL from ", config_->certificateRevocationListPath())); } @@ -155,7 +155,7 @@ int DefaultCertValidator::initializeSslContexts(std::vector contexts, cert_validation_config->subjectAltNameMatchers()) { auto san_matcher = createStringSanMatcher(matcher); if (san_matcher == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Failed to create string SAN matcher of type ", matcher.san_type())); } subject_alt_name_matchers_.push_back(std::move(san_matcher)); @@ -172,7 +172,7 @@ int DefaultCertValidator::initializeSslContexts(std::vector contexts, } const auto& decoded = Hex::decode(hash); if (decoded.size() != SHA256_DIGEST_LENGTH) { - throw EnvoyException(absl::StrCat("Invalid hex-encoded SHA-256 ", hash)); + throwEnvoyExceptionOrPanic(absl::StrCat("Invalid hex-encoded SHA-256 ", hash)); } verify_certificate_hash_list_.push_back(decoded); } @@ -183,7 +183,7 @@ int DefaultCertValidator::initializeSslContexts(std::vector contexts, for (const auto& hash : cert_validation_config->verifyCertificateSpkiList()) { const auto decoded = Base64::decode(hash); if (decoded.size() != SHA256_DIGEST_LENGTH) { - throw EnvoyException(absl::StrCat("Invalid base64-encoded SHA-256 ", hash)); + throwEnvoyExceptionOrPanic(absl::StrCat("Invalid base64-encoded SHA-256 ", hash)); } verify_certificate_spki_list_.emplace_back(decoded.begin(), decoded.end()); } @@ -501,8 +501,8 @@ void DefaultCertValidator::addClientValidationContext(SSL_CTX* ctx, bool require } X509_NAME* name = X509_get_subject_name(cert.get()); if (name == nullptr) { - throw EnvoyException(absl::StrCat("Failed to load trusted client CA certificates from ", - config_->caCertPath())); + throwEnvoyExceptionOrPanic(absl::StrCat("Failed to load trusted client CA certificates from ", + config_->caCertPath())); } // Check for duplicates. if (sk_X509_NAME_find(list.get(), nullptr, name)) { @@ -510,8 +510,8 @@ void DefaultCertValidator::addClientValidationContext(SSL_CTX* ctx, bool require } bssl::UniquePtr name_dup(X509_NAME_dup(name)); if (name_dup == nullptr || !sk_X509_NAME_push(list.get(), name_dup.release())) { - throw EnvoyException(absl::StrCat("Failed to load trusted client CA certificates from ", - config_->caCertPath())); + throwEnvoyExceptionOrPanic(absl::StrCat("Failed to load trusted client CA certificates from ", + config_->caCertPath())); } } @@ -520,7 +520,7 @@ void DefaultCertValidator::addClientValidationContext(SSL_CTX* ctx, bool require if (ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE) { ERR_clear_error(); } else { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Failed to load trusted client CA certificates from ", config_->caCertPath())); } SSL_CTX_set_client_CA_list(ctx, list.release()); diff --git a/source/extensions/transport_sockets/tls/context_config_impl.cc b/source/extensions/transport_sockets/tls/context_config_impl.cc index 2fdf9c5ba8ab..95eb9682e7ca 100644 --- a/source/extensions/transport_sockets/tls/context_config_impl.cc +++ b/source/extensions/transport_sockets/tls/context_config_impl.cc @@ -50,7 +50,8 @@ std::vector getTlsCertificateConf auto secret_provider = factory_context.secretManager().findStaticTlsCertificateProvider( sds_secret_config.name()); if (!secret_provider) { - throw EnvoyException(fmt::format("Unknown static secret: {}", sds_secret_config.name())); + throwEnvoyExceptionOrPanic( + fmt::format("Unknown static secret: {}", sds_secret_config.name())); } providers.push_back(secret_provider); } @@ -74,8 +75,8 @@ Secret::CertificateValidationContextConfigProviderSharedPtr getProviderFromSds( factory_context.secretManager().findStaticCertificateValidationContextProvider( sds_secret_config.name()); if (!secret_provider) { - throw EnvoyException(fmt::format("Unknown static certificate validation context: {}", - sds_secret_config.name())); + throwEnvoyExceptionOrPanic(fmt::format("Unknown static certificate validation context: {}", + sds_secret_config.name())); } return secret_provider; } @@ -133,7 +134,7 @@ Secret::TlsSessionTicketKeysConfigProviderSharedPtr getTlsSessionTicketKeysConfi factory_context.secretManager().findStaticTlsSessionTicketKeysContextProvider( sds_secret_config.name()); if (!secret_provider) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Unknown tls session ticket keys: {}", sds_secret_config.name())); } return secret_provider; @@ -145,8 +146,8 @@ Secret::TlsSessionTicketKeysConfigProviderSharedPtr getTlsSessionTicketKeysConfi SessionTicketKeysTypeCase::SESSION_TICKET_KEYS_TYPE_NOT_SET: return nullptr; default: - throw EnvoyException(fmt::format("Unexpected case for oneof session_ticket_keys: {}", - config.session_ticket_keys_type_case())); + throwEnvoyExceptionOrPanic(fmt::format("Unexpected case for oneof session_ticket_keys: {}", + config.session_ticket_keys_type_case())); } } @@ -211,7 +212,7 @@ ContextConfigImpl::ContextConfigImpl( auto config_or_status = Envoy::Ssl::CertificateValidationContextConfigImpl::create( *certificate_validation_context_provider_->secret(), api_); if (!config_or_status.status().ok()) { - throw EnvoyException(std::string(config_or_status.status().message())); + throwEnvoyExceptionOrPanic(std::string(config_or_status.status().message())); } validation_context_config_ = std::move(config_or_status.value()); } @@ -257,7 +258,7 @@ Ssl::CertificateValidationContextConfigPtr ContextConfigImpl::getCombinedValidat auto config_or_status = Envoy::Ssl::CertificateValidationContextConfigImpl::create(combined_cvc, api_); if (!config_or_status.status().ok()) { - throw EnvoyException(std::string(config_or_status.status().message())); + throwEnvoyExceptionOrPanic(std::string(config_or_status.status().message())); } return std::move(config_or_status.value()); } @@ -298,7 +299,7 @@ void ContextConfigImpl::setSecretUpdateCallback(std::function callback) auto config_or_status = Envoy::Ssl::CertificateValidationContextConfigImpl::create( *certificate_validation_context_provider_->secret(), api_); if (!config_or_status.status().ok()) { - throw EnvoyException(std::string(config_or_status.status().message())); + throwEnvoyExceptionOrPanic(std::string(config_or_status.status().message())); } validation_context_config_ = std::move(config_or_status.value()); callback(); @@ -362,12 +363,12 @@ ClientContextConfigImpl::ClientContextConfigImpl( // BoringSSL treats this as a C string, so embedded NULL characters will not // be handled correctly. if (server_name_indication_.find('\0') != std::string::npos) { - throw EnvoyException("SNI names containing NULL-byte are not allowed"); + throwEnvoyExceptionOrPanic("SNI names containing NULL-byte are not allowed"); } // TODO(PiotrSikora): Support multiple TLS certificates. if ((config.common_tls_context().tls_certificates().size() + config.common_tls_context().tls_certificate_sds_secret_configs().size()) > 1) { - throw EnvoyException("Multiple TLS certificates are not supported for client contexts"); + throwEnvoyExceptionOrPanic("Multiple TLS certificates are not supported for client contexts"); } } @@ -422,10 +423,11 @@ ServerContextConfigImpl::ServerContextConfigImpl( if (!capabilities().provides_certificates) { if ((config.common_tls_context().tls_certificates().size() + config.common_tls_context().tls_certificate_sds_secret_configs().size()) == 0) { - throw EnvoyException("No TLS certificates found for server context"); + throwEnvoyExceptionOrPanic("No TLS certificates found for server context"); } else if (!config.common_tls_context().tls_certificates().empty() && !config.common_tls_context().tls_certificate_sds_secret_configs().empty()) { - throw EnvoyException("SDS and non-SDS TLS certificates may not be mixed in server contexts"); + throwEnvoyExceptionOrPanic( + "SDS and non-SDS TLS certificates may not be mixed in server contexts"); } } @@ -468,9 +470,9 @@ ServerContextConfigImpl::getSessionTicketKey(const std::string& key_data) { static_assert(sizeof(SessionTicketKey) == 80, "Input is expected to be this size"); if (key_data.size() != sizeof(SessionTicketKey)) { - throw EnvoyException(fmt::format("Incorrect TLS session ticket key length. " - "Length {}, expected length {}.", - key_data.size(), sizeof(SessionTicketKey))); + throwEnvoyExceptionOrPanic(fmt::format("Incorrect TLS session ticket key length. " + "Length {}, expected length {}.", + key_data.size(), sizeof(SessionTicketKey))); } SessionTicketKey dst_key; diff --git a/source/extensions/transport_sockets/tls/context_impl.cc b/source/extensions/transport_sockets/tls/context_impl.cc index 4d7a7023a352..cc2680cb85ed 100644 --- a/source/extensions/transport_sockets/tls/context_impl.cc +++ b/source/extensions/transport_sockets/tls/context_impl.cc @@ -99,7 +99,7 @@ ContextImpl::ContextImpl(Stats::Scope& scope, const Envoy::Ssl::ContextConfig& c Registry::FactoryRegistry::getFactory(cert_validator_name); if (!cert_validator_factory) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Failed to get certificate validator factory for ", cert_validator_name)); } @@ -148,21 +148,23 @@ ContextImpl::ContextImpl(Stats::Scope& scope, const Envoy::Ssl::ContextConfig& c bad_ciphers.push_back(cipher_str); } } - throw EnvoyException(fmt::format("Failed to initialize cipher suites {}. The following " - "ciphers were rejected when tried individually: {}", - config.cipherSuites(), absl::StrJoin(bad_ciphers, ", "))); + throwEnvoyExceptionOrPanic(fmt::format("Failed to initialize cipher suites {}. The following " + "ciphers were rejected when tried individually: {}", + config.cipherSuites(), + absl::StrJoin(bad_ciphers, ", "))); } if (!capabilities_.provides_ciphers_and_curves && !SSL_CTX_set1_curves_list(ctx.ssl_ctx_.get(), config.ecdhCurves().c_str())) { - throw EnvoyException(absl::StrCat("Failed to initialize ECDH curves ", config.ecdhCurves())); + throwEnvoyExceptionOrPanic( + absl::StrCat("Failed to initialize ECDH curves ", config.ecdhCurves())); } // Set signature algorithms if given, otherwise fall back to BoringSSL defaults. if (!capabilities_.provides_sigalgs && !config.signatureAlgorithms().empty()) { if (!SSL_CTX_set1_sigalgs_list(ctx.ssl_ctx_.get(), config.signatureAlgorithms().c_str())) { - throw EnvoyException(absl::StrCat("Failed to initialize TLS signature algorithms ", - config.signatureAlgorithms())); + throwEnvoyExceptionOrPanic(absl::StrCat("Failed to initialize TLS signature algorithms ", + config.signatureAlgorithms())); } } } @@ -189,7 +191,7 @@ ContextImpl::ContextImpl(Stats::Scope& scope, const Envoy::Ssl::ContextConfig& c #ifdef BORINGSSL_FIPS if (!capabilities_.is_fips_compliant) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Can't load a FIPS noncompliant custom handshaker while running in FIPS compliant mode."); } #endif @@ -228,9 +230,10 @@ ContextImpl::ContextImpl(Stats::Scope& scope, const Envoy::Ssl::ContextConfig& c const EC_GROUP* ecdsa_group = EC_KEY_get0_group(ecdsa_public_key); if (ecdsa_group == nullptr || EC_GROUP_get_curve_name(ecdsa_group) != NID_X9_62_prime256v1) { - throw EnvoyException(fmt::format("Failed to load certificate chain from {}, only P-256 " - "ECDSA certificates are supported", - ctx.cert_chain_file_path_)); + throwEnvoyExceptionOrPanic( + fmt::format("Failed to load certificate chain from {}, only P-256 " + "ECDSA certificates are supported", + ctx.cert_chain_file_path_)); } ctx.is_ecdsa_ = true; } break; @@ -242,14 +245,14 @@ ContextImpl::ContextImpl(Stats::Scope& scope, const Envoy::Ssl::ContextConfig& c const unsigned rsa_key_length = RSA_bits(rsa_public_key); #ifdef BORINGSSL_FIPS if (rsa_key_length != 2048 && rsa_key_length != 3072 && rsa_key_length != 4096) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Failed to load certificate chain from {}, only RSA certificates with " "2048-bit, 3072-bit or 4096-bit keys are supported in FIPS mode", ctx.cert_chain_file_path_)); } #else if (rsa_key_length < 2048) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Failed to load certificate chain from {}, only RSA " "certificates with 2048-bit or larger keys are supported", ctx.cert_chain_file_path_)); @@ -258,9 +261,10 @@ ContextImpl::ContextImpl(Stats::Scope& scope, const Envoy::Ssl::ContextConfig& c } break; #ifdef BORINGSSL_FIPS default: - throw EnvoyException(fmt::format("Failed to load certificate chain from {}, only RSA and " - "ECDSA certificates are supported in FIPS mode", - ctx.cert_chain_file_path_)); + throwEnvoyExceptionOrPanic( + fmt::format("Failed to load certificate chain from {}, only RSA and " + "ECDSA certificates are supported in FIPS mode", + ctx.cert_chain_file_path_)); #endif } @@ -273,12 +277,12 @@ ContextImpl::ContextImpl(Stats::Scope& scope, const Envoy::Ssl::ContextConfig& c Ssl::BoringSslPrivateKeyMethodSharedPtr private_key_method = private_key_method_provider->getBoringSslPrivateKeyMethod(); if (private_key_method == nullptr) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Failed to get BoringSSL private key method from provider")); } #ifdef BORINGSSL_FIPS if (!ctx.private_key_method_provider_->checkFips()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Private key method doesn't support FIPS mode with current parameters")); } #endif @@ -431,7 +435,7 @@ std::vector ContextImpl::parseAlpnProtocols(const std::string& alpn_pro } if (alpn_protocols.size() >= 65535) { - throw EnvoyException("Invalid ALPN protocol string"); + throwEnvoyExceptionOrPanic("Invalid ALPN protocol string"); } std::vector out(alpn_protocols.size() + 1); @@ -439,7 +443,7 @@ std::vector ContextImpl::parseAlpnProtocols(const std::string& alpn_pro for (size_t i = 0; i <= alpn_protocols.size(); i++) { if (i == alpn_protocols.size() || alpn_protocols[i] == ',') { if (i - start > 255) { - throw EnvoyException("Invalid ALPN protocol string"); + throwEnvoyExceptionOrPanic("Invalid ALPN protocol string"); } out[start] = i - start; @@ -784,7 +788,7 @@ ServerContextImpl::ServerContextImpl(Stats::Scope& scope, ocsp_staple_policy_(config.ocspStaplePolicy()), full_scan_certs_on_sni_mismatch_(config.fullScanCertsOnSNIMismatch()) { if (config.tlsCertificates().empty() && !config.capabilities().provides_certificates) { - throw EnvoyException("Server TlsCertificates must have a certificate specified"); + throwEnvoyExceptionOrPanic("Server TlsCertificates must have a certificate specified"); } for (auto& ctx : tls_contexts_) { @@ -870,15 +874,15 @@ ServerContextImpl::ServerContextImpl(Stats::Scope& scope, auto& ocsp_resp_bytes = tls_certificates[i].get().ocspStaple(); if (ocsp_resp_bytes.empty()) { if (ctx.is_must_staple_) { - throw EnvoyException("OCSP response is required for must-staple certificate"); + throwEnvoyExceptionOrPanic("OCSP response is required for must-staple certificate"); } if (ocsp_staple_policy_ == Ssl::ServerContextConfig::OcspStaplePolicy::MustStaple) { - throw EnvoyException("Required OCSP response is missing from TLS context"); + throwEnvoyExceptionOrPanic("Required OCSP response is missing from TLS context"); } } else { auto response = std::make_unique(ocsp_resp_bytes, time_source_); if (!response->matchesCertificate(*ctx.cert_chain_)) { - throw EnvoyException("OCSP response does not match its TLS certificate"); + throwEnvoyExceptionOrPanic("OCSP response does not match its TLS certificate"); } ctx.ocsp_response_ = std::move(response); } @@ -971,7 +975,7 @@ ServerContextImpl::generateHashForSessionContextId(const std::vector(password.c_str()) : nullptr)); if (pkey == nullptr || !SSL_CTX_use_PrivateKey(ssl_ctx_.get(), pkey.get())) { - throw EnvoyException(fmt::format("Failed to load private key from {}, Cause: {}", data_path, - Utility::getLastCryptoError().value_or("unknown"))); + throwEnvoyExceptionOrPanic(fmt::format("Failed to load private key from {}, Cause: {}", + data_path, + Utility::getLastCryptoError().value_or("unknown"))); } checkPrivateKey(pkey, data_path); @@ -1458,7 +1463,7 @@ void TlsContext::loadPkcs12(const std::string& data, const std::string& data_pat !PKCS12_parse(pkcs12.get(), !password.empty() ? const_cast(password.c_str()) : nullptr, &temp_private_key, &temp_cert, &temp_ca_certs)) { logSslErrorChain(); - throw EnvoyException(absl::StrCat("Failed to load pkcs12 from ", data_path)); + throwEnvoyExceptionOrPanic(absl::StrCat("Failed to load pkcs12 from ", data_path)); } cert_chain_.reset(temp_cert); bssl::UniquePtr pkey(temp_private_key); @@ -1472,11 +1477,12 @@ void TlsContext::loadPkcs12(const std::string& data, const std::string& data_pat } if (!SSL_CTX_use_certificate(ssl_ctx_.get(), cert_chain_.get())) { logSslErrorChain(); - throw EnvoyException(absl::StrCat("Failed to load certificate from ", data_path)); + throwEnvoyExceptionOrPanic(absl::StrCat("Failed to load certificate from ", data_path)); } if (temp_private_key == nullptr || !SSL_CTX_use_PrivateKey(ssl_ctx_.get(), pkey.get())) { - throw EnvoyException(fmt::format("Failed to load private key from {}, Cause: {}", data_path, - Utility::getLastCryptoError().value_or("unknown"))); + throwEnvoyExceptionOrPanic(fmt::format("Failed to load private key from {}, Cause: {}", + data_path, + Utility::getLastCryptoError().value_or("unknown"))); } checkPrivateKey(pkey, data_path); @@ -1490,17 +1496,17 @@ void TlsContext::checkPrivateKey(const bssl::UniquePtr& pkey, case EVP_PKEY_EC: { const EC_KEY* ecdsa_private_key = EVP_PKEY_get0_EC_KEY(pkey.get()); if (!EC_KEY_check_fips(ecdsa_private_key)) { - throw EnvoyException(fmt::format("Failed to load private key from {}, ECDSA key failed " - "pairwise consistency test required in FIPS mode", - key_path)); + throwEnvoyExceptionOrPanic(fmt::format("Failed to load private key from {}, ECDSA key failed " + "pairwise consistency test required in FIPS mode", + key_path)); } } break; case EVP_PKEY_RSA: { RSA* rsa_private_key = EVP_PKEY_get0_RSA(pkey.get()); if (!RSA_check_fips(rsa_private_key)) { - throw EnvoyException(fmt::format("Failed to load private key from {}, RSA key failed " - "pairwise consistency test required in FIPS mode", - key_path)); + throwEnvoyExceptionOrPanic(fmt::format("Failed to load private key from {}, RSA key failed " + "pairwise consistency test required in FIPS mode", + key_path)); } } break; } diff --git a/source/extensions/transport_sockets/tls/ocsp/ocsp.cc b/source/extensions/transport_sockets/tls/ocsp/ocsp.cc index 76063188b7f7..bfa0ee6523d6 100644 --- a/source/extensions/transport_sockets/tls/ocsp/ocsp.cc +++ b/source/extensions/transport_sockets/tls/ocsp/ocsp.cc @@ -19,13 +19,13 @@ template T unwrap(ParsingResult res) { return absl::get<0>(res); } - throw EnvoyException(std::string(absl::get<1>(res))); + throwEnvoyExceptionOrPanic(std::string(absl::get<1>(res))); } unsigned parseTag(CBS& cbs) { unsigned tag; if (!CBS_get_any_asn1_element(&cbs, nullptr, &tag, nullptr)) { - throw EnvoyException("Failed to parse ASN.1 element tag"); + throwEnvoyExceptionOrPanic("Failed to parse ASN.1 element tag"); } return tag; } @@ -36,7 +36,7 @@ std::unique_ptr readDerEncodedOcspResponse(const std::vector der_response, Time time_source_(time_source) { if (response_->status_ != OcspResponseStatus::Successful) { - throw EnvoyException("OCSP response was unsuccessful"); + throwEnvoyExceptionOrPanic("OCSP response was unsuccessful"); } if (response_->response_ == nullptr) { - throw EnvoyException("OCSP response has no body"); + throwEnvoyExceptionOrPanic("OCSP response has no body"); } // We only permit a 1:1 of certificate to response. if (response_->response_->getNumCerts() != 1) { - throw EnvoyException("OCSP Response must be for one certificate only"); + throwEnvoyExceptionOrPanic("OCSP Response must be for one certificate only"); } auto& this_update = response_->response_->getThisUpdate(); @@ -160,7 +160,7 @@ std::unique_ptr Asn1OcspUtility::parseOcspResponse(CBS& cbs) { CBS elem; if (!CBS_get_asn1(&cbs, &elem, CBS_ASN1_SEQUENCE)) { - throw EnvoyException("OCSP Response is not a well-formed ASN.1 SEQUENCE"); + throwEnvoyExceptionOrPanic("OCSP Response is not a well-formed ASN.1 SEQUENCE"); } OcspResponseStatus status = Asn1OcspUtility::parseResponseStatus(elem); @@ -186,7 +186,7 @@ OcspResponseStatus Asn1OcspUtility::parseResponseStatus(CBS& cbs) { // } CBS status; if (!CBS_get_asn1(&cbs, &status, CBS_ASN1_ENUMERATED)) { - throw EnvoyException("OCSP ResponseStatus is not a well-formed ASN.1 ENUMERATED"); + throwEnvoyExceptionOrPanic("OCSP ResponseStatus is not a well-formed ASN.1 ENUMERATED"); } auto status_ordinal = *CBS_data(&status); @@ -204,7 +204,8 @@ OcspResponseStatus Asn1OcspUtility::parseResponseStatus(CBS& cbs) { case 6: return OcspResponseStatus::Unauthorized; default: - throw EnvoyException(absl::StrCat("Unknown OCSP Response Status variant: ", status_ordinal)); + throwEnvoyExceptionOrPanic( + absl::StrCat("Unknown OCSP Response Status variant: ", status_ordinal)); } } @@ -217,18 +218,18 @@ ResponsePtr Asn1OcspUtility::parseResponseBytes(CBS& cbs) { // } CBS elem, response; if (!CBS_get_asn1(&cbs, &elem, CBS_ASN1_SEQUENCE)) { - throw EnvoyException("OCSP ResponseBytes is not a well-formed SEQUENCE"); + throwEnvoyExceptionOrPanic("OCSP ResponseBytes is not a well-formed SEQUENCE"); } auto oid_str = unwrap(Asn1Utility::parseOid(elem)); if (!CBS_get_asn1(&elem, &response, CBS_ASN1_OCTETSTRING)) { - throw EnvoyException("Expected ASN.1 OCTETSTRING for response"); + throwEnvoyExceptionOrPanic("Expected ASN.1 OCTETSTRING for response"); } if (oid_str == BasicOcspResponse::OID) { return Asn1OcspUtility::parseBasicOcspResponse(response); } - throw EnvoyException(absl::StrCat("Unknown OCSP Response type with OID: ", oid_str)); + throwEnvoyExceptionOrPanic(absl::StrCat("Unknown OCSP Response type with OID: ", oid_str)); } std::unique_ptr Asn1OcspUtility::parseBasicOcspResponse(CBS& cbs) { @@ -242,7 +243,7 @@ std::unique_ptr Asn1OcspUtility::parseBasicOcspResponse(CBS& // } CBS elem; if (!CBS_get_asn1(&cbs, &elem, CBS_ASN1_SEQUENCE)) { - throw EnvoyException("OCSP BasicOCSPResponse is not a wellf-formed ASN.1 SEQUENCE"); + throwEnvoyExceptionOrPanic("OCSP BasicOCSPResponse is not a wellf-formed ASN.1 SEQUENCE"); } auto response_data = Asn1OcspUtility::parseResponseData(elem); // The `signatureAlgorithm` and `signature` are ignored because OCSP @@ -262,7 +263,7 @@ ResponseData Asn1OcspUtility::parseResponseData(CBS& cbs) { // } CBS elem; if (!CBS_get_asn1(&cbs, &elem, CBS_ASN1_SEQUENCE)) { - throw EnvoyException("OCSP ResponseData is not a well-formed ASN.1 SEQUENCE"); + throwEnvoyExceptionOrPanic("OCSP ResponseData is not a well-formed ASN.1 SEQUENCE"); } // only support v1, the value of v1 is 0x00 @@ -271,7 +272,8 @@ ResponseData Asn1OcspUtility::parseResponseData(CBS& cbs) { if (version_cbs.has_value()) { auto version = unwrap(Asn1Utility::parseInteger(*version_cbs)); if (version != "00") { - throw EnvoyException(fmt::format("OCSP ResponseData version 0x{} is not supported", version)); + throwEnvoyExceptionOrPanic( + fmt::format("OCSP ResponseData version 0x{} is not supported", version)); } } @@ -294,7 +296,7 @@ SingleResponse Asn1OcspUtility::parseSingleResponse(CBS& cbs) { // } CBS elem; if (!CBS_get_asn1(&cbs, &elem, CBS_ASN1_SEQUENCE)) { - throw EnvoyException("OCSP SingleResponse is not a well-formed ASN.1 SEQUENCE"); + throwEnvoyExceptionOrPanic("OCSP SingleResponse is not a well-formed ASN.1 SEQUENCE"); } auto cert_id = Asn1OcspUtility::parseCertId(elem); @@ -317,7 +319,7 @@ CertId Asn1OcspUtility::parseCertId(CBS& cbs) { // } CBS elem; if (!CBS_get_asn1(&cbs, &elem, CBS_ASN1_SEQUENCE)) { - throw EnvoyException("OCSP CertID is not a well-formed ASN.1 SEQUENCE"); + throwEnvoyExceptionOrPanic("OCSP CertID is not a well-formed ASN.1 SEQUENCE"); } unwrap(Asn1Utility::skip(elem, CBS_ASN1_SEQUENCE)); diff --git a/source/extensions/upstreams/http/config.cc b/source/extensions/upstreams/http/config.cc index 2d8a704e0a3e..a60a135e0e22 100644 --- a/source/extensions/upstreams/http/config.cc +++ b/source/extensions/upstreams/http/config.cc @@ -88,12 +88,13 @@ getAlternateProtocolsCacheOptions( Server::Configuration::ServerFactoryContext& server_context) { if (options.has_auto_config() && options.auto_config().has_http3_protocol_options()) { if (!options.auto_config().has_alternate_protocols_cache_options()) { - throw EnvoyException(fmt::format("alternate protocols cache must be configured when HTTP/3 " - "is enabled with auto_config")); + throwEnvoyExceptionOrPanic( + fmt::format("alternate protocols cache must be configured when HTTP/3 " + "is enabled with auto_config")); } auto cache_options = options.auto_config().alternate_protocols_cache_options(); if (cache_options.has_key_value_store_config() && server_context.options().concurrency() != 1) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("options has key value store but Envoy has concurrency = {} : {}", server_context.options().concurrency(), cache_options.DebugString())); } @@ -133,26 +134,26 @@ Envoy::Http::HeaderValidatorFactoryPtr createHeaderValidatorFactory( auto* factory = Envoy::Config::Utility::getFactory( header_validator_config); if (!factory) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Header validator extension not found: '{}'", header_validator_config.name())); } header_validator_factory = factory->createFromProto(header_validator_config.typed_config(), server_context); if (!header_validator_factory) { - throw EnvoyException(fmt::format("Header validator extension could not be created: '{}'", - header_validator_config.name())); + throwEnvoyExceptionOrPanic(fmt::format("Header validator extension could not be created: '{}'", + header_validator_config.name())); } #else if (options.has_header_validation_config()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("This Envoy binary does not support header validator extensions: '{}'", options.header_validation_config().name())); } if (Runtime::runtimeFeatureEnabled( "envoy.reloadable_features.enable_universal_header_validator")) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( "Header validator can not be enabled since this Envoy binary does not support it."); } #endif diff --git a/source/server/configuration_impl.cc b/source/server/configuration_impl.cc index dddbe09c77df..283a22125df1 100644 --- a/source/server/configuration_impl.cc +++ b/source/server/configuration_impl.cc @@ -86,7 +86,8 @@ StatsConfigImpl::StatsConfigImpl(const envoy::config::bootstrap::v3::Bootstrap& if (bootstrap.has_stats_flush_interval() && bootstrap.stats_flush_case() != envoy::config::bootstrap::v3::Bootstrap::STATS_FLUSH_NOT_SET) { - throw EnvoyException("Only one of stats_flush_interval or stats_flush_on_admin should be set!"); + throwEnvoyExceptionOrPanic( + "Only one of stats_flush_interval or stats_flush_on_admin should be set!"); } flush_interval_ = @@ -131,7 +132,7 @@ void MainImpl::initialize(const envoy::config::bootstrap::v3::Bootstrap& bootstr absl::StatusOr update_or_error = server.listenerManager().addOrUpdateListener(listeners[i], "", false); if (!update_or_error.status().ok()) { - throw EnvoyException(std::string(update_or_error.status().message())); + throwEnvoyExceptionOrPanic(std::string(update_or_error.status().message())); } } initializeWatchdogs(bootstrap, server); @@ -183,7 +184,7 @@ void MainImpl::initializeTracers(const envoy::config::trace::v3::Tracing& config void MainImpl::initializeWatchdogs(const envoy::config::bootstrap::v3::Bootstrap& bootstrap, Instance& server) { if (bootstrap.has_watchdog() && bootstrap.has_watchdogs()) { - throw EnvoyException("Only one of watchdog or watchdogs should be set!"); + throwEnvoyExceptionOrPanic("Only one of watchdog or watchdogs should be set!"); } if (bootstrap.has_watchdog()) { diff --git a/source/server/options_impl.cc b/source/server/options_impl.cc index 62268d2d84d7..abfda9fb2df6 100644 --- a/source/server/options_impl.cc +++ b/source/server/options_impl.cc @@ -32,6 +32,11 @@ std::vector toArgsVector(int argc, const char* const* argv) { } return args; } + +void throwMalformedArgExceptionOrPanic(std::string message) { + throwExceptionOrPanic(MalformedArgvException, message); +} + } // namespace OptionsImpl::OptionsImpl(int argc, const char* const* argv, @@ -179,7 +184,8 @@ OptionsImpl::OptionsImpl(std::vector args, } END_TRY MULTI_CATCH( - TCLAP::ArgException & e, { failure_function(e); }, { throw NoServingException(); }); + TCLAP::ArgException & e, { failure_function(e); }, + { throw NoServingException("NoServingException"); }); hot_restart_disabled_ = disable_hot_restart.getValue(); mutex_tracing_enabled_ = enable_mutex_tracing.getValue(); @@ -208,7 +214,7 @@ OptionsImpl::OptionsImpl(std::vector args, mode_ = Server::Mode::InitOnly; } else { const std::string message = fmt::format("error: unknown mode '{}'", mode.getValue()); - throw MalformedArgvException(message); + throwMalformedArgExceptionOrPanic(message); } if (local_address_ip_version.getValue() == "v4") { @@ -218,7 +224,7 @@ OptionsImpl::OptionsImpl(std::vector args, } else { const std::string message = fmt::format("error: unknown IP address version '{}'", local_address_ip_version.getValue()); - throw MalformedArgvException(message); + throwMalformedArgExceptionOrPanic(message); } base_id_ = base_id.getValue(); use_dynamic_base_id_ = use_dynamic_base_id.getValue(); @@ -228,7 +234,7 @@ OptionsImpl::OptionsImpl(std::vector args, if (use_dynamic_base_id_ && restart_epoch_ > 0) { const std::string message = fmt::format( "error: cannot use --restart-epoch={} with --use-dynamic-base-id", restart_epoch_); - throw MalformedArgvException(message); + throwMalformedArgExceptionOrPanic(message); } if (!concurrency.isSet() && cpuset_threads_) { @@ -269,8 +275,8 @@ OptionsImpl::OptionsImpl(std::vector args, } else { uint64_t socket_mode_helper; if (!StringUtil::atoull(socket_mode.getValue().c_str(), socket_mode_helper, 8)) { - throw MalformedArgvException( - fmt::format("error: invalid socket-mode '{}'", socket_mode.getValue())); + throwExceptionOrPanic(MalformedArgvException, + fmt::format("error: invalid socket-mode '{}'", socket_mode.getValue())); } socket_mode_ = socket_mode_helper; } @@ -280,13 +286,13 @@ OptionsImpl::OptionsImpl(std::vector args, } else if (drain_strategy.getValue() == "gradual") { drain_strategy_ = Server::DrainStrategy::Gradual; } else { - throw MalformedArgvException( - fmt::format("error: unknown drain-strategy '{}'", mode.getValue())); + throwExceptionOrPanic(MalformedArgvException, + fmt::format("error: unknown drain-strategy '{}'", mode.getValue())); } if (hot_restart_version_option.getValue()) { std::cerr << hot_restart_version_cb(!hot_restart_disabled_); - throw NoServingException(); + throwExceptionOrPanic(NoServingException, "NoServingException"); } if (!disable_extensions.getValue().empty()) { @@ -299,20 +305,22 @@ OptionsImpl::OptionsImpl(std::vector args, std::vector cli_tag_pair_tokens = absl::StrSplit(cli_tag_pair, absl::MaxSplits(':', 1)); if (cli_tag_pair_tokens.size() != 2) { - throw MalformedArgvException( - fmt::format("error: misformatted stats-tag '{}'", cli_tag_pair)); + throwExceptionOrPanic(MalformedArgvException, + fmt::format("error: misformatted stats-tag '{}'", cli_tag_pair)); } auto name = cli_tag_pair_tokens[0]; if (!Stats::TagUtility::isTagNameValid(name)) { - throw MalformedArgvException( + throwExceptionOrPanic( + MalformedArgvException, fmt::format("error: misformatted stats-tag '{}' contains invalid char in '{}'", cli_tag_pair, name)); } auto value = cli_tag_pair_tokens[1]; if (!Stats::TagUtility::isTagValueValid(value)) { - throw MalformedArgvException( + throwExceptionOrPanic( + MalformedArgvException, fmt::format("error: misformatted stats-tag '{}' contains invalid char in '{}'", cli_tag_pair, value)); } @@ -377,7 +385,7 @@ void OptionsImpl::parseComponentLogLevels(const std::string& component_log_level uint32_t OptionsImpl::count() const { return count_; } -void OptionsImpl::logError(const std::string& error) { throw MalformedArgvException(error); } +void OptionsImpl::logError(const std::string& error) { throwMalformedArgExceptionOrPanic(error); } Server::CommandLineOptionsPtr OptionsImpl::toCommandLineOptions() const { Server::CommandLineOptionsPtr command_line_options = diff --git a/source/server/options_impl.h b/source/server/options_impl.h index d02f37dce5bc..d9bb3b395d41 100644 --- a/source/server/options_impl.h +++ b/source/server/options_impl.h @@ -240,7 +240,7 @@ class OptionsImpl : public Server::Options, protected Logger::Loggable= saturated_threshold_) { - throw EnvoyException("scaling_threshold must be less than saturation_threshold"); + throwEnvoyExceptionOrPanic("scaling_threshold must be less than saturation_threshold"); } } @@ -90,7 +90,7 @@ TriggerPtr createTriggerFromConfig(const envoy::config::overload::v3::Trigger& t trigger = std::make_unique(trigger_config.scaled()); break; case envoy::config::overload::v3::Trigger::TriggerOneofCase::TRIGGER_ONEOF_NOT_SET: - throw EnvoyException(absl::StrCat("action not set for trigger ", trigger_config.name())); + throwEnvoyExceptionOrPanic(absl::StrCat("action not set for trigger ", trigger_config.name())); } return trigger; @@ -130,7 +130,7 @@ Event::ScaledTimerType parseTimerType( case Config::TRANSPORT_SOCKET_CONNECT: return Event::ScaledTimerType::TransportSocketConnectTimeout; default: - throw EnvoyException(fmt::format("Unknown timer type {}", config_timer_type)); + throwEnvoyExceptionOrPanic(fmt::format("Unknown timer type {}", config_timer_type)); } } @@ -156,8 +156,8 @@ parseTimerMinimums(const ProtobufWkt::Any& typed_config, auto [_, inserted] = timer_map.insert(std::make_pair(timer_type, minimum)); UNREFERENCED_PARAMETER(_); if (!inserted) { - throw EnvoyException(fmt::format("Found duplicate entry for timer type {}", - Config::TimerType_Name(scale_timer.timer()))); + throwEnvoyExceptionOrPanic(fmt::format("Found duplicate entry for timer type {}", + Config::TimerType_Name(scale_timer.timer()))); } } @@ -274,7 +274,7 @@ OverloadAction::OverloadAction(const envoy::config::overload::v3::OverloadAction for (const auto& trigger_config : config.triggers()) { if (!triggers_.try_emplace(trigger_config.name(), createTriggerFromConfig(trigger_config)) .second) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Duplicate trigger resource for overload action ", config.name())); } } @@ -321,7 +321,7 @@ LoadShedPointImpl::LoadShedPointImpl(const envoy::config::overload::v3::LoadShed for (const auto& trigger_config : config.triggers()) { if (!triggers_.try_emplace(trigger_config.name(), createTriggerFromConfig(trigger_config)) .second) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( absl::StrCat("Duplicate trigger resource for LoadShedPoint ", config.name())); } } @@ -410,7 +410,7 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S result = resources_.try_emplace(name, name, std::move(monitor), *this, stats_scope).second; } if (!result) { - throw EnvoyException(absl::StrCat("Duplicate resource monitor ", name)); + throwEnvoyExceptionOrPanic(absl::StrCat("Duplicate resource monitor ", name)); } } @@ -425,7 +425,7 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S auto& well_known_actions = OverloadActionNames::get().WellKnownActions; if (std::find(well_known_actions.begin(), well_known_actions.end(), name) == well_known_actions.end()) { - throw EnvoyException(absl::StrCat("Unknown Overload Manager Action ", name)); + throwEnvoyExceptionOrPanic(absl::StrCat("Unknown Overload Manager Action ", name)); } } @@ -436,7 +436,7 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S // an invalid free. auto result = actions_.try_emplace(symbol, OverloadAction(action, stats_scope)); if (!result.second) { - throw EnvoyException(absl::StrCat("Duplicate overload action ", name)); + throwEnvoyExceptionOrPanic(absl::StrCat("Duplicate overload action ", name)); } if (name == OverloadActionNames::get().ReduceTimeouts) { @@ -444,12 +444,12 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S parseTimerMinimums(action.typed_config(), validation_visitor)); } else if (name == OverloadActionNames::get().ResetStreams) { if (!config.has_buffer_factory_config()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Overload action \"{}\" requires buffer_factory_config.", name)); } makeCounter(api.rootScope(), OverloadActionStatsNames::get().ResetStreamsCount); } else if (action.has_typed_config()) { - throw EnvoyException(fmt::format( + throwEnvoyExceptionOrPanic(fmt::format( "Overload action \"{}\" has an unexpected value for the typed_config field", name)); } @@ -461,7 +461,7 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S if (resources_.find(resource) == resources_.end() && proactive_resource_it == OverloadProactiveResources::get().proactive_action_name_to_resource_.end()) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("Unknown trigger resource {} for overload action {}", resource, name)); } resource_to_actions_.insert(std::make_pair(resource, symbol)); @@ -472,8 +472,8 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S for (const auto& point : config.loadshed_points()) { for (const auto& trigger : point.triggers()) { if (!resources_.contains(trigger.name())) { - throw EnvoyException(fmt::format("Unknown trigger resource {} for loadshed point {}", - trigger.name(), point.name())); + throwEnvoyExceptionOrPanic(fmt::format("Unknown trigger resource {} for loadshed point {}", + trigger.name(), point.name())); } } @@ -482,7 +482,7 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S std::make_unique(point, api.rootScope(), api.randomGenerator())); if (!result.second) { - throw EnvoyException(absl::StrCat("Duplicate loadshed point ", point.name())); + throwEnvoyExceptionOrPanic(absl::StrCat("Duplicate loadshed point ", point.name())); } } } diff --git a/source/server/server.cc b/source/server/server.cc index 4da9bad71220..283f7e5147dd 100644 --- a/source/server/server.cc +++ b/source/server/server.cc @@ -339,8 +339,8 @@ void registerCustomInlineHeadersFromBootstrap( for (const auto& inline_header : bootstrap.inline_headers()) { const Http::LowerCaseString lower_case_name(inline_header.inline_header_name()); if (!canBeRegisteredAsInlineHeader(lower_case_name)) { - throw EnvoyException(fmt::format("Header {} cannot be registered as an inline header.", - inline_header.inline_header_name())); + throwEnvoyExceptionOrPanic(fmt::format("Header {} cannot be registered as an inline header.", + inline_header.inline_header_name())); } switch (inline_header.inline_header_type()) { case envoy::config::bootstrap::v3::CustomInlineHeader::REQUEST_HEADER: @@ -377,8 +377,9 @@ void InstanceUtil::loadBootstrapConfig(envoy::config::bootstrap::v3::Bootstrap& // One of config_path and config_yaml or bootstrap should be specified. if (config_path.empty() && config_yaml.empty() && config_proto.ByteSizeLong() == 0) { - throw EnvoyException("At least one of --config-path or --config-yaml or Options::configProto() " - "should be non-empty"); + throwEnvoyExceptionOrPanic( + "At least one of --config-path or --config-yaml or Options::configProto() " + "should be non-empty"); } if (!config_path.empty()) { @@ -386,7 +387,7 @@ void InstanceUtil::loadBootstrapConfig(envoy::config::bootstrap::v3::Bootstrap& MessageUtil::loadFromFile(config_path, bootstrap, validation_visitor, api); #else if (!config_path.empty()) { - throw EnvoyException("Cannot load from file with YAML disabled\n"); + throwEnvoyExceptionOrPanic("Cannot load from file with YAML disabled\n"); } UNREFERENCED_PARAMETER(api); #endif @@ -398,7 +399,7 @@ void InstanceUtil::loadBootstrapConfig(envoy::config::bootstrap::v3::Bootstrap& // TODO(snowp): The fact that we do a merge here doesn't seem to be covered under test. bootstrap.MergeFrom(bootstrap_override); #else - throw EnvoyException("Cannot load from YAML with YAML disabled\n"); + throwEnvoyExceptionOrPanic("Cannot load from YAML with YAML disabled\n"); #endif } if (config_proto.ByteSizeLong() != 0) { @@ -449,7 +450,7 @@ void InstanceImpl::initialize(Network::Address::InstanceConstSharedPtr local_add tracing_session_ = perfetto::Tracing::NewTrace(); tracing_fd_ = open(pftrace_path.c_str(), O_RDWR | O_CREAT | O_TRUNC, 0600); if (tracing_fd_ == -1) { - throw EnvoyException( + throwEnvoyExceptionOrPanic( fmt::format("unable to open tracing file {}: {}", pftrace_path, errorDetails(errno))); } // Configure the tracing session. @@ -516,7 +517,7 @@ void InstanceImpl::initialize(Network::Address::InstanceConstSharedPtr local_add version_int = bootstrap_.stats_server_version_override().value(); } else { if (!StringUtil::atoull(VersionInfo::revision().substr(0, 6).c_str(), version_int, 16)) { - throw EnvoyException("compiled GIT SHA is invalid. Invalid build."); + throwEnvoyExceptionOrPanic("compiled GIT SHA is invalid. Invalid build."); } } server_stats_->version_.set(version_int); @@ -691,7 +692,7 @@ void InstanceImpl::initialize(Network::Address::InstanceConstSharedPtr local_add if (initial_config.admin().address()) { if (!admin_) { - throw EnvoyException("Admin address configured but admin support compiled out"); + throwEnvoyExceptionOrPanic("Admin address configured but admin support compiled out"); } admin_->startHttpListener(initial_config.admin().accessLogs(), options_.adminAddressPath(), initial_config.admin().address(), diff --git a/source/server/ssl_context_manager.cc b/source/server/ssl_context_manager.cc index f2f086c7a7f7..d3b8df9d17f5 100644 --- a/source/server/ssl_context_manager.cc +++ b/source/server/ssl_context_manager.cc @@ -40,13 +40,13 @@ class SslContextManagerNoTlsStub final : public Envoy::Ssl::ContextManager { void removeContext(const Envoy::Ssl::ContextSharedPtr& old_context) override { if (old_context) { - throw EnvoyException("SSL is not supported in this configuration"); + throwEnvoyExceptionOrPanic("SSL is not supported in this configuration"); } } private: [[noreturn]] void throwException() { - throw EnvoyException("SSL is not supported in this configuration"); + throwEnvoyExceptionOrPanic("SSL is not supported in this configuration"); } };