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