Make Singleton dependency on Symbolizer Facebook-only
[folly.git] / folly / experimental / Singleton.h
1 /*
2  * Copyright 2014 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 // Within same compilation unit you should directly access it by the variable
38 // defining the singleton via get_fast()/get_weak_fast(), and even treat that
39 // variable like a smart pointer (dereferencing it or using the -> operator):
40 //
41 // MyExpensiveService* instance = the_singleton.get_fast();
42 // or
43 // std::weak_ptr<MyExpensiveService> instance = the_singleton.get_weak_fast();
44 // or even
45 // the_singleton->doSomething();
46 //
47 // *_fast() accessors are faster than static accessors, and have performance
48 // similar to Meyers singletons/static objects.
49 //
50 // Please note, however, that all non-weak_ptr interfaces are
51 // inherently subject to races with destruction.  Use responsibly.
52 //
53 // The singleton will be created on demand.  If the constructor for
54 // MyExpensiveService actually makes use of *another* Singleton, then
55 // the right thing will happen -- that other singleton will complete
56 // construction before get() returns.  However, in the event of a
57 // circular dependency, a runtime error will occur.
58 //
59 // You can have multiple singletons of the same underlying type, but
60 // each must be given a unique tag. If no tag is specified - default tag is used
61 //
62 // namespace {
63 // struct Tag1 {};
64 // struct Tag2 {};
65 // folly::Singleton<MyExpensiveService> s_default();
66 // folly::Singleton<MyExpensiveService, Tag1> s1();
67 // folly::Singleton<MyExpensiveService, Tag2> s2();
68 // }
69 // ...
70 // MyExpensiveService* svc_default = s_default.get_fast();
71 // MyExpensiveService* svc1 = s1.get_fast();
72 // MyExpensiveService* svc2 = s2.get_fast();
73 //
74 // By default, the singleton instance is constructed via new and
75 // deleted via delete, but this is configurable:
76 //
77 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
78 //                                                                destroy); }
79 //
80 // Where create and destroy are functions, Singleton<T>::CreateFunc
81 // Singleton<T>::TeardownFunc.
82 //
83 // What if you need to destroy all of your singletons?  Say, some of
84 // your singletons manage threads, but you need to fork?  Or your unit
85 // test wants to clean up all global state?  Then you can call
86 // SingletonVault::singleton()->destroyInstances(), which invokes the
87 // TeardownFunc for each singleton, in the reverse order they were
88 // created.  It is your responsibility to ensure your singletons can
89 // handle cases where the singletons they depend on go away, however.
90 // Singletons won't be recreated after destroyInstances call. If you
91 // want to re-enable singleton creation (say after fork was called) you
92 // should call reenableInstances.
93
94 #pragma once
95 #include <folly/Baton.h>
96 #include <folly/Exception.h>
97 #include <folly/Hash.h>
98 #include <folly/Memory.h>
99 #include <folly/RWSpinLock.h>
100 #include <folly/Demangle.h>
101 #include <folly/io/async/Request.h>
102
103 #include <algorithm>
104 #include <vector>
105 #include <mutex>
106 #include <thread>
107 #include <condition_variable>
108 #include <string>
109 #include <unordered_map>
110 #include <functional>
111 #include <typeinfo>
112 #include <typeindex>
113
114 #include <glog/logging.h>
115
116 namespace folly {
117
118 // For actual usage, please see the Singleton<T> class at the bottom
119 // of this file; that is what you will actually interact with.
120
121 // SingletonVault is the class that manages singleton instances.  It
122 // is unaware of the underlying types of singletons, and simply
123 // manages lifecycles and invokes CreateFunc and TeardownFunc when
124 // appropriate.  In general, you won't need to interact with the
125 // SingletonVault itself.
126 //
127 // A vault goes through a few stages of life:
128 //
129 //   1. Registration phase; singletons can be registered, but no
130 //      singleton can be created.
131 //   2. registrationComplete() has been called; singletons can no
132 //      longer be registered, but they can be created.
133 //   3. A vault can return to stage 1 when destroyInstances is called.
134 //
135 // In general, you don't need to worry about any of the above; just
136 // ensure registrationComplete() is called near the top of your main()
137 // function, otherwise no singletons can be instantiated.
138
139 class SingletonVault;
140
141 namespace detail {
142
143 struct DefaultTag {};
144
145 // A TypeDescriptor is the unique handle for a given singleton.  It is
146 // a combinaiton of the type and of the optional name, and is used as
147 // a key in unordered_maps.
148 class TypeDescriptor {
149  public:
150   TypeDescriptor(const std::type_info& ti,
151                  const std::type_info& tag_ti)
152       : ti_(ti), tag_ti_(tag_ti) {
153   }
154
155   TypeDescriptor(const TypeDescriptor& other)
156       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
157   }
158
159   TypeDescriptor& operator=(const TypeDescriptor& other) {
160     if (this != &other) {
161       ti_ = other.ti_;
162       tag_ti_ = other.tag_ti_;
163     }
164
165     return *this;
166   }
167
168   std::string name() const {
169     auto ret = demangle(ti_.name());
170     if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
171       ret += "/";
172       ret += demangle(tag_ti_.name());
173     }
174     return ret.toStdString();
175   }
176
177   friend class TypeDescriptorHasher;
178
179   bool operator==(const TypeDescriptor& other) const {
180     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
181   }
182
183  private:
184   std::type_index ti_;
185   std::type_index tag_ti_;
186 };
187
188 class TypeDescriptorHasher {
189  public:
190   size_t operator()(const TypeDescriptor& ti) const {
191     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
192   }
193 };
194
195 // This interface is used by SingletonVault to interact with SingletonHolders.
196 // Having a non-template interface allows SingletonVault to keep a list of all
197 // SingletonHolders.
198 class SingletonHolderBase {
199  public:
200   virtual ~SingletonHolderBase() {}
201
202   virtual TypeDescriptor type() = 0;
203   virtual bool hasLiveInstance() = 0;
204   virtual void destroyInstance() = 0;
205
206  protected:
207   static constexpr std::chrono::seconds kDestroyWaitTime{5};
208 };
209
210 // An actual instance of a singleton, tracking the instance itself,
211 // its state as described above, and the create and teardown
212 // functions.
213 template <typename T>
214 struct SingletonHolder : public SingletonHolderBase {
215  public:
216   typedef std::function<void(T*)> TeardownFunc;
217   typedef std::function<T*(void)> CreateFunc;
218
219   template <typename Tag, typename VaultTag>
220   inline static SingletonHolder<T>& singleton();
221
222   inline T* get();
223   inline std::weak_ptr<T> get_weak();
224
225   void registerSingleton(CreateFunc c, TeardownFunc t);
226   void registerSingletonMock(CreateFunc c, TeardownFunc t);
227   virtual TypeDescriptor type();
228   virtual bool hasLiveInstance();
229   virtual void destroyInstance();
230
231  private:
232   SingletonHolder(TypeDescriptor type, SingletonVault& vault);
233
234   void createInstance();
235
236   enum class SingletonHolderState {
237     NotRegistered,
238     Dead,
239     Living,
240   };
241
242   TypeDescriptor type_;
243   SingletonVault& vault_;
244
245   // mutex protects the entire entry during construction/destruction
246   std::mutex mutex_;
247
248   // State of the singleton entry. If state is Living, instance_ptr and
249   // instance_weak can be safely accessed w/o synchronization.
250   std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
251
252   // the thread creating the singleton (only valid while creating an object)
253   std::thread::id creating_thread_;
254
255   // The singleton itself and related functions.
256
257   // holds a shared_ptr to singleton instance, set when state is changed from
258   // Dead to Living. Reset when state is changed from Living to Dead.
259   std::shared_ptr<T> instance_;
260   // weak_ptr to the singleton instance, set when state is changed from Dead
261   // to Living. We never write to this object after initialization, so it is
262   // safe to read it from different threads w/o synchronization if we know
263   // that state is set to Living
264   std::weak_ptr<T> instance_weak_;
265   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
266   std::shared_ptr<folly::Baton<>> destroy_baton_;
267   T* instance_ptr_ = nullptr;
268   CreateFunc create_ = nullptr;
269   TeardownFunc teardown_ = nullptr;
270
271   std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
272
273   SingletonHolder(const SingletonHolder&) = delete;
274   SingletonHolder& operator=(const SingletonHolder&) = delete;
275   SingletonHolder& operator=(SingletonHolder&&) = delete;
276   SingletonHolder(SingletonHolder&&) = delete;
277 };
278
279 }
280
281 class SingletonVault {
282  public:
283   enum class Type { Strict, Relaxed };
284
285   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
286
287   // Destructor is only called by unit tests to check destroyInstances.
288   ~SingletonVault();
289
290   typedef std::function<void(void*)> TeardownFunc;
291   typedef std::function<void*(void)> CreateFunc;
292
293   // Ensure that Singleton has not been registered previously and that
294   // registration is not complete. If validations succeeds,
295   // register a singleton of a given type with the create and teardown
296   // functions.
297   void registerSingleton(detail::SingletonHolderBase* entry) {
298     RWSpinLock::ReadHolder rh(&stateMutex_);
299
300     stateCheck(SingletonVaultState::Running);
301
302     if (UNLIKELY(registrationComplete_)) {
303       throw std::logic_error(
304         "Registering singleton after registrationComplete().");
305     }
306
307     RWSpinLock::ReadHolder rhMutex(&mutex_);
308     CHECK_THROW(singletons_.find(entry->type()) == singletons_.end(),
309                 std::logic_error);
310
311     RWSpinLock::UpgradedHolder wh(&mutex_);
312     singletons_[entry->type()] = entry;
313   }
314
315   // Mark registration is complete; no more singletons can be
316   // registered at this point.
317   void registrationComplete() {
318     RequestContext::getStaticContext();
319     std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
320
321     RWSpinLock::WriteHolder wh(&stateMutex_);
322
323     stateCheck(SingletonVaultState::Running);
324
325     if (type_ == Type::Strict) {
326       for (const auto& p: singletons_) {
327         if (p.second->hasLiveInstance()) {
328           throw std::runtime_error(
329             "Singleton created before registration was complete.");
330         }
331       }
332     }
333
334     registrationComplete_ = true;
335   }
336
337   // Destroy all singletons; when complete, the vault can't create
338   // singletons once again until reenableInstances() is called.
339   void destroyInstances();
340
341   // Enable re-creating singletons after destroyInstances() was called.
342   void reenableInstances();
343
344   // For testing; how many registered and living singletons we have.
345   size_t registeredSingletonCount() const {
346     RWSpinLock::ReadHolder rh(&mutex_);
347
348     return singletons_.size();
349   }
350
351   size_t livingSingletonCount() const {
352     RWSpinLock::ReadHolder rh(&mutex_);
353
354     size_t ret = 0;
355     for (const auto& p : singletons_) {
356       if (p.second->hasLiveInstance()) {
357         ++ret;
358       }
359     }
360
361     return ret;
362   }
363
364   // A well-known vault; you can actually have others, but this is the
365   // default.
366   static SingletonVault* singleton() {
367     return singleton<>();
368   }
369
370   // Gets singleton vault for any Tag. Non-default tag should be used in unit
371   // tests only.
372   template <typename VaultTag = detail::DefaultTag>
373   static SingletonVault* singleton() {
374     static SingletonVault* vault = new SingletonVault();
375     return vault;
376   }
377
378   typedef std::string(*StackTraceGetterPtr)();
379
380   static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
381     static std::atomic<StackTraceGetterPtr> stackTraceGetterPtr;
382     return stackTraceGetterPtr;
383   }
384
385  private:
386   template <typename T>
387   friend class detail::SingletonHolder;
388
389   // The two stages of life for a vault, as mentioned in the class comment.
390   enum class SingletonVaultState {
391     Running,
392     Quiescing,
393   };
394
395   // Each singleton in the vault can be in two states: dead
396   // (registered but never created), living (CreateFunc returned an instance).
397
398   void stateCheck(SingletonVaultState expected,
399                   const char* msg="Unexpected singleton state change") {
400     if (expected != state_) {
401         throw std::logic_error(msg);
402     }
403   }
404
405   // This method only matters if registrationComplete() is never called.
406   // Otherwise destroyInstances is scheduled to be executed atexit.
407   //
408   // Initializes static object, which calls destroyInstances on destruction.
409   // Used to have better deletion ordering with singleton not managed by
410   // folly::Singleton. The desruction will happen in the following order:
411   // 1. Singletons, not managed by folly::Singleton, which were created after
412   //    any of the singletons managed by folly::Singleton was requested.
413   // 2. All singletons managed by folly::Singleton
414   // 3. Singletons, not managed by folly::Singleton, which were created before
415   //    any of the singletons managed by folly::Singleton was requested.
416   static void scheduleDestroyInstances();
417
418   typedef std::unordered_map<detail::TypeDescriptor,
419                              detail::SingletonHolderBase*,
420                              detail::TypeDescriptorHasher> SingletonMap;
421
422   mutable folly::RWSpinLock mutex_;
423   SingletonMap singletons_;
424   std::vector<detail::TypeDescriptor> creation_order_;
425   SingletonVaultState state_{SingletonVaultState::Running};
426   bool registrationComplete_{false};
427   folly::RWSpinLock stateMutex_;
428   Type type_{Type::Relaxed};
429 };
430
431 // This is the wrapper class that most users actually interact with.
432 // It allows for simple access to registering and instantiating
433 // singletons.  Create instances of this class in the global scope of
434 // type Singleton<T> to register your singleton for later access via
435 // Singleton<T>::get().
436 template <typename T,
437           typename Tag = detail::DefaultTag,
438           typename VaultTag = detail::DefaultTag /* for testing */>
439 class Singleton {
440  public:
441   typedef std::function<T*(void)> CreateFunc;
442   typedef std::function<void(T*)> TeardownFunc;
443
444   // Generally your program life cycle should be fine with calling
445   // get() repeatedly rather than saving the reference, and then not
446   // call get() during process shutdown.
447   static T* get() {
448     return getEntry().get();
449   }
450
451   // Same as get, but should be preffered to it in the same compilation
452   // unit, where Singleton is registered.
453   T* get_fast() {
454     return entry_.get();
455   }
456
457   // If, however, you do need to hold a reference to the specific
458   // singleton, you can try to do so with a weak_ptr.  Avoid this when
459   // possible but the inability to lock the weak pointer can be a
460   // signal that the vault has been destroyed.
461   static std::weak_ptr<T> get_weak() {
462     return getEntry().get_weak();
463   }
464
465   // Same as get_weak, but should be preffered to it in the same compilation
466   // unit, where Singleton is registered.
467   std::weak_ptr<T> get_weak_fast() {
468     return entry_.get_weak();
469   }
470
471   // Allow the Singleton<t> instance to also retrieve the underlying
472   // singleton, if desired.
473   T* ptr() { return get_fast(); }
474   T& operator*() { return *ptr(); }
475   T* operator->() { return ptr(); }
476
477   explicit Singleton(std::nullptr_t _ = nullptr,
478                      Singleton::TeardownFunc t = nullptr) :
479       Singleton ([]() { return new T; }, std::move(t)) {
480   }
481
482   explicit Singleton(Singleton::CreateFunc c,
483                      Singleton::TeardownFunc t = nullptr) : entry_(getEntry()) {
484     if (c == nullptr) {
485       throw std::logic_error(
486         "nullptr_t should be passed if you want T to be default constructed");
487     }
488
489     auto vault = SingletonVault::singleton<VaultTag>();
490     entry_.registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
491     vault->registerSingleton(&entry_);
492   }
493
494   /**
495   * Construct and inject a mock singleton which should be used only from tests.
496   * Unlike regular singletons which are initialized once per process lifetime,
497   * mock singletons live for the duration of a test. This means that one process
498   * running multiple tests can initialize and register the same singleton
499   * multiple times. This functionality should be used only from tests
500   * since it relaxes validation and performance in order to be able to perform
501   * the injection. The returned mock singleton is functionality identical to
502   * regular singletons.
503   */
504   static void make_mock(std::nullptr_t c = nullptr,
505                         typename Singleton<T>::TeardownFunc t = nullptr) {
506     make_mock([]() { return new T; }, t);
507   }
508
509   static void make_mock(CreateFunc c,
510                         typename Singleton<T>::TeardownFunc t = nullptr) {
511     if (c == nullptr) {
512       throw std::logic_error(
513         "nullptr_t should be passed if you want T to be default constructed");
514     }
515
516     auto& entry = getEntry();
517
518     entry.registerSingletonMock(c, getTeardownFunc(t));
519   }
520
521  private:
522   inline static detail::SingletonHolder<T>& getEntry() {
523     return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
524   }
525
526   // Construct TeardownFunc.
527   static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
528       TeardownFunc t)  {
529     if (t == nullptr) {
530       return  [](T* v) { delete v; };
531     } else {
532       return t;
533     }
534   }
535
536   // This is pointing to SingletonHolder paired with this singleton object. This
537   // is never reset, so each SingletonHolder should never be destroyed.
538   // We rely on the fact that Singleton destructor won't reset this pointer, so
539   // it can be "safely" used even after static Singleton object is destroyed.
540   detail::SingletonHolder<T>& entry_;
541 };
542
543 }
544
545 #include <folly/experimental/Singleton-inl.h>