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