7c9d6e0704bcb7128577f6a8b68887d69a97c5aa
[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/io/async/Request.h>
101
102 #include <algorithm>
103 #include <vector>
104 #include <mutex>
105 #include <thread>
106 #include <condition_variable>
107 #include <string>
108 #include <unordered_map>
109 #include <functional>
110 #include <typeinfo>
111 #include <typeindex>
112
113 #include <glog/logging.h>
114
115 namespace folly {
116
117 // For actual usage, please see the Singleton<T> class at the bottom
118 // of this file; that is what you will actually interact with.
119
120 // SingletonVault is the class that manages singleton instances.  It
121 // is unaware of the underlying types of singletons, and simply
122 // manages lifecycles and invokes CreateFunc and TeardownFunc when
123 // appropriate.  In general, you won't need to interact with the
124 // SingletonVault itself.
125 //
126 // A vault goes through a few stages of life:
127 //
128 //   1. Registration phase; singletons can be registered, but no
129 //      singleton can be created.
130 //   2. registrationComplete() has been called; singletons can no
131 //      longer be registered, but they can be created.
132 //   3. A vault can return to stage 1 when destroyInstances is called.
133 //
134 // In general, you don't need to worry about any of the above; just
135 // ensure registrationComplete() is called near the top of your main()
136 // function, otherwise no singletons can be instantiated.
137
138 namespace detail {
139
140 struct DefaultTag {};
141
142 // A TypeDescriptor is the unique handle for a given singleton.  It is
143 // a combinaiton of the type and of the optional name, and is used as
144 // a key in unordered_maps.
145 class TypeDescriptor {
146  public:
147   TypeDescriptor(const std::type_info& ti,
148                  const std::type_info& tag_ti)
149       : ti_(ti), tag_ti_(tag_ti) {
150   }
151
152   TypeDescriptor(const TypeDescriptor& other)
153       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
154   }
155
156   TypeDescriptor& operator=(const TypeDescriptor& other) {
157     if (this != &other) {
158       ti_ = other.ti_;
159       tag_ti_ = other.tag_ti_;
160     }
161
162     return *this;
163   }
164
165   std::string name() const {
166     std::string ret = ti_.name();
167     if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
168       ret += "/";
169       ret += tag_ti_.name();
170     }
171     return ret;
172   }
173
174   friend class TypeDescriptorHasher;
175
176   bool operator==(const TypeDescriptor& other) const {
177     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
178   }
179
180  private:
181   std::type_index ti_;
182   std::type_index tag_ti_;
183 };
184
185 class TypeDescriptorHasher {
186  public:
187   size_t operator()(const TypeDescriptor& ti) const {
188     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
189   }
190 };
191
192 enum class SingletonEntryState {
193   Dead,
194   Living,
195 };
196
197 // An actual instance of a singleton, tracking the instance itself,
198 // its state as described above, and the create and teardown
199 // functions.
200 struct SingletonEntry {
201   typedef std::function<void(void*)> TeardownFunc;
202   typedef std::function<void*(void)> CreateFunc;
203
204   SingletonEntry(CreateFunc c, TeardownFunc t) :
205       create(std::move(c)), teardown(std::move(t)) {}
206
207   // mutex protects the entire entry during construction/destruction
208   std::mutex mutex;
209
210   // State of the singleton entry. If state is Living, instance_ptr and
211   // instance_weak can be safely accessed w/o synchronization.
212   std::atomic<SingletonEntryState> state{SingletonEntryState::Dead};
213
214   // the thread creating the singleton (only valid while creating an object)
215   std::thread::id creating_thread;
216
217   // The singleton itself and related functions.
218
219   // holds a shared_ptr to singleton instance, set when state is changed from
220   // Dead to Living. Reset when state is changed from Living to Dead.
221   std::shared_ptr<void> instance;
222   // weak_ptr to the singleton instance, set when state is changed from Dead
223   // to Living. We never write to this object after initialization, so it is
224   // safe to read it from different threads w/o synchronization if we know
225   // that state is set to Living
226   std::weak_ptr<void> instance_weak;
227   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
228   std::shared_ptr<folly::Baton<>> destroy_baton;
229   void* instance_ptr = nullptr;
230   CreateFunc create = nullptr;
231   TeardownFunc teardown = nullptr;
232
233   SingletonEntry(const SingletonEntry&) = delete;
234   SingletonEntry& operator=(const SingletonEntry&) = delete;
235   SingletonEntry& operator=(SingletonEntry&&) = delete;
236   SingletonEntry(SingletonEntry&&) = delete;
237 };
238
239 }
240
241 class SingletonVault {
242  public:
243   enum class Type { Strict, Relaxed };
244
245   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
246
247   // Destructor is only called by unit tests to check destroyInstances.
248   ~SingletonVault();
249
250   typedef std::function<void(void*)> TeardownFunc;
251   typedef std::function<void*(void)> CreateFunc;
252
253   // Ensure that Singleton has not been registered previously and that
254   // registration is not complete. If validations succeeds,
255   // register a singleton of a given type with the create and teardown
256   // functions.
257   detail::SingletonEntry& registerSingleton(detail::TypeDescriptor type,
258                                             CreateFunc create,
259                                             TeardownFunc teardown) {
260     RWSpinLock::ReadHolder rh(&stateMutex_);
261
262     stateCheck(SingletonVaultState::Running);
263
264     if (UNLIKELY(registrationComplete_)) {
265       throw std::logic_error(
266         "Registering singleton after registrationComplete().");
267     }
268
269     RWSpinLock::ReadHolder rhMutex(&mutex_);
270     CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
271
272     return registerSingletonImpl(type, create, teardown);
273   }
274
275   // Register a singleton of a given type with the create and teardown
276   // functions. Must hold reader locks on stateMutex_ and mutex_
277   // when invoking this function.
278   detail::SingletonEntry& registerSingletonImpl(detail::TypeDescriptor type,
279                              CreateFunc create,
280                              TeardownFunc teardown) {
281     RWSpinLock::UpgradedHolder wh(&mutex_);
282
283     singletons_[type] =
284       folly::make_unique<detail::SingletonEntry>(std::move(create),
285                                                  std::move(teardown));
286     return *singletons_[type];
287   }
288
289   /* Register a mock singleton used for testing of singletons which
290    * depend on other private singletons which cannot be otherwise injected.
291    */
292   void registerMockSingleton(detail::TypeDescriptor type,
293                              CreateFunc create,
294                              TeardownFunc teardown) {
295     RWSpinLock::ReadHolder rh(&stateMutex_);
296     RWSpinLock::ReadHolder rhMutex(&mutex_);
297
298     auto entry_it = singletons_.find(type);
299     // Mock singleton registration, we allow existing entry to be overridden.
300     if (entry_it == singletons_.end()) {
301       throw std::logic_error(
302         "Registering mock before the singleton was registered");
303     }
304
305     {
306       auto& entry = *(entry_it->second);
307       // Destroy existing singleton.
308       std::lock_guard<std::mutex> entry_lg(entry.mutex);
309
310       destroyInstance(entry_it);
311       entry.create = create;
312       entry.teardown = teardown;
313     }
314
315     // Upgrade to write lock.
316     RWSpinLock::UpgradedHolder whMutex(&mutex_);
317
318     // Remove singleton from creation order and singletons_.
319     // This happens only in test code and not frequently.
320     // Performance is not a concern here.
321     auto creation_order_it = std::find(
322       creation_order_.begin(),
323       creation_order_.end(),
324       type);
325     if (creation_order_it != creation_order_.end()) {
326       creation_order_.erase(creation_order_it);
327     }
328   }
329
330   // Mark registration is complete; no more singletons can be
331   // registered at this point.
332   void registrationComplete() {
333     RequestContext::getStaticContext();
334     std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
335
336     RWSpinLock::WriteHolder wh(&stateMutex_);
337
338     stateCheck(SingletonVaultState::Running);
339
340     if (type_ == Type::Strict) {
341       for (const auto& id_singleton_entry: singletons_) {
342         const auto& singleton_entry = *id_singleton_entry.second;
343         if (singleton_entry.state != detail::SingletonEntryState::Dead) {
344           throw std::runtime_error(
345             "Singleton created before registration was complete.");
346         }
347       }
348     }
349
350     registrationComplete_ = true;
351   }
352
353   // Destroy all singletons; when complete, the vault can't create
354   // singletons once again until reenableInstances() is called.
355   void destroyInstances();
356
357   // Enable re-creating singletons after destroyInstances() was called.
358   void reenableInstances();
359
360   // Retrieve a singleton from the vault, creating it if necessary.
361   std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
362     auto entry = get_entry_create(type);
363     return entry->instance_weak;
364   }
365
366   // This function is inherently racy since we don't hold the
367   // shared_ptr that contains the Singleton.  It is the caller's
368   // responsibility to be sane with this, but it is preferable to use
369   // the weak_ptr interface for true safety.
370   void* get_ptr(detail::TypeDescriptor type) {
371     auto entry = get_entry_create(type);
372     if (UNLIKELY(entry->instance_weak.expired())) {
373       throw std::runtime_error(
374         "Raw pointer to a singleton requested after its destruction.");
375     }
376     return entry->instance_ptr;
377   }
378
379   // For testing; how many registered and living singletons we have.
380   size_t registeredSingletonCount() const {
381     RWSpinLock::ReadHolder rh(&mutex_);
382
383     return singletons_.size();
384   }
385
386   size_t livingSingletonCount() const {
387     RWSpinLock::ReadHolder rh(&mutex_);
388
389     size_t ret = 0;
390     for (const auto& p : singletons_) {
391       if (p.second->state == detail::SingletonEntryState::Living) {
392         ++ret;
393       }
394     }
395
396     return ret;
397   }
398
399   // A well-known vault; you can actually have others, but this is the
400   // default.
401   static SingletonVault* singleton();
402
403  private:
404   // The two stages of life for a vault, as mentioned in the class comment.
405   enum class SingletonVaultState {
406     Running,
407     Quiescing,
408   };
409
410   // Each singleton in the vault can be in two states: dead
411   // (registered but never created), living (CreateFunc returned an instance).
412
413   void stateCheck(SingletonVaultState expected,
414                   const char* msg="Unexpected singleton state change") {
415     if (expected != state_) {
416         throw std::logic_error(msg);
417     }
418   }
419
420   // This method only matters if registrationComplete() is never called.
421   // Otherwise destroyInstances is scheduled to be executed atexit.
422   //
423   // Initializes static object, which calls destroyInstances on destruction.
424   // Used to have better deletion ordering with singleton not managed by
425   // folly::Singleton. The desruction will happen in the following order:
426   // 1. Singletons, not managed by folly::Singleton, which were created after
427   //    any of the singletons managed by folly::Singleton was requested.
428   // 2. All singletons managed by folly::Singleton
429   // 3. Singletons, not managed by folly::Singleton, which were created before
430   //    any of the singletons managed by folly::Singleton was requested.
431   static void scheduleDestroyInstances();
432
433   detail::SingletonEntry* get_entry(detail::TypeDescriptor type) {
434     RWSpinLock::ReadHolder rh(&mutex_);
435
436     auto it = singletons_.find(type);
437     if (it == singletons_.end()) {
438       throw std::out_of_range(std::string("non-existent singleton: ") +
439                               type.name());
440     }
441
442     return it->second.get();
443   }
444
445   // Get a pointer to the living SingletonEntry for the specified
446   // type.  The singleton is created as part of this function, if
447   // necessary.
448   detail::SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
449     auto entry = get_entry(type);
450
451     if (LIKELY(entry->state == detail::SingletonEntryState::Living)) {
452       return entry;
453     }
454
455     // There's no synchronization here, so we may not see the current value
456     // for creating_thread if it was set by other thread, but we only care about
457     // it if it was set by current thread anyways.
458     if (entry->creating_thread == std::this_thread::get_id()) {
459       throw std::out_of_range(std::string("circular singleton dependency: ") +
460                               type.name());
461     }
462
463     std::lock_guard<std::mutex> entry_lock(entry->mutex);
464
465     if (entry->state == detail::SingletonEntryState::Living) {
466       return entry;
467     }
468
469     entry->creating_thread = std::this_thread::get_id();
470
471     RWSpinLock::ReadHolder rh(&stateMutex_);
472     if (state_ == SingletonVaultState::Quiescing) {
473       entry->creating_thread = std::thread::id();
474       return entry;
475     }
476
477     auto destroy_baton = std::make_shared<folly::Baton<>>();
478     auto teardown = entry->teardown;
479
480     // Can't use make_shared -- no support for a custom deleter, sadly.
481     auto instance = std::shared_ptr<void>(
482       entry->create(),
483       [destroy_baton, teardown](void* instance_ptr) mutable {
484         teardown(instance_ptr);
485         destroy_baton->post();
486       });
487
488     // We should schedule destroyInstances() only after the singleton was
489     // created. This will ensure it will be destroyed before singletons,
490     // not managed by folly::Singleton, which were initialized in its
491     // constructor
492     scheduleDestroyInstances();
493
494     entry->instance = instance;
495     entry->instance_weak = instance;
496     entry->instance_ptr = instance.get();
497     entry->creating_thread = std::thread::id();
498     entry->destroy_baton = std::move(destroy_baton);
499
500     // This has to be the last step, because once state is Living other threads
501     // may access instance and instance_weak w/o synchronization.
502     entry->state.store(detail::SingletonEntryState::Living);
503
504     {
505       RWSpinLock::WriteHolder wh(&mutex_);
506       creation_order_.push_back(type);
507     }
508     return entry;
509   }
510
511   typedef std::unique_ptr<detail::SingletonEntry> SingletonEntryPtr;
512   typedef std::unordered_map<detail::TypeDescriptor,
513                              SingletonEntryPtr,
514                              detail::TypeDescriptorHasher> SingletonMap;
515
516   /* Destroy and clean-up one singleton. Must be invoked while holding
517    * a read lock on mutex_.
518    * @param typeDescriptor - the type key for the removed singleton.
519    */
520   void destroyInstance(SingletonMap::iterator entry_it);
521
522   mutable folly::RWSpinLock mutex_;
523   SingletonMap singletons_;
524   std::vector<detail::TypeDescriptor> creation_order_;
525   SingletonVaultState state_{SingletonVaultState::Running};
526   bool registrationComplete_{false};
527   folly::RWSpinLock stateMutex_;
528   Type type_{Type::Relaxed};
529 };
530
531 // This is the wrapper class that most users actually interact with.
532 // It allows for simple access to registering and instantiating
533 // singletons.  Create instances of this class in the global scope of
534 // type Singleton<T> to register your singleton for later access via
535 // Singleton<T>::get().
536 template <typename T, typename Tag = detail::DefaultTag>
537 class Singleton {
538  public:
539   typedef std::function<T*(void)> CreateFunc;
540   typedef std::function<void(T*)> TeardownFunc;
541
542   // Generally your program life cycle should be fine with calling
543   // get() repeatedly rather than saving the reference, and then not
544   // call get() during process shutdown.
545   static T* get(SingletonVault* vault = nullptr /* for testing */) {
546     return static_cast<T*>(
547       (vault ?: SingletonVault::singleton())->get_ptr(typeDescriptor()));
548   }
549
550   // Same as get, but should be preffered to it in the same compilation
551   // unit, where Singleton is registered.
552   T* get_fast() {
553     if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
554       return reinterpret_cast<T*>(entry_->instance_ptr);
555     } else {
556       return get(vault_);
557     }
558   }
559
560   // If, however, you do need to hold a reference to the specific
561   // singleton, you can try to do so with a weak_ptr.  Avoid this when
562   // possible but the inability to lock the weak pointer can be a
563   // signal that the vault has been destroyed.
564   static std::weak_ptr<T> get_weak(
565       SingletonVault* vault = nullptr /* for testing */) {
566     auto weak_void_ptr =
567       (vault ?: SingletonVault::singleton())->get_weak(typeDescriptor());
568
569     // This is ugly and inefficient, but there's no other way to do it, because
570     // there's no static_pointer_cast for weak_ptr.
571     auto shared_void_ptr = weak_void_ptr.lock();
572     if (!shared_void_ptr) {
573       return std::weak_ptr<T>();
574     }
575     return std::static_pointer_cast<T>(shared_void_ptr);
576   }
577
578   // Same as get_weak, but should be preffered to it in the same compilation
579   // unit, where Singleton is registered.
580   std::weak_ptr<T> get_weak_fast() {
581     if (LIKELY(entry_->state == detail::SingletonEntryState::Living)) {
582       // This is ugly and inefficient, but there's no other way to do it,
583       // because there's no static_pointer_cast for weak_ptr.
584       auto shared_void_ptr = entry_->instance_weak.lock();
585       if (!shared_void_ptr) {
586         return std::weak_ptr<T>();
587       }
588       return std::static_pointer_cast<T>(shared_void_ptr);
589     } else {
590       return get_weak(vault_);
591     }
592   }
593
594   // Allow the Singleton<t> instance to also retrieve the underlying
595   // singleton, if desired.
596   T* ptr() { return get_fast(); }
597   T& operator*() { return *ptr(); }
598   T* operator->() { return ptr(); }
599
600   explicit Singleton(std::nullptr_t _ = nullptr,
601                      Singleton::TeardownFunc t = nullptr,
602                      SingletonVault* vault = nullptr) :
603       Singleton ([]() { return new T; },
604                  std::move(t),
605                  vault) {
606   }
607
608   explicit Singleton(Singleton::CreateFunc c,
609                      Singleton::TeardownFunc t = nullptr,
610                      SingletonVault* vault = nullptr) {
611     if (c == nullptr) {
612       throw std::logic_error(
613         "nullptr_t should be passed if you want T to be default constructed");
614     }
615
616     if (vault == nullptr) {
617       vault = SingletonVault::singleton();
618     }
619
620     vault_ = vault;
621     entry_ =
622       &(vault->registerSingleton(typeDescriptor(), c, getTeardownFunc(t)));
623   }
624
625   /**
626   * Construct and inject a mock singleton which should be used only from tests.
627   * Unlike regular singletons which are initialized once per process lifetime,
628   * mock singletons live for the duration of a test. This means that one process
629   * running multiple tests can initialize and register the same singleton
630   * multiple times. This functionality should be used only from tests
631   * since it relaxes validation and performance in order to be able to perform
632   * the injection. The returned mock singleton is functionality identical to
633   * regular singletons.
634   */
635   static void make_mock(std::nullptr_t c = nullptr,
636                         typename Singleton<T>::TeardownFunc t = nullptr,
637                         SingletonVault* vault = nullptr /* for testing */ ) {
638     make_mock([]() { return new T; }, t, vault);
639   }
640
641   static void make_mock(CreateFunc c,
642                         typename Singleton<T>::TeardownFunc t = nullptr,
643                         SingletonVault* vault = nullptr /* for testing */ ) {
644     if (c == nullptr) {
645       throw std::logic_error(
646         "nullptr_t should be passed if you want T to be default constructed");
647     }
648
649     if (vault == nullptr) {
650       vault = SingletonVault::singleton();
651     }
652
653     vault->registerMockSingleton(
654       typeDescriptor(),
655       c,
656       getTeardownFunc(t));
657   }
658
659  private:
660   static detail::TypeDescriptor typeDescriptor() {
661     return {typeid(T), typeid(Tag)};
662   }
663
664   // Construct SingletonVault::TeardownFunc.
665   static SingletonVault::TeardownFunc getTeardownFunc(
666       TeardownFunc t) {
667     SingletonVault::TeardownFunc teardown;
668     if (t == nullptr) {
669       teardown = [](void* v) { delete static_cast<T*>(v); };
670     } else {
671       teardown = [t](void* v) { t(static_cast<T*>(v)); };
672     }
673
674     return teardown;
675   }
676
677   // This is pointing to SingletonEntry paired with this singleton object. This
678   // is never reset, so each SingletonEntry should never be destroyed.
679   // We rely on the fact that Singleton destructor won't reset this pointer, so
680   // it can be "safely" used even after static Singleton object is destroyed.
681   detail::SingletonEntry* entry_;
682   SingletonVault* vault_;
683 };
684
685 }