| 1 | /* |
| 2 | * Copyright 2014-present Facebook, Inc. |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | // SingletonVault - a library to manage the creation and destruction |
| 17 | // of interdependent singletons. |
| 18 | // |
| 19 | // Recommended usage of this class: suppose you have a class |
| 20 | // called MyExpensiveService, and you only want to construct one (ie, |
| 21 | // it's a singleton), but you only want to construct it if it is used. |
| 22 | // |
| 23 | // In your .h file: |
| 24 | // class MyExpensiveService { |
| 25 | // // Caution - may return a null ptr during startup and shutdown. |
| 26 | // static std::shared_ptr<MyExpensiveService> getInstance(); |
| 27 | // .... |
| 28 | // }; |
| 29 | // |
| 30 | // In your .cpp file: |
| 31 | // namespace { struct PrivateTag {}; } |
| 32 | // static folly::Singleton<MyExpensiveService, PrivateTag> the_singleton; |
| 33 | // std::shared_ptr<MyExpensiveService> MyExpensiveService::getInstance() { |
| 34 | // return the_singleton.try_get(); |
| 35 | // } |
| 36 | // |
| 37 | // Code in other modules can access it via: |
| 38 | // |
| 39 | // auto instance = MyExpensiveService::getInstance(); |
| 40 | // |
| 41 | // Advanced usage and notes: |
| 42 | // |
| 43 | // You can also access a singleton instance with |
| 44 | // `Singleton<ObjectType, TagType>::try_get()`. We recommend |
| 45 | // that you prefer the form `the_singleton.try_get()` because it ensures that |
| 46 | // `the_singleton` is used and cannot be garbage-collected during linking: this |
| 47 | // is necessary because the constructor of `the_singleton` is what registers it |
| 48 | // to the SingletonVault. |
| 49 | // |
| 50 | // The singleton will be created on demand. If the constructor for |
| 51 | // MyExpensiveService actually makes use of *another* Singleton, then |
| 52 | // the right thing will happen -- that other singleton will complete |
| 53 | // construction before get() returns. However, in the event of a |
| 54 | // circular dependency, a runtime error will occur. |
| 55 | // |
| 56 | // You can have multiple singletons of the same underlying type, but |
| 57 | // each must be given a unique tag. If no tag is specified a default tag is |
| 58 | // used. We recommend that you use a tag from an anonymous namespace private to |
| 59 | // your implementation file, as this ensures that the singleton is only |
| 60 | // available via your interface and not also through Singleton<T>::try_get() |
| 61 | // |
| 62 | // namespace { |
| 63 | // struct Tag1 {}; |
| 64 | // struct Tag2 {}; |
| 65 | // folly::Singleton<MyExpensiveService> s_default; |
| 66 | // folly::Singleton<MyExpensiveService, Tag1> s1; |
| 67 | // folly::Singleton<MyExpensiveService, Tag2> s2; |
| 68 | // } |
| 69 | // ... |
| 70 | // MyExpensiveService* svc_default = s_default.get(); |
| 71 | // MyExpensiveService* svc1 = s1.get(); |
| 72 | // MyExpensiveService* svc2 = s2.get(); |
| 73 | // |
| 74 | // By default, the singleton instance is constructed via new and |
| 75 | // deleted via delete, but this is configurable: |
| 76 | // |
| 77 | // namespace { folly::Singleton<MyExpensiveService> the_singleton(create, |
| 78 | // destroy); } |
| 79 | // |
| 80 | // Where create and destroy are functions, Singleton<T>::CreateFunc |
| 81 | // Singleton<T>::TeardownFunc. |
| 82 | // |
| 83 | // For example, if you need to pass arguments to your class's constructor: |
| 84 | // class X { |
| 85 | // public: |
| 86 | // X(int a1, std::string a2); |
| 87 | // // ... |
| 88 | // } |
| 89 | // Make your singleton like this: |
| 90 | // folly::Singleton<X> singleton_x([]() { return new X(42, "foo"); }); |
| 91 | // |
| 92 | // The above examples detail a situation where an expensive singleton is loaded |
| 93 | // on-demand (thus only if needed). However if there is an expensive singleton |
| 94 | // that will likely be needed, and initialization takes a potentially long time, |
| 95 | // e.g. while initializing, parsing some files, talking to remote services, |
| 96 | // making uses of other singletons, and so on, the initialization of those can |
| 97 | // be scheduled up front, or "eagerly". |
| 98 | // |
| 99 | // In that case the singleton can be declared this way: |
| 100 | // |
| 101 | // namespace { |
| 102 | // auto the_singleton = |
| 103 | // folly::Singleton<MyExpensiveService>(/* optional create, destroy args */) |
| 104 | // .shouldEagerInit(); |
| 105 | // } |
| 106 | // |
| 107 | // This way the singleton's instance is built at program initialization, |
| 108 | // if the program opted-in to that feature by calling "doEagerInit" or |
| 109 | // "doEagerInitVia" during its startup. |
| 110 | // |
| 111 | // What if you need to destroy all of your singletons? Say, some of |
| 112 | // your singletons manage threads, but you need to fork? Or your unit |
| 113 | // test wants to clean up all global state? Then you can call |
| 114 | // SingletonVault::singleton()->destroyInstances(), which invokes the |
| 115 | // TeardownFunc for each singleton, in the reverse order they were |
| 116 | // created. It is your responsibility to ensure your singletons can |
| 117 | // handle cases where the singletons they depend on go away, however. |
| 118 | // Singletons won't be recreated after destroyInstances call. If you |
| 119 | // want to re-enable singleton creation (say after fork was called) you |
| 120 | // should call reenableInstances. |
| 121 | |
| 122 | #pragma once |
| 123 | |
| 124 | #include <folly/Exception.h> |
| 125 | #include <folly/Executor.h> |
| 126 | #include <folly/Memory.h> |
| 127 | #include <folly/Synchronized.h> |
| 128 | #include <folly/detail/Singleton.h> |
| 129 | #include <folly/detail/StaticSingletonManager.h> |
| 130 | #include <folly/experimental/ReadMostlySharedPtr.h> |
| 131 | #include <folly/hash/Hash.h> |
| 132 | #include <folly/lang/Exception.h> |
| 133 | #include <folly/synchronization/Baton.h> |
| 134 | #include <folly/synchronization/RWSpinLock.h> |
| 135 | |
| 136 | #include <algorithm> |
| 137 | #include <atomic> |
| 138 | #include <condition_variable> |
| 139 | #include <functional> |
| 140 | #include <list> |
| 141 | #include <memory> |
| 142 | #include <mutex> |
| 143 | #include <string> |
| 144 | #include <thread> |
| 145 | #include <typeindex> |
| 146 | #include <typeinfo> |
| 147 | #include <unordered_map> |
| 148 | #include <unordered_set> |
| 149 | #include <vector> |
| 150 | |
| 151 | #include <glog/logging.h> |
| 152 | |
| 153 | // use this guard to handleSingleton breaking change in 3rd party code |
| 154 | #ifndef FOLLY_SINGLETON_TRY_GET |
| 155 | #define FOLLY_SINGLETON_TRY_GET |
| 156 | #endif |
| 157 | |
| 158 | namespace folly { |
| 159 | |
| 160 | // For actual usage, please see the Singleton<T> class at the bottom |
| 161 | // of this file; that is what you will actually interact with. |
| 162 | |
| 163 | // SingletonVault is the class that manages singleton instances. It |
| 164 | // is unaware of the underlying types of singletons, and simply |
| 165 | // manages lifecycles and invokes CreateFunc and TeardownFunc when |
| 166 | // appropriate. In general, you won't need to interact with the |
| 167 | // SingletonVault itself. |
| 168 | // |
| 169 | // A vault goes through a few stages of life: |
| 170 | // |
| 171 | // 1. Registration phase; singletons can be registered: |
| 172 | // a) Strict: no singleton can be created in this stage. |
| 173 | // b) Relaxed: singleton can be created (the default vault is Relaxed). |
| 174 | // 2. registrationComplete() has been called; singletons can no |
| 175 | // longer be registered, but they can be created. |
| 176 | // 3. A vault can return to stage 1 when destroyInstances is called. |
| 177 | // |
| 178 | // In general, you don't need to worry about any of the above; just |
| 179 | // ensure registrationComplete() is called near the top of your main() |
| 180 | // function, otherwise no singletons can be instantiated. |
| 181 | |
| 182 | class SingletonVault; |
| 183 | |
| 184 | namespace detail { |
| 185 | |
| 186 | // A TypeDescriptor is the unique handle for a given singleton. It is |
| 187 | // a combinaiton of the type and of the optional name, and is used as |
| 188 | // a key in unordered_maps. |
| 189 | class TypeDescriptor { |
| 190 | public: |
| 191 | TypeDescriptor(const std::type_info& ti, const std::type_info& tag_ti) |
| 192 | : ti_(ti), tag_ti_(tag_ti) {} |
| 193 | |
| 194 | TypeDescriptor(const TypeDescriptor& other) |
| 195 | : ti_(other.ti_), tag_ti_(other.tag_ti_) {} |
| 196 | |
| 197 | TypeDescriptor& operator=(const TypeDescriptor& other) { |
| 198 | if (this != &other) { |
| 199 | ti_ = other.ti_; |
| 200 | tag_ti_ = other.tag_ti_; |
| 201 | } |
| 202 | |
| 203 | return *this; |
| 204 | } |
| 205 | |
| 206 | std::string name() const; |
| 207 | |
| 208 | friend class TypeDescriptorHasher; |
| 209 | |
| 210 | bool operator==(const TypeDescriptor& other) const { |
| 211 | return ti_ == other.ti_ && tag_ti_ == other.tag_ti_; |
| 212 | } |
| 213 | |
| 214 | private: |
| 215 | std::type_index ti_; |
| 216 | std::type_index tag_ti_; |
| 217 | }; |
| 218 | |
| 219 | class TypeDescriptorHasher { |
| 220 | public: |
| 221 | size_t operator()(const TypeDescriptor& ti) const { |
| 222 | return folly::hash::hash_combine(ti.ti_, ti.tag_ti_); |
| 223 | } |
| 224 | }; |
| 225 | |
| 226 | [[noreturn]] void singletonWarnLeakyDoubleRegistrationAndAbort( |
| 227 | const TypeDescriptor& type); |
| 228 | |
| 229 | [[noreturn]] void singletonWarnLeakyInstantiatingNotRegisteredAndAbort( |
| 230 | const TypeDescriptor& type); |
| 231 | |
| 232 | [[noreturn]] void singletonWarnRegisterMockEarlyAndAbort( |
| 233 | const TypeDescriptor& type); |
| 234 | |
| 235 | void singletonWarnDestroyInstanceLeak( |
| 236 | const TypeDescriptor& type, |
| 237 | const void* ptr); |
| 238 | |
| 239 | [[noreturn]] void singletonWarnCreateCircularDependencyAndAbort( |
| 240 | const TypeDescriptor& type); |
| 241 | |
| 242 | [[noreturn]] void singletonWarnCreateUnregisteredAndAbort( |
| 243 | const TypeDescriptor& type); |
| 244 | |
| 245 | [[noreturn]] void singletonWarnCreateBeforeRegistrationCompleteAndAbort( |
| 246 | const TypeDescriptor& type); |
| 247 | |
| 248 | void singletonPrintDestructionStackTrace(const TypeDescriptor& type); |
| 249 | |
| 250 | [[noreturn]] void singletonThrowNullCreator(const std::type_info& type); |
| 251 | |
| 252 | [[noreturn]] void singletonThrowGetInvokedAfterDestruction( |
| 253 | const TypeDescriptor& type); |
| 254 | |
| 255 | struct SingletonVaultState { |
| 256 | // The two stages of life for a vault, as mentioned in the class comment. |
| 257 | enum class Type { |
| 258 | Running, |
| 259 | Quiescing, |
| 260 | }; |
| 261 | |
| 262 | Type state{Type::Running}; |
| 263 | bool registrationComplete{false}; |
| 264 | |
| 265 | // Each singleton in the vault can be in two states: dead |
| 266 | // (registered but never created), living (CreateFunc returned an instance). |
| 267 | |
| 268 | void check( |
| 269 | Type expected, |
| 270 | const char* msg = "Unexpected singleton state change" ) const { |
| 271 | if (expected != state) { |
| 272 | throw_exception<std::logic_error>(msg); |
| 273 | } |
| 274 | } |
| 275 | }; |
| 276 | |
| 277 | // This interface is used by SingletonVault to interact with SingletonHolders. |
| 278 | // Having a non-template interface allows SingletonVault to keep a list of all |
| 279 | // SingletonHolders. |
| 280 | class SingletonHolderBase { |
| 281 | public: |
| 282 | explicit SingletonHolderBase(TypeDescriptor typeDesc) : type_(typeDesc) {} |
| 283 | virtual ~SingletonHolderBase() = default; |
| 284 | |
| 285 | TypeDescriptor type() const { |
| 286 | return type_; |
| 287 | } |
| 288 | virtual bool hasLiveInstance() = 0; |
| 289 | virtual void createInstance() = 0; |
| 290 | virtual bool creationStarted() = 0; |
| 291 | virtual void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) = 0; |
| 292 | virtual void destroyInstance() = 0; |
| 293 | |
| 294 | private: |
| 295 | TypeDescriptor type_; |
| 296 | }; |
| 297 | |
| 298 | // An actual instance of a singleton, tracking the instance itself, |
| 299 | // its state as described above, and the create and teardown |
| 300 | // functions. |
| 301 | template <typename T> |
| 302 | struct SingletonHolder : public SingletonHolderBase { |
| 303 | public: |
| 304 | typedef std::function<void(T*)> TeardownFunc; |
| 305 | typedef std::function<T*(void)> CreateFunc; |
| 306 | |
| 307 | template <typename Tag, typename VaultTag> |
| 308 | inline static SingletonHolder<T>& singleton(); |
| 309 | |
| 310 | inline T* get(); |
| 311 | inline std::weak_ptr<T> get_weak(); |
| 312 | inline std::shared_ptr<T> try_get(); |
| 313 | inline folly::ReadMostlySharedPtr<T> try_get_fast(); |
| 314 | inline void vivify(); |
| 315 | |
| 316 | void registerSingleton(CreateFunc c, TeardownFunc t); |
| 317 | void registerSingletonMock(CreateFunc c, TeardownFunc t); |
| 318 | bool hasLiveInstance() override; |
| 319 | void createInstance() override; |
| 320 | bool creationStarted() override; |
| 321 | void preDestroyInstance(ReadMostlyMainPtrDeleter<>&) override; |
| 322 | void destroyInstance() override; |
| 323 | |
| 324 | private: |
| 325 | template <typename Tag, typename VaultTag> |
| 326 | struct Impl; |
| 327 | |
| 328 | SingletonHolder(TypeDescriptor type, SingletonVault& vault); |
| 329 | |
| 330 | enum class SingletonHolderState { |
| 331 | NotRegistered, |
| 332 | Dead, |
| 333 | Living, |
| 334 | }; |
| 335 | |
| 336 | SingletonVault& vault_; |
| 337 | |
| 338 | // mutex protects the entire entry during construction/destruction |
| 339 | std::mutex mutex_; |
| 340 | |
| 341 | // State of the singleton entry. If state is Living, instance_ptr and |
| 342 | // instance_weak can be safely accessed w/o synchronization. |
| 343 | std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered}; |
| 344 | |
| 345 | // the thread creating the singleton (only valid while creating an object) |
| 346 | std::atomic<std::thread::id> creating_thread_{}; |
| 347 | |
| 348 | // The singleton itself and related functions. |
| 349 | |
| 350 | // holds a ReadMostlyMainPtr to singleton instance, set when state is changed |
| 351 | // from Dead to Living. Reset when state is changed from Living to Dead. |
| 352 | folly::ReadMostlyMainPtr<T> instance_; |
| 353 | // used to release all ReadMostlyMainPtrs at once |
| 354 | folly::ReadMostlySharedPtr<T> instance_copy_; |
| 355 | // weak_ptr to the singleton instance, set when state is changed from Dead |
| 356 | // to Living. We never write to this object after initialization, so it is |
| 357 | // safe to read it from different threads w/o synchronization if we know |
| 358 | // that state is set to Living |
| 359 | std::weak_ptr<T> instance_weak_; |
| 360 | // Fast equivalent of instance_weak_ |
| 361 | folly::ReadMostlyWeakPtr<T> instance_weak_fast_; |
| 362 | // Time we wait on destroy_baton after releasing Singleton shared_ptr. |
| 363 | std::shared_ptr<folly::Baton<>> destroy_baton_; |
| 364 | T* instance_ptr_ = nullptr; |
| 365 | CreateFunc create_ = nullptr; |
| 366 | TeardownFunc teardown_ = nullptr; |
| 367 | |
| 368 | std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_; |
| 369 | |
| 370 | SingletonHolder(const SingletonHolder&) = delete; |
| 371 | SingletonHolder& operator=(const SingletonHolder&) = delete; |
| 372 | SingletonHolder& operator=(SingletonHolder&&) = delete; |
| 373 | SingletonHolder(SingletonHolder&&) = delete; |
| 374 | }; |
| 375 | |
| 376 | } // namespace detail |
| 377 | |
| 378 | class SingletonVault { |
| 379 | public: |
| 380 | enum class Type { |
| 381 | Strict, // Singletons can't be created before registrationComplete() |
| 382 | Relaxed, // Singletons can be created before registrationComplete() |
| 383 | }; |
| 384 | |
| 385 | /** |
| 386 | * Clears all singletons in the given vault at ctor and dtor times. |
| 387 | * Useful for unit-tests that need to clear the world. |
| 388 | * |
| 389 | * This need can arise when a unit-test needs to swap out an object used by a |
| 390 | * singleton for a test-double, but the singleton needing its dependency to be |
| 391 | * swapped has a type or a tag local to some other translation unit and |
| 392 | * unavailable in the current translation unit. |
| 393 | * |
| 394 | * Other, better approaches to this need are "plz 2 refactor" .... |
| 395 | */ |
| 396 | struct ScopedExpunger { |
| 397 | SingletonVault* vault; |
| 398 | explicit ScopedExpunger(SingletonVault* v) : vault(v) { |
| 399 | expunge(); |
| 400 | } |
| 401 | ~ScopedExpunger() { |
| 402 | expunge(); |
| 403 | } |
| 404 | void expunge() { |
| 405 | vault->destroyInstances(); |
| 406 | vault->reenableInstances(); |
| 407 | } |
| 408 | }; |
| 409 | |
| 410 | static Type defaultVaultType(); |
| 411 | |
| 412 | explicit SingletonVault(Type type = defaultVaultType()) : type_(type) {} |
| 413 | |
| 414 | // Destructor is only called by unit tests to check destroyInstances. |
| 415 | ~SingletonVault(); |
| 416 | |
| 417 | typedef std::function<void(void*)> TeardownFunc; |
| 418 | typedef std::function<void*(void)> CreateFunc; |
| 419 | |
| 420 | // Ensure that Singleton has not been registered previously and that |
| 421 | // registration is not complete. If validations succeeds, |
| 422 | // register a singleton of a given type with the create and teardown |
| 423 | // functions. |
| 424 | void registerSingleton(detail::SingletonHolderBase* entry); |
| 425 | |
| 426 | /** |
| 427 | * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance |
| 428 | * is built when `doEagerInit[Via]` is called; see those methods |
| 429 | * for more info. |
| 430 | */ |
| 431 | void addEagerInitSingleton(detail::SingletonHolderBase* entry); |
| 432 | |
| 433 | // Mark registration is complete; no more singletons can be |
| 434 | // registered at this point. |
| 435 | void registrationComplete(); |
| 436 | |
| 437 | /** |
| 438 | * Initialize all singletons which were marked as eager-initialized |
| 439 | * (using `shouldEagerInit()`). No return value. Propagates exceptions |
| 440 | * from constructors / create functions, as is the usual case when calling |
| 441 | * for example `Singleton<Foo>::get_weak()`. |
| 442 | */ |
| 443 | void doEagerInit(); |
| 444 | |
| 445 | /** |
| 446 | * Schedule eager singletons' initializations through the given executor. |
| 447 | * If baton ptr is not null, its `post` method is called after all |
| 448 | * early initialization has completed. |
| 449 | * |
| 450 | * If exceptions are thrown during initialization, this method will still |
| 451 | * `post` the baton to indicate completion. The exception will not propagate |
| 452 | * and future attempts to `try_get` or `get_weak` the failed singleton will |
| 453 | * retry initialization. |
| 454 | * |
| 455 | * Sample usage: |
| 456 | * |
| 457 | * folly::IOThreadPoolExecutor executor(max_concurrency_level); |
| 458 | * folly::Baton<> done; |
| 459 | * doEagerInitVia(executor, &done); |
| 460 | * done.wait(); // or 'try_wait_for', etc. |
| 461 | * |
| 462 | */ |
| 463 | void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr); |
| 464 | |
| 465 | // Destroy all singletons; when complete, the vault can't create |
| 466 | // singletons once again until reenableInstances() is called. |
| 467 | void destroyInstances(); |
| 468 | |
| 469 | // Enable re-creating singletons after destroyInstances() was called. |
| 470 | void reenableInstances(); |
| 471 | |
| 472 | // For testing; how many registered and living singletons we have. |
| 473 | size_t registeredSingletonCount() const { |
| 474 | return singletons_.rlock()->size(); |
| 475 | } |
| 476 | |
| 477 | /** |
| 478 | * Flips to true if eager initialization was used, and has completed. |
| 479 | * Never set to true if "doEagerInit()" or "doEagerInitVia" never called. |
| 480 | */ |
| 481 | bool eagerInitComplete() const; |
| 482 | |
| 483 | size_t livingSingletonCount() const { |
| 484 | auto singletons = singletons_.rlock(); |
| 485 | |
| 486 | size_t ret = 0; |
| 487 | for (const auto& p : *singletons) { |
| 488 | if (p.second->hasLiveInstance()) { |
| 489 | ++ret; |
| 490 | } |
| 491 | } |
| 492 | |
| 493 | return ret; |
| 494 | } |
| 495 | |
| 496 | // A well-known vault; you can actually have others, but this is the |
| 497 | // default. |
| 498 | static SingletonVault* singleton() { |
| 499 | return singleton<>(); |
| 500 | } |
| 501 | |
| 502 | // Gets singleton vault for any Tag. Non-default tag should be used in unit |
| 503 | // tests only. |
| 504 | template <typename VaultTag = detail::DefaultTag> |
| 505 | static SingletonVault* singleton() { |
| 506 | return &detail::createGlobal<SingletonVault, VaultTag>(); |
| 507 | } |
| 508 | |
| 509 | void setType(Type type) { |
| 510 | type_ = type; |
| 511 | } |
| 512 | |
| 513 | private: |
| 514 | template <typename T> |
| 515 | friend struct detail::SingletonHolder; |
| 516 | |
| 517 | // This method only matters if registrationComplete() is never called. |
| 518 | // Otherwise destroyInstances is scheduled to be executed atexit. |
| 519 | // |
| 520 | // Initializes static object, which calls destroyInstances on destruction. |
| 521 | // Used to have better deletion ordering with singleton not managed by |
| 522 | // folly::Singleton. The desruction will happen in the following order: |
| 523 | // 1. Singletons, not managed by folly::Singleton, which were created after |
| 524 | // any of the singletons managed by folly::Singleton was requested. |
| 525 | // 2. All singletons managed by folly::Singleton |
| 526 | // 3. Singletons, not managed by folly::Singleton, which were created before |
| 527 | // any of the singletons managed by folly::Singleton was requested. |
| 528 | static void scheduleDestroyInstances(); |
| 529 | |
| 530 | typedef std::unordered_map< |
| 531 | detail::TypeDescriptor, |
| 532 | detail::SingletonHolderBase*, |
| 533 | detail::TypeDescriptorHasher> |
| 534 | SingletonMap; |
| 535 | |
| 536 | // Use SharedMutexSuppressTSAN to suppress noisy lock inversions when building |
| 537 | // with TSAN. If TSAN is not enabled, SharedMutexSuppressTSAN is equivalent |
| 538 | // to a normal SharedMutex. |
| 539 | Synchronized<SingletonMap, SharedMutexSuppressTSAN> singletons_; |
| 540 | Synchronized< |
| 541 | std::unordered_set<detail::SingletonHolderBase*>, |
| 542 | SharedMutexSuppressTSAN> |
| 543 | eagerInitSingletons_; |
| 544 | Synchronized<std::vector<detail::TypeDescriptor>, SharedMutexSuppressTSAN> |
| 545 | creationOrder_; |
| 546 | |
| 547 | // Using SharedMutexReadPriority is important here, because we want to make |
| 548 | // sure we don't block nested singleton creation happening concurrently with |
| 549 | // destroyInstances(). |
| 550 | Synchronized<detail::SingletonVaultState, SharedMutexReadPriority> state_; |
| 551 | |
| 552 | Type type_; |
| 553 | }; |
| 554 | |
| 555 | // This is the wrapper class that most users actually interact with. |
| 556 | // It allows for simple access to registering and instantiating |
| 557 | // singletons. Create instances of this class in the global scope of |
| 558 | // type Singleton<T> to register your singleton for later access via |
| 559 | // Singleton<T>::try_get(). |
| 560 | template < |
| 561 | typename T, |
| 562 | typename Tag = detail::DefaultTag, |
| 563 | typename VaultTag = detail::DefaultTag /* for testing */> |
| 564 | class Singleton { |
| 565 | public: |
| 566 | typedef std::function<T*(void)> CreateFunc; |
| 567 | typedef std::function<void(T*)> TeardownFunc; |
| 568 | |
| 569 | // Generally your program life cycle should be fine with calling |
| 570 | // get() repeatedly rather than saving the reference, and then not |
| 571 | // call get() during process shutdown. |
| 572 | [[deprecated("Replaced by try_get" )]] static T* get() { |
| 573 | return getEntry().get(); |
| 574 | } |
| 575 | |
| 576 | // If, however, you do need to hold a reference to the specific |
| 577 | // singleton, you can try to do so with a weak_ptr. Avoid this when |
| 578 | // possible but the inability to lock the weak pointer can be a |
| 579 | // signal that the vault has been destroyed. |
| 580 | [[deprecated("Replaced by try_get" )]] static std::weak_ptr<T> get_weak() { |
| 581 | return getEntry().get_weak(); |
| 582 | } |
| 583 | |
| 584 | // Preferred alternative to get_weak, it returns shared_ptr that can be |
| 585 | // stored; a singleton won't be destroyed unless shared_ptr is destroyed. |
| 586 | // Avoid holding these shared_ptrs beyond the scope of a function; |
| 587 | // don't put them in member variables, always use try_get() instead |
| 588 | // |
| 589 | // try_get() can return nullptr if the singleton was destroyed, caller is |
| 590 | // responsible for handling nullptr return |
| 591 | static std::shared_ptr<T> try_get() { |
| 592 | return getEntry().try_get(); |
| 593 | } |
| 594 | |
| 595 | static folly::ReadMostlySharedPtr<T> try_get_fast() { |
| 596 | return getEntry().try_get_fast(); |
| 597 | } |
| 598 | |
| 599 | // Quickly ensure the instance exists. |
| 600 | static void vivify() { |
| 601 | getEntry().vivify(); |
| 602 | } |
| 603 | |
| 604 | explicit Singleton( |
| 605 | std::nullptr_t /* _ */ = nullptr, |
| 606 | typename Singleton::TeardownFunc t = nullptr) |
| 607 | : Singleton([]() { return new T; }, std::move(t)) {} |
| 608 | |
| 609 | explicit Singleton( |
| 610 | typename Singleton::CreateFunc c, |
| 611 | typename Singleton::TeardownFunc t = nullptr) { |
| 612 | if (c == nullptr) { |
| 613 | detail::singletonThrowNullCreator(typeid(T)); |
| 614 | } |
| 615 | |
| 616 | auto vault = SingletonVault::singleton<VaultTag>(); |
| 617 | getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t))); |
| 618 | vault->registerSingleton(&getEntry()); |
| 619 | } |
| 620 | |
| 621 | /** |
| 622 | * Should be instantiated as soon as "doEagerInit[Via]" is called. |
| 623 | * Singletons are usually lazy-loaded (built on-demand) but for those which |
| 624 | * are known to be needed, to avoid the potential lag for objects that take |
| 625 | * long to construct during runtime, there is an option to make sure these |
| 626 | * are built up-front. |
| 627 | * |
| 628 | * Use like: |
| 629 | * Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit(); |
| 630 | * |
| 631 | * Or alternately, define the singleton as usual, and say |
| 632 | * gFooInstance.shouldEagerInit(); |
| 633 | * |
| 634 | * at some point prior to calling registrationComplete(). |
| 635 | * Then doEagerInit() or doEagerInitVia(Executor*) can be called. |
| 636 | */ |
| 637 | Singleton& shouldEagerInit() { |
| 638 | auto vault = SingletonVault::singleton<VaultTag>(); |
| 639 | vault->addEagerInitSingleton(&getEntry()); |
| 640 | return *this; |
| 641 | } |
| 642 | |
| 643 | /** |
| 644 | * Construct and inject a mock singleton which should be used only from tests. |
| 645 | * Unlike regular singletons which are initialized once per process lifetime, |
| 646 | * mock singletons live for the duration of a test. This means that one |
| 647 | * process running multiple tests can initialize and register the same |
| 648 | * singleton multiple times. This functionality should be used only from tests |
| 649 | * since it relaxes validation and performance in order to be able to perform |
| 650 | * the injection. The returned mock singleton is functionality identical to |
| 651 | * regular singletons. |
| 652 | */ |
| 653 | static void make_mock( |
| 654 | std::nullptr_t /* c */ = nullptr, |
| 655 | typename Singleton<T>::TeardownFunc t = nullptr) { |
| 656 | make_mock([]() { return new T; }, t); |
| 657 | } |
| 658 | |
| 659 | static void make_mock( |
| 660 | CreateFunc c, |
| 661 | typename Singleton<T>::TeardownFunc t = nullptr) { |
| 662 | if (c == nullptr) { |
| 663 | detail::singletonThrowNullCreator(typeid(T)); |
| 664 | } |
| 665 | |
| 666 | auto& entry = getEntry(); |
| 667 | |
| 668 | entry.registerSingletonMock(c, getTeardownFunc(t)); |
| 669 | } |
| 670 | |
| 671 | private: |
| 672 | inline static detail::SingletonHolder<T>& getEntry() { |
| 673 | return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>(); |
| 674 | } |
| 675 | |
| 676 | // Construct TeardownFunc. |
| 677 | static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc( |
| 678 | TeardownFunc t) { |
| 679 | if (t == nullptr) { |
| 680 | return [](T* v) { delete v; }; |
| 681 | } else { |
| 682 | return t; |
| 683 | } |
| 684 | } |
| 685 | }; |
| 686 | |
| 687 | template <typename T, typename Tag = detail::DefaultTag> |
| 688 | class LeakySingleton { |
| 689 | public: |
| 690 | using CreateFunc = std::function<T*()>; |
| 691 | |
| 692 | LeakySingleton() : LeakySingleton([] { return new T(); }) {} |
| 693 | |
| 694 | explicit LeakySingleton(CreateFunc createFunc) { |
| 695 | auto& entry = entryInstance(); |
| 696 | if (entry.state != State::NotRegistered) { |
| 697 | detail::singletonWarnLeakyDoubleRegistrationAndAbort(entry.type_); |
| 698 | } |
| 699 | entry.createFunc = createFunc; |
| 700 | entry.state = State::Dead; |
| 701 | } |
| 702 | |
| 703 | static T& get() { |
| 704 | return instance(); |
| 705 | } |
| 706 | |
| 707 | static void make_mock(std::nullptr_t /* c */ = nullptr) { |
| 708 | make_mock([]() { return new T; }); |
| 709 | } |
| 710 | |
| 711 | static void make_mock(CreateFunc createFunc) { |
| 712 | if (createFunc == nullptr) { |
| 713 | detail::singletonThrowNullCreator(typeid(T)); |
| 714 | } |
| 715 | |
| 716 | auto& entry = entryInstance(); |
| 717 | if (entry.ptr) { |
| 718 | // Make sure existing pointer doesn't get reported as a leak by LSAN. |
| 719 | entry.leakedPtrs.push_back(std::exchange(entry.ptr, nullptr)); |
| 720 | } |
| 721 | entry.createFunc = createFunc; |
| 722 | entry.state = State::Dead; |
| 723 | } |
| 724 | |
| 725 | private: |
| 726 | enum class State { NotRegistered, Dead, Living }; |
| 727 | |
| 728 | struct Entry { |
| 729 | Entry() {} |
| 730 | Entry(const Entry&) = delete; |
| 731 | Entry& operator=(const Entry&) = delete; |
| 732 | |
| 733 | std::atomic<State> state{State::NotRegistered}; |
| 734 | T* ptr{nullptr}; |
| 735 | CreateFunc createFunc; |
| 736 | std::mutex mutex; |
| 737 | detail::TypeDescriptor type_{typeid(T), typeid(Tag)}; |
| 738 | std::list<T*> leakedPtrs; |
| 739 | }; |
| 740 | |
| 741 | static Entry& entryInstance() { |
| 742 | return detail::createGlobal<Entry, Tag>(); |
| 743 | } |
| 744 | |
| 745 | static T& instance() { |
| 746 | auto& entry = entryInstance(); |
| 747 | if (UNLIKELY(entry.state != State::Living)) { |
| 748 | createInstance(); |
| 749 | } |
| 750 | |
| 751 | return *entry.ptr; |
| 752 | } |
| 753 | |
| 754 | static void createInstance() { |
| 755 | auto& entry = entryInstance(); |
| 756 | |
| 757 | std::lock_guard<std::mutex> lg(entry.mutex); |
| 758 | if (entry.state == State::Living) { |
| 759 | return; |
| 760 | } |
| 761 | |
| 762 | if (entry.state == State::NotRegistered) { |
| 763 | detail::singletonWarnLeakyInstantiatingNotRegisteredAndAbort(entry.type_); |
| 764 | } |
| 765 | |
| 766 | entry.ptr = entry.createFunc(); |
| 767 | entry.state = State::Living; |
| 768 | } |
| 769 | }; |
| 770 | } // namespace folly |
| 771 | |
| 772 | #include <folly/Singleton-inl.h> |
| 773 | |