Don't re-create singletons
[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::shared_ptr<void> get_shared(detail::TypeDescriptor type) {
237     auto entry = get_entry_create(type);
238     if (UNLIKELY(!entry)) {
239       return std::shared_ptr<void>();
240     }
241     return entry->instance;
242   }
243
244   // This function is inherently racy since we don't hold the
245   // shared_ptr that contains the Singleton.  It is the caller's
246   // responsibility to be sane with this, but it is preferable to use
247   // the weak_ptr interface for true safety.
248   void* get_ptr(detail::TypeDescriptor type) {
249     auto entry = get_entry_create(type);
250     if (UNLIKELY(!entry)) {
251       throw std::runtime_error(
252         "Raw pointer to a singleton requested after its destruction.");
253     }
254     return entry->instance_ptr;
255   }
256
257   // For testing; how many registered and living singletons we have.
258   size_t registeredSingletonCount() const {
259     RWSpinLock::ReadHolder rh(&mutex_);
260
261     return singletons_.size();
262   }
263
264   size_t livingSingletonCount() const {
265     RWSpinLock::ReadHolder rh(&mutex_);
266
267     size_t ret = 0;
268     for (const auto& p : singletons_) {
269       std::lock_guard<std::mutex> entry_guard(p.second->mutex);
270       if (p.second->instance) {
271         ++ret;
272       }
273     }
274
275     return ret;
276   }
277
278   // A well-known vault; you can actually have others, but this is the
279   // default.
280   static SingletonVault* singleton();
281
282  private:
283   // The two stages of life for a vault, as mentioned in the class comment.
284   enum class SingletonVaultState {
285     Running,
286     Quiescing,
287   };
288
289   // Each singleton in the vault can be in three states: dead
290   // (registered but never created), being born (running the
291   // CreateFunc), and living (CreateFunc returned an instance).
292   enum class SingletonEntryState {
293     Dead,
294     BeingBorn,
295     Living,
296   };
297
298   void stateCheck(SingletonVaultState expected,
299                   const char* msg="Unexpected singleton state change") {
300     if (expected != state_) {
301         throw std::logic_error(msg);
302     }
303   }
304
305   // An actual instance of a singleton, tracking the instance itself,
306   // its state as described above, and the create and teardown
307   // functions.
308   struct SingletonEntry {
309     // mutex protects the entire entry
310     std::mutex mutex;
311
312     // state changes notify state_condvar
313     SingletonEntryState state = SingletonEntryState::Dead;
314     std::condition_variable state_condvar;
315
316     // the thread creating the singleton
317     std::thread::id creating_thread;
318
319     // The singleton itself and related functions.
320     std::shared_ptr<void> instance;
321     void* instance_ptr = nullptr;
322     CreateFunc create = nullptr;
323     TeardownFunc teardown = nullptr;
324
325     SingletonEntry() = default;
326     SingletonEntry(const SingletonEntry&) = delete;
327     SingletonEntry& operator=(const SingletonEntry&) = delete;
328     SingletonEntry& operator=(SingletonEntry&&) = delete;
329     SingletonEntry(SingletonEntry&&) = delete;
330   };
331
332   SingletonEntry* get_entry(detail::TypeDescriptor type) {
333     RWSpinLock::ReadHolder rh(&mutex_);
334
335     auto it = singletons_.find(type);
336     if (it == singletons_.end()) {
337       throw std::out_of_range(std::string("non-existent singleton: ") +
338                               type.name());
339     }
340
341     return it->second.get();
342   }
343
344   // Get a pointer to the living SingletonEntry for the specified
345   // type.  The singleton is created as part of this function, if
346   // necessary.
347   SingletonEntry* get_entry_create(detail::TypeDescriptor type) {
348     auto entry = get_entry(type);
349
350     std::unique_lock<std::mutex> entry_lock(entry->mutex);
351
352     if (entry->state == SingletonEntryState::BeingBorn) {
353       // If this thread is trying to give birth to the singleton, it's
354       // a circular dependency and we must panic.
355       if (entry->creating_thread == std::this_thread::get_id()) {
356         throw std::out_of_range(std::string("circular singleton dependency: ") +
357                                 type.name());
358       }
359
360       entry->state_condvar.wait(entry_lock, [&entry]() {
361         return entry->state != SingletonEntryState::BeingBorn;
362       });
363     }
364
365     if (entry->instance == nullptr) {
366       RWSpinLock::ReadHolder rh(&stateMutex_);
367       if (state_ == SingletonVaultState::Quiescing) {
368         return nullptr;
369       }
370
371       CHECK(entry->state == SingletonEntryState::Dead);
372       entry->state = SingletonEntryState::BeingBorn;
373       entry->creating_thread = std::this_thread::get_id();
374
375       entry_lock.unlock();
376       // Can't use make_shared -- no support for a custom deleter, sadly.
377       auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
378       entry_lock.lock();
379
380       CHECK(entry->state == SingletonEntryState::BeingBorn);
381       entry->instance = instance;
382       entry->instance_ptr = instance.get();
383       entry->state = SingletonEntryState::Living;
384       entry->state_condvar.notify_all();
385
386       {
387         RWSpinLock::WriteHolder wh(&mutex_);
388
389         creation_order_.push_back(type);
390       }
391     }
392     CHECK(entry->state == SingletonEntryState::Living);
393     return entry;
394   }
395
396   mutable folly::RWSpinLock mutex_;
397   typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
398   std::unordered_map<detail::TypeDescriptor,
399                      SingletonEntryPtr,
400                      detail::TypeDescriptorHasher> singletons_;
401   std::vector<detail::TypeDescriptor> creation_order_;
402   SingletonVaultState state_{SingletonVaultState::Running};
403   bool registrationComplete_{false};
404   folly::RWSpinLock stateMutex_;
405   Type type_{Type::Relaxed};
406 };
407
408 // This is the wrapper class that most users actually interact with.
409 // It allows for simple access to registering and instantiating
410 // singletons.  Create instances of this class in the global scope of
411 // type Singleton<T> to register your singleton for later access via
412 // Singleton<T>::get().
413 template <typename T>
414 class Singleton {
415  public:
416   typedef std::function<T*(void)> CreateFunc;
417   typedef std::function<void(T*)> TeardownFunc;
418
419   // Generally your program life cycle should be fine with calling
420   // get() repeatedly rather than saving the reference, and then not
421   // call get() during process shutdown.
422   static T* get(SingletonVault* vault = nullptr /* for testing */) {
423     return get_ptr({typeid(T), ""}, vault);
424   }
425
426   static T* get(const char* name,
427                 SingletonVault* vault = nullptr /* for testing */) {
428     return get_ptr({typeid(T), name}, vault);
429   }
430
431   // If, however, you do need to hold a reference to the specific
432   // singleton, you can try to do so with a weak_ptr.  Avoid this when
433   // possible but the inability to lock the weak pointer can be a
434   // signal that the vault has been destroyed.
435   static std::weak_ptr<T> get_weak(
436       SingletonVault* vault = nullptr /* for testing */) {
437     return get_weak("", vault);
438   }
439
440   static std::weak_ptr<T> get_weak(
441       const char* name, SingletonVault* vault = nullptr /* for testing */) {
442     return std::weak_ptr<T>(get_shared({typeid(T), name}, vault));
443   }
444
445   // Allow the Singleton<t> instance to also retrieve the underlying
446   // singleton, if desired.
447   T* ptr() { return get_ptr(type_descriptor_, vault_); }
448   T& operator*() { return *ptr(); }
449   T* operator->() { return ptr(); }
450
451   template <typename CreateFunc = std::nullptr_t>
452   explicit Singleton(CreateFunc c = nullptr,
453                      Singleton::TeardownFunc t = nullptr,
454                      SingletonVault* vault = nullptr /* for testing */)
455       : Singleton({typeid(T), ""}, c, t, vault) {}
456
457   template <typename CreateFunc = std::nullptr_t>
458   explicit Singleton(const char* name,
459                      CreateFunc c = nullptr,
460                      Singleton::TeardownFunc t = nullptr,
461                      SingletonVault* vault = nullptr /* for testing */)
462       : Singleton({typeid(T), name}, c, t, vault) {}
463
464  private:
465   explicit Singleton(detail::TypeDescriptor type,
466                      std::nullptr_t,
467                      Singleton::TeardownFunc t,
468                      SingletonVault* vault) :
469       Singleton (type,
470                  []() { return new T; },
471                  std::move(t),
472                  vault) {
473   }
474
475   explicit Singleton(detail::TypeDescriptor type,
476                      Singleton::CreateFunc c,
477                      Singleton::TeardownFunc t,
478                      SingletonVault* vault)
479       : type_descriptor_(type) {
480     if (c == nullptr) {
481       throw std::logic_error(
482         "nullptr_t should be passed if you want T to be default constructed");
483     }
484     SingletonVault::TeardownFunc teardown;
485     if (t == nullptr) {
486       teardown = [](void* v) { delete static_cast<T*>(v); };
487     } else {
488       teardown = [t](void* v) { t(static_cast<T*>(v)); };
489     }
490
491     if (vault == nullptr) {
492       vault = SingletonVault::singleton();
493     }
494     vault_ = vault;
495     vault->registerSingleton(type, c, teardown);
496   }
497
498   static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
499                     SingletonVault* vault = nullptr /* for testing */) {
500     return static_cast<T*>(
501         (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
502   }
503
504   // Don't use this function, it's private for a reason!  Using it
505   // would defeat the *entire purpose* of the vault in that we lose
506   // the ability to guarantee that, after a destroyInstances is
507   // called, all instances are, in fact, destroyed.  You should use
508   // weak_ptr if you need to hold a reference to the singleton and
509   // guarantee briefly that it exists.
510   //
511   // Yes, you can just get the weak pointer and lock it, but hopefully
512   // if you have taken the time to read this far, you see why that
513   // would be bad.
514   static std::shared_ptr<T> get_shared(
515       detail::TypeDescriptor type_descriptor = {typeid(T), ""},
516       SingletonVault* vault = nullptr /* for testing */) {
517     return std::static_pointer_cast<T>(
518         (vault ?: SingletonVault::singleton())->get_shared(type_descriptor));
519   }
520
521   detail::TypeDescriptor type_descriptor_;
522   SingletonVault* vault_;
523 };
524 }