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