Fix TimedMutex deadlock when used both from fiber and main context
[folly.git] / folly / experimental / FunctionScheduler.cpp
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 #include <folly/experimental/FunctionScheduler.h>
18
19 #include <random>
20
21 #include <folly/Conv.h>
22 #include <folly/Random.h>
23 #include <folly/String.h>
24 #include <folly/ThreadName.h>
25
26 using std::chrono::milliseconds;
27 using std::chrono::steady_clock;
28
29 namespace folly {
30
31 namespace {
32
33 struct ConstIntervalFunctor {
34   const milliseconds constInterval;
35
36   explicit ConstIntervalFunctor(milliseconds interval)
37       : constInterval(interval) {
38     if (interval < milliseconds::zero()) {
39       throw std::invalid_argument(
40           "FunctionScheduler: "
41           "time interval must be non-negative");
42     }
43   }
44
45   milliseconds operator()() const { return constInterval; }
46 };
47
48 struct PoissonDistributionFunctor {
49   std::default_random_engine generator;
50   std::poisson_distribution<int> poissonRandom;
51
52   explicit PoissonDistributionFunctor(double meanPoissonMs)
53       : poissonRandom(meanPoissonMs) {
54     if (meanPoissonMs < 0.0) {
55       throw std::invalid_argument(
56           "FunctionScheduler: "
57           "Poisson mean interval must be non-negative");
58     }
59   }
60
61   milliseconds operator()() { return milliseconds(poissonRandom(generator)); }
62 };
63
64 struct UniformDistributionFunctor {
65   std::default_random_engine generator;
66   std::uniform_int_distribution<milliseconds::rep> dist;
67
68   UniformDistributionFunctor(milliseconds minInterval, milliseconds maxInterval)
69       : generator(Random::rand32()),
70         dist(minInterval.count(), maxInterval.count()) {
71     if (minInterval > maxInterval) {
72       throw std::invalid_argument(
73           "FunctionScheduler: "
74           "min time interval must be less or equal than max interval");
75     }
76     if (minInterval < milliseconds::zero()) {
77       throw std::invalid_argument(
78           "FunctionScheduler: "
79           "time interval must be non-negative");
80     }
81   }
82
83   milliseconds operator()() { return milliseconds(dist(generator)); }
84 };
85
86 } // anonymous namespace
87
88 FunctionScheduler::FunctionScheduler() {}
89
90 FunctionScheduler::~FunctionScheduler() {
91   // make sure to stop the thread (if running)
92   shutdown();
93 }
94
95 void FunctionScheduler::addFunction(Function<void()>&& cb,
96                                     milliseconds interval,
97                                     StringPiece nameID,
98                                     milliseconds startDelay) {
99   addFunctionInternal(
100       std::move(cb),
101       ConstIntervalFunctor(interval),
102       nameID.str(),
103       to<std::string>(interval.count(), "ms"),
104       startDelay,
105       false /*runOnce*/);
106 }
107
108 void FunctionScheduler::addFunction(Function<void()>&& cb,
109                                     milliseconds interval,
110                                     const LatencyDistribution& latencyDistr,
111                                     StringPiece nameID,
112                                     milliseconds startDelay) {
113   if (latencyDistr.isPoisson) {
114     addFunctionInternal(
115         std::move(cb),
116         PoissonDistributionFunctor(latencyDistr.poissonMean),
117         nameID.str(),
118         to<std::string>(latencyDistr.poissonMean, "ms (Poisson mean)"),
119         startDelay,
120         false /*runOnce*/);
121   } else {
122     addFunction(std::move(cb), interval, nameID, startDelay);
123   }
124 }
125
126 void FunctionScheduler::addFunctionOnce(
127     Function<void()>&& cb,
128     StringPiece nameID,
129     milliseconds startDelay) {
130   addFunctionInternal(
131       std::move(cb),
132       ConstIntervalFunctor(milliseconds::zero()),
133       nameID.str(),
134       "once",
135       startDelay,
136       true /*runOnce*/);
137 }
138
139 void FunctionScheduler::addFunctionUniformDistribution(
140     Function<void()>&& cb,
141     milliseconds minInterval,
142     milliseconds maxInterval,
143     StringPiece nameID,
144     milliseconds startDelay) {
145   addFunctionInternal(
146       std::move(cb),
147       UniformDistributionFunctor(minInterval, maxInterval),
148       nameID.str(),
149       to<std::string>(
150           "[", minInterval.count(), " , ", maxInterval.count(), "] ms"),
151       startDelay,
152       false /*runOnce*/);
153 }
154
155 void FunctionScheduler::addFunctionGenericDistribution(
156     Function<void()>&& cb,
157     IntervalDistributionFunc&& intervalFunc,
158     const std::string& nameID,
159     const std::string& intervalDescr,
160     milliseconds startDelay) {
161   addFunctionInternal(
162       std::move(cb),
163       std::move(intervalFunc),
164       nameID,
165       intervalDescr,
166       startDelay,
167       false /*runOnce*/);
168 }
169
170 void FunctionScheduler::addFunctionInternal(
171     Function<void()>&& cb,
172     IntervalDistributionFunc&& intervalFunc,
173     const std::string& nameID,
174     const std::string& intervalDescr,
175     milliseconds startDelay,
176     bool runOnce) {
177   if (!cb) {
178     throw std::invalid_argument(
179         "FunctionScheduler: Scheduled function must be set");
180   }
181   if (!intervalFunc) {
182     throw std::invalid_argument(
183         "FunctionScheduler: interval distribution function must be set");
184   }
185   if (startDelay < milliseconds::zero()) {
186     throw std::invalid_argument(
187         "FunctionScheduler: start delay must be non-negative");
188   }
189
190   std::unique_lock<std::mutex> l(mutex_);
191   // check if the nameID is unique
192   for (const auto& f : functions_) {
193     if (f.isValid() && f.name == nameID) {
194       throw std::invalid_argument(
195           to<std::string>("FunctionScheduler: a function named \"",
196                           nameID,
197                           "\" already exists"));
198     }
199   }
200   if (currentFunction_ && currentFunction_->name == nameID) {
201     throw std::invalid_argument(to<std::string>(
202         "FunctionScheduler: a function named \"", nameID, "\" already exists"));
203   }
204
205   addFunctionToHeap(
206       l,
207       RepeatFunc(
208           std::move(cb),
209           std::move(intervalFunc),
210           nameID,
211           intervalDescr,
212           startDelay,
213           runOnce));
214 }
215
216 bool FunctionScheduler::cancelFunction(StringPiece nameID) {
217   std::unique_lock<std::mutex> l(mutex_);
218
219   if (currentFunction_ && currentFunction_->name == nameID) {
220     // This function is currently being run. Clear currentFunction_
221     // The running thread will see this and won't reschedule the function.
222     currentFunction_ = nullptr;
223     return true;
224   }
225
226   for (auto it = functions_.begin(); it != functions_.end(); ++it) {
227     if (it->isValid() && it->name == nameID) {
228       cancelFunction(l, it);
229       return true;
230     }
231   }
232   return false;
233 }
234
235 void FunctionScheduler::cancelFunction(const std::unique_lock<std::mutex>& l,
236                                        FunctionHeap::iterator it) {
237   // This function should only be called with mutex_ already locked.
238   DCHECK(l.mutex() == &mutex_);
239   DCHECK(l.owns_lock());
240
241   if (running_) {
242     // Internally gcc has an __adjust_heap() function to fill in a hole in the
243     // heap.  Unfortunately it isn't part of the standard API.
244     //
245     // For now we just leave the RepeatFunc in our heap, but mark it as unused.
246     // When its nextTimeInterval comes up, the runner thread will pop it from
247     // the heap and simply throw it away.
248     it->cancel();
249   } else {
250     // We're not running, so functions_ doesn't need to be maintained in heap
251     // order.
252     functions_.erase(it);
253   }
254 }
255
256 void FunctionScheduler::cancelAllFunctions() {
257   std::unique_lock<std::mutex> l(mutex_);
258   functions_.clear();
259   currentFunction_ = nullptr;
260 }
261
262 bool FunctionScheduler::resetFunctionTimer(StringPiece nameID) {
263   std::unique_lock<std::mutex> l(mutex_);
264   if (currentFunction_ && currentFunction_->name == nameID) {
265     RepeatFunc* funcPtrCopy = currentFunction_;
266     // This function is currently being run. Clear currentFunction_
267     // to avoid rescheduling it, and add the function again to honor the
268     // startDelay.
269     currentFunction_ = nullptr;
270     addFunctionToHeap(l, std::move(*funcPtrCopy));
271     return true;
272   }
273
274   // Since __adjust_heap() isn't a part of the standard API, there's no way to
275   // fix the heap ordering if we adjust the key (nextRunTime) for the existing
276   // RepeatFunc. Instead, we just cancel it and add an identical object.
277   for (auto it = functions_.begin(); it != functions_.end(); ++it) {
278     if (it->isValid() && it->name == nameID) {
279       RepeatFunc funcCopy(std::move(*it));
280       cancelFunction(l, it);
281       addFunctionToHeap(l, std::move(funcCopy));
282       return true;
283     }
284   }
285   return false;
286 }
287
288 bool FunctionScheduler::start() {
289   std::unique_lock<std::mutex> l(mutex_);
290   if (running_) {
291     return false;
292   }
293
294   running_ = true;
295
296   VLOG(1) << "Starting FunctionScheduler with " << functions_.size()
297           << " functions.";
298   auto now = steady_clock::now();
299   // Reset the next run time. for all functions.
300   // note: this is needed since one can shutdown() and start() again
301   for (auto& f : functions_) {
302     f.resetNextRunTime(now);
303     VLOG(1) << "   - func: " << (f.name.empty() ? "(anon)" : f.name.c_str())
304             << ", period = " << f.intervalDescr
305             << ", delay = " << f.startDelay.count() << "ms";
306   }
307   std::make_heap(functions_.begin(), functions_.end(), fnCmp_);
308
309   thread_ = std::thread([&] { this->run(); });
310   return true;
311 }
312
313 bool FunctionScheduler::shutdown() {
314   {
315     std::lock_guard<std::mutex> g(mutex_);
316     if (!running_) {
317       return false;
318     }
319
320     running_ = false;
321     runningCondvar_.notify_one();
322   }
323   thread_.join();
324   return true;
325 }
326
327 void FunctionScheduler::run() {
328   std::unique_lock<std::mutex> lock(mutex_);
329
330   if (!threadName_.empty()) {
331     folly::setThreadName(threadName_);
332   }
333
334   while (running_) {
335     // If we have nothing to run, wait until a function is added or until we
336     // are stopped.
337     if (functions_.empty()) {
338       runningCondvar_.wait(lock);
339       continue;
340     }
341
342     auto now = steady_clock::now();
343
344     // Move the next function to run to the end of functions_
345     std::pop_heap(functions_.begin(), functions_.end(), fnCmp_);
346
347     // Check to see if the function was cancelled.
348     // If so, just remove it and continue around the loop.
349     if (!functions_.back().isValid()) {
350       functions_.pop_back();
351       continue;
352     }
353
354     auto sleepTime = functions_.back().getNextRunTime() - now;
355     if (sleepTime < milliseconds::zero()) {
356       // We need to run this function now
357       runOneFunction(lock, now);
358     } else {
359       // Re-add the function to the heap, and wait until we actually
360       // need to run it.
361       std::push_heap(functions_.begin(), functions_.end(), fnCmp_);
362       runningCondvar_.wait_for(lock, sleepTime);
363     }
364   }
365 }
366
367 void FunctionScheduler::runOneFunction(std::unique_lock<std::mutex>& lock,
368                                        steady_clock::time_point now) {
369   DCHECK(lock.mutex() == &mutex_);
370   DCHECK(lock.owns_lock());
371
372   // The function to run will be at the end of functions_ already.
373   //
374   // Fully remove it from functions_ now.
375   // We need to release mutex_ while we invoke this function, and we need to
376   // maintain the heap property on functions_ while mutex_ is unlocked.
377   RepeatFunc func(std::move(functions_.back()));
378   functions_.pop_back();
379   if (!func.cb) {
380     VLOG(5) << func.name << "function has been canceled while waiting";
381     return;
382   }
383   currentFunction_ = &func;
384
385   // Update the function's next run time.
386   if (steady_) {
387     // This allows scheduler to catch up
388     func.setNextRunTimeSteady();
389   } else {
390     // Note that we set nextRunTime based on the current time where we started
391     // the function call, rather than the time when the function finishes.
392     // This ensures that we call the function once every time interval, as
393     // opposed to waiting time interval seconds between calls.  (These can be
394     // different if the function takes a significant amount of time to run.)
395     func.setNextRunTimeStrict(now);
396   }
397
398   // Release the lock while we invoke the user's function
399   lock.unlock();
400
401   // Invoke the function
402   try {
403     VLOG(5) << "Now running " << func.name;
404     func.cb();
405   } catch (const std::exception& ex) {
406     LOG(ERROR) << "Error running the scheduled function <"
407       << func.name << ">: " << exceptionStr(ex);
408   }
409
410   // Re-acquire the lock
411   lock.lock();
412
413   if (!currentFunction_) {
414     // The function was cancelled while we were running it.
415     // We shouldn't reschedule it;
416     return;
417   }
418   if (currentFunction_->runOnce) {
419     // Don't reschedule if the function only needed to run once.
420     return;
421   }
422   // Clear currentFunction_
423   CHECK_EQ(currentFunction_, &func);
424   currentFunction_ = nullptr;
425
426   // Re-insert the function into our functions_ heap.
427   // We only maintain the heap property while running_ is set.  (running_ may
428   // have been cleared while we were invoking the user's function.)
429   functions_.push_back(std::move(func));
430   if (running_) {
431     std::push_heap(functions_.begin(), functions_.end(), fnCmp_);
432   }
433 }
434
435 void FunctionScheduler::addFunctionToHeap(
436     const std::unique_lock<std::mutex>& lock,
437     RepeatFunc&& func) {
438   // This function should only be called with mutex_ already locked.
439   DCHECK(lock.mutex() == &mutex_);
440   DCHECK(lock.owns_lock());
441
442   functions_.emplace_back(std::move(func));
443   if (running_) {
444     functions_.back().resetNextRunTime(steady_clock::now());
445     std::push_heap(functions_.begin(), functions_.end(), fnCmp_);
446     // Signal the running thread to wake up and see if it needs to change
447     // its current scheduling decision.
448     runningCondvar_.notify_one();
449   }
450 }
451
452 void FunctionScheduler::setThreadName(StringPiece threadName) {
453   std::unique_lock<std::mutex> l(mutex_);
454   threadName_ = threadName.str();
455 }
456
457 }