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