Don't derive name on singleton creation
[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) << "Registering mock before singleton was registered: "
70                << type().name();
71   }
72   destroyInstance();
73
74   {
75     RWSpinLock::WriteHolder wh(&vault_.mutex_);
76
77     auto it = std::find(
78         vault_.creation_order_.begin(), vault_.creation_order_.end(), type());
79     if (it != vault_.creation_order_.end()) {
80       vault_.creation_order_.erase(it);
81     }
82   }
83
84   std::lock_guard<std::mutex> entry_lock(mutex_);
85
86   create_ = std::move(c);
87   teardown_ = std::move(t);
88 }
89
90 template <typename T>
91 T* SingletonHolder<T>::get() {
92   if (LIKELY(state_.load(std::memory_order_acquire) ==
93              SingletonHolderState::Living)) {
94     return instance_ptr_;
95   }
96   createInstance();
97
98   if (instance_weak_.expired()) {
99     throw std::runtime_error(
100         "Raw pointer to a singleton requested after its destruction."
101         " Singleton type is: " +
102         type().name());
103   }
104
105   return instance_ptr_;
106 }
107
108 template <typename T>
109 std::weak_ptr<T> SingletonHolder<T>::get_weak() {
110   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
111                SingletonHolderState::Living)) {
112     createInstance();
113   }
114
115   return instance_weak_;
116 }
117
118 template <typename T>
119 std::shared_ptr<T> SingletonHolder<T>::try_get() {
120   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
121                SingletonHolderState::Living)) {
122     createInstance();
123   }
124
125   return instance_weak_.lock();
126 }
127
128 template <typename T>
129 folly::ReadMostlySharedPtr<T> SingletonHolder<T>::try_get_fast() {
130   if (UNLIKELY(state_.load(std::memory_order_acquire) !=
131                SingletonHolderState::Living)) {
132     createInstance();
133   }
134
135   return instance_weak_fast_.lock();
136 }
137
138 template <typename T>
139 bool SingletonHolder<T>::hasLiveInstance() {
140   return !instance_weak_.expired();
141 }
142
143 template <typename T>
144 void SingletonHolder<T>::preDestroyInstance(
145     ReadMostlyMainPtrDeleter<>& deleter) {
146   instance_copy_ = instance_;
147   deleter.add(std::move(instance_));
148 }
149
150 template <typename T>
151 void SingletonHolder<T>::destroyInstance() {
152   state_ = SingletonHolderState::Dead;
153   instance_.reset();
154   instance_copy_.reset();
155   if (destroy_baton_) {
156     constexpr std::chrono::seconds kDestroyWaitTime{5};
157     auto wait_result = destroy_baton_->timed_wait(
158       std::chrono::steady_clock::now() + kDestroyWaitTime);
159     if (!wait_result) {
160       print_destructor_stack_trace_->store(true);
161       LOG(ERROR) << "Singleton of type " << type().name() << " has a "
162                  << "living reference at destroyInstances time; beware! Raw "
163                  << "pointer is " << instance_ptr_ << ". It is very likely "
164                  << "that some other singleton is holding a shared_ptr to it. "
165                  << "Make sure dependencies between these singletons are "
166                  << "properly defined.";
167     }
168   }
169 }
170
171 template <typename T>
172 SingletonHolder<T>::SingletonHolder(
173     TypeDescriptor typeDesc,
174     SingletonVault& vault)
175     : SingletonHolderBase(typeDesc), vault_(vault) {}
176
177 template <typename T>
178 bool SingletonHolder<T>::creationStarted() {
179   // If alive, then creation was of course started.
180   // This is flipped after creating_thread_ was set, and before it was reset.
181   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
182     return true;
183   }
184
185   // Not yet built.  Is it currently in progress?
186   if (creating_thread_.load(std::memory_order_acquire) != std::thread::id()) {
187     return true;
188   }
189
190   return false;
191 }
192
193 template <typename T>
194 void SingletonHolder<T>::createInstance() {
195   if (creating_thread_.load(std::memory_order_acquire) ==
196         std::this_thread::get_id()) {
197     LOG(FATAL) << "circular singleton dependency: " << type().name();
198   }
199
200   std::lock_guard<std::mutex> entry_lock(mutex_);
201   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
202     return;
203   }
204   if (state_.load(std::memory_order_acquire) ==
205         SingletonHolderState::NotRegistered) {
206     auto ptr = SingletonVault::stackTraceGetter().load();
207     LOG(FATAL) << "Creating instance for unregistered singleton: "
208                << type().name() << "\n"
209                << "Stacktrace:"
210                << "\n"
211                << (ptr ? (*ptr)() : "(not available)");
212   }
213
214   if (state_.load(std::memory_order_acquire) == SingletonHolderState::Living) {
215     return;
216   }
217
218   SCOPE_EXIT {
219     // Clean up creator thread when complete, and also, in case of errors here,
220     // so that subsequent attempts don't think this is still in the process of
221     // being built.
222     creating_thread_.store(std::thread::id(), std::memory_order_release);
223   };
224
225   creating_thread_.store(std::this_thread::get_id(), std::memory_order_release);
226
227   RWSpinLock::ReadHolder rh(&vault_.stateMutex_);
228   if (vault_.state_ == SingletonVault::SingletonVaultState::Quiescing) {
229     return;
230   }
231
232   auto destroy_baton = std::make_shared<folly::Baton<>>();
233   auto print_destructor_stack_trace =
234     std::make_shared<std::atomic<bool>>(false);
235   auto teardown = teardown_;
236
237   // Can't use make_shared -- no support for a custom deleter, sadly.
238   std::shared_ptr<T> instance(
239     create_(),
240     [destroy_baton, print_destructor_stack_trace, teardown, type = type()]
241     (T* instance_ptr) mutable {
242       teardown(instance_ptr);
243       destroy_baton->post();
244       if (print_destructor_stack_trace->load()) {
245         std::string output = "Singleton " + type.name() + " was destroyed.\n";
246
247         auto stack_trace_getter = SingletonVault::stackTraceGetter().load();
248         auto stack_trace = stack_trace_getter ? stack_trace_getter() : "";
249         if (stack_trace.empty()) {
250           output += "Failed to get destructor stack trace.";
251         } else {
252           output += "Destructor stack trace:\n";
253           output += stack_trace;
254         }
255
256         LOG(ERROR) << output;
257       }
258     });
259
260   // We should schedule destroyInstances() only after the singleton was
261   // created. This will ensure it will be destroyed before singletons,
262   // not managed by folly::Singleton, which were initialized in its
263   // constructor
264   SingletonVault::scheduleDestroyInstances();
265
266   instance_weak_ = instance;
267   instance_ptr_ = instance.get();
268   instance_.reset(std::move(instance));
269   instance_weak_fast_ = instance_;
270
271   destroy_baton_ = std::move(destroy_baton);
272   print_destructor_stack_trace_ = std::move(print_destructor_stack_trace);
273
274   // This has to be the last step, because once state is Living other threads
275   // may access instance and instance_weak w/o synchronization.
276   state_.store(SingletonHolderState::Living, std::memory_order_release);
277
278   {
279     RWSpinLock::WriteHolder wh(&vault_.mutex_);
280     vault_.creation_order_.push_back(type());
281   }
282 }
283
284 }
285
286 }