Singleton: remove dependency on Future
[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/io/async/Request.h>
113
114 #include <algorithm>
115 #include <vector>
116 #include <mutex>
117 #include <thread>
118 #include <condition_variable>
119 #include <string>
120 #include <unordered_map>
121 #include <unordered_set>
122 #include <functional>
123 #include <typeinfo>
124 #include <typeindex>
125
126 #include <glog/logging.h>
127
128 // use this guard to handleSingleton breaking change in 3rd party code
129 #ifndef FOLLY_SINGLETON_TRY_GET
130 #define FOLLY_SINGLETON_TRY_GET
131 #endif
132
133 namespace folly {
134
135 // For actual usage, please see the Singleton<T> class at the bottom
136 // of this file; that is what you will actually interact with.
137
138 // SingletonVault is the class that manages singleton instances.  It
139 // is unaware of the underlying types of singletons, and simply
140 // manages lifecycles and invokes CreateFunc and TeardownFunc when
141 // appropriate.  In general, you won't need to interact with the
142 // SingletonVault itself.
143 //
144 // A vault goes through a few stages of life:
145 //
146 //   1. Registration phase; singletons can be registered:
147 //      a) Strict: no singleton can be created in this stage.
148 //      b) Relaxed: singleton can be created (the default vault is Relaxed).
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 {
304     Strict, // Singletons can't be created before registrationComplete()
305     Relaxed, // Singletons can be created before registrationComplete()
306   };
307
308   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
309
310   // Destructor is only called by unit tests to check destroyInstances.
311   ~SingletonVault();
312
313   typedef std::function<void(void*)> TeardownFunc;
314   typedef std::function<void*(void)> CreateFunc;
315
316   // Ensure that Singleton has not been registered previously and that
317   // registration is not complete. If validations succeeds,
318   // register a singleton of a given type with the create and teardown
319   // functions.
320   void registerSingleton(detail::SingletonHolderBase* entry);
321
322   /**
323    * Called by `Singleton<T>.shouldEagerInit()` to ensure the instance
324    * is built when `doEagerInit[Via]` is called; see those methods
325    * for more info.
326    */
327   void addEagerInitSingleton(detail::SingletonHolderBase* entry);
328
329   // Mark registration is complete; no more singletons can be
330   // registered at this point.
331   void registrationComplete();
332
333   /**
334    * Initialize all singletons which were marked as eager-initialized
335    * (using `shouldEagerInit()`).  No return value.  Propagates exceptions
336    * from constructors / create functions, as is the usual case when calling
337    * for example `Singleton<Foo>::get_weak()`.
338    */
339   void doEagerInit();
340
341   /**
342    * Schedule eager singletons' initializations through the given executor.
343    */
344   void doEagerInitVia(Executor* exe);
345
346   // Destroy all singletons; when complete, the vault can't create
347   // singletons once again until reenableInstances() is called.
348   void destroyInstances();
349
350   // Enable re-creating singletons after destroyInstances() was called.
351   void reenableInstances();
352
353   // For testing; how many registered and living singletons we have.
354   size_t registeredSingletonCount() const {
355     RWSpinLock::ReadHolder rh(&mutex_);
356
357     return singletons_.size();
358   }
359
360   size_t livingSingletonCount() const {
361     RWSpinLock::ReadHolder rh(&mutex_);
362
363     size_t ret = 0;
364     for (const auto& p : singletons_) {
365       if (p.second->hasLiveInstance()) {
366         ++ret;
367       }
368     }
369
370     return ret;
371   }
372
373   // A well-known vault; you can actually have others, but this is the
374   // default.
375   static SingletonVault* singleton() {
376     return singleton<>();
377   }
378
379   // Gets singleton vault for any Tag. Non-default tag should be used in unit
380   // tests only.
381   template <typename VaultTag = detail::DefaultTag>
382   static SingletonVault* singleton() {
383     static SingletonVault* vault = new SingletonVault();
384     return vault;
385   }
386
387   typedef std::string(*StackTraceGetterPtr)();
388
389   static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
390     static std::atomic<StackTraceGetterPtr> stackTraceGetterPtr;
391     return stackTraceGetterPtr;
392   }
393
394  private:
395   template <typename T>
396   friend struct detail::SingletonHolder;
397
398   // The two stages of life for a vault, as mentioned in the class comment.
399   enum class SingletonVaultState {
400     Running,
401     Quiescing,
402   };
403
404   // Each singleton in the vault can be in two states: dead
405   // (registered but never created), living (CreateFunc returned an instance).
406
407   void stateCheck(SingletonVaultState expected,
408                   const char* msg="Unexpected singleton state change") {
409     if (expected != state_) {
410         throw std::logic_error(msg);
411     }
412   }
413
414   // This method only matters if registrationComplete() is never called.
415   // Otherwise destroyInstances is scheduled to be executed atexit.
416   //
417   // Initializes static object, which calls destroyInstances on destruction.
418   // Used to have better deletion ordering with singleton not managed by
419   // folly::Singleton. The desruction will happen in the following order:
420   // 1. Singletons, not managed by folly::Singleton, which were created after
421   //    any of the singletons managed by folly::Singleton was requested.
422   // 2. All singletons managed by folly::Singleton
423   // 3. Singletons, not managed by folly::Singleton, which were created before
424   //    any of the singletons managed by folly::Singleton was requested.
425   static void scheduleDestroyInstances();
426
427   typedef std::unordered_map<detail::TypeDescriptor,
428                              detail::SingletonHolderBase*,
429                              detail::TypeDescriptorHasher> SingletonMap;
430
431   mutable folly::RWSpinLock mutex_;
432   SingletonMap singletons_;
433   std::unordered_set<detail::SingletonHolderBase*> eagerInitSingletons_;
434   std::vector<detail::TypeDescriptor> creation_order_;
435   SingletonVaultState state_{SingletonVaultState::Running};
436   bool registrationComplete_{false};
437   folly::RWSpinLock stateMutex_;
438   Type type_{Type::Relaxed};
439 };
440
441 // This is the wrapper class that most users actually interact with.
442 // It allows for simple access to registering and instantiating
443 // singletons.  Create instances of this class in the global scope of
444 // type Singleton<T> to register your singleton for later access via
445 // Singleton<T>::try_get().
446 template <typename T,
447           typename Tag = detail::DefaultTag,
448           typename VaultTag = detail::DefaultTag /* for testing */>
449 class Singleton {
450  public:
451   typedef std::function<T*(void)> CreateFunc;
452   typedef std::function<void(T*)> TeardownFunc;
453
454   // Generally your program life cycle should be fine with calling
455   // get() repeatedly rather than saving the reference, and then not
456   // call get() during process shutdown.
457   static T* get() __attribute__ ((__deprecated__("Replaced by try_get"))) {
458     return getEntry().get();
459   }
460
461   // If, however, you do need to hold a reference to the specific
462   // singleton, you can try to do so with a weak_ptr.  Avoid this when
463   // possible but the inability to lock the weak pointer can be a
464   // signal that the vault has been destroyed.
465   static std::weak_ptr<T> get_weak() {
466     return getEntry().get_weak();
467   }
468
469   // Preferred alternative to get_weak, it returns shared_ptr that can be
470   // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
471   // Avoid holding these shared_ptrs beyond the scope of a function;
472   // don't put them in member variables, always use try_get() instead
473   static std::shared_ptr<T> try_get() {
474     auto ret = get_weak().lock();
475     if (!ret) {
476       LOG(DFATAL) <<
477         "folly::Singleton<" << getEntry().type().name() <<
478         ">::get_weak() called on destructed singleton; "
479         "returning nullptr, possible segfault coming";
480     }
481     return ret;
482   }
483
484   explicit Singleton(std::nullptr_t _ = nullptr,
485                      typename Singleton::TeardownFunc t = nullptr) :
486       Singleton ([]() { return new T; }, std::move(t)) {
487   }
488
489   explicit Singleton(typename Singleton::CreateFunc c,
490                      typename Singleton::TeardownFunc t = nullptr) {
491     if (c == nullptr) {
492       throw std::logic_error(
493         "nullptr_t should be passed if you want T to be default constructed");
494     }
495
496     auto vault = SingletonVault::singleton<VaultTag>();
497     getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
498     vault->registerSingleton(&getEntry());
499   }
500
501   /**
502    * Should be instantiated as soon as "doEagerInit[Via]" is called.
503    * Singletons are usually lazy-loaded (built on-demand) but for those which
504    * are known to be needed, to avoid the potential lag for objects that take
505    * long to construct during runtime, there is an option to make sure these
506    * are built up-front.
507    *
508    * Use like:
509    *   Singleton<Foo> gFooInstance = Singleton<Foo>(...).shouldEagerInit();
510    *
511    * Or alternately, define the singleton as usual, and say
512    *   gFooInstance.shouldEagerInit();
513    *
514    * at some point prior to calling registrationComplete().
515    * Then doEagerInit() or doEagerInitVia(Executor*) can be called.
516    */
517   Singleton& shouldEagerInit() {
518     auto vault = SingletonVault::singleton<VaultTag>();
519     vault->addEagerInitSingleton(&getEntry());
520     return *this;
521   }
522
523   /**
524   * Construct and inject a mock singleton which should be used only from tests.
525   * Unlike regular singletons which are initialized once per process lifetime,
526   * mock singletons live for the duration of a test. This means that one process
527   * running multiple tests can initialize and register the same singleton
528   * multiple times. This functionality should be used only from tests
529   * since it relaxes validation and performance in order to be able to perform
530   * the injection. The returned mock singleton is functionality identical to
531   * regular singletons.
532   */
533   static void make_mock(std::nullptr_t c = nullptr,
534                         typename Singleton<T>::TeardownFunc t = nullptr) {
535     make_mock([]() { return new T; }, t);
536   }
537
538   static void make_mock(CreateFunc c,
539                         typename Singleton<T>::TeardownFunc t = nullptr) {
540     if (c == nullptr) {
541       throw std::logic_error(
542         "nullptr_t should be passed if you want T to be default constructed");
543     }
544
545     auto& entry = getEntry();
546
547     entry.registerSingletonMock(c, getTeardownFunc(t));
548   }
549
550  private:
551   inline static detail::SingletonHolder<T>& getEntry() {
552     return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
553   }
554
555   // Construct TeardownFunc.
556   static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
557       TeardownFunc t)  {
558     if (t == nullptr) {
559       return  [](T* v) { delete v; };
560     } else {
561       return t;
562     }
563   }
564 };
565
566 }
567
568 #include <folly/Singleton-inl.h>