folly Singleton: "eager" option to initialize upfront
[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 // time, or more accurately, when "registrationComplete()" or
91 // "startEagerInit()" is called. (More about that below; see the
92 // section starting with "A vault goes through a few stages of life".)
93 //
94 // What if you need to destroy all of your singletons?  Say, some of
95 // your singletons manage threads, but you need to fork?  Or your unit
96 // test wants to clean up all global state?  Then you can call
97 // SingletonVault::singleton()->destroyInstances(), which invokes the
98 // TeardownFunc for each singleton, in the reverse order they were
99 // created.  It is your responsibility to ensure your singletons can
100 // handle cases where the singletons they depend on go away, however.
101 // Singletons won't be recreated after destroyInstances call. If you
102 // want to re-enable singleton creation (say after fork was called) you
103 // should call reenableInstances.
104
105 #pragma once
106 #include <folly/Baton.h>
107 #include <folly/Exception.h>
108 #include <folly/Hash.h>
109 #include <folly/Memory.h>
110 #include <folly/RWSpinLock.h>
111 #include <folly/Demangle.h>
112 #include <folly/Executor.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, but no
148 //      singleton can be created.
149 //   2. registrationComplete() has been called; singletons can no
150 //      longer be registered, but they can be created.
151 //   3. A vault can return to stage 1 when destroyInstances is called.
152 //
153 // In general, you don't need to worry about any of the above; just
154 // ensure registrationComplete() is called near the top of your main()
155 // function, otherwise no singletons can be instantiated.
156
157 class SingletonVault;
158
159 namespace detail {
160
161 struct DefaultTag {};
162
163 // A TypeDescriptor is the unique handle for a given singleton.  It is
164 // a combinaiton of the type and of the optional name, and is used as
165 // a key in unordered_maps.
166 class TypeDescriptor {
167  public:
168   TypeDescriptor(const std::type_info& ti,
169                  const std::type_info& tag_ti)
170       : ti_(ti), tag_ti_(tag_ti) {
171   }
172
173   TypeDescriptor(const TypeDescriptor& other)
174       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
175   }
176
177   TypeDescriptor& operator=(const TypeDescriptor& other) {
178     if (this != &other) {
179       ti_ = other.ti_;
180       tag_ti_ = other.tag_ti_;
181     }
182
183     return *this;
184   }
185
186   std::string name() const {
187     auto ret = demangle(ti_.name());
188     if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
189       ret += "/";
190       ret += demangle(tag_ti_.name());
191     }
192     return ret.toStdString();
193   }
194
195   friend class TypeDescriptorHasher;
196
197   bool operator==(const TypeDescriptor& other) const {
198     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
199   }
200
201  private:
202   std::type_index ti_;
203   std::type_index tag_ti_;
204 };
205
206 class TypeDescriptorHasher {
207  public:
208   size_t operator()(const TypeDescriptor& ti) const {
209     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
210   }
211 };
212
213 // This interface is used by SingletonVault to interact with SingletonHolders.
214 // Having a non-template interface allows SingletonVault to keep a list of all
215 // SingletonHolders.
216 class SingletonHolderBase {
217  public:
218   virtual ~SingletonHolderBase() = default;
219
220   virtual TypeDescriptor type() = 0;
221   virtual bool hasLiveInstance() = 0;
222   virtual void createInstance() = 0;
223   virtual bool creationStarted() = 0;
224   virtual void destroyInstance() = 0;
225
226  protected:
227   static constexpr std::chrono::seconds kDestroyWaitTime{5};
228 };
229
230 // An actual instance of a singleton, tracking the instance itself,
231 // its state as described above, and the create and teardown
232 // functions.
233 template <typename T>
234 struct SingletonHolder : public SingletonHolderBase {
235  public:
236   typedef std::function<void(T*)> TeardownFunc;
237   typedef std::function<T*(void)> CreateFunc;
238
239   template <typename Tag, typename VaultTag>
240   inline static SingletonHolder<T>& singleton();
241
242   inline T* get();
243   inline std::weak_ptr<T> get_weak();
244
245   void registerSingleton(CreateFunc c, TeardownFunc t);
246   void registerSingletonMock(CreateFunc c, TeardownFunc t);
247   virtual TypeDescriptor type() override;
248   virtual bool hasLiveInstance() override;
249   virtual void createInstance() override;
250   virtual bool creationStarted() override;
251   virtual void destroyInstance() override;
252
253  private:
254   SingletonHolder(TypeDescriptor type, SingletonVault& vault);
255
256   enum class SingletonHolderState {
257     NotRegistered,
258     Dead,
259     Living,
260   };
261
262   TypeDescriptor type_;
263   SingletonVault& vault_;
264
265   // mutex protects the entire entry during construction/destruction
266   std::mutex mutex_;
267
268   // State of the singleton entry. If state is Living, instance_ptr and
269   // instance_weak can be safely accessed w/o synchronization.
270   std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
271
272   // the thread creating the singleton (only valid while creating an object)
273   std::atomic<std::thread::id> creating_thread_;
274
275   // The singleton itself and related functions.
276
277   // holds a shared_ptr to singleton instance, set when state is changed from
278   // Dead to Living. Reset when state is changed from Living to Dead.
279   std::shared_ptr<T> instance_;
280   // weak_ptr to the singleton instance, set when state is changed from Dead
281   // to Living. We never write to this object after initialization, so it is
282   // safe to read it from different threads w/o synchronization if we know
283   // that state is set to Living
284   std::weak_ptr<T> instance_weak_;
285   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
286   std::shared_ptr<folly::Baton<>> destroy_baton_;
287   T* instance_ptr_ = nullptr;
288   CreateFunc create_ = nullptr;
289   TeardownFunc teardown_ = nullptr;
290
291   std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
292
293   SingletonHolder(const SingletonHolder&) = delete;
294   SingletonHolder& operator=(const SingletonHolder&) = delete;
295   SingletonHolder& operator=(SingletonHolder&&) = delete;
296   SingletonHolder(SingletonHolder&&) = delete;
297 };
298
299 }
300
301 class SingletonVault {
302  public:
303   enum class Type { Strict, Relaxed };
304
305   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
306
307   // Destructor is only called by unit tests to check destroyInstances.
308   ~SingletonVault();
309
310   typedef std::function<void(void*)> TeardownFunc;
311   typedef std::function<void*(void)> CreateFunc;
312
313   // Ensure that Singleton has not been registered previously and that
314   // registration is not complete. If validations succeeds,
315   // register a singleton of a given type with the create and teardown
316   // functions.
317   void registerSingleton(detail::SingletonHolderBase* entry) {
318     RWSpinLock::ReadHolder rh(&stateMutex_);
319
320     stateCheck(SingletonVaultState::Running);
321
322     if (UNLIKELY(registrationComplete_)) {
323       throw std::logic_error(
324         "Registering singleton after registrationComplete().");
325     }
326
327     RWSpinLock::ReadHolder rhMutex(&mutex_);
328     CHECK_THROW(singletons_.find(entry->type()) == singletons_.end(),
329                 std::logic_error);
330
331     RWSpinLock::UpgradedHolder wh(&mutex_);
332     singletons_[entry->type()] = entry;
333   }
334
335   /**
336    * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
337    * is built when registrationComplete() is called; see that method
338    * for more info.
339    */
340   void addEagerInitSingleton(detail::SingletonHolderBase* entry) {
341     RWSpinLock::ReadHolder rh(&stateMutex_);
342
343     stateCheck(SingletonVaultState::Running);
344
345     if (UNLIKELY(registrationComplete_)) {
346       throw std::logic_error(
347         "Registering for eager-load after registrationComplete().");
348     }
349
350     RWSpinLock::ReadHolder rhMutex(&mutex_);
351     CHECK_THROW(singletons_.find(entry->type()) != singletons_.end(),
352                 std::logic_error);
353
354     RWSpinLock::UpgradedHolder wh(&mutex_);
355     eagerInitSingletons_.insert(entry);
356   }
357
358   // Mark registration is complete; no more singletons can be
359   // registered at this point.  Kicks off eagerly-initialized singletons
360   // (if requested; default behavior is to do so).
361   void registrationComplete(bool autoStartEagerInit = true) {
362     RequestContext::saveContext();
363     std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
364
365     {
366       RWSpinLock::WriteHolder wh(&stateMutex_);
367
368       stateCheck(SingletonVaultState::Running);
369
370       if (type_ == Type::Strict) {
371         for (const auto& p: singletons_) {
372           if (p.second->hasLiveInstance()) {
373             throw std::runtime_error(
374               "Singleton created before registration was complete.");
375           }
376         }
377       }
378
379       registrationComplete_ = true;
380     }
381
382     if (autoStartEagerInit) {
383       startEagerInit();
384     }
385   }
386
387  /**
388   * If eagerInitExecutor_ is non-nullptr (default is nullptr) then
389   * schedule eager singletons' initializations through it.
390   * Otherwise, initializes them synchronously, in a loop.
391   */
392   void startEagerInit() {
393     std::unordered_set<detail::SingletonHolderBase*> singletonSet;
394     {
395       RWSpinLock::ReadHolder rh(&stateMutex_);
396       stateCheck(SingletonVaultState::Running);
397       if (UNLIKELY(!registrationComplete_)) {
398         throw std::logic_error(
399           "registrationComplete() not yet called");
400       }
401       singletonSet = eagerInitSingletons_;  // copy set of pointers
402     }
403
404     auto *exe = eagerInitExecutor_;  // default value is nullptr
405     for (auto *single : singletonSet) {
406       if (exe) {
407         eagerInitExecutor_->add([single] {
408           if (!single->creationStarted()) {
409             single->createInstance();
410           }
411         });
412       } else {
413         single->createInstance();
414       }
415     }
416   }
417
418   /**
419    * Provide an executor through which startEagerInit would run tasks.
420    * If there are several singletons which may be independently initialized,
421    * and their construction takes long, they could possibly be run in parallel
422    * to cut down on startup time.  Unusual; default (synchronous initialization
423    * in a loop) is probably fine for most use cases, and most apps can most
424    * likely avoid using this.
425    */
426   void setEagerInitExecutor(folly::Executor *exe) {
427     eagerInitExecutor_ = exe;
428   }
429
430   // Destroy all singletons; when complete, the vault can't create
431   // singletons once again until reenableInstances() is called.
432   void destroyInstances();
433
434   // Enable re-creating singletons after destroyInstances() was called.
435   void reenableInstances();
436
437   // For testing; how many registered and living singletons we have.
438   size_t registeredSingletonCount() const {
439     RWSpinLock::ReadHolder rh(&mutex_);
440
441     return singletons_.size();
442   }
443
444   size_t livingSingletonCount() const {
445     RWSpinLock::ReadHolder rh(&mutex_);
446
447     size_t ret = 0;
448     for (const auto& p : singletons_) {
449       if (p.second->hasLiveInstance()) {
450         ++ret;
451       }
452     }
453
454     return ret;
455   }
456
457   // A well-known vault; you can actually have others, but this is the
458   // default.
459   static SingletonVault* singleton() {
460     return singleton<>();
461   }
462
463   // Gets singleton vault for any Tag. Non-default tag should be used in unit
464   // tests only.
465   template <typename VaultTag = detail::DefaultTag>
466   static SingletonVault* singleton() {
467     static SingletonVault* vault = new SingletonVault();
468     return vault;
469   }
470
471   typedef std::string(*StackTraceGetterPtr)();
472
473   static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
474     static std::atomic<StackTraceGetterPtr> stackTraceGetterPtr;
475     return stackTraceGetterPtr;
476   }
477
478  private:
479   template <typename T>
480   friend struct detail::SingletonHolder;
481
482   // The two stages of life for a vault, as mentioned in the class comment.
483   enum class SingletonVaultState {
484     Running,
485     Quiescing,
486   };
487
488   // Each singleton in the vault can be in two states: dead
489   // (registered but never created), living (CreateFunc returned an instance).
490
491   void stateCheck(SingletonVaultState expected,
492                   const char* msg="Unexpected singleton state change") {
493     if (expected != state_) {
494         throw std::logic_error(msg);
495     }
496   }
497
498   // This method only matters if registrationComplete() is never called.
499   // Otherwise destroyInstances is scheduled to be executed atexit.
500   //
501   // Initializes static object, which calls destroyInstances on destruction.
502   // Used to have better deletion ordering with singleton not managed by
503   // folly::Singleton. The desruction will happen in the following order:
504   // 1. Singletons, not managed by folly::Singleton, which were created after
505   //    any of the singletons managed by folly::Singleton was requested.
506   // 2. All singletons managed by folly::Singleton
507   // 3. Singletons, not managed by folly::Singleton, which were created before
508   //    any of the singletons managed by folly::Singleton was requested.
509   static void scheduleDestroyInstances();
510
511   typedef std::unordered_map<detail::TypeDescriptor,
512                              detail::SingletonHolderBase*,
513                              detail::TypeDescriptorHasher> SingletonMap;
514
515   mutable folly::RWSpinLock mutex_;
516   SingletonMap singletons_;
517   std::unordered_set<detail::SingletonHolderBase*> eagerInitSingletons_;
518   folly::Executor* eagerInitExecutor_{nullptr};
519   std::vector<detail::TypeDescriptor> creation_order_;
520   SingletonVaultState state_{SingletonVaultState::Running};
521   bool registrationComplete_{false};
522   folly::RWSpinLock stateMutex_;
523   Type type_{Type::Relaxed};
524 };
525
526 // This is the wrapper class that most users actually interact with.
527 // It allows for simple access to registering and instantiating
528 // singletons.  Create instances of this class in the global scope of
529 // type Singleton<T> to register your singleton for later access via
530 // Singleton<T>::try_get().
531 template <typename T,
532           typename Tag = detail::DefaultTag,
533           typename VaultTag = detail::DefaultTag /* for testing */>
534 class Singleton {
535  public:
536   typedef std::function<T*(void)> CreateFunc;
537   typedef std::function<void(T*)> TeardownFunc;
538
539   // Generally your program life cycle should be fine with calling
540   // get() repeatedly rather than saving the reference, and then not
541   // call get() during process shutdown.
542   static T* get() __attribute__ ((__deprecated__("Replaced by try_get"))) {
543     return getEntry().get();
544   }
545
546   // If, however, you do need to hold a reference to the specific
547   // singleton, you can try to do so with a weak_ptr.  Avoid this when
548   // possible but the inability to lock the weak pointer can be a
549   // signal that the vault has been destroyed.
550   static std::weak_ptr<T> get_weak() {
551     return getEntry().get_weak();
552   }
553
554   // Preferred alternative to get_weak, it returns shared_ptr that can be
555   // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
556   // Avoid holding these shared_ptrs beyond the scope of a function;
557   // don't put them in member variables, always use try_get() instead
558   static std::shared_ptr<T> try_get() {
559     auto ret = get_weak().lock();
560     if (!ret) {
561       LOG(DFATAL) <<
562         "folly::Singleton<" << getEntry().type().name() <<
563         ">::get_weak() called on destructed singleton; "
564         "returning nullptr, possible segfault coming";
565     }
566     return ret;
567   }
568
569   explicit Singleton(std::nullptr_t _ = nullptr,
570                      typename Singleton::TeardownFunc t = nullptr) :
571       Singleton ([]() { return new T; }, std::move(t)) {
572   }
573
574   explicit Singleton(typename Singleton::CreateFunc c,
575                      typename Singleton::TeardownFunc t = nullptr) {
576     if (c == nullptr) {
577       throw std::logic_error(
578         "nullptr_t should be passed if you want T to be default constructed");
579     }
580
581     auto vault = SingletonVault::singleton<VaultTag>();
582     getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
583     vault->registerSingleton(&getEntry());
584   }
585
586   /**
587    * Should be instantiated as soon as "registrationComplete()" is called.
588    * Singletons are usually lazy-loaded (built on-demand) but for those which
589    * are known to be needed, to avoid the potential lag for objects that take
590    * long to construct during runtime, there is an option to make sure these
591    * are built up-front.
592    *
593    * Use like:
594    *   Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
595    *
596    * Or alternately, define the singleton as usual, and say
597    *   gFooInstance.shouldEagerInit()
598    *
599    * at some point prior to calling registrationComplete().
600    * Then registrationComplete can be called (by default it will kick off
601    * init of the eager singletons); alternately, you can use
602    * startEagerInit().
603    */
604   Singleton& shouldEagerInit() {
605     auto vault = SingletonVault::singleton<VaultTag>();
606     vault->addEagerInitSingleton(&getEntry());
607     return *this;
608   }
609
610   /**
611   * Construct and inject a mock singleton which should be used only from tests.
612   * Unlike regular singletons which are initialized once per process lifetime,
613   * mock singletons live for the duration of a test. This means that one process
614   * running multiple tests can initialize and register the same singleton
615   * multiple times. This functionality should be used only from tests
616   * since it relaxes validation and performance in order to be able to perform
617   * the injection. The returned mock singleton is functionality identical to
618   * regular singletons.
619   */
620   static void make_mock(std::nullptr_t c = nullptr,
621                         typename Singleton<T>::TeardownFunc t = nullptr) {
622     make_mock([]() { return new T; }, t);
623   }
624
625   static void make_mock(CreateFunc c,
626                         typename Singleton<T>::TeardownFunc t = nullptr) {
627     if (c == nullptr) {
628       throw std::logic_error(
629         "nullptr_t should be passed if you want T to be default constructed");
630     }
631
632     auto& entry = getEntry();
633
634     entry.registerSingletonMock(c, getTeardownFunc(t));
635   }
636
637  private:
638   inline static detail::SingletonHolder<T>& getEntry() {
639     return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
640   }
641
642   // Construct TeardownFunc.
643   static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
644       TeardownFunc t)  {
645     if (t == nullptr) {
646       return  [](T* v) { delete v; };
647     } else {
648       return t;
649     }
650   }
651 };
652
653 }
654
655 #include <folly/Singleton-inl.h>