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