diff --git a/mcrouter/CarbonRouterInstance-inl.h b/mcrouter/CarbonRouterInstance-inl.h index 4157bdedd..ccbd4f30b 100644 --- a/mcrouter/CarbonRouterInstance-inl.h +++ b/mcrouter/CarbonRouterInstance-inl.h @@ -18,6 +18,8 @@ #include #include +#include + #include "mcrouter/AsyncWriter.h" #include "mcrouter/CarbonRouterInstanceBase.h" #include "mcrouter/ExecutorObserver.h" @@ -127,7 +129,15 @@ CarbonRouterInstance* CarbonRouterInstance::createRaw( initFailureLogger(); } - auto router = new CarbonRouterInstance(std::move(input_options)); + // Deleter is only called if unique_ptr::get() returns non-null. + auto deleter = [](CarbonRouterInstance* inst) { + LOG_EVERY_MS(WARNING, 10000) << "Destroying CarbonRouterInstance"; + delete inst; + }; + auto router = + std::unique_ptr, decltype(deleter)>( + new CarbonRouterInstance(std::move(input_options)), + deleter); folly::Expected result; try { @@ -141,7 +151,7 @@ CarbonRouterInstance* CarbonRouterInstance::createRaw( result = router->spinUp(); if (result.hasValue()) { - return router; + return router.release(); } } catch (...) { result = folly::makeUnexpected( @@ -161,10 +171,20 @@ CarbonRouterInstance* CarbonRouterInstance::createRaw( // can be released. // We schedule the deletion on auxiliary thread pool // to avoid potential deadlock with the current thread. - auxThreadPool->add([router, auxThreadPool]() mutable { - router->resetMetadata(); - router->resetAxonProxyClientFactory(); - }); + auxThreadPool->add( + [router = std::move(router), + auxThreadPool, + deleteRouter = + input_options.delete_carbon_instance_upon_init_failure]() mutable { + router->resetMetadata(); + router->resetAxonProxyClientFactory(); + if (!deleteRouter) { + // Leak it. unique_ptr::get() is guaranteed to return nullptr after + // this. + router.release(); + } + // router gets destroyed here, unless configuration asks to leak it. + }); throw std::runtime_error(std::move(result.error())); } diff --git a/mcrouter/mcrouter_options_list.h b/mcrouter/mcrouter_options_list.h index 076d4f26b..bce29bb94 100644 --- a/mcrouter/mcrouter_options_list.h +++ b/mcrouter/mcrouter_options_list.h @@ -958,6 +958,13 @@ MCROUTER_OPTION_INTEGER( "Measure proxy CPU utilization every proxy_cpu_interval_s seconds. " "0 means disabled.") +MCROUTER_OPTION_TOGGLE( + delete_carbon_instance_upon_init_failure, + true, + "delete-carbon-instance-upon-init-failure", + no_short, + "Controls whether we delete the carbon instance upon failures or leak it") + #ifdef ADDITIONAL_OPTIONS_FILE #include ADDITIONAL_OPTIONS_FILE #endif