Update SSLContext to use folly::Random and discrete_distribution
[folly.git] / folly / Singleton.cpp
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 #include <folly/Singleton.h>
18
19 #include <atomic>
20 #include <string>
21
22 #include <folly/ScopeGuard.h>
23
24 namespace folly {
25
26 namespace detail {
27
28 constexpr std::chrono::seconds SingletonHolderBase::kDestroyWaitTime;
29
30 }
31
32 namespace {
33
34 struct FatalHelper {
35   ~FatalHelper() {
36     if (!leakedSingletons_.empty()) {
37       std::string leakedTypes;
38       for (const auto& singleton : leakedSingletons_) {
39         leakedTypes += "\t" + singleton.name() + "\n";
40       }
41       LOG(DFATAL) << "Singletons of the following types had living references "
42                   << "after destroyInstances was finished:\n" << leakedTypes
43                   << "beware! It is very likely that those singleton instances "
44                   << "are leaked.";
45     }
46   }
47
48   std::vector<detail::TypeDescriptor> leakedSingletons_;
49 };
50
51 #if defined(__APPLE__) || defined(_MSC_VER)
52 // OS X doesn't support constructor priorities.
53 FatalHelper fatalHelper;
54 #else
55 FatalHelper __attribute__ ((__init_priority__ (101))) fatalHelper;
56 #endif
57
58 }
59
60 SingletonVault::~SingletonVault() { destroyInstances(); }
61
62 void SingletonVault::registerSingleton(detail::SingletonHolderBase* entry) {
63   RWSpinLock::ReadHolder rh(&stateMutex_);
64
65   stateCheck(SingletonVaultState::Running);
66
67   if (UNLIKELY(registrationComplete_)) {
68     throw std::logic_error(
69       "Registering singleton after registrationComplete().");
70   }
71
72   RWSpinLock::ReadHolder rhMutex(&mutex_);
73   CHECK_THROW(singletons_.find(entry->type()) == singletons_.end(),
74               std::logic_error);
75
76   RWSpinLock::UpgradedHolder wh(&mutex_);
77   singletons_[entry->type()] = entry;
78 }
79
80 void SingletonVault::addEagerInitSingleton(detail::SingletonHolderBase* entry) {
81   RWSpinLock::ReadHolder rh(&stateMutex_);
82
83   stateCheck(SingletonVaultState::Running);
84
85   if (UNLIKELY(registrationComplete_)) {
86     throw std::logic_error(
87         "Registering for eager-load after registrationComplete().");
88   }
89
90   RWSpinLock::ReadHolder rhMutex(&mutex_);
91   CHECK_THROW(singletons_.find(entry->type()) != singletons_.end(),
92               std::logic_error);
93
94   RWSpinLock::UpgradedHolder wh(&mutex_);
95   eagerInitSingletons_.insert(entry);
96 }
97
98 void SingletonVault::registrationComplete() {
99   RequestContext::saveContext();
100   std::atexit([](){ SingletonVault::singleton()->destroyInstances(); });
101
102   RWSpinLock::WriteHolder wh(&stateMutex_);
103
104   stateCheck(SingletonVaultState::Running);
105
106   if (type_ == Type::Strict) {
107     for (const auto& p : singletons_) {
108       if (p.second->hasLiveInstance()) {
109         throw std::runtime_error(
110             "Singleton created before registration was complete.");
111       }
112     }
113   }
114
115   registrationComplete_ = true;
116 }
117
118 void SingletonVault::doEagerInit() {
119   std::unordered_set<detail::SingletonHolderBase*> singletonSet;
120   {
121     RWSpinLock::ReadHolder rh(&stateMutex_);
122     stateCheck(SingletonVaultState::Running);
123     if (UNLIKELY(!registrationComplete_)) {
124       throw std::logic_error("registrationComplete() not yet called");
125     }
126     singletonSet = eagerInitSingletons_; // copy set of pointers
127   }
128
129   for (auto *single : singletonSet) {
130     single->createInstance();
131   }
132 }
133
134 void SingletonVault::doEagerInitVia(Executor& exe, folly::Baton<>* done) {
135   std::unordered_set<detail::SingletonHolderBase*> singletonSet;
136   {
137     RWSpinLock::ReadHolder rh(&stateMutex_);
138     stateCheck(SingletonVaultState::Running);
139     if (UNLIKELY(!registrationComplete_)) {
140       throw std::logic_error("registrationComplete() not yet called");
141     }
142     singletonSet = eagerInitSingletons_; // copy set of pointers
143   }
144
145   auto countdown = std::make_shared<std::atomic<size_t>>(singletonSet.size());
146   for (auto* single : singletonSet) {
147     // countdown is retained by shared_ptr, and will be alive until last lambda
148     // is done.  notifyBaton is provided by the caller, and expected to remain
149     // present (if it's non-nullptr).  singletonSet can go out of scope but
150     // its values, which are SingletonHolderBase pointers, are alive as long as
151     // SingletonVault is not being destroyed.
152     exe.add([=] {
153       // decrement counter and notify if requested, whether initialization
154       // was successful, was skipped (already initialized), or exception thrown.
155       SCOPE_EXIT {
156         if (--(*countdown) == 0) {
157           if (done != nullptr) {
158             done->post();
159           }
160         }
161       };
162       // if initialization is in progress in another thread, don't try to init
163       // here.  Otherwise the current thread will block on 'createInstance'.
164       if (!single->creationStarted()) {
165         single->createInstance();
166       }
167     });
168   }
169 }
170
171 void SingletonVault::destroyInstances() {
172   RWSpinLock::WriteHolder state_wh(&stateMutex_);
173
174   if (state_ == SingletonVaultState::Quiescing) {
175     return;
176   }
177   state_ = SingletonVaultState::Quiescing;
178
179   RWSpinLock::ReadHolder state_rh(std::move(state_wh));
180
181   {
182     RWSpinLock::ReadHolder rh(&mutex_);
183
184     CHECK_GE(singletons_.size(), creation_order_.size());
185
186     for (auto type_iter = creation_order_.rbegin();
187          type_iter != creation_order_.rend();
188          ++type_iter) {
189       singletons_[*type_iter]->destroyInstance();
190     }
191
192     for (auto& singleton_type: creation_order_) {
193       auto singleton = singletons_[singleton_type];
194       if (!singleton->hasLiveInstance()) {
195         continue;
196       }
197
198       fatalHelper.leakedSingletons_.push_back(singleton->type());
199     }
200   }
201
202   {
203     RWSpinLock::WriteHolder wh(&mutex_);
204     creation_order_.clear();
205   }
206 }
207
208 void SingletonVault::reenableInstances() {
209   RWSpinLock::WriteHolder state_wh(&stateMutex_);
210
211   stateCheck(SingletonVaultState::Quiescing);
212
213   state_ = SingletonVaultState::Running;
214 }
215
216 void SingletonVault::scheduleDestroyInstances() {
217   RequestContext::saveContext();
218
219   class SingletonVaultDestructor {
220    public:
221     ~SingletonVaultDestructor() {
222       SingletonVault::singleton()->destroyInstances();
223     }
224   };
225
226   // Here we intialize a singleton, which calls destroyInstances in its
227   // destructor. Because of singleton destruction order - it will be destroyed
228   // before all the singletons, which were initialized before it and after all
229   // the singletons initialized after it.
230   static SingletonVaultDestructor singletonVaultDestructor;
231 }
232
233 }