Add a default timeout parameter to HHWheelTimer.
[folly.git] / folly / Singleton.h
1 /*
2  * Copyright 2015 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 tag. If no tag is specified - default tag is used
52 //
53 // namespace {
54 // struct Tag1 {};
55 // struct Tag2 {};
56 // folly::Singleton<MyExpensiveService> s_default;
57 // folly::Singleton<MyExpensiveService, Tag1> s1;
58 // folly::Singleton<MyExpensiveService, Tag2> s2;
59 // }
60 // ...
61 // MyExpensiveService* svc_default = s_default.get();
62 // MyExpensiveService* svc1 = s1.get();
63 // MyExpensiveService* svc2 = s2.get();
64 //
65 // By default, the singleton instance is constructed via new and
66 // deleted via delete, but this is configurable:
67 //
68 // namespace { folly::Singleton<MyExpensiveService> the_singleton(create,
69 //                                                                destroy); }
70 //
71 // Where create and destroy are functions, Singleton<T>::CreateFunc
72 // Singleton<T>::TeardownFunc.
73 //
74 // What if you need to destroy all of your singletons?  Say, some of
75 // your singletons manage threads, but you need to fork?  Or your unit
76 // test wants to clean up all global state?  Then you can call
77 // SingletonVault::singleton()->destroyInstances(), which invokes the
78 // TeardownFunc for each singleton, in the reverse order they were
79 // created.  It is your responsibility to ensure your singletons can
80 // handle cases where the singletons they depend on go away, however.
81 // Singletons won't be recreated after destroyInstances call. If you
82 // want to re-enable singleton creation (say after fork was called) you
83 // should call reenableInstances.
84
85 #pragma once
86 #include <folly/Baton.h>
87 #include <folly/Exception.h>
88 #include <folly/Hash.h>
89 #include <folly/Memory.h>
90 #include <folly/RWSpinLock.h>
91 #include <folly/Demangle.h>
92 #include <folly/io/async/Request.h>
93
94 #include <algorithm>
95 #include <vector>
96 #include <mutex>
97 #include <thread>
98 #include <condition_variable>
99 #include <string>
100 #include <unordered_map>
101 #include <functional>
102 #include <typeinfo>
103 #include <typeindex>
104
105 #include <glog/logging.h>
106
107 // use this guard to handleSingleton breaking change in 3rd party code
108 #ifndef FOLLY_SINGLETON_TRY_GET
109 #define FOLLY_SINGLETON_TRY_GET
110 #endif
111
112 namespace folly {
113
114 // For actual usage, please see the Singleton<T> class at the bottom
115 // of this file; that is what you will actually interact with.
116
117 // SingletonVault is the class that manages singleton instances.  It
118 // is unaware of the underlying types of singletons, and simply
119 // manages lifecycles and invokes CreateFunc and TeardownFunc when
120 // appropriate.  In general, you won't need to interact with the
121 // SingletonVault itself.
122 //
123 // A vault goes through a few stages of life:
124 //
125 //   1. Registration phase; singletons can be registered, but no
126 //      singleton can be created.
127 //   2. registrationComplete() has been called; singletons can no
128 //      longer be registered, but they can be created.
129 //   3. A vault can return to stage 1 when destroyInstances is called.
130 //
131 // In general, you don't need to worry about any of the above; just
132 // ensure registrationComplete() is called near the top of your main()
133 // function, otherwise no singletons can be instantiated.
134
135 class SingletonVault;
136
137 namespace detail {
138
139 struct DefaultTag {};
140
141 // A TypeDescriptor is the unique handle for a given singleton.  It is
142 // a combinaiton of the type and of the optional name, and is used as
143 // a key in unordered_maps.
144 class TypeDescriptor {
145  public:
146   TypeDescriptor(const std::type_info& ti,
147                  const std::type_info& tag_ti)
148       : ti_(ti), tag_ti_(tag_ti) {
149   }
150
151   TypeDescriptor(const TypeDescriptor& other)
152       : ti_(other.ti_), tag_ti_(other.tag_ti_) {
153   }
154
155   TypeDescriptor& operator=(const TypeDescriptor& other) {
156     if (this != &other) {
157       ti_ = other.ti_;
158       tag_ti_ = other.tag_ti_;
159     }
160
161     return *this;
162   }
163
164   std::string name() const {
165     auto ret = demangle(ti_.name());
166     if (tag_ti_ != std::type_index(typeid(DefaultTag))) {
167       ret += "/";
168       ret += demangle(tag_ti_.name());
169     }
170     return ret.toStdString();
171   }
172
173   friend class TypeDescriptorHasher;
174
175   bool operator==(const TypeDescriptor& other) const {
176     return ti_ == other.ti_ && tag_ti_ == other.tag_ti_;
177   }
178
179  private:
180   std::type_index ti_;
181   std::type_index tag_ti_;
182 };
183
184 class TypeDescriptorHasher {
185  public:
186   size_t operator()(const TypeDescriptor& ti) const {
187     return folly::hash::hash_combine(ti.ti_, ti.tag_ti_);
188   }
189 };
190
191 // This interface is used by SingletonVault to interact with SingletonHolders.
192 // Having a non-template interface allows SingletonVault to keep a list of all
193 // SingletonHolders.
194 class SingletonHolderBase {
195  public:
196   virtual ~SingletonHolderBase() = default;
197
198   virtual TypeDescriptor type() = 0;
199   virtual bool hasLiveInstance() = 0;
200   virtual void destroyInstance() = 0;
201
202  protected:
203   static constexpr std::chrono::seconds kDestroyWaitTime{5};
204 };
205
206 // An actual instance of a singleton, tracking the instance itself,
207 // its state as described above, and the create and teardown
208 // functions.
209 template <typename T>
210 struct SingletonHolder : public SingletonHolderBase {
211  public:
212   typedef std::function<void(T*)> TeardownFunc;
213   typedef std::function<T*(void)> CreateFunc;
214
215   template <typename Tag, typename VaultTag>
216   inline static SingletonHolder<T>& singleton();
217
218   inline T* get();
219   inline std::weak_ptr<T> get_weak();
220
221   void registerSingleton(CreateFunc c, TeardownFunc t);
222   void registerSingletonMock(CreateFunc c, TeardownFunc t);
223   virtual TypeDescriptor type();
224   virtual bool hasLiveInstance();
225   virtual void destroyInstance();
226
227  private:
228   SingletonHolder(TypeDescriptor type, SingletonVault& vault);
229
230   void createInstance();
231
232   enum class SingletonHolderState {
233     NotRegistered,
234     Dead,
235     Living,
236   };
237
238   TypeDescriptor type_;
239   SingletonVault& vault_;
240
241   // mutex protects the entire entry during construction/destruction
242   std::mutex mutex_;
243
244   // State of the singleton entry. If state is Living, instance_ptr and
245   // instance_weak can be safely accessed w/o synchronization.
246   std::atomic<SingletonHolderState> state_{SingletonHolderState::NotRegistered};
247
248   // the thread creating the singleton (only valid while creating an object)
249   std::thread::id creating_thread_;
250
251   // The singleton itself and related functions.
252
253   // holds a shared_ptr to singleton instance, set when state is changed from
254   // Dead to Living. Reset when state is changed from Living to Dead.
255   std::shared_ptr<T> instance_;
256   // weak_ptr to the singleton instance, set when state is changed from Dead
257   // to Living. We never write to this object after initialization, so it is
258   // safe to read it from different threads w/o synchronization if we know
259   // that state is set to Living
260   std::weak_ptr<T> instance_weak_;
261   // Time we wait on destroy_baton after releasing Singleton shared_ptr.
262   std::shared_ptr<folly::Baton<>> destroy_baton_;
263   T* instance_ptr_ = nullptr;
264   CreateFunc create_ = nullptr;
265   TeardownFunc teardown_ = nullptr;
266
267   std::shared_ptr<std::atomic<bool>> print_destructor_stack_trace_;
268
269   SingletonHolder(const SingletonHolder&) = delete;
270   SingletonHolder& operator=(const SingletonHolder&) = delete;
271   SingletonHolder& operator=(SingletonHolder&&) = delete;
272   SingletonHolder(SingletonHolder&&) = delete;
273 };
274
275 }
276
277 class SingletonVault {
278  public:
279   enum class Type { Strict, Relaxed };
280
281   explicit SingletonVault(Type type = Type::Relaxed) : type_(type) {}
282
283   // Destructor is only called by unit tests to check destroyInstances.
284   ~SingletonVault();
285
286   typedef std::function<void(void*)> TeardownFunc;
287   typedef std::function<void*(void)> CreateFunc;
288
289   // Ensure that Singleton has not been registered previously and that
290   // registration is not complete. If validations succeeds,
291   // register a singleton of a given type with the create and teardown
292   // functions.
293   void registerSingleton(detail::SingletonHolderBase* entry) {
294     RWSpinLock::ReadHolder rh(&stateMutex_);
295
296     stateCheck(SingletonVaultState::Running);
297
298     if (UNLIKELY(registrationComplete_)) {
299       throw std::logic_error(
300         "Registering singleton after registrationComplete().");
301     }
302
303     RWSpinLock::ReadHolder rhMutex(&mutex_);
304     CHECK_THROW(singletons_.find(entry->type()) == singletons_.end(),
305                 std::logic_error);
306
307     RWSpinLock::UpgradedHolder wh(&mutex_);
308     singletons_[entry->type()] = entry;
309   }
310
311   // Mark registration is complete; no more singletons can be
312   // registered at this point.
313   void registrationComplete() {
314     RequestContext::saveContext();
315     std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
316
317     RWSpinLock::WriteHolder wh(&stateMutex_);
318
319     stateCheck(SingletonVaultState::Running);
320
321     if (type_ == Type::Strict) {
322       for (const auto& p: singletons_) {
323         if (p.second->hasLiveInstance()) {
324           throw std::runtime_error(
325             "Singleton created before registration was complete.");
326         }
327       }
328     }
329
330     registrationComplete_ = true;
331   }
332
333   // Destroy all singletons; when complete, the vault can't create
334   // singletons once again until reenableInstances() is called.
335   void destroyInstances();
336
337   // Enable re-creating singletons after destroyInstances() was called.
338   void reenableInstances();
339
340   // For testing; how many registered and living singletons we have.
341   size_t registeredSingletonCount() const {
342     RWSpinLock::ReadHolder rh(&mutex_);
343
344     return singletons_.size();
345   }
346
347   size_t livingSingletonCount() const {
348     RWSpinLock::ReadHolder rh(&mutex_);
349
350     size_t ret = 0;
351     for (const auto& p : singletons_) {
352       if (p.second->hasLiveInstance()) {
353         ++ret;
354       }
355     }
356
357     return ret;
358   }
359
360   // A well-known vault; you can actually have others, but this is the
361   // default.
362   static SingletonVault* singleton() {
363     return singleton<>();
364   }
365
366   // Gets singleton vault for any Tag. Non-default tag should be used in unit
367   // tests only.
368   template <typename VaultTag = detail::DefaultTag>
369   static SingletonVault* singleton() {
370     static SingletonVault* vault = new SingletonVault();
371     return vault;
372   }
373
374   typedef std::string(*StackTraceGetterPtr)();
375
376   static std::atomic<StackTraceGetterPtr>& stackTraceGetter() {
377     static std::atomic<StackTraceGetterPtr> stackTraceGetterPtr;
378     return stackTraceGetterPtr;
379   }
380
381  private:
382   template <typename T>
383   friend struct detail::SingletonHolder;
384
385   // The two stages of life for a vault, as mentioned in the class comment.
386   enum class SingletonVaultState {
387     Running,
388     Quiescing,
389   };
390
391   // Each singleton in the vault can be in two states: dead
392   // (registered but never created), living (CreateFunc returned an instance).
393
394   void stateCheck(SingletonVaultState expected,
395                   const char* msg="Unexpected singleton state change") {
396     if (expected != state_) {
397         throw std::logic_error(msg);
398     }
399   }
400
401   // This method only matters if registrationComplete() is never called.
402   // Otherwise destroyInstances is scheduled to be executed atexit.
403   //
404   // Initializes static object, which calls destroyInstances on destruction.
405   // Used to have better deletion ordering with singleton not managed by
406   // folly::Singleton. The desruction will happen in the following order:
407   // 1. Singletons, not managed by folly::Singleton, which were created after
408   //    any of the singletons managed by folly::Singleton was requested.
409   // 2. All singletons managed by folly::Singleton
410   // 3. Singletons, not managed by folly::Singleton, which were created before
411   //    any of the singletons managed by folly::Singleton was requested.
412   static void scheduleDestroyInstances();
413
414   typedef std::unordered_map<detail::TypeDescriptor,
415                              detail::SingletonHolderBase*,
416                              detail::TypeDescriptorHasher> SingletonMap;
417
418   mutable folly::RWSpinLock mutex_;
419   SingletonMap singletons_;
420   std::vector<detail::TypeDescriptor> creation_order_;
421   SingletonVaultState state_{SingletonVaultState::Running};
422   bool registrationComplete_{false};
423   folly::RWSpinLock stateMutex_;
424   Type type_{Type::Relaxed};
425 };
426
427 // This is the wrapper class that most users actually interact with.
428 // It allows for simple access to registering and instantiating
429 // singletons.  Create instances of this class in the global scope of
430 // type Singleton<T> to register your singleton for later access via
431 // Singleton<T>::try_get().
432 template <typename T,
433           typename Tag = detail::DefaultTag,
434           typename VaultTag = detail::DefaultTag /* for testing */>
435 class Singleton {
436  public:
437   typedef std::function<T*(void)> CreateFunc;
438   typedef std::function<void(T*)> TeardownFunc;
439
440   // Generally your program life cycle should be fine with calling
441   // get() repeatedly rather than saving the reference, and then not
442   // call get() during process shutdown.
443   static T* get() __attribute__ ((__deprecated__("Replaced by try_get"))) {
444     return getEntry().get();
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     return getEntry().get_weak();
453   }
454
455   // Preferred alternative to get_weak, it returns shared_ptr that can be
456   // stored; a singleton won't be destroyed unless shared_ptr is destroyed.
457   // Avoid holding these shared_ptrs beyond the scope of a function;
458   // don't put them in member variables, always use try_get() instead
459   static std::shared_ptr<T> try_get() {
460     auto ret = get_weak().lock();
461     if (!ret) {
462       LOG(DFATAL) <<
463         "folly::Singleton<" << getEntry().type().name() <<
464         ">::get_weak() called on destructed singleton; "
465         "returning nullptr, possible segfault coming";
466     }
467     return ret;
468   }
469
470   explicit Singleton(std::nullptr_t _ = nullptr,
471                      typename Singleton::TeardownFunc t = nullptr) :
472       Singleton ([]() { return new T; }, std::move(t)) {
473   }
474
475   explicit Singleton(typename Singleton::CreateFunc c,
476                      typename Singleton::TeardownFunc t = nullptr) {
477     if (c == nullptr) {
478       throw std::logic_error(
479         "nullptr_t should be passed if you want T to be default constructed");
480     }
481
482     auto vault = SingletonVault::singleton<VaultTag>();
483     getEntry().registerSingleton(std::move(c), getTeardownFunc(std::move(t)));
484     vault->registerSingleton(&getEntry());
485   }
486
487   /**
488   * Construct and inject a mock singleton which should be used only from tests.
489   * Unlike regular singletons which are initialized once per process lifetime,
490   * mock singletons live for the duration of a test. This means that one process
491   * running multiple tests can initialize and register the same singleton
492   * multiple times. This functionality should be used only from tests
493   * since it relaxes validation and performance in order to be able to perform
494   * the injection. The returned mock singleton is functionality identical to
495   * regular singletons.
496   */
497   static void make_mock(std::nullptr_t c = nullptr,
498                         typename Singleton<T>::TeardownFunc t = nullptr) {
499     make_mock([]() { return new T; }, t);
500   }
501
502   static void make_mock(CreateFunc c,
503                         typename Singleton<T>::TeardownFunc t = nullptr) {
504     if (c == nullptr) {
505       throw std::logic_error(
506         "nullptr_t should be passed if you want T to be default constructed");
507     }
508
509     auto& entry = getEntry();
510
511     entry.registerSingletonMock(c, getTeardownFunc(t));
512   }
513
514  private:
515   inline static detail::SingletonHolder<T>& getEntry() {
516     return detail::SingletonHolder<T>::template singleton<Tag, VaultTag>();
517   }
518
519   // Construct TeardownFunc.
520   static typename detail::SingletonHolder<T>::TeardownFunc getTeardownFunc(
521       TeardownFunc t)  {
522     if (t == nullptr) {
523       return  [](T* v) { delete v; };
524     } else {
525       return t;
526     }
527   }
528 };
529
530 }
531
532 #include <folly/Singleton-inl.h>