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