folly: Singleton: update doc to match new Strict vs Relaxed types
[folly.git] / folly / Singleton.h
1 /*
2  * Copyright 2015 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
17 // SingletonVault - a library to manage the creation and destruction
18 // of interdependent singletons.
19 //
20 // Basic usage of this class is very simple; suppose you have a class
21 // called MyExpensiveService, and you only want to construct one (ie,
22 // it's a singleton), but you only want to construct it if it is used.
23 //
24 // In your .h file:
25 // class MyExpensiveService { ... };
26 //
27 // In your .cpp file:
28 // namespace { folly::Singleton<MyExpensiveService> the_singleton; }
29 //
30 // Code can access it via:
31 //
32 // MyExpensiveService* instance = Singleton<MyExpensiveService>::get();
33 // or
34 // std::weak_ptr<MyExpensiveService> instance =
35 //     Singleton<MyExpensiveService>::get_weak();
36 //
37 // You also can directly access it by the variable defining the
38 // singleton rather than via get(), and even treat that variable like
39 // a smart pointer (dereferencing it or using the -> operator).
40 //
41 // Please note, however, that all non-weak_ptr interfaces are
42 // inherently subject to races with destruction.  Use responsibly.
43 //
44 // The singleton will be created on demand.  If the constructor for
45 // MyExpensiveService actually makes use of *another* Singleton, then
46 // the right thing will happen -- that other singleton will complete
47 // construction before get() returns.  However, in the event of a
48 // circular dependency, a runtime error will occur.
49 //
50 // You can have multiple singletons of the same underlying type, but
51 // each must be given a unique tag. If no tag is specified - default tag is used
52 //
53 // namespace {
54 // struct Tag1 {};
55 // struct Tag2 {};
56 // folly::Singleton<MyExpensiveService> s_default;
57 // folly::Singleton<MyExpensiveService, Tag1> s1;
58 // folly::Singleton<MyExpensiveService, Tag2> s2;
59 // }
60 // ...
61 // MyExpensiveService* svc_default = s_default.get();
62 // MyExpensiveService* svc1 = s1.get();
63 // MyExpensiveService* svc2 = s2.get();
64 //
65 // By default, the singleton instance is constructed via new and
66 // deleted via delete, but this is configurable:
67 //
68 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
69 //                                                                destroy); }
70 //
71 // Where create and destroy are functions, Singleton<T>::CreateFunc
72 // Singleton<T>::TeardownFunc.
73 //
74 // The above examples detail a situation where an expensive singleton is loaded
75 // on-demand (thus only if needed).  However if there is an expensive singleton
76 // that will likely be needed, and initialization takes a potentially long time,
77 // e.g. while initializing, parsing some files, talking to remote services,
78 // making uses of other singletons, and so on, the initialization of those can
79 // be scheduled up front, or "eagerly".
80 //
81 // In that case the singleton can be declared this way:
82 //
83 // namespace {
84 // auto the_singleton =
85 //     folly::Singleton<MyExpensiveService>(/* optional create, destroy args */)
86 //     .shouldEagerInit();
87 // }
88 //
89 // This way the singleton's instance is built at program initialization,
90 // if the program opted-in to that feature by calling "doEagerInit" or
91 // "doEagerInitVia" during its startup.
92 //
93 // What if you need to destroy all of your singletons?  Say, some of
94 // your singletons manage threads, but you need to fork?  Or your unit
95 // test wants to clean up all global state?  Then you can call
96 // SingletonVault::singleton()->destroyInstances(), which invokes the
97 // TeardownFunc for each singleton, in the reverse order they were
98 // created.  It is your responsibility to ensure your singletons can
99 // handle cases where the singletons they depend on go away, however.
100 // Singletons won't be recreated after destroyInstances call. If you
101 // want to re-enable singleton creation (say after fork was called) you
102 // should call reenableInstances.
103
104 #pragma once
105 #include <folly/Baton.h>
106 #include <folly/Exception.h>
107 #include <folly/Hash.h>
108 #include <folly/Memory.h>
109 #include <folly/RWSpinLock.h>
110 #include <folly/Demangle.h>
111 #include <folly/Executor.h>
112 #include <folly/futures/Future.h>
113 #include <folly/io/async/Request.h>
114
115 #include <algorithm>
116 #include <vector>
117 #include <mutex>
118 #include <thread>
119 #include <condition_variable>
120 #include <string>
121 #include <unordered_map>
122 #include <unordered_set>
123 #include <functional>
124 #include <typeinfo>
125 #include <typeindex>
126
127 #include <glog/logging.h>
128
129 // use this guard to handleSingleton breaking change in 3rd party code
130 #ifndef FOLLY_SINGLETON_TRY_GET
131 #define FOLLY_SINGLETON_TRY_GET
132 #endif
133
134 namespace folly {
135
136 // For actual usage, please see the Singleton<T> class at the bottom
137 // of this file; that is what you will actually interact with.
138
139 // SingletonVault is the class that manages singleton instances.  It
140 // is unaware of the underlying types of singletons, and simply
141 // manages lifecycles and invokes CreateFunc and TeardownFunc when
142 // appropriate.  In general, you won't need to interact with the
143 // SingletonVault itself.
144 //
145 // A vault goes through a few stages of life:
146 //
147 //   1. Registration phase; singletons can be registered:
148 //      a) Strict: no singleton can be created in this stage.
149 //      b) Relaxed: singleton can be created (the default vault is Relaxed).
150 //   2. registrationComplete() has been called; singletons can no
151 //      longer be registered, but they can be created.
152 //   3. A vault can return to stage 1 when destroyInstances is called.
153 //
154 // In general, you don't need to worry about any of the above; just
155 // ensure registrationComplete() is called near the top of your main()
156 // function, otherwise no singletons can be instantiated.
157
158 class SingletonVault;
159
160 namespace detail {
161
162 struct DefaultTag {};
163
164 // A TypeDescriptor is the unique handle for a given singleton.  It is
165 // a combinaiton of the type and of the optional name, and is used as
166 // a key in unordered_maps.
167 class TypeDescriptor {
168  public:
169   TypeDescriptor(const std::type_info& ti,
170                  const std::type_info& tag_ti)
171       : ti_(ti), tag_ti_(tag_ti) {
172   }
173
174   TypeDescriptor(const TypeDescriptor& other)
175       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
176   }
177
178   TypeDescriptor& operator=(const TypeDescriptor& other) {
179     if (this != &other) {
180       ti_ = other.ti_;
181       tag_ti_ = other.tag_ti_;
182     }
183
184     return *this;
185   }
186
187   std::string name() const {
188     auto ret = demangle(ti_.name());
189     if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
190       ret += "/";
191       ret += demangle(tag_ti_.name());
192     }
193     return ret.toStdString();
194   }
195
196   friend class TypeDescriptorHasher;
197
198   bool operator==(const TypeDescriptor& other) const {
199     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
200   }
201
202  private:
203   std::type_index ti_;
204   std::type_index tag_ti_;
205 };
206
207 class TypeDescriptorHasher {
208  public:
209   size_t operator()(const TypeDescriptor& ti) const {
210     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
211   }
212 };
213
214 // This interface is used by SingletonVault to interact with SingletonHolders.
215 // Having a non-template interface allows SingletonVault to keep a list of all
216 // SingletonHolders.
217 class SingletonHolderBase {
218  public:
219   virtual ~SingletonHolderBase() = default;
220
221   virtual TypeDescriptor type() = 0;
222   virtual bool hasLiveInstance() = 0;
223   virtual void createInstance() = 0;
224   virtual bool creationStarted() = 0;
225   virtual void destroyInstance() = 0;
226
227  protected:
228   static constexpr std::chrono::seconds kDestroyWaitTime{5};
229 };
230
231 // An actual instance of a singleton, tracking the instance itself,
232 // its state as described above, and the create and teardown
233 // functions.
234 template <typename T>
235 struct SingletonHolder : public SingletonHolderBase {
236  public:
237   typedef std::function<void(T*)> TeardownFunc;
238   typedef std::function<T*(void)> CreateFunc;
239
240   template <typename Tag, typename VaultTag>
241   inline static SingletonHolder<T>& singleton();
242
243   inline T* get();
244   inline std::weak_ptr<T> get_weak();
245
246   void registerSingleton(CreateFunc c, TeardownFunc t);
247   void registerSingletonMock(CreateFunc c, TeardownFunc t);
248   virtual TypeDescriptor type() override;
249   virtual bool hasLiveInstance() override;
250   virtual void createInstance() override;
251   virtual bool creationStarted() override;
252   virtual void destroyInstance() override;
253
254  private:
255   SingletonHolder(TypeDescriptor type, SingletonVault& vault);
256
257   enum class SingletonHolderState {
258     NotRegistered,
259     Dead,
260     Living,
261   };
262
263   TypeDescriptor type_;
264   SingletonVault& vault_;
265
266   // mutex protects the entire entry during construction/destruction
267   std::mutex mutex_;
268
269   // State of the singleton entry. If state is Living, instance_ptr and
270   // instance_weak can be safely accessed w/o synchronization.
271   std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
272
273   // the thread creating the singleton (only valid while creating an object)
274   std::atomic<std::thread::id> creating_thread_;
275
276   // The singleton itself and related functions.
277
278   // holds a shared_ptr to singleton instance, set when state is changed from
279   // Dead to Living. Reset when state is changed from Living to Dead.
280   std::shared_ptr<T> instance_;
281   // weak_ptr to the singleton instance, set when state is changed from Dead
282   // to Living. We never write to this object after initialization, so it is
283   // safe to read it from different threads w/o synchronization if we know
284   // that state is set to Living
285   std::weak_ptr<T> instance_weak_;
286   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
287   std::shared_ptr<folly::Baton<>> destroy_baton_;
288   T* instance_ptr_ = nullptr;
289   CreateFunc create_ = nullptr;
290   TeardownFunc teardown_ = nullptr;
291
292   std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
293
294   SingletonHolder(const SingletonHolder&) = delete;
295   SingletonHolder& operator=(const SingletonHolder&) = delete;
296   SingletonHolder& operator=(SingletonHolder&&) = delete;
297   SingletonHolder(SingletonHolder&&) = delete;
298 };
299
300 }
301
302 class SingletonVault {
303  public:
304   enum class Type {
305     Strict, // Singletons can't be created before registrationComplete()
306     Relaxed, // Singletons can be created before registrationComplete()
307   };
308
309   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
310
311   // Destructor is only called by unit tests to check destroyInstances.
312   ~SingletonVault();
313
314   typedef std::function<void(void*)> TeardownFunc;
315   typedef std::function<void*(void)> CreateFunc;
316
317   // Ensure that Singleton has not been registered previously and that
318   // registration is not complete. If validations succeeds,
319   // register a singleton of a given type with the create and teardown
320   // functions.
321   void registerSingleton(detail::SingletonHolderBase* entry) {
322     RWSpinLock::ReadHolder rh(&stateMutex_);
323
324     stateCheck(SingletonVaultState::Running);
325
326     if (UNLIKELY(registrationComplete_)) {
327       throw std::logic_error(
328         "Registering singleton after registrationComplete().");
329     }
330
331     RWSpinLock::ReadHolder rhMutex(&mutex_);
332     CHECK_THROW(singletons_.find(entry->type()) == singletons_.end(),
333                 std::logic_error);
334
335     RWSpinLock::UpgradedHolder wh(&mutex_);
336     singletons_[entry->type()] = entry;
337   }
338
339   /**
340    * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
341    * is built when `doEagerInit[Via]` is called; see those methods
342    * for more info.
343    */
344   void addEagerInitSingleton(detail::SingletonHolderBase* entry) {
345     RWSpinLock::ReadHolder rh(&stateMutex_);
346
347     stateCheck(SingletonVaultState::Running);
348
349     if (UNLIKELY(registrationComplete_)) {
350       throw std::logic_error(
351           "Registering for eager-load after registrationComplete().");
352     }
353
354     RWSpinLock::ReadHolder rhMutex(&mutex_);
355     CHECK_THROW(singletons_.find(entry->type()) != singletons_.end(),
356                 std::logic_error);
357
358     RWSpinLock::UpgradedHolder wh(&mutex_);
359     eagerInitSingletons_.insert(entry);
360   }
361
362   // Mark registration is complete; no more singletons can be
363   // registered at this point.
364   void registrationComplete() {
365     RequestContext::saveContext();
366     std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
367
368     RWSpinLock::WriteHolder wh(&stateMutex_);
369
370     stateCheck(SingletonVaultState::Running);
371
372     if (type_ == Type::Strict) {
373       for (const auto& p : singletons_) {
374         if (p.second->hasLiveInstance()) {
375           throw std::runtime_error(
376               "Singleton created before registration was complete.");
377         }
378       }
379     }
380
381     registrationComplete_ = true;
382   }
383
384   /**
385    * Initialize all singletons which were marked as eager-initialized
386    * (using `shouldEagerInit()`).  No return value.  Propagates exceptions
387    * from constructors / create functions, as is the usual case when calling
388    * for example `Singleton<Foo>::get_weak()`.
389    */
390   void doEagerInit() {
391     std::unordered_set<detail::SingletonHolderBase*> singletonSet;
392     {
393       RWSpinLock::ReadHolder rh(&stateMutex_);
394       stateCheck(SingletonVaultState::Running);
395       if (UNLIKELY(!registrationComplete_)) {
396         throw std::logic_error("registrationComplete() not yet called");
397       }
398       singletonSet = eagerInitSingletons_; // copy set of pointers
399     }
400
401     for (auto *single : singletonSet) {
402       single->createInstance();
403     }
404   }
405
406   /**
407    * Schedule eager singletons' initializations through the given executor.
408    * Return a future which is fulfilled after all the initialization functions
409    * complete.
410    */
411   Future<Unit> doEagerInitVia(Executor* exe) {
412     std::unordered_set<detail::SingletonHolderBase*> singletonSet;
413     {
414       RWSpinLock::ReadHolder rh(&stateMutex_);
415       stateCheck(SingletonVaultState::Running);
416       if (UNLIKELY(!registrationComplete_)) {
417         throw std::logic_error("registrationComplete() not yet called");
418       }
419       singletonSet = eagerInitSingletons_; // copy set of pointers
420     }
421
422     std::vector<Future<Unit>> resultFutures;
423     for (auto* single : singletonSet) {
424       resultFutures.emplace_back(via(exe).then([single] {
425         if (!single->creationStarted()) {
426           single->createInstance();
427         }
428       }));
429     }
430
431     return collectAll(resultFutures).via(exe).then();
432   }
433
434   // Destroy all singletons; when complete, the vault can't create
435   // singletons once again until reenableInstances() is called.
436   void destroyInstances();
437
438   // Enable re-creating singletons after destroyInstances() was called.
439   void reenableInstances();
440
441   // For testing; how many registered and living singletons we have.
442   size_t registeredSingletonCount() const {
443     RWSpinLock::ReadHolder rh(&mutex_);
444
445     return singletons_.size();
446   }
447
448   size_t livingSingletonCount() const {
449     RWSpinLock::ReadHolder rh(&mutex_);
450
451     size_t ret = 0;
452     for (const auto& p : singletons_) {
453       if (p.second->hasLiveInstance()) {
454         ++ret;
455       }
456     }
457
458     return ret;
459   }
460
461   // A well-known vault; you can actually have others, but this is the
462   // default.
463   static SingletonVault* singleton() {
464     return singleton<>();
465   }
466
467   // Gets singleton vault for any Tag. Non-default tag should be used in unit
468   // tests only.
469   template <typename VaultTag = detail::DefaultTag>
470   static SingletonVault* singleton() {
471     static SingletonVault* vault = new SingletonVault();
472     return vault;
473   }
474
475   typedef std::string(*StackTraceGetterPtr)();
476
477   static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
478     static std::atomic<StackTraceGetterPtr> stackTraceGetterPtr;
479     return stackTraceGetterPtr;
480   }
481
482  private:
483   template <typename T>
484   friend struct detail::SingletonHolder;
485
486   // The two stages of life for a vault, as mentioned in the class comment.
487   enum class SingletonVaultState {
488     Running,
489     Quiescing,
490   };
491
492   // Each singleton in the vault can be in two states: dead
493   // (registered but never created), living (CreateFunc returned an instance).
494
495   void stateCheck(SingletonVaultState expected,
496                   const char* msg="Unexpected singleton state change") {
497     if (expected != state_) {
498         throw std::logic_error(msg);
499     }
500   }
501
502   // This method only matters if registrationComplete() is never called.
503   // Otherwise destroyInstances is scheduled to be executed atexit.
504   //
505   // Initializes static object, which calls destroyInstances on destruction.
506   // Used to have better deletion ordering with singleton not managed by
507   // folly::Singleton. The desruction will happen in the following order:
508   // 1. Singletons, not managed by folly::Singleton, which were created after
509   //    any of the singletons managed by folly::Singleton was requested.
510   // 2. All singletons managed by folly::Singleton
511   // 3. Singletons, not managed by folly::Singleton, which were created before
512   //    any of the singletons managed by folly::Singleton was requested.
513   static void scheduleDestroyInstances();
514
515   typedef std::unordered_map<detail::TypeDescriptor,
516                              detail::SingletonHolderBase*,
517                              detail::TypeDescriptorHasher> SingletonMap;
518
519   mutable folly::RWSpinLock mutex_;
520   SingletonMap singletons_;
521   std::unordered_set<detail::SingletonHolderBase*> eagerInitSingletons_;
522   std::vector<detail::TypeDescriptor> creation_order_;
523   SingletonVaultState state_{SingletonVaultState::Running};
524   bool registrationComplete_{false};
525   folly::RWSpinLock stateMutex_;
526   Type type_{Type::Relaxed};
527 };
528
529 // This is the wrapper class that most users actually interact with.
530 // It allows for simple access to registering and instantiating
531 // singletons.  Create instances of this class in the global scope of
532 // type Singleton<T> to register your singleton for later access via
533 // Singleton<T>::try_get().
534 template <typename T,
535           typename Tag = detail::DefaultTag,
536           typename VaultTag = detail::DefaultTag /* for testing */>
537 class Singleton {
538  public:
539   typedef std::function<T*(void)> CreateFunc;
540   typedef std::function<void(T*)> TeardownFunc;
541
542   // Generally your program life cycle should be fine with calling
543   // get() repeatedly rather than saving the reference, and then not
544   // call get() during process shutdown.
545   static T* get() __attribute__ ((__deprecated__("Replaced by try_get"))) {
546     return getEntry().get();
547   }
548
549   // If, however, you do need to hold a reference to the specific
550   // singleton, you can try to do so with a weak_ptr.  Avoid this when
551   // possible but the inability to lock the weak pointer can be a
552   // signal that the vault has been destroyed.
553   static std::weak_ptr<T> get_weak() {
554     return getEntry().get_weak();
555   }
556
557   // Preferred alternative to get_weak, it returns shared_ptr that can be
558   // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
559   // Avoid holding these shared_ptrs beyond the scope of a function;
560   // don't put them in member variables, always use try_get() instead
561   static std::shared_ptr<T> try_get() {
562     auto ret = get_weak().lock();
563     if (!ret) {
564       LOG(DFATAL) <<
565         "folly::Singleton<" << getEntry().type().name() <<
566         ">::get_weak() called on destructed singleton; "
567         "returning nullptr, possible segfault coming";
568     }
569     return ret;
570   }
571
572   explicit Singleton(std::nullptr_t _ = nullptr,
573                      typename Singleton::TeardownFunc t = nullptr) :
574       Singleton ([]() { return new T; }, std::move(t)) {
575   }
576
577   explicit Singleton(typename Singleton::CreateFunc c,
578                      typename Singleton::TeardownFunc t = nullptr) {
579     if (c == nullptr) {
580       throw std::logic_error(
581         "nullptr_t should be passed if you want T to be default constructed");
582     }
583
584     auto vault = SingletonVault::singleton<VaultTag>();
585     getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
586     vault->registerSingleton(&getEntry());
587   }
588
589   /**
590    * Should be instantiated as soon as "doEagerInit[Via]" is called.
591    * Singletons are usually lazy-loaded (built on-demand) but for those which
592    * are known to be needed, to avoid the potential lag for objects that take
593    * long to construct during runtime, there is an option to make sure these
594    * are built up-front.
595    *
596    * Use like:
597    *   Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
598    *
599    * Or alternately, define the singleton as usual, and say
600    *   gFooInstance.shouldEagerInit();
601    *
602    * at some point prior to calling registrationComplete().
603    * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
604    */
605   Singleton& shouldEagerInit() {
606     auto vault = SingletonVault::singleton<VaultTag>();
607     vault->addEagerInitSingleton(&getEntry());
608     return *this;
609   }
610
611   /**
612   * Construct and inject a mock singleton which should be used only from tests.
613   * Unlike regular singletons which are initialized once per process lifetime,
614   * mock singletons live for the duration of a test. This means that one process
615   * running multiple tests can initialize and register the same singleton
616   * multiple times. This functionality should be used only from tests
617   * since it relaxes validation and performance in order to be able to perform
618   * the injection. The returned mock singleton is functionality identical to
619   * regular singletons.
620   */
621   static void make_mock(std::nullptr_t c = nullptr,
622                         typename Singleton<T>::TeardownFunc t = nullptr) {
623     make_mock([]() { return new T; }, t);
624   }
625
626   static void make_mock(CreateFunc c,
627                         typename Singleton<T>::TeardownFunc t = nullptr) {
628     if (c == nullptr) {
629       throw std::logic_error(
630         "nullptr_t should be passed if you want T to be default constructed");
631     }
632
633     auto& entry = getEntry();
634
635     entry.registerSingletonMock(c, getTeardownFunc(t));
636   }
637
638  private:
639   inline static detail::SingletonHolder<T>& getEntry() {
640     return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
641   }
642
643   // Construct TeardownFunc.
644   static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
645       TeardownFunc t)  {
646     if (t == nullptr) {
647       return  [](T* v) { delete v; };
648     } else {
649       return t;
650     }
651   }
652 };
653
654 }
655
656 #include <folly/Singleton-inl.h>