Fix bug in circular singleton creation detection
[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
78 #pragma once
79 #include <folly/Exception.h>
80 #include <folly/Hash.h>
81
82 #include <vector>
83 #include <mutex>
84 #include <thread>
85 #include <condition_variable>
86 #include <string>
87 #include <unordered_map>
88 #include <functional>
89 #include <typeinfo>
90 #include <typeindex>
91
92 #include <glog/logging.h>
93
94 namespace folly {
95
96 // For actual usage, please see the Singleton<T> class at the bottom
97 // of this file; that is what you will actually interact with.
98
99 // SingletonVault is the class that manages singleton instances.  It
100 // is unaware of the underlying types of singletons, and simply
101 // manages lifecycles and invokes CreateFunc and TeardownFunc when
102 // appropriate.  In general, you won't need to interact with the
103 // SingletonVault itself.
104 //
105 // A vault goes through a few stages of life:
106 //
107 //   1. Registration phase; singletons can be registered, but no
108 //      singleton can be created.
109 //   2. registrationComplete() has been called; singletons can no
110 //      longer be registered, but they can be created.
111 //   3. A vault can return to stage 1 when destroyInstances is called.
112 //
113 // In general, you don't need to worry about any of the above; just
114 // ensure registrationComplete() is called near the top of your main()
115 // function, otherwise no singletons can be instantiated.
116
117 namespace detail {
118
119 const char* const kDefaultTypeDescriptorName = "(default)";
120 // A TypeDescriptor is the unique handle for a given singleton.  It is
121 // a combinaiton of the type and of the optional name, and is used as
122 // a key in unordered_maps.
123 class TypeDescriptor {
124  public:
125   TypeDescriptor(const std::type_info& ti, std::string name)
126       : ti_(ti), name_(name) {
127     if (name_ == kDefaultTypeDescriptorName) {
128       LOG(DFATAL) << "Caller used the default name as their literal name; "
129                   << "name your singleton something other than "
130                   << kDefaultTypeDescriptorName;
131     }
132   }
133
134   std::string name() const {
135     std::string ret = ti_.name();
136     ret += "/";
137     if (name_.empty()) {
138       ret += kDefaultTypeDescriptorName;
139     } else {
140       ret += name_;
141     }
142     return ret;
143   }
144
145   friend class TypeDescriptorHasher;
146
147   bool operator==(const TypeDescriptor& other) const {
148     return ti_ == other.ti_ && name_ == other.name_;
149   }
150
151  private:
152   const std::type_index ti_;
153   const std::string name_;
154 };
155
156 class TypeDescriptorHasher {
157  public:
158   size_t operator()(const TypeDescriptor& ti) const {
159     return folly::hash::hash_combine(ti.ti_, ti.name_);
160   }
161 };
162 }
163
164 class SingletonVault {
165  public:
166   SingletonVault() {};
167   ~SingletonVault();
168
169   typedef std::function<void(void*)> TeardownFunc;
170   typedef std::function<void*(void)> CreateFunc;
171
172   // Register a singleton of a given type with the create and teardown
173   // functions.
174   void registerSingleton(detail::TypeDescriptor type,
175                          CreateFunc create,
176                          TeardownFunc teardown) {
177     std::lock_guard<std::mutex> guard(mutex_);
178
179     CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
180     CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
181     auto& entry = singletons_[type];
182     if (!entry) {
183       entry.reset(new SingletonEntry);
184     }
185
186     std::lock_guard<std::mutex> entry_guard(entry->mutex);
187     CHECK(entry->instance == nullptr);
188     CHECK(create);
189     CHECK(teardown);
190     entry->create = create;
191     entry->teardown = teardown;
192     entry->state = SingletonEntryState::Dead;
193   }
194
195   // Mark registration is complete; no more singletons can be
196   // registered at this point.
197   void registrationComplete() {
198     std::lock_guard<std::mutex> guard(mutex_);
199     CHECK_THROW(state_ == SingletonVaultState::Registering, std::logic_error);
200     state_ = SingletonVaultState::Running;
201   }
202
203   // Destroy all singletons; when complete, the vault can create
204   // singletons once again, or remain dormant.
205   void destroyInstances();
206
207   // Retrieve a singleton from the vault, creating it if necessary.
208   std::shared_ptr<void> get_shared(detail::TypeDescriptor type) {
209     std::unique_lock<std::mutex> lock(mutex_);
210     auto entry = get_entry(type, &lock);
211     return entry->instance;
212   }
213
214   // This function is inherently racy since we don't hold the
215   // shared_ptr that contains the Singleton.  It is the caller's
216   // responsibility to be sane with this, but it is preferable to use
217   // the weak_ptr interface for true safety.
218   void* get_ptr(detail::TypeDescriptor type) {
219     std::unique_lock<std::mutex> lock(mutex_);
220     auto entry = get_entry(type, &lock);
221     return entry->instance_ptr;
222   }
223
224   // For testing; how many registered and living singletons we have.
225   size_t registeredSingletonCount() const {
226     std::lock_guard<std::mutex> guard(mutex_);
227     return singletons_.size();
228   }
229
230   size_t livingSingletonCount() const {
231     std::lock_guard<std::mutex> guard(mutex_);
232     size_t ret = 0;
233     for (const auto& p : singletons_) {
234       if (p.second->instance) {
235         ++ret;
236       }
237     }
238
239     return ret;
240   }
241
242   // A well-known vault; you can actually have others, but this is the
243   // default.
244   static SingletonVault* singleton();
245
246  private:
247   // The two stages of life for a vault, as mentioned in the class comment.
248   enum class SingletonVaultState {
249     Registering,
250     Running,
251   };
252
253   // Each singleton in the vault can be in three states: dead
254   // (registered but never created), being born (running the
255   // CreateFunc), and living (CreateFunc returned an instance).
256   enum class SingletonEntryState {
257     Dead,
258     BeingBorn,
259     Living,
260   };
261
262   // An actual instance of a singleton, tracking the instance itself,
263   // its state as described above, and the create and teardown
264   // functions.
265   struct SingletonEntry {
266     // mutex protects the entire entry
267     std::mutex mutex;
268
269     // state changes notify state_condvar
270     SingletonEntryState state = SingletonEntryState::Dead;
271     std::condition_variable state_condvar;
272
273     // the thread creating the singleton
274     std::thread::id creating_thread;
275
276     // The singleton itself and related functions.
277     std::shared_ptr<void> instance;
278     void* instance_ptr = nullptr;
279     CreateFunc create = nullptr;
280     TeardownFunc teardown = nullptr;
281
282     SingletonEntry() = default;
283     SingletonEntry(const SingletonEntry&) = delete;
284     SingletonEntry& operator=(const SingletonEntry&) = delete;
285     SingletonEntry& operator=(SingletonEntry&&) = delete;
286     SingletonEntry(SingletonEntry&&) = delete;
287   };
288
289   // Get a pointer to the living SingletonEntry for the specified
290   // type.  The singleton is created as part of this function, if
291   // necessary.
292   SingletonEntry* get_entry(detail::TypeDescriptor type,
293                             std::unique_lock<std::mutex>* lock) {
294     // mutex must be held when calling this function
295     if (state_ != SingletonVaultState::Running) {
296       throw std::logic_error(
297           "Attempt to load a singleton before "
298           "SingletonVault::registrationComplete was called (hint: you probably "
299           "didn't call initFacebook)");
300     }
301
302     auto it = singletons_.find(type);
303     if (it == singletons_.end()) {
304       throw std::out_of_range(std::string("non-existent singleton: ") +
305                               type.name());
306     }
307
308     auto entry = it->second.get();
309     std::unique_lock<std::mutex> entry_lock(entry->mutex);
310
311     if (entry->state == SingletonEntryState::BeingBorn) {
312       // If this thread is trying to give birth to the singleton, it's
313       // a circular dependency and we must panic.
314       if (entry->creating_thread == std::this_thread::get_id()) {
315         throw std::out_of_range(std::string("circular singleton dependency: ") +
316                                 type.name());
317       }
318
319       // Otherwise, another thread is constructing the singleton;
320       // let's wait on a condvar to see it complete.  We release and
321       // reaquire lock while waiting on the entry to resolve its state.
322       lock->unlock();
323       entry->state_condvar.wait(entry_lock, [&entry]() {
324         return entry->state != SingletonEntryState::BeingBorn;
325       });
326       lock->lock();
327     }
328
329     if (entry->instance == nullptr) {
330       CHECK(entry->state == SingletonEntryState::Dead);
331       entry->state = SingletonEntryState::BeingBorn;
332       entry->creating_thread = std::this_thread::get_id();
333
334       entry_lock.unlock();
335       lock->unlock();
336       // Can't use make_shared -- no support for a custom deleter, sadly.
337       auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
338       lock->lock();
339       entry_lock.lock();
340
341       CHECK(entry->state == SingletonEntryState::BeingBorn);
342       entry->instance = instance;
343       entry->instance_ptr = instance.get();
344       entry->state = SingletonEntryState::Living;
345       entry->state_condvar.notify_all();
346
347       creation_order_.push_back(type);
348     }
349     CHECK(entry->state == SingletonEntryState::Living);
350     return entry;
351   }
352
353   mutable std::mutex mutex_;
354   typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
355   std::unordered_map<detail::TypeDescriptor,
356                      SingletonEntryPtr,
357                      detail::TypeDescriptorHasher> singletons_;
358   std::vector<detail::TypeDescriptor> creation_order_;
359   SingletonVaultState state_ = SingletonVaultState::Registering;
360 };
361
362 // This is the wrapper class that most users actually interact with.
363 // It allows for simple access to registering and instantiating
364 // singletons.  Create instances of this class in the global scope of
365 // type Singleton<T> to register your singleton for later access via
366 // Singleton<T>::get().
367 template <typename T>
368 class Singleton {
369  public:
370   typedef std::function<T*(void)> CreateFunc;
371   typedef std::function<void(T*)> TeardownFunc;
372
373   // Generally your program life cycle should be fine with calling
374   // get() repeatedly rather than saving the reference, and then not
375   // call get() during process shutdown.
376   static T* get(SingletonVault* vault = nullptr /* for testing */) {
377     return get_ptr({typeid(T), ""}, vault);
378   }
379
380   static T* get(const char* name,
381                 SingletonVault* vault = nullptr /* for testing */) {
382     return get_ptr({typeid(T), name}, vault);
383   }
384
385   // If, however, you do need to hold a reference to the specific
386   // singleton, you can try to do so with a weak_ptr.  Avoid this when
387   // possible but the inability to lock the weak pointer can be a
388   // signal that the vault has been destroyed.
389   static std::weak_ptr<T> get_weak(
390       SingletonVault* vault = nullptr /* for testing */) {
391     return get_weak("", vault);
392   }
393
394   static std::weak_ptr<T> get_weak(
395       const char* name, SingletonVault* vault = nullptr /* for testing */) {
396     return std::weak_ptr<T>(get_shared({typeid(T), name}, vault));
397   }
398
399   std::weak_ptr<T> get_weak(const char* name) {
400     return std::weak_ptr<T>(get_shared({typeid(T), name}, vault_));
401   }
402
403   // Allow the Singleton<t> instance to also retrieve the underlying
404   // singleton, if desired.
405   T* ptr() { return get_ptr(type_descriptor_, vault_); }
406   T& operator*() { return *ptr(); }
407   T* operator->() { return ptr(); }
408
409   explicit Singleton(Singleton::CreateFunc c = nullptr,
410                      Singleton::TeardownFunc t = nullptr,
411                      SingletonVault* vault = nullptr /* for testing */)
412       : Singleton({typeid(T), ""}, c, t, vault) {}
413
414   explicit Singleton(const char* name,
415                      Singleton::CreateFunc c = nullptr,
416                      Singleton::TeardownFunc t = nullptr,
417                      SingletonVault* vault = nullptr /* for testing */)
418       : Singleton({typeid(T), name}, c, t, vault) {}
419
420  private:
421   explicit Singleton(detail::TypeDescriptor type,
422                      Singleton::CreateFunc c = nullptr,
423                      Singleton::TeardownFunc t = nullptr,
424                      SingletonVault* vault = nullptr /* for testing */)
425       : type_descriptor_(type) {
426     if (c == nullptr) {
427       c = []() { return new T; };
428     }
429     SingletonVault::TeardownFunc teardown;
430     if (t == nullptr) {
431       teardown = [](void* v) { delete static_cast<T*>(v); };
432     } else {
433       teardown = [t](void* v) { t(static_cast<T*>(v)); };
434     }
435
436     if (vault == nullptr) {
437       vault = SingletonVault::singleton();
438     }
439     vault_ = vault;
440     vault->registerSingleton(type, c, teardown);
441   }
442
443   static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
444                     SingletonVault* vault = nullptr /* for testing */) {
445     return static_cast<T*>(
446         (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
447   }
448
449   // Don't use this function, it's private for a reason!  Using it
450   // would defeat the *entire purpose* of the vault in that we lose
451   // the ability to guarantee that, after a destroyInstances is
452   // called, all instances are, in fact, destroyed.  You should use
453   // weak_ptr if you need to hold a reference to the singleton and
454   // guarantee briefly that it exists.
455   //
456   // Yes, you can just get the weak pointer and lock it, but hopefully
457   // if you have taken the time to read this far, you see why that
458   // would be bad.
459   static std::shared_ptr<T> get_shared(
460       detail::TypeDescriptor type_descriptor = {typeid(T), ""},
461       SingletonVault* vault = nullptr /* for testing */) {
462     return std::static_pointer_cast<T>(
463         (vault ?: SingletonVault::singleton())->get_shared(type_descriptor));
464   }
465
466   detail::TypeDescriptor type_descriptor_;
467   SingletonVault* vault_;
468 };
469 }