1 // Copyright (c) 2012-2020 The Bitcoin Core developers
2 // Distributed under the MIT software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include <random.h>
6 #include <scheduler.h>
7 #include <util/time.h>
8
9 #include <boost/test/unit_test.hpp>
10 #include <boost/thread/thread.hpp>
11
12 #include <mutex>
13
BOOST_AUTO_TEST_SUITE(scheduler_tests)14 BOOST_AUTO_TEST_SUITE(scheduler_tests)
15
16 static void microTask(CScheduler& s, std::mutex& mutex, int& counter, int delta, std::chrono::system_clock::time_point rescheduleTime)
17 {
18 {
19 std::lock_guard<std::mutex> lock(mutex);
20 counter += delta;
21 }
22 std::chrono::system_clock::time_point noTime = std::chrono::system_clock::time_point::min();
23 if (rescheduleTime != noTime) {
24 CScheduler::Function f = std::bind(µTask, std::ref(s), std::ref(mutex), std::ref(counter), -delta + 1, noTime);
25 s.schedule(f, rescheduleTime);
26 }
27 }
28
BOOST_AUTO_TEST_CASE(manythreads)29 BOOST_AUTO_TEST_CASE(manythreads)
30 {
31 // Stress test: hundreds of microsecond-scheduled tasks,
32 // serviced by 10 threads.
33 //
34 // So... ten shared counters, which if all the tasks execute
35 // properly will sum to the number of tasks done.
36 // Each task adds or subtracts a random amount from one of the
37 // counters, and then schedules another task 0-1000
38 // microseconds in the future to subtract or add from
39 // the counter -random_amount+1, so in the end the shared
40 // counters should sum to the number of initial tasks performed.
41 CScheduler microTasks;
42
43 std::mutex counterMutex[10];
44 int counter[10] = { 0 };
45 FastRandomContext rng{/* fDeterministic */ true};
46 auto zeroToNine = [](FastRandomContext& rc) -> int { return rc.randrange(10); }; // [0, 9]
47 auto randomMsec = [](FastRandomContext& rc) -> int { return -11 + (int)rc.randrange(1012); }; // [-11, 1000]
48 auto randomDelta = [](FastRandomContext& rc) -> int { return -1000 + (int)rc.randrange(2001); }; // [-1000, 1000]
49
50 std::chrono::system_clock::time_point start = std::chrono::system_clock::now();
51 std::chrono::system_clock::time_point now = start;
52 std::chrono::system_clock::time_point first, last;
53 size_t nTasks = microTasks.getQueueInfo(first, last);
54 BOOST_CHECK(nTasks == 0);
55
56 for (int i = 0; i < 100; ++i) {
57 std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng));
58 std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng));
59 int whichCounter = zeroToNine(rng);
60 CScheduler::Function f = std::bind(µTask, std::ref(microTasks),
61 std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]),
62 randomDelta(rng), tReschedule);
63 microTasks.schedule(f, t);
64 }
65 nTasks = microTasks.getQueueInfo(first, last);
66 BOOST_CHECK(nTasks == 100);
67 BOOST_CHECK(first < last);
68 BOOST_CHECK(last > now);
69
70 // As soon as these are created they will start running and servicing the queue
71 boost::thread_group microThreads;
72 for (int i = 0; i < 5; i++)
73 microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks));
74
75 UninterruptibleSleep(std::chrono::microseconds{600});
76 now = std::chrono::system_clock::now();
77
78 // More threads and more tasks:
79 for (int i = 0; i < 5; i++)
80 microThreads.create_thread(std::bind(&CScheduler::serviceQueue, µTasks));
81 for (int i = 0; i < 100; i++) {
82 std::chrono::system_clock::time_point t = now + std::chrono::microseconds(randomMsec(rng));
83 std::chrono::system_clock::time_point tReschedule = now + std::chrono::microseconds(500 + randomMsec(rng));
84 int whichCounter = zeroToNine(rng);
85 CScheduler::Function f = std::bind(µTask, std::ref(microTasks),
86 std::ref(counterMutex[whichCounter]), std::ref(counter[whichCounter]),
87 randomDelta(rng), tReschedule);
88 microTasks.schedule(f, t);
89 }
90
91 // Drain the task queue then exit threads
92 microTasks.StopWhenDrained();
93 microThreads.join_all(); // ... wait until all the threads are done
94
95 int counterSum = 0;
96 for (int i = 0; i < 10; i++) {
97 BOOST_CHECK(counter[i] != 0);
98 counterSum += counter[i];
99 }
100 BOOST_CHECK_EQUAL(counterSum, 200);
101 }
102
BOOST_AUTO_TEST_CASE(wait_until_past)103 BOOST_AUTO_TEST_CASE(wait_until_past)
104 {
105 std::condition_variable condvar;
106 Mutex mtx;
107 WAIT_LOCK(mtx, lock);
108
109 const auto no_wait= [&](const std::chrono::seconds& d) {
110 return condvar.wait_until(lock, std::chrono::system_clock::now() - d);
111 };
112
113 BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::seconds{1}));
114 BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::minutes{1}));
115 BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1}));
116 BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{10}));
117 BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{100}));
118 BOOST_CHECK(std::cv_status::timeout == no_wait(std::chrono::hours{1000}));
119 }
120
BOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered)121 BOOST_AUTO_TEST_CASE(singlethreadedscheduler_ordered)
122 {
123 CScheduler scheduler;
124
125 // each queue should be well ordered with respect to itself but not other queues
126 SingleThreadedSchedulerClient queue1(&scheduler);
127 SingleThreadedSchedulerClient queue2(&scheduler);
128
129 // create more threads than queues
130 // if the queues only permit execution of one task at once then
131 // the extra threads should effectively be doing nothing
132 // if they don't we'll get out of order behaviour
133 boost::thread_group threads;
134 for (int i = 0; i < 5; ++i) {
135 threads.create_thread(std::bind(&CScheduler::serviceQueue, &scheduler));
136 }
137
138 // these are not atomic, if SinglethreadedSchedulerClient prevents
139 // parallel execution at the queue level no synchronization should be required here
140 int counter1 = 0;
141 int counter2 = 0;
142
143 // just simply count up on each queue - if execution is properly ordered then
144 // the callbacks should run in exactly the order in which they were enqueued
145 for (int i = 0; i < 100; ++i) {
146 queue1.AddToProcessQueue([i, &counter1]() {
147 bool expectation = i == counter1++;
148 assert(expectation);
149 });
150
151 queue2.AddToProcessQueue([i, &counter2]() {
152 bool expectation = i == counter2++;
153 assert(expectation);
154 });
155 }
156
157 // finish up
158 scheduler.StopWhenDrained();
159 threads.join_all();
160
161 BOOST_CHECK_EQUAL(counter1, 100);
162 BOOST_CHECK_EQUAL(counter2, 100);
163 }
164
BOOST_AUTO_TEST_CASE(mockforward)165 BOOST_AUTO_TEST_CASE(mockforward)
166 {
167 CScheduler scheduler;
168
169 int counter{0};
170 CScheduler::Function dummy = [&counter]{counter++;};
171
172 // schedule jobs for 2, 5 & 8 minutes into the future
173
174 scheduler.scheduleFromNow(dummy, std::chrono::minutes{2});
175 scheduler.scheduleFromNow(dummy, std::chrono::minutes{5});
176 scheduler.scheduleFromNow(dummy, std::chrono::minutes{8});
177
178 // check taskQueue
179 std::chrono::system_clock::time_point first, last;
180 size_t num_tasks = scheduler.getQueueInfo(first, last);
181 BOOST_CHECK_EQUAL(num_tasks, 3ul);
182
183 std::thread scheduler_thread([&]() { scheduler.serviceQueue(); });
184
185 // bump the scheduler forward 5 minutes
186 scheduler.MockForward(std::chrono::minutes{5});
187
188 // ensure scheduler has chance to process all tasks queued for before 1 ms from now.
189 scheduler.scheduleFromNow([&scheduler] { scheduler.stop(); }, std::chrono::milliseconds{1});
190 scheduler_thread.join();
191
192 // check that the queue only has one job remaining
193 num_tasks = scheduler.getQueueInfo(first, last);
194 BOOST_CHECK_EQUAL(num_tasks, 1ul);
195
196 // check that the dummy function actually ran
197 BOOST_CHECK_EQUAL(counter, 2);
198
199 // check that the time of the remaining job has been updated
200 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
201 int delta = std::chrono::duration_cast<std::chrono::seconds>(first - now).count();
202 // should be between 2 & 3 minutes from now
203 BOOST_CHECK(delta > 2*60 && delta < 3*60);
204 }
205
206 BOOST_AUTO_TEST_SUITE_END()
207