Adding IO stats in AsyncIO.
[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   enum class Type { Strict, Relaxed };
167
168   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
169   ~SingletonVault();
170
171   typedef std::function<void(void*)> TeardownFunc;
172   typedef std::function<void*(void)> CreateFunc;
173
174   // Register a singleton of a given type with the create and teardown
175   // functions.
176   void registerSingleton(detail::TypeDescriptor type,
177                          CreateFunc create,
178                          TeardownFunc teardown) {
179     std::lock_guard<std::mutex> guard(mutex_);
180
181     stateCheck(SingletonVaultState::Registering);
182     CHECK_THROW(singletons_.find(type) == singletons_.end(), std::logic_error);
183     auto& entry = singletons_[type];
184     if (!entry) {
185       entry.reset(new SingletonEntry);
186     }
187
188     std::lock_guard<std::mutex> entry_guard(entry->mutex);
189     CHECK(entry->instance == nullptr);
190     CHECK(create);
191     CHECK(teardown);
192     entry->create = create;
193     entry->teardown = teardown;
194     entry->state = SingletonEntryState::Dead;
195   }
196
197   // Mark registration is complete; no more singletons can be
198   // registered at this point.
199   void registrationComplete() {
200     std::lock_guard<std::mutex> guard(mutex_);
201     stateCheck(SingletonVaultState::Registering);
202     state_ = SingletonVaultState::Running;
203   }
204
205   // Destroy all singletons; when complete, the vault can create
206   // singletons once again, or remain dormant.
207   void destroyInstances();
208
209   // Retrieve a singleton from the vault, creating it if necessary.
210   std::shared_ptr<void> get_shared(detail::TypeDescriptor type) {
211     std::unique_lock<std::mutex> lock(mutex_);
212     auto entry = get_entry(type, &lock);
213     return entry->instance;
214   }
215
216   // This function is inherently racy since we don't hold the
217   // shared_ptr that contains the Singleton.  It is the caller's
218   // responsibility to be sane with this, but it is preferable to use
219   // the weak_ptr interface for true safety.
220   void* get_ptr(detail::TypeDescriptor type) {
221     std::unique_lock<std::mutex> lock(mutex_);
222     auto entry = get_entry(type, &lock);
223     return entry->instance_ptr;
224   }
225
226   // For testing; how many registered and living singletons we have.
227   size_t registeredSingletonCount() const {
228     std::lock_guard<std::mutex> guard(mutex_);
229     return singletons_.size();
230   }
231
232   size_t livingSingletonCount() const {
233     std::lock_guard<std::mutex> guard(mutex_);
234     size_t ret = 0;
235     for (const auto& p : singletons_) {
236       if (p.second->instance) {
237         ++ret;
238       }
239     }
240
241     return ret;
242   }
243
244   // A well-known vault; you can actually have others, but this is the
245   // default.
246   static SingletonVault* singleton();
247
248  private:
249   // The two stages of life for a vault, as mentioned in the class comment.
250   enum class SingletonVaultState {
251     Registering,
252     Running,
253   };
254
255   // Each singleton in the vault can be in three states: dead
256   // (registered but never created), being born (running the
257   // CreateFunc), and living (CreateFunc returned an instance).
258   enum class SingletonEntryState {
259     Dead,
260     BeingBorn,
261     Living,
262   };
263
264   void stateCheck(SingletonVaultState expected,
265                   const char* msg="Unexpected singleton state change") {
266     if (type_ == Type::Strict && expected != state_) {
267         throw std::logic_error(msg);
268     }
269   }
270
271   // An actual instance of a singleton, tracking the instance itself,
272   // its state as described above, and the create and teardown
273   // functions.
274   struct SingletonEntry {
275     // mutex protects the entire entry
276     std::mutex mutex;
277
278     // state changes notify state_condvar
279     SingletonEntryState state = SingletonEntryState::Dead;
280     std::condition_variable state_condvar;
281
282     // the thread creating the singleton
283     std::thread::id creating_thread;
284
285     // The singleton itself and related functions.
286     std::shared_ptr<void> instance;
287     void* instance_ptr = nullptr;
288     CreateFunc create = nullptr;
289     TeardownFunc teardown = nullptr;
290
291     SingletonEntry() = default;
292     SingletonEntry(const SingletonEntry&) = delete;
293     SingletonEntry& operator=(const SingletonEntry&) = delete;
294     SingletonEntry& operator=(SingletonEntry&&) = delete;
295     SingletonEntry(SingletonEntry&&) = delete;
296   };
297
298   // Get a pointer to the living SingletonEntry for the specified
299   // type.  The singleton is created as part of this function, if
300   // necessary.
301   SingletonEntry* get_entry(detail::TypeDescriptor type,
302                             std::unique_lock<std::mutex>* lock) {
303     // mutex must be held when calling this function
304     stateCheck(
305         SingletonVaultState::Running,
306         "Attempt to load a singleton before "
307         "SingletonVault::registrationComplete was called (hint: you probably "
308         "didn't call initFacebook)");
309
310     auto it = singletons_.find(type);
311     if (it == singletons_.end()) {
312       throw std::out_of_range(std::string("non-existent singleton: ") +
313                               type.name());
314     }
315
316     auto entry = it->second.get();
317     std::unique_lock<std::mutex> entry_lock(entry->mutex);
318
319     if (entry->state == SingletonEntryState::BeingBorn) {
320       // If this thread is trying to give birth to the singleton, it's
321       // a circular dependency and we must panic.
322       if (entry->creating_thread == std::this_thread::get_id()) {
323         throw std::out_of_range(std::string("circular singleton dependency: ") +
324                                 type.name());
325       }
326
327       // Otherwise, another thread is constructing the singleton;
328       // let's wait on a condvar to see it complete.  We release and
329       // reaquire lock while waiting on the entry to resolve its state.
330       lock->unlock();
331       entry->state_condvar.wait(entry_lock, [&entry]() {
332         return entry->state != SingletonEntryState::BeingBorn;
333       });
334       lock->lock();
335     }
336
337     if (entry->instance == nullptr) {
338       CHECK(entry->state == SingletonEntryState::Dead);
339       entry->state = SingletonEntryState::BeingBorn;
340       entry->creating_thread = std::this_thread::get_id();
341
342       entry_lock.unlock();
343       lock->unlock();
344       // Can't use make_shared -- no support for a custom deleter, sadly.
345       auto instance = std::shared_ptr<void>(entry->create(), entry->teardown);
346       lock->lock();
347       entry_lock.lock();
348
349       CHECK(entry->state == SingletonEntryState::BeingBorn);
350       entry->instance = instance;
351       entry->instance_ptr = instance.get();
352       entry->state = SingletonEntryState::Living;
353       entry->state_condvar.notify_all();
354
355       creation_order_.push_back(type);
356     }
357     CHECK(entry->state == SingletonEntryState::Living);
358     return entry;
359   }
360
361   mutable std::mutex mutex_;
362   typedef std::unique_ptr<SingletonEntry> SingletonEntryPtr;
363   std::unordered_map<detail::TypeDescriptor,
364                      SingletonEntryPtr,
365                      detail::TypeDescriptorHasher> singletons_;
366   std::vector<detail::TypeDescriptor> creation_order_;
367   SingletonVaultState state_ = SingletonVaultState::Registering;
368   Type type_ = Type::Relaxed;
369 };
370
371 // This is the wrapper class that most users actually interact with.
372 // It allows for simple access to registering and instantiating
373 // singletons.  Create instances of this class in the global scope of
374 // type Singleton<T> to register your singleton for later access via
375 // Singleton<T>::get().
376 template <typename T>
377 class Singleton {
378  public:
379   typedef std::function<T*(void)> CreateFunc;
380   typedef std::function<void(T*)> TeardownFunc;
381
382   // Generally your program life cycle should be fine with calling
383   // get() repeatedly rather than saving the reference, and then not
384   // call get() during process shutdown.
385   static T* get(SingletonVault* vault = nullptr /* for testing */) {
386     return get_ptr({typeid(T), ""}, vault);
387   }
388
389   static T* get(const char* name,
390                 SingletonVault* vault = nullptr /* for testing */) {
391     return get_ptr({typeid(T), name}, vault);
392   }
393
394   // If, however, you do need to hold a reference to the specific
395   // singleton, you can try to do so with a weak_ptr.  Avoid this when
396   // possible but the inability to lock the weak pointer can be a
397   // signal that the vault has been destroyed.
398   static std::weak_ptr<T> get_weak(
399       SingletonVault* vault = nullptr /* for testing */) {
400     return get_weak("", vault);
401   }
402
403   static std::weak_ptr<T> get_weak(
404       const char* name, SingletonVault* vault = nullptr /* for testing */) {
405     return std::weak_ptr<T>(get_shared({typeid(T), name}, vault));
406   }
407
408   std::weak_ptr<T> get_weak(const char* name) {
409     return std::weak_ptr<T>(get_shared({typeid(T), name}, vault_));
410   }
411
412   // Allow the Singleton<t> instance to also retrieve the underlying
413   // singleton, if desired.
414   T* ptr() { return get_ptr(type_descriptor_, vault_); }
415   T& operator*() { return *ptr(); }
416   T* operator->() { return ptr(); }
417
418   explicit Singleton(Singleton::CreateFunc c = nullptr,
419                      Singleton::TeardownFunc t = nullptr,
420                      SingletonVault* vault = nullptr /* for testing */)
421       : Singleton({typeid(T), ""}, c, t, vault) {}
422
423   explicit Singleton(const char* name,
424                      Singleton::CreateFunc c = nullptr,
425                      Singleton::TeardownFunc t = nullptr,
426                      SingletonVault* vault = nullptr /* for testing */)
427       : Singleton({typeid(T), name}, c, t, vault) {}
428
429  private:
430   explicit Singleton(detail::TypeDescriptor type,
431                      Singleton::CreateFunc c = nullptr,
432                      Singleton::TeardownFunc t = nullptr,
433                      SingletonVault* vault = nullptr /* for testing */)
434       : type_descriptor_(type) {
435     if (c == nullptr) {
436       c = []() { return new T; };
437     }
438     SingletonVault::TeardownFunc teardown;
439     if (t == nullptr) {
440       teardown = [](void* v) { delete static_cast<T*>(v); };
441     } else {
442       teardown = [t](void* v) { t(static_cast<T*>(v)); };
443     }
444
445     if (vault == nullptr) {
446       vault = SingletonVault::singleton();
447     }
448     vault_ = vault;
449     vault->registerSingleton(type, c, teardown);
450   }
451
452   static T* get_ptr(detail::TypeDescriptor type_descriptor = {typeid(T), ""},
453                     SingletonVault* vault = nullptr /* for testing */) {
454     return static_cast<T*>(
455         (vault ?: SingletonVault::singleton())->get_ptr(type_descriptor));
456   }
457
458   // Don't use this function, it's private for a reason!  Using it
459   // would defeat the *entire purpose* of the vault in that we lose
460   // the ability to guarantee that, after a destroyInstances is
461   // called, all instances are, in fact, destroyed.  You should use
462   // weak_ptr if you need to hold a reference to the singleton and
463   // guarantee briefly that it exists.
464   //
465   // Yes, you can just get the weak pointer and lock it, but hopefully
466   // if you have taken the time to read this far, you see why that
467   // would be bad.
468   static std::shared_ptr<T> get_shared(
469       detail::TypeDescriptor type_descriptor = {typeid(T), ""},
470       SingletonVault* vault = nullptr /* for testing */) {
471     return std::static_pointer_cast<T>(
472         (vault ?: SingletonVault::singleton())->get_shared(type_descriptor));
473   }
474
475   detail::TypeDescriptor type_descriptor_;
476   SingletonVault* vault_;
477 };
478 }