make Range::size() constexpr
[folly.git] / folly / Singleton-inl.h
1 /*
2  * Copyright 2016 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 namespace folly {
18
19 namespace detail {
20
21 template <typename T>
22 template <typename Tag, typename VaultTag>
23 SingletonHolder<T>& SingletonHolder<T>::singleton() {
24   static auto entry =
25       createGlobal<SingletonHolder<T>, std::pair<Tag, VaultTag>>([]() {
26         return new SingletonHolder<T>({typeid(T), typeid(Tag)},
27                                       *SingletonVault::singleton<VaultTag>());
28       });
29   return *entry;
30 }
31
32 [[noreturn]] void singletonWarnDoubleRegistrationAndAbort(
33     const TypeDescriptor& type);
34
35 template <typename T>
36 void SingletonHolder<T>::registerSingleton(CreateFunc c, TeardownFunc t) {
37   std::lock_guard<std::mutex> entry_lock(mutex_);
38
39   if (state_ != SingletonHolderState::NotRegistered) {
40     /* Possible causes:
41      *
42      * You have two instances of the same
43      * folly::Singleton<Class>. Probably because you define the
44      * singleton in a header included in multiple places? In general,
45      * folly::Singleton shouldn't be in the header, only off in some
46      * anonymous namespace in a cpp file. Code needing the singleton
47      * will find it when that code references folly::Singleton<Class>.
48      *
49      * Alternatively, you could have 2 singletons with the same type
50      * defined with a different name in a .cpp (source) file. For
51      * example:
52      *
53      * Singleton<int> a([] { return new int(3); });
54      * Singleton<int> b([] { return new int(4); });
55      *
56      */
57     singletonWarnDoubleRegistrationAndAbort(type_);
58   }
59
60   create_ = std::move(c);
61   teardown_ = std::move(t);
62
63   state_ = SingletonHolderState::Dead;
64 }
65
66 template <typename T>
67 void SingletonHolder<T>::registerSingletonMock(CreateFunc c, TeardownFunc t) {
68   if (state_ == SingletonHolderState::NotRegistered) {
69     LOG(FATAL)
70         << "Registering mock before singleton was registered: " << type_.name();
71   }
72   destroyInstance();
73
74   std::lock_guard<std::mutex> entry_lock(mutex_);
75
76   create_ = std::move(c);
77   teardown_ = std::move(t);
78 }
79
80 template <typename T>
81 T* SingletonHolder<T>::get() {
82   if (LIKELY(state_.load(std::memory_order_acquire) ==
83              SingletonHolderState::Living)) {
84     return instance_ptr_;
85   }
86   createInstance();
87
88   if (instance_weak_.expired()) {
89     throw std::runtime_error(
90         "Raw pointer to a singleton requested after its destruction."
91         " Singleton type is: " +
92         type_.name());
93   }
94
95   return instance_ptr_;
96 }
97
98 template <typename T>
99 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
100   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
101                SingletonHolderState::Living)) {
102     createInstance();
103   }
104
105   return instance_weak_;
106 }
107
108 template <typename T>
109 std::shared_ptr<T> SingletonHolder<T>::try_get() {
110   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
111                SingletonHolderState::Living)) {
112     createInstance();
113   }
114
115   return instance_weak_.lock();
116 }
117
118 template <typename T>
119 folly::ReadMostlySharedPtr<T> SingletonHolder<T>::try_get_fast() {
120   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
121                SingletonHolderState::Living)) {
122     createInstance();
123   }
124
125   return instance_weak_fast_.lock();
126 }
127
128 template <typename T>
129 TypeDescriptor SingletonHolder<T>::type() {
130   return type_;
131 }
132
133 template <typename T>
134 bool SingletonHolder<T>::hasLiveInstance() {
135   return !instance_weak_.expired();
136 }
137
138 template <typename T>
139 void SingletonHolder<T>::destroyInstance() {
140   state_ = SingletonHolderState::Dead;
141   instance_.reset();
142   if (destroy_baton_) {
143     constexpr std::chrono::seconds kDestroyWaitTime{5};
144     auto wait_result = destroy_baton_->timed_wait(
145       std::chrono::steady_clock::now() + kDestroyWaitTime);
146     if (!wait_result) {
147       print_destructor_stack_trace_->store(true);
148       LOG(ERROR) << "Singleton of type " << type_.name() << " has a "
149                  << "living reference at destroyInstances time; beware! Raw "
150                  << "pointer is " << instance_ptr_ << ". It is very likely "
151                  << "that some other singleton is holding a shared_ptr to it. "
152                  << "Make sure dependencies between these singletons are "
153                  << "properly defined.";
154     }
155   }
156 }
157
158 template <typename T>
159 SingletonHolder<T>::SingletonHolder(TypeDescriptor type__,
160                                     SingletonVault& vault) :
161     type_(type__), vault_(vault) {
162 }
163
164 template <typename T>
165 bool SingletonHolder<T>::creationStarted() {
166   // If alive, then creation was of course started.
167   // This is flipped after creating_thread_ was set, and before it was reset.
168   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
169     return true;
170   }
171
172   // Not yet built.  Is it currently in progress?
173   if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) {
174     return true;
175   }
176
177   return false;
178 }
179
180 template <typename T>
181 void SingletonHolder<T>::createInstance() {
182   if (creating_thread_.load(std::memory_order_acquire) ==
183         std::this_thread::get_id()) {
184     LOG(FATAL) << "circular singleton dependency: " << type_.name();
185   }
186
187   std::lock_guard<std::mutex> entry_lock(mutex_);
188   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
189     return;
190   }
191   if (state_.load(std::memory_order_acquire) ==
192         SingletonHolderState::NotRegistered) {
193     auto ptr = SingletonVault::stackTraceGetter().load();
194     LOG(FATAL) << "Creating instance for unregistered singleton: "
195                << type_.name() << "\n"
196                << "Stacktrace:"
197                << "\n" << (ptr ? (*ptr)() : "(not available)");
198   }
199
200   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
201     return;
202   }
203
204   SCOPE_EXIT {
205     // Clean up creator thread when complete, and also, in case of errors here,
206     // so that subsequent attempts don't think this is still in the process of
207     // being built.
208     creating_thread_.store(std::thread::id(), std::memory_order_release);
209   };
210
211   creating_thread_.store(std::this_thread::get_id(), std::memory_order_release);
212
213   RWSpinLock::ReadHolder rh(&vault_.stateMutex_);
214   if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) {
215     return;
216   }
217
218   auto destroy_baton = std::make_shared<folly::Baton<>>();
219   auto print_destructor_stack_trace =
220     std::make_shared<std::atomic<bool>>(false);
221   auto teardown = teardown_;
222   auto type_name = type_.name();
223
224   // Can't use make_shared -- no support for a custom deleter, sadly.
225   std::shared_ptr<T> instance(
226     create_(),
227     [destroy_baton, print_destructor_stack_trace, teardown, type_name]
228     (T* instance_ptr) mutable {
229       teardown(instance_ptr);
230       destroy_baton->post();
231       if (print_destructor_stack_trace->load()) {
232         std::string output = "Singleton " + type_name + " was destroyed.\n";
233
234         auto stack_trace_getter = SingletonVault::stackTraceGetter().load();
235         auto stack_trace = stack_trace_getter ? stack_trace_getter() : "";
236         if (stack_trace.empty()) {
237           output += "Failed to get destructor stack trace.";
238         } else {
239           output += "Destructor stack trace:\n";
240           output += stack_trace;
241         }
242
243         LOG(ERROR) << output;
244       }
245     });
246
247   // We should schedule destroyInstances() only after the singleton was
248   // created. This will ensure it will be destroyed before singletons,
249   // not managed by folly::Singleton, which were initialized in its
250   // constructor
251   SingletonVault::scheduleDestroyInstances();
252
253   instance_weak_ = instance;
254   instance_ptr_ = instance.get();
255   instance_.reset(std::move(instance));
256   instance_weak_fast_ = instance_;
257
258   destroy_baton_ = std::move(destroy_baton);
259   print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
260
261   // This has to be the last step, because once state is Living other threads
262   // may access instance and instance_weak w/o synchronization.
263   state_.store(SingletonHolderState::Living, std::memory_order_release);
264
265   {
266     RWSpinLock::WriteHolder wh(&vault_.mutex_);
267     vault_.creation_order_.push_back(type_);
268   }
269 }
270
271 }
272
273 }