Don't throw in Singleton::get() if singleton is alive
[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 // 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 name:
52 //
53 // namespace {
54 // folly::Singleton<MyExpensiveService> s1("name1");
55 // folly::Singleton<MyExpensiveService> s2("name2");
56 // }
57 // ...
58 // MyExpensiveService* svc1 = Singleton<MyExpensiveService>::get("name1");
59 // MyExpensiveService* svc2 = Singleton<MyExpensiveService>::get("name2");
60 //
61 // By default, the singleton instance is constructed via new and
62 // deleted via delete, but this is configurable:
63 //
64 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
65 //                                                                destroy); }
66 //
67 // Where create and destroy are functions, Singleton<T>::CreateFunc
68 // Singleton<T>::TeardownFunc.
69 //
70 // What if you need to destroy all of your singletons?  Say, some of
71 // your singletons manage threads, but you need to fork?  Or your unit
72 // test wants to clean up all global state?  Then you can call
73 // SingletonVault::singleton()->destroyInstances(), which invokes the
74 // TeardownFunc for each singleton, in the reverse order they were
75 // created.  It is your responsibility to ensure your singletons can
76 // handle cases where the singletons they depend on go away, however.
77 // Singletons won't be recreated after destroyInstances call. If you
78 // want to re-enable singleton creation (say after fork was called) you
79 // should call reenableInstances.
80
81 #pragma once
82 #include <folly/Exception.h>
83 #include <folly/Hash.h>
84 #include <folly/RWSpinLock.h>
85
86 #include <vector>
87 #include <mutex>
88 #include <thread>
89 #include <condition_variable>
90 #include <string>
91 #include <unordered_map>
92 #include <functional>
93 #include <typeinfo>
94 #include <typeindex>
95
96 #include <glog/logging.h>
97
98 namespace folly {
99
100 // For actual usage, please see the Singleton<T> class at the bottom
101 // of this file; that is what you will actually interact with.
102
103 // SingletonVault is the class that manages singleton instances.  It
104 // is unaware of the underlying types of singletons, and simply
105 // manages lifecycles and invokes CreateFunc and TeardownFunc when
106 // appropriate.  In general, you won't need to interact with the
107 // SingletonVault itself.
108 //
109 // A vault goes through a few stages of life:
110 //
111 //   1. Registration phase; singletons can be registered, but no
112 //      singleton can be created.
113 //   2. registrationComplete() has been called; singletons can no
114 //      longer be registered, but they can be created.
115 //   3. A vault can return to stage 1 when destroyInstances is called.
116 //
117 // In general, you don't need to worry about any of the above; just
118 // ensure registrationComplete() is called near the top of your main()
119 // function, otherwise no singletons can be instantiated.
120
121 namespace detail {
122
123 const char* const kDefaultTypeDescriptorName = "(default)";
124 // A TypeDescriptor is the unique handle for a given singleton.  It is
125 // a combinaiton of the type and of the optional name, and is used as
126 // a key in unordered_maps.
127 class TypeDescriptor {
128  public:
129   TypeDescriptor(const std::type_info& ti, std::string name)
130       : ti_(ti), name_(name) {
131     if (name_ == kDefaultTypeDescriptorName) {
132       LOG(DFATAL) << "Caller used the default name as their literal name; "
133                   << "name your singleton something other than "
134                   << kDefaultTypeDescriptorName;
135     }
136   }
137
138   std::string name() const {
139     std::string ret = ti_.name();
140     ret += "/";
141     if (name_.empty()) {
142       ret += kDefaultTypeDescriptorName;
143     } else {
144       ret += name_;
145     }
146     return ret;
147   }
148
149   friend class TypeDescriptorHasher;
150
151   bool operator==(const TypeDescriptor& other) const {
152     return ti_ == other.ti_ && name_ == other.name_;
153   }
154
155  private:
156   const std::type_index ti_;
157   const std::string name_;
158 };
159
160 class TypeDescriptorHasher {
161  public:
162   size_t operator()(const TypeDescriptor& ti) const {
163     return folly::hash::hash_combine(ti.ti_, ti.name_);
164   }
165 };
166 }
167
168 class SingletonVault {
169  public:
170   enum class Type { Strict, Relaxed };
171
172   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
173
174   // Destructor is only called by unit tests to check destroyInstances.
175   ~SingletonVault();
176
177   typedef std::function<void(void*)> TeardownFunc;
178   typedef std::function<void*(void)> CreateFunc;
179
180   // Register a singleton of a given type with the create and teardown
181   // functions.
182   void registerSingleton(detail::TypeDescriptor type,
183                          CreateFunc create,
184                          TeardownFunc teardown) {
185     RWSpinLock::ReadHolder rh(&stateMutex_);
186
187     stateCheck(SingletonVaultState::Running);
188     if (UNLIKELY(registrationComplete_)) {
189       throw std::logic_error(
190         "Registering singleton after registrationComplete().");
191     }
192
193     RWSpinLock::WriteHolder wh(&mutex_);
194
195     CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
196     auto& entry = singletons_[type];
197     entry.reset(new SingletonEntry);
198
199     std::lock_guard<std::mutex> entry_guard(entry->mutex);
200     CHECK(entry->instance == nullptr);
201     CHECK(create);
202     CHECK(teardown);
203     entry->create = create;
204     entry->teardown = teardown;
205     entry->state = SingletonEntryState::Dead;
206   }
207
208   // Mark registration is complete; no more singletons can be
209   // registered at this point.
210   void registrationComplete() {
211     RWSpinLock::WriteHolder wh(&stateMutex_);
212
213     stateCheck(SingletonVaultState::Running);
214
215     if (type_ == Type::Strict) {
216       for (const auto& id_singleton_entry: singletons_) {
217         const auto& singleton_entry = *id_singleton_entry.second;
218         if (singleton_entry.state != SingletonEntryState::Dead) {
219           throw std::runtime_error(
220             "Singleton created before registration was complete.");
221         }
222       }
223     }
224
225     registrationComplete_ = true;
226   }
227
228   // Destroy all singletons; when complete, the vault can't create
229   // singletons once again until reenableInstances() is called.
230   void destroyInstances();
231
232   // Enable re-creating singletons after destroyInstances() was called.
233   void reenableInstances();
234
235   // Retrieve a singleton from the vault, creating it if necessary.
236   std::weak_ptr<void> get_weak(detail::TypeDescriptor type) {
237     auto entry = get_entry_create(type);
238     return entry->instance_weak;
239   }
240
241   // This function is inherently racy since we don't hold the
242   // shared_ptr that contains the Singleton.  It is the caller's
243   // responsibility to be sane with this, but it is preferable to use
244   // the weak_ptr interface for true safety.
245   void* get_ptr(detail::TypeDescriptor type) {
246     auto entry = get_entry_create(type);
247     if (UNLIKELY(entry->instance_weak.expired())) {
248       throw std::runtime_error(
249         "Raw pointer to a singleton requested after its destruction.");
250     }
251     return entry->instance_ptr;
252   }
253
254   // For testing; how many registered and living singletons we have.
255   size_t registeredSingletonCount() const {
256     RWSpinLock::ReadHolder rh(&mutex_);
257
258     return singletons_.size();
259   }
260
261   size_t livingSingletonCount() const {
262     RWSpinLock::ReadHolder rh(&mutex_);
263
264     size_t ret = 0;
265     for (const auto& p : singletons_) {
266       std::lock_guard<std::mutex> entry_guard(p.second->mutex);
267       if (p.second->instance) {
268         ++ret;
269       }
270     }
271
272     return ret;
273   }
274
275   // A well-known vault; you can actually have others, but this is the
276   // default.
277   static SingletonVault* singleton();
278
279  private:
280   // The two stages of life for a vault, as mentioned in the class comment.
281   enum class SingletonVaultState {
282     Running,
283     Quiescing,
284   };
285
286   // Each singleton in the vault can be in three states: dead
287   // (registered but never created), being born (running the
288   // CreateFunc), and living (CreateFunc returned an instance).
289   enum class SingletonEntryState {
290     Dead,
291     BeingBorn,
292     Living,
293   };
294
295   void stateCheck(SingletonVaultState expected,
296                   const char* msg="Unexpected singleton state change") {
297     if (expected != state_) {
298         throw std::logic_error(msg);
299     }
300   }
301
302   // An actual instance of a singleton, tracking the instance itself,
303   // its state as described above, and the create and teardown
304   // functions.
305   struct SingletonEntry {
306     // mutex protects the entire entry
307     std::mutex mutex;
308
309     // state changes notify state_condvar
310     SingletonEntryState state = SingletonEntryState::Dead;
311     std::condition_variable state_condvar;
312
313     // the thread creating the singleton
314     std::thread::id creating_thread;
315
316     // The singleton itself and related functions.
317     std::shared_ptr<void> instance;
318     std::weak_ptr<void> instance_weak;
319     void* instance_ptr = nullptr;
320     CreateFunc create = nullptr;
321     TeardownFunc teardown = nullptr;
322
323     SingletonEntry() = default;
324     SingletonEntry(const SingletonEntry&) = delete;
325     SingletonEntry& operator=(const SingletonEntry&) = delete;
326     SingletonEntry& operator=(SingletonEntry&&) = delete;
327     SingletonEntry(SingletonEntry&&) = delete;
328   };
329
330   // Initializes static object, which calls destroyInstances on destruction.
331   // Used to have better deletion ordering with singleton not managed by
332   // folly::Singleton. The desruction will happen in the following order:
333   // 1. Singletons, not managed by folly::Singleton, which were created after
334   //    any of the singletons managed by folly::Singleton was requested.
335   // 2. All singletons managed by folly::Singleton
336   // 3. Singletons, not managed by folly::Singleton, which were created before
337   //    any of the singletons managed by folly::Singleton was requested.
338   static void scheduleDestroyInstances();
339
340   SingletonEntry* get_entry(detail::TypeDescriptor type) {
341     RWSpinLock::ReadHolder rh(&mutex_);
342
343     auto it = singletons_.find(type);
344     if (it == singletons_.end()) {
345       throw std::out_of_range(std::string("non-existent singleton: ") +
346                               type.name());
347     }
348
349     return it->second.get();
350   }
351
352   // Get a pointer to the living SingletonEntry for the specified
353   // type.  The singleton is created as part of this function, if
354   // necessary.
355   SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
356     auto entry = get_entry(type);
357
358     std::unique_lock<std::mutex> entry_lock(entry->mutex);
359
360     if (entry->state == SingletonEntryState::BeingBorn) {
361       // If this thread is trying to give birth to the singleton, it's
362       // a circular dependency and we must panic.
363       if (entry->creating_thread == std::this_thread::get_id()) {
364         throw std::out_of_range(std::string("circular singleton dependency: ") +
365                                 type.name());
366       }
367
368       entry->state_condvar.wait(entry_lock, [&entry]() {
369         return entry->state != SingletonEntryState::BeingBorn;
370       });
371     }
372
373     if (entry->instance == nullptr) {
374       RWSpinLock::ReadHolder rh(&stateMutex_);
375       if (state_ == SingletonVaultState::Quiescing) {
376         return entry;
377       }
378
379       CHECK(entry->state == SingletonEntryState::Dead);
380       entry->state = SingletonEntryState::BeingBorn;
381       entry->creating_thread = std::this_thread::get_id();
382
383       entry_lock.unlock();
384       // Can't use make_shared -- no support for a custom deleter, sadly.
385       auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
386
387       // We should schedule destroyInstances() only after the singleton was
388       // created. This will ensure it will be destroyed before singletons,
389       // not managed by folly::Singleton, which were initialized in its
390       // constructor
391       scheduleDestroyInstances();
392
393       entry_lock.lock();
394
395       CHECK(entry->state == SingletonEntryState::BeingBorn);
396       entry->instance = instance;
397       entry->instance_weak = instance;
398       entry->instance_ptr = instance.get();
399       entry->state = SingletonEntryState::Living;
400       entry->state_condvar.notify_all();
401
402       {
403         RWSpinLock::WriteHolder wh(&mutex_);
404
405         creation_order_.push_back(type);
406       }
407     }
408     CHECK(entry->state == SingletonEntryState::Living);
409     return entry;
410   }
411
412   mutable folly::RWSpinLock mutex_;
413   typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
414   std::unordered_map<detail::TypeDescriptor,
415                      SingletonEntryPtr,
416                      detail::TypeDescriptorHasher> singletons_;
417   std::vector<detail::TypeDescriptor> creation_order_;
418   SingletonVaultState state_{SingletonVaultState::Running};
419   bool registrationComplete_{false};
420   folly::RWSpinLock stateMutex_;
421   Type type_{Type::Relaxed};
422 };
423
424 // This is the wrapper class that most users actually interact with.
425 // It allows for simple access to registering and instantiating
426 // singletons.  Create instances of this class in the global scope of
427 // type Singleton<T> to register your singleton for later access via
428 // Singleton<T>::get().
429 template <typename T>
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(SingletonVault* vault = nullptr /* for testing */) {
439     return get_ptr({typeid(T), ""}, vault);
440   }
441
442   static T* get(const char* name,
443                 SingletonVault* vault = nullptr /* for testing */) {
444     return get_ptr({typeid(T), name}, vault);
445   }
446
447   // If, however, you do need to hold a reference to the specific
448   // singleton, you can try to do so with a weak_ptr.  Avoid this when
449   // possible but the inability to lock the weak pointer can be a
450   // signal that the vault has been destroyed.
451   static std::weak_ptr<T> get_weak(
452       SingletonVault* vault = nullptr /* for testing */) {
453     return get_weak("", vault);
454   }
455
456   static std::weak_ptr<T> get_weak(
457       const char* name, SingletonVault* vault = nullptr /* for testing */) {
458     auto weak_void_ptr =
459       (vault ?: SingletonVault::singleton())->get_weak({typeid(T), name});
460
461     // This is ugly and inefficient, but there's no other way to do it, because
462     // there's no static_pointer_cast for weak_ptr.
463     auto shared_void_ptr = weak_void_ptr.lock();
464     if (!shared_void_ptr) {
465       return std::weak_ptr<T>();
466     }
467     return std::static_pointer_cast<T>(shared_void_ptr);
468   }
469
470   // Allow the Singleton<t> instance to also retrieve the underlying
471   // singleton, if desired.
472   T* ptr() { return get_ptr(type_descriptor_, vault_); }
473   T& operator*() { return *ptr(); }
474   T* operator->() { return ptr(); }
475
476   template <typename CreateFunc = std::nullptr_t>
477   explicit Singleton(CreateFunc c = nullptr,
478                      Singleton::TeardownFunc t = nullptr,
479                      SingletonVault* vault = nullptr /* for testing */)
480       : Singleton({typeid(T), ""}, c, t, vault) {}
481
482   template <typename CreateFunc = std::nullptr_t>
483   explicit Singleton(const char* name,
484                      CreateFunc c = nullptr,
485                      Singleton::TeardownFunc t = nullptr,
486                      SingletonVault* vault = nullptr /* for testing */)
487       : Singleton({typeid(T), name}, c, t, vault) {}
488
489  private:
490   explicit Singleton(detail::TypeDescriptor type,
491                      std::nullptr_t,
492                      Singleton::TeardownFunc t,
493                      SingletonVault* vault) :
494       Singleton (type,
495                  []() { return new T; },
496                  std::move(t),
497                  vault) {
498   }
499
500   explicit Singleton(detail::TypeDescriptor type,
501                      Singleton::CreateFunc c,
502                      Singleton::TeardownFunc t,
503                      SingletonVault* vault)
504       : type_descriptor_(type) {
505     if (c == nullptr) {
506       throw std::logic_error(
507         "nullptr_t should be passed if you want T to be default constructed");
508     }
509     SingletonVault::TeardownFunc teardown;
510     if (t == nullptr) {
511       teardown = [](void* v) { delete static_cast<T*>(v); };
512     } else {
513       teardown = [t](void* v) { t(static_cast<T*>(v)); };
514     }
515
516     if (vault == nullptr) {
517       vault = SingletonVault::singleton();
518     }
519     vault_ = vault;
520     vault->registerSingleton(type, c, teardown);
521   }
522
523   static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
524                     SingletonVault* vault = nullptr /* for testing */) {
525     return static_cast<T*>(
526         (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
527   }
528
529   // Don't use this function, it's private for a reason!  Using it
530   // would defeat the *entire purpose* of the vault in that we lose
531   // the ability to guarantee that, after a destroyInstances is
532   // called, all instances are, in fact, destroyed.  You should use
533   // weak_ptr if you need to hold a reference to the singleton and
534   // guarantee briefly that it exists.
535   //
536   // Yes, you can just get the weak pointer and lock it, but hopefully
537   // if you have taken the time to read this far, you see why that
538   // would be bad.
539   static std::shared_ptr<T> get_shared(
540       detail::TypeDescriptor type_descriptor = {typeid(T), ""},
541       SingletonVault* vault = nullptr /* for testing */) {
542     return std::static_pointer_cast<T>(
543       (vault ?: SingletonVault::singleton())->get_weak(type_descriptor).lock());
544   }
545
546   detail::TypeDescriptor type_descriptor_;
547   SingletonVault* vault_;
548 };
549 }