732a6112d9df8ae690aac8cfb33fb20674d6afa9
[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/experimental/ReadMostlySharedPtr.h>
113
114 #include <algorithm>
115 #include <atomic>
116 #include <condition_variable>
117 #include <functional>
118 #include <memory>
119 #include <mutex>
120 #include <string>
121 #include <thread>
122 #include <typeindex>
123 #include <typeinfo>
124 #include <unordered_map>
125 #include <unordered_set>
126 #include <vector>
127
128 #include <glog/logging.h>
129
130 // use this guard to handleSingleton breaking change in 3rd party code
131 #ifndef FOLLY_SINGLETON_TRY_GET
132 #define FOLLY_SINGLETON_TRY_GET
133 #endif
134
135 namespace folly {
136
137 // For actual usage, please see the Singleton<T> class at the bottom
138 // of this file; that is what you will actually interact with.
139
140 // SingletonVault is the class that manages singleton instances.  It
141 // is unaware of the underlying types of singletons, and simply
142 // manages lifecycles and invokes CreateFunc and TeardownFunc when
143 // appropriate.  In general, you won't need to interact with the
144 // SingletonVault itself.
145 //
146 // A vault goes through a few stages of life:
147 //
148 //   1. Registration phase; singletons can be registered:
149 //      a) Strict: no singleton can be created in this stage.
150 //      b) Relaxed: singleton can be created (the default vault is Relaxed).
151 //   2. registrationComplete() has been called; singletons can no
152 //      longer be registered, but they can be created.
153 //   3. A vault can return to stage 1 when destroyInstances is called.
154 //
155 // In general, you don't need to worry about any of the above; just
156 // ensure registrationComplete() is called near the top of your main()
157 // function, otherwise no singletons can be instantiated.
158
159 class SingletonVault;
160
161 namespace detail {
162
163 struct DefaultTag {};
164
165 // A TypeDescriptor is the unique handle for a given singleton.  It is
166 // a combinaiton of the type and of the optional name, and is used as
167 // a key in unordered_maps.
168 class TypeDescriptor {
169  public:
170   TypeDescriptor(const std::type_info& ti,
171                  const std::type_info& tag_ti)
172       : ti_(ti), tag_ti_(tag_ti) {
173   }
174
175   TypeDescriptor(const TypeDescriptor& other)
176       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
177   }
178
179   TypeDescriptor& operator=(const TypeDescriptor& other) {
180     if (this != &other) {
181       ti_ = other.ti_;
182       tag_ti_ = other.tag_ti_;
183     }
184
185     return *this;
186   }
187
188   std::string name() const {
189     auto ret = demangle(ti_.name());
190     if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
191       ret += "/";
192       ret += demangle(tag_ti_.name());
193     }
194     return ret.toStdString();
195   }
196
197   friend class TypeDescriptorHasher;
198
199   bool operator==(const TypeDescriptor& other) const {
200     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
201   }
202
203  private:
204   std::type_index ti_;
205   std::type_index tag_ti_;
206 };
207
208 class TypeDescriptorHasher {
209  public:
210   size_t operator()(const TypeDescriptor& ti) const {
211     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
212   }
213 };
214
215 // This interface is used by SingletonVault to interact with SingletonHolders.
216 // Having a non-template interface allows SingletonVault to keep a list of all
217 // SingletonHolders.
218 class SingletonHolderBase {
219  public:
220   virtual ~SingletonHolderBase() = default;
221
222   virtual TypeDescriptor type() = 0;
223   virtual bool hasLiveInstance() = 0;
224   virtual void createInstance() = 0;
225   virtual bool creationStarted() = 0;
226   virtual void destroyInstance() = 0;
227
228  protected:
229   static constexpr std::chrono::seconds kDestroyWaitTime{5};
230 };
231
232 // An actual instance of a singleton, tracking the instance itself,
233 // its state as described above, and the create and teardown
234 // functions.
235 template <typename T>
236 struct SingletonHolder : public SingletonHolderBase {
237  public:
238   typedef std::function<void(T*)> TeardownFunc;
239   typedef std::function<T*(void)> CreateFunc;
240
241   template <typename Tag, typename VaultTag>
242   inline static SingletonHolder<T>& singleton();
243
244   inline T* get();
245   inline std::weak_ptr<T> get_weak();
246   inline std::shared_ptr<T> try_get();
247   inline folly::ReadMostlySharedPtr<T> try_get_fast();
248
249   void registerSingleton(CreateFunc c, TeardownFunc t);
250   void registerSingletonMock(CreateFunc c, TeardownFunc t);
251   virtual TypeDescriptor type() override;
252   virtual bool hasLiveInstance() override;
253   virtual void createInstance() override;
254   virtual bool creationStarted() override;
255   virtual void destroyInstance() override;
256
257  private:
258   SingletonHolder(TypeDescriptor type, SingletonVault& vault);
259
260   enum class SingletonHolderState {
261     NotRegistered,
262     Dead,
263     Living,
264   };
265
266   TypeDescriptor type_;
267   SingletonVault& vault_;
268
269   // mutex protects the entire entry during construction/destruction
270   std::mutex mutex_;
271
272   // State of the singleton entry. If state is Living, instance_ptr and
273   // instance_weak can be safely accessed w/o synchronization.
274   std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
275
276   // the thread creating the singleton (only valid while creating an object)
277   std::atomic<std::thread::id> creating_thread_;
278
279   // The singleton itself and related functions.
280
281   // holds a ReadMostlyMainPtr to singleton instance, set when state is changed
282   // from Dead to Living. Reset when state is changed from Living to Dead.
283   folly::ReadMostlyMainPtr<T> instance_;
284   // weak_ptr to the singleton instance, set when state is changed from Dead
285   // to Living. We never write to this object after initialization, so it is
286   // safe to read it from different threads w/o synchronization if we know
287   // that state is set to Living
288   std::weak_ptr<T> instance_weak_;
289   // Fast equivalent of instance_weak_
290   folly::ReadMostlyWeakPtr<T> instance_weak_fast_;
291   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
292   std::shared_ptr<folly::Baton<>> destroy_baton_;
293   T* instance_ptr_ = nullptr;
294   CreateFunc create_ = nullptr;
295   TeardownFunc teardown_ = nullptr;
296
297   std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
298
299   SingletonHolder(const SingletonHolder&) = delete;
300   SingletonHolder& operator=(const SingletonHolder&) = delete;
301   SingletonHolder& operator=(SingletonHolder&&) = delete;
302   SingletonHolder(SingletonHolder&&) = delete;
303 };
304
305 }
306
307 class SingletonVault {
308  public:
309   enum class Type {
310     Strict, // Singletons can't be created before registrationComplete()
311     Relaxed, // Singletons can be created before registrationComplete()
312   };
313
314   /**
315    * Clears all singletons in the given vault at ctor and dtor times.
316    * Useful for unit-tests that need to clear the world.
317    *
318    * This need can arise when a unit-test needs to swap out an object used by a
319    * singleton for a test-double, but the singleton needing its dependency to be
320    * swapped has a type or a tag local to some other translation unit and
321    * unavailable in the current translation unit.
322    *
323    * Other, better approaches to this need are "plz 2 refactor" ....
324    */
325   struct ScopedExpunger {
326     SingletonVault* vault;
327     explicit ScopedExpunger(SingletonVault* v) : vault(v) { expunge(); }
328     ~ScopedExpunger() { expunge(); }
329     void expunge() {
330       vault->destroyInstances();
331       vault->reenableInstances();
332     }
333   };
334
335   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
336
337   // Destructor is only called by unit tests to check destroyInstances.
338   ~SingletonVault();
339
340   typedef std::function<void(void*)> TeardownFunc;
341   typedef std::function<void*(void)> CreateFunc;
342
343   // Ensure that Singleton has not been registered previously and that
344   // registration is not complete. If validations succeeds,
345   // register a singleton of a given type with the create and teardown
346   // functions.
347   void registerSingleton(detail::SingletonHolderBase* entry);
348
349   /**
350    * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
351    * is built when `doEagerInit[Via]` is called; see those methods
352    * for more info.
353    */
354   void addEagerInitSingleton(detail::SingletonHolderBase* entry);
355
356   // Mark registration is complete; no more singletons can be
357   // registered at this point.
358   void registrationComplete();
359
360   /**
361    * Initialize all singletons which were marked as eager-initialized
362    * (using `shouldEagerInit()`).  No return value.  Propagates exceptions
363    * from constructors / create functions, as is the usual case when calling
364    * for example `Singleton<Foo>::get_weak()`.
365    */
366   void doEagerInit();
367
368   /**
369    * Schedule eager singletons' initializations through the given executor.
370    * If baton ptr is not null, its `post` method is called after all
371    * early initialization has completed.
372    *
373    * If exceptions are thrown during initialization, this method will still
374    * `post` the baton to indicate completion.  The exception will not propagate
375    * and future attempts to `try_get` or `get_weak` the failed singleton will
376    * retry initialization.
377    *
378    * Sample usage:
379    *
380    *   wangle::IOThreadPoolExecutor executor(max_concurrency_level);
381    *   folly::Baton<> done;
382    *   doEagerInitVia(executor, &done);
383    *   done.wait();  // or 'timed_wait', or spin with 'try_wait'
384    *
385    */
386   void doEagerInitVia(Executor& exe, folly::Baton<>* done = nullptr);
387
388   // Destroy all singletons; when complete, the vault can't create
389   // singletons once again until reenableInstances() is called.
390   void destroyInstances();
391
392   // Enable re-creating singletons after destroyInstances() was called.
393   void reenableInstances();
394
395   // For testing; how many registered and living singletons we have.
396   size_t registeredSingletonCount() const {
397     RWSpinLock::ReadHolder rh(&mutex_);
398
399     return singletons_.size();
400   }
401
402   /**
403    * Flips to true if eager initialization was used, and has completed.
404    * Never set to true if "doEagerInit()" or "doEagerInitVia" never called.
405    */
406   bool eagerInitComplete() const;
407
408   size_t livingSingletonCount() const {
409     RWSpinLock::ReadHolder rh(&mutex_);
410
411     size_t ret = 0;
412     for (const auto& p : singletons_) {
413       if (p.second->hasLiveInstance()) {
414         ++ret;
415       }
416     }
417
418     return ret;
419   }
420
421   // A well-known vault; you can actually have others, but this is the
422   // default.
423   static SingletonVault* singleton() {
424     return singleton<>();
425   }
426
427   // Gets singleton vault for any Tag. Non-default tag should be used in unit
428   // tests only.
429   template <typename VaultTag = detail::DefaultTag>
430   static SingletonVault* singleton() {
431     static SingletonVault* vault = new SingletonVault();
432     return vault;
433   }
434
435   typedef std::string(*StackTraceGetterPtr)();
436
437   static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
438     static std::atomic<StackTraceGetterPtr> stackTraceGetterPtr;
439     return stackTraceGetterPtr;
440   }
441
442  private:
443   template <typename T>
444   friend struct detail::SingletonHolder;
445
446   // The two stages of life for a vault, as mentioned in the class comment.
447   enum class SingletonVaultState {
448     Running,
449     Quiescing,
450   };
451
452   // Each singleton in the vault can be in two states: dead
453   // (registered but never created), living (CreateFunc returned an instance).
454
455   void stateCheck(SingletonVaultState expected,
456                   const char* msg="Unexpected singleton state change") {
457     if (expected != state_) {
458         throw std::logic_error(msg);
459     }
460   }
461
462   // This method only matters if registrationComplete() is never called.
463   // Otherwise destroyInstances is scheduled to be executed atexit.
464   //
465   // Initializes static object, which calls destroyInstances on destruction.
466   // Used to have better deletion ordering with singleton not managed by
467   // folly::Singleton. The desruction will happen in the following order:
468   // 1. Singletons, not managed by folly::Singleton, which were created after
469   //    any of the singletons managed by folly::Singleton was requested.
470   // 2. All singletons managed by folly::Singleton
471   // 3. Singletons, not managed by folly::Singleton, which were created before
472   //    any of the singletons managed by folly::Singleton was requested.
473   static void scheduleDestroyInstances();
474
475   typedef std::unordered_map<detail::TypeDescriptor,
476                              detail::SingletonHolderBase*,
477                              detail::TypeDescriptorHasher> SingletonMap;
478
479   mutable folly::RWSpinLock mutex_;
480   SingletonMap singletons_;
481   std::unordered_set<detail::SingletonHolderBase*> eagerInitSingletons_;
482   std::vector<detail::TypeDescriptor> creation_order_;
483   SingletonVaultState state_{SingletonVaultState::Running};
484   bool registrationComplete_{false};
485   folly::RWSpinLock stateMutex_;
486   Type type_{Type::Relaxed};
487 };
488
489 // This is the wrapper class that most users actually interact with.
490 // It allows for simple access to registering and instantiating
491 // singletons.  Create instances of this class in the global scope of
492 // type Singleton<T> to register your singleton for later access via
493 // Singleton<T>::try_get().
494 template <typename T,
495           typename Tag = detail::DefaultTag,
496           typename VaultTag = detail::DefaultTag /* for testing */>
497 class Singleton {
498  public:
499   typedef std::function<T*(void)> CreateFunc;
500   typedef std::function<void(T*)> TeardownFunc;
501
502   // Generally your program life cycle should be fine with calling
503   // get() repeatedly rather than saving the reference, and then not
504   // call get() during process shutdown.
505   FOLLY_DEPRECATED("Replaced by try_get")
506   static T* get() { return getEntry().get(); }
507
508   // If, however, you do need to hold a reference to the specific
509   // singleton, you can try to do so with a weak_ptr.  Avoid this when
510   // possible but the inability to lock the weak pointer can be a
511   // signal that the vault has been destroyed.
512   FOLLY_DEPRECATED("Replaced by try_get")
513   static std::weak_ptr<T> get_weak() { return getEntry().get_weak(); }
514
515   // Preferred alternative to get_weak, it returns shared_ptr that can be
516   // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
517   // Avoid holding these shared_ptrs beyond the scope of a function;
518   // don't put them in member variables, always use try_get() instead
519   //
520   // try_get() can return nullptr if the singleton was destroyed, caller is
521   // responsible for handling nullptr return
522   static std::shared_ptr<T> try_get() {
523     return getEntry().try_get();
524   }
525
526   static folly::ReadMostlySharedPtr<T> try_get_fast() {
527     return getEntry().try_get_fast();
528   }
529
530   explicit Singleton(std::nullptr_t /* _ */ = nullptr,
531                      typename Singleton::TeardownFunc t = nullptr)
532       : Singleton([]() { return new T; }, std::move(t)) {}
533
534   explicit Singleton(typename Singleton::CreateFunc c,
535                      typename Singleton::TeardownFunc t = nullptr) {
536     if (c == nullptr) {
537       throw std::logic_error(
538         "nullptr_t should be passed if you want T to be default constructed");
539     }
540
541     auto vault = SingletonVault::singleton<VaultTag>();
542     getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
543     vault->registerSingleton(&getEntry());
544   }
545
546   /**
547    * Should be instantiated as soon as "doEagerInit[Via]" is called.
548    * Singletons are usually lazy-loaded (built on-demand) but for those which
549    * are known to be needed, to avoid the potential lag for objects that take
550    * long to construct during runtime, there is an option to make sure these
551    * are built up-front.
552    *
553    * Use like:
554    *   Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
555    *
556    * Or alternately, define the singleton as usual, and say
557    *   gFooInstance.shouldEagerInit();
558    *
559    * at some point prior to calling registrationComplete().
560    * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
561    */
562   Singleton& shouldEagerInit() {
563     auto vault = SingletonVault::singleton<VaultTag>();
564     vault->addEagerInitSingleton(&getEntry());
565     return *this;
566   }
567
568   /**
569   * Construct and inject a mock singleton which should be used only from tests.
570   * Unlike regular singletons which are initialized once per process lifetime,
571   * mock singletons live for the duration of a test. This means that one process
572   * running multiple tests can initialize and register the same singleton
573   * multiple times. This functionality should be used only from tests
574   * since it relaxes validation and performance in order to be able to perform
575   * the injection. The returned mock singleton is functionality identical to
576   * regular singletons.
577   */
578   static void make_mock(std::nullptr_t /* c */ = nullptr,
579                         typename Singleton<T>::TeardownFunc t = nullptr) {
580     make_mock([]() { return new T; }, t);
581   }
582
583   static void make_mock(CreateFunc c,
584                         typename Singleton<T>::TeardownFunc t = nullptr) {
585     if (c == nullptr) {
586       throw std::logic_error(
587         "nullptr_t should be passed if you want T to be default constructed");
588     }
589
590     auto& entry = getEntry();
591
592     entry.registerSingletonMock(c, getTeardownFunc(t));
593   }
594
595  private:
596   inline static detail::SingletonHolder<T>& getEntry() {
597     return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
598   }
599
600   // Construct TeardownFunc.
601   static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
602       TeardownFunc t)  {
603     if (t == nullptr) {
604       return  [](T* v) { delete v; };
605     } else {
606       return t;
607     }
608   }
609 };
610
611 template <typename T, typename Tag = detail::DefaultTag>
612 class LeakySingleton {
613  public:
614   using CreateFunc = std::function<T*()>;
615
616   LeakySingleton() : LeakySingleton([] { return new T(); }) {}
617
618   explicit LeakySingleton(CreateFunc createFunc) {
619     auto& entry = entryInstance();
620     if (entry.state != State::NotRegistered) {
621       LOG(FATAL) << "Double registration of singletons of the same "
622                  << "underlying type; check for multiple definitions "
623                  << "of type folly::LeakySingleton<" + entry.type_.name() + ">";
624     }
625     entry.createFunc = createFunc;
626     entry.state = State::Dead;
627   }
628
629   static T& get() { return instance(); }
630
631  private:
632   enum class State { NotRegistered, Dead, Living };
633
634   struct Entry {
635     Entry() {}
636     Entry(const Entry&) = delete;
637     Entry& operator=(const Entry&) = delete;
638
639     std::atomic<State> state{State::NotRegistered};
640     T* ptr{nullptr};
641     CreateFunc createFunc;
642     std::mutex mutex;
643     detail::TypeDescriptor type_{typeid(T), typeid(Tag)};
644   };
645
646   static Entry& entryInstance() {
647     static auto entry = new Entry();
648     return *entry;
649   }
650
651   static T& instance() {
652     auto& entry = entryInstance();
653     if (UNLIKELY(entry.state != State::Living)) {
654       createInstance();
655     }
656
657     return *entry.ptr;
658   }
659
660   static void createInstance() {
661     auto& entry = entryInstance();
662
663     std::lock_guard<std::mutex> lg(entry.mutex);
664     if (entry.state == State::Living) {
665       return;
666     }
667
668     if (entry.state == State::NotRegistered) {
669       auto ptr = SingletonVault::stackTraceGetter().load();
670       LOG(FATAL) << "Creating instance for unregistered singleton: "
671                  << entry.type_.name() << "\n"
672                  << "Stacktrace:"
673                  << "\n" << (ptr ? (*ptr)() : "(not available)");
674     }
675
676     entry.ptr = entry.createFunc();
677     entry.state = State::Living;
678   }
679 };
680 }
681
682 #include <folly/Singleton-inl.h>