1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
// Copyright (C) 2019-2023 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

#include <config.h>

#include <exceptions/exceptions.h>
#include <util/multi_threading_mgr.h>
#include <testutils/gtest_utils.h>

#include <gtest/gtest.h><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

using namespace isc::util;
using namespace isc;

/// @brief Fixture used to reset multi-threading before and after each test.
struct MultiThreadingMgrTest : ::testing::Test {
    /// @brief Constructor.
    MultiThreadingMgrTest() {
        MultiThreadingMgr::instance().apply(false, 0, 0);
    }

    /// @brief Destructor.
    ~MultiThreadingMgrTest() {
        MultiThreadingMgr::instance().apply(false, 0, 0);
    }

    /// @brief Check thread pool state.
    ///
    /// @param mode The multi-threading mode.
    /// @param size The thread pool size.
    /// @param count The thread queue size.
    /// @param running The running threads count.
    /// @param in_cs Flag which indicates if running inside critical section.
    /// @param enabled Flag which indicates if thread pool is started and running.
    /// @param paused Flag which indicates if thread pool is started and paused.
    void checkState(bool mode, size_t size, size_t count, size_t running,
                    bool in_cs = false, bool enabled = false, bool paused = false) {
        EXPECT_EQ(MultiThreadingMgr::instance().getMode(), mode);
        EXPECT_EQ(MultiThreadingMgr::instance().getThreadPoolSize(), size);
        EXPECT_EQ(MultiThreadingMgr::instance().getPacketQueueSize(), count);
        EXPECT_EQ(MultiThreadingMgr::instance().getThreadPool().size(), running);
        EXPECT_EQ(MultiThreadingMgr::instance().isInCriticalSection(), in_cs);
        EXPECT_EQ(MultiThreadingMgr::instance().getThreadPool().enabled(), enabled);
        EXPECT_EQ(MultiThreadingMgr::instance().getThreadPool().paused(), paused);
    }
};

/// @brief Verifies that the default mode is false (MT disabled).
TEST_F(MultiThreadingMgrTest, defaultMode) {
    // MT should be disabled
    EXPECT_FALSE(MultiThreadingMgr::instance().getMode());
}

/// @brief Verifies that the mode setter works.
TEST_F(MultiThreadingMgrTest, setMode) {
    // enable MT
    EXPECT_NO_THROW(MultiThreadingMgr::instance().setMode(true));
    // MT should be enabled
    EXPECT_TRUE(MultiThreadingMgr::instance().getMode());
    // disable MT
    EXPECT_NO_THROW(MultiThreadingMgr::instance().setMode(false));
    // MT should be disabled
    EXPECT_FALSE(MultiThreadingMgr::instance().getMode());
}

/// @brief Verifies that accessing the thread pool works.
TEST_F(MultiThreadingMgrTest, threadPool) {
    // get the thread pool
    EXPECT_NO_THROW(MultiThreadingMgr::instance().getThreadPool());
}

/// @brief Verifies that the thread pool size setter works.
TEST_F(MultiThreadingMgrTest, threadPoolSize) {
    // default thread count is 0
    EXPECT_EQ(MultiThreadingMgr::instance().getThreadPoolSize(), 0);
    // set thread count to 16
    EXPECT_NO_THROW(MultiThreadingMgr::instance().setThreadPoolSize(16));
    // thread count should be 16
    EXPECT_EQ(MultiThreadingMgr::instance().getThreadPoolSize(), 16);
    // set thread count to 0
    EXPECT_NO_THROW(MultiThreadingMgr::instance().setThreadPoolSize(0));
    // thread count should be 0
    EXPECT_EQ(MultiThreadingMgr::instance().getThreadPoolSize(), 0);
}

/// @brief Verifies that the packet queue size setter works.
TEST_F(MultiThreadingMgrTest, packetQueueSize) {
    // default queue size is 0
    EXPECT_EQ(MultiThreadingMgr::instance().getPacketQueueSize(), 0);
    EXPECT_EQ(MultiThreadingMgr::instance().getThreadPool().getMaxQueueSize(), 0);
    // set queue size to 16
    EXPECT_NO_THROW(MultiThreadingMgr::instance().setPacketQueueSize(16));
    // queue size should be 16
    EXPECT_EQ(MultiThreadingMgr::instance().getPacketQueueSize(), 16);
    EXPECT_EQ(MultiThreadingMgr::instance().getThreadPool().getMaxQueueSize(), 16);
    // set queue size to 0
    EXPECT_NO_THROW(MultiThreadingMgr::instance().setPacketQueueSize(0));
    // queue size should be 0
    EXPECT_EQ(MultiThreadingMgr::instance().getPacketQueueSize(), 0);
    EXPECT_EQ(MultiThreadingMgr::instance().getThreadPool().getMaxQueueSize(), 0);
}

/// @brief Verifies that detecting thread count works.
TEST_F(MultiThreadingMgrTest, detectThreadCount) {
    // detecting thread count should work
    EXPECT_NE(MultiThreadingMgr::detectThreadCount(), 0);
}

/// @brief Verifies that apply settings works.
TEST_F(MultiThreadingMgrTest, applyConfig) {
    checkState(false, 0, 0, 0);
    // enable MT with 16 threads and queue size 256
    EXPECT_NO_THROW(MultiThreadingMgr::instance().apply(true, 16, 256));
    checkState(true, 16, 256, 16, false, true);
    // disable MT
    EXPECT_NO_THROW(MultiThreadingMgr::instance().apply(false, 16, 256));
    checkState(false, 0, 0, 0);
    // enable MT with auto scaling
    EXPECT_NO_THROW(MultiThreadingMgr::instance().apply(true, 0, 0));
    checkState(true, MultiThreadingMgr::detectThreadCount(), 0, MultiThreadingMgr::detectThreadCount(), false, true);
    // disable MT
    EXPECT_NO_THROW(MultiThreadingMgr::instance().apply(false, 0, 0));
    checkState(false, 0, 0, 0);
}

/// @brief Verifies that the critical section flag works.
TEST_F(MultiThreadingMgrTest, criticalSectionFlag) {
    checkState(false, 0, 0, 0);
    // exit critical section
    EXPECT_THROW(MultiThreadingMgr::instance().exitCriticalSection(), InvalidOperation);
    // critical section should be disabled
    EXPECT_FALSE(MultiThreadingMgr::instance().isInCriticalSection());
    // enter critical section
    EXPECT_NO_THROW(MultiThreadingMgr::instance().enterCriticalSection());
    // critical section should be enabled
    EXPECT_TRUE(MultiThreadingMgr::instance().isInCriticalSection());
    // enable MT with 16 threads and queue size 256
    EXPECT_NO_THROW(MultiThreadingMgr::instance().apply(true, 16, 256));
    checkState(true, 16, 256, 0, true);
    // exit critical section
    EXPECT_NO_THROW(MultiThreadingMgr::instance().exitCriticalSection());
    // critical section should be disabled
    EXPECT_FALSE(MultiThreadingMgr::instance().isInCriticalSection());
    // exit critical section
    EXPECT_THROW(MultiThreadingMgr::instance().exitCriticalSection(), InvalidOperation);
    // critical section should be disabled
    EXPECT_FALSE(MultiThreadingMgr::instance().isInCriticalSection());
    // disable MT
    EXPECT_NO_THROW(MultiThreadingMgr::instance().apply(false, 0, 0));
    checkState(false, 0, 0, 0);
}

/// @brief Verifies that the critical section works.
TEST_F(MultiThreadingMgrTest, criticalSection) {
    checkState(false, 0, 0, 0);
    // apply multi-threading configuration with 16 threads and queue size 256
    MultiThreadingMgr::instance().apply(true, 16, 256);
    checkState(true, 16, 256, 16, false, true);
    // use scope to test constructor and destructor
    {
        MultiThreadingCriticalSection cs;
        checkState(true, 16, 256, 16, true, true, true);
        // use scope to test constructor and destructor
        {
            MultiThreadingCriticalSection inner_cs;
            checkState(true, 16, 256, 16, true, true, true);
        }
        checkState(true, 16, 256, 16, true, true, true);
    }
    checkState(true, 16, 256, 16, false, true);
    // use scope to test constructor and destructor
    {
        MultiThreadingCriticalSection cs;
        checkState(true, 16, 256, 16, true, true, true);
        // apply multi-threading configuration with 64 threads and queue size 4
        MultiThreadingMgr::instance().apply(true, 64, 4);
        checkState(true, 64, 4, 0, true);
    }
    checkState(true, 64, 4, 64, false, true);
    // use scope to test constructor and destructor
    {
        MultiThreadingCriticalSection cs;
        checkState(true, 64, 4, 64, true, true, true);
        // apply multi-threading configuration with 0 threads
        MultiThreadingMgr::instance().apply(false, 64, 256);
        checkState(false, 0, 0, 0, true);
    }
    checkState(false, 0, 0, 0);
    // use scope to test constructor and destructor
    {
        MultiThreadingCriticalSection cs;
        checkState(false, 0, 0, 0, true);
        // use scope to test constructor and destructor
        {
            MultiThreadingCriticalSection inner_cs;
            checkState(false, 0, 0, 0, true);
        }
        checkState(false, 0, 0, 0, true);
    }
    checkState(false, 0, 0, 0);
    // use scope to test constructor and destructor
    {
        MultiThreadingCriticalSection cs;
        checkState(false, 0, 0, 0, true);
        // apply multi-threading configuration with 64 threads
        MultiThreadingMgr::instance().apply(true, 64, 256);
        checkState(true, 64, 256, 0, true);
    }
    checkState(true, 64, 256, 64, false, true);
    // apply multi-threading configuration with 0 threads
    MultiThreadingMgr::instance().apply(false, 0, 0);
    checkState(false, 0, 0, 0);
}

/// @brief Checks that the lock works only when multi-threading is enabled and
/// only during its lifetime.
TEST(MultiThreadingLockTest, scope) {
    // Check that the mutex is unlocked by default at first.
    std::mutex mutex;
    ASSERT_TRUE(mutex.try_lock());
    mutex.unlock();

    EXPECT_NO_THROW(MultiThreadingMgr::instance().setMode(false));

    // Check that the lock does not locks the mutex if multi-threading is disabled.
    {
        MultiThreadingLock lock(mutex);
        ASSERT_TRUE(mutex.try_lock());
        mutex.unlock();
    }

    // Check that the mutex is still unlocked when the lock goes out of scope.
    ASSERT_TRUE(mutex.try_lock());
    mutex.unlock();

    EXPECT_NO_THROW(MultiThreadingMgr::instance().setMode(true));

    // Check that the lock actively locks the mutex if multi-threading is enabled.
    {
        MultiThreadingLock lock(mutex);
        ASSERT_FALSE(mutex.try_lock());
    }

    // Check that the mutex is unlocked when the lock goes out of scope.
    ASSERT_TRUE(mutex.try_lock());
    mutex.unlock();
}

/// @brief Test fixture for exercised CriticalSection callbacks.
class CriticalSectionCallbackTest : public ::testing::Test {
public:
    /// @brief Constructor.
    CriticalSectionCallbackTest() {
        MultiThreadingMgr::instance().apply(false, 0, 0);
    }

    /// @brief Destructor.
    ~CriticalSectionCallbackTest() {
        MultiThreadingMgr::instance().apply(false, 0, 0);
    }

    /// @brief A callback that adds the value 1 to invocations lists.
    void one() {
        invocations_.push_back(1);
    }

    /// @brief A callback that adds the value 2 to invocations lists.
    void two() {
        invocations_.push_back(2);
    }

    /// @brief A callback that adds the value 3 to invocations lists.
    void three() {
        invocations_.push_back(3);
    }

    /// @brief A callback that adds the value 4 to invocations lists.
    void four() {
        invocations_.push_back(4);
    }

    /// @brief A callback that throws @ref isc::Exception which is ignored.
    void ignoredException() {
        isc_throw(isc::Exception, "ignored");
    }

    /// @brief A callback that throws @ref isc::MultiThreadingInvalidOperation
    /// which is propagated to the scope of the
    /// @ref MultiThreadingCriticalSection constructor.
    void observedException() {
        isc_throw(isc::MultiThreadingInvalidOperation, "observed");
    }

    /// @brief Indicates whether or not the DHCP thread pool is running.
    ///
    /// @return True if the pool is running, false otherwise.
    bool isThreadPoolRunning() {
        return (!MultiThreadingMgr::instance().getThreadPool().paused());
    }

    /// @brief Checks callback invocations over a series of nested
    /// CriticalSections.
    ///
    /// @param entries A vector of the invocation values that should
    /// be present after entry into the outermost CriticalSection.  The
    /// expected values should be in the order the callbacks were added
    /// to the MultiThreadingMgr's list of callbacks.
    /// @param exits A vector of the invocation values that should
    /// be present after exiting the outermost CriticalSection.  The
    /// expected values should be in the order the callbacks were added
    /// to the MultiThreadingMgr's list of callbacks.
    /// @param should_throw The flag indicating if the CriticalSection should
    /// throw, simulating a dead-lock scenario when a processing thread tries
    /// to stop the thread pool.
    void runCriticalSections(std::vector<int> entries, std::vector<int>exits,
                             bool should_throw = false) {
        // Pool must be running.
        ASSERT_TRUE(isThreadPoolRunning());

        // Clear the invocations list.
        invocations_.clear();

        // Use scope to create nested CriticalSections.
        if (!should_throw) {
            // Enter a critical section.
            MultiThreadingCriticalSection cs;

            // Thread pool should be stopped.
            ASSERT_FALSE(isThreadPoolRunning());

            if (entries.size()) {
                // We expect entry invocations.
                ASSERT_EQ(invocations_.size(), entries.size());
                ASSERT_EQ(invocations_, entries);
            } else {
                // We do not expect entry invocations.
                ASSERT_FALSE(invocations_.size());
            }

            // Clear the invocations list.
            invocations_.clear();

            {
                // Enter another CriticalSection.
                MultiThreadingCriticalSection inner_cs;

                // Thread pool should still be stopped.
                ASSERT_FALSE(isThreadPoolRunning());

                // We should not have had any callback invocations.
                ASSERT_FALSE(invocations_.size());
            }

            // After exiting inner section, the thread pool should
            // still be stopped.
            ASSERT_FALSE(isThreadPoolRunning());

            // We should not have had more callback invocations.
            ASSERT_FALSE(invocations_.size());
        } else {
            ASSERT_THROW(MultiThreadingCriticalSection cs, MultiThreadingInvalidOperation);

            if (entries.size()) {
                // We expect entry invocations.
                ASSERT_EQ(invocations_.size(), entries.size());
                ASSERT_EQ(invocations_, entries);
            } else {
                // We do not expect entry invocations.
                ASSERT_FALSE(invocations_.size());
            }

            // Clear the invocations list.
            invocations_.clear();
        }

        // After exiting the outer section, the thread pool should
        // match the thread count.
        ASSERT_TRUE(isThreadPoolRunning());

        if (exits.size()) {
            // We expect exit invocations.
            ASSERT_EQ(invocations_, exits);
        } else {
            // We do not expect exit invocations.
            ASSERT_FALSE(invocations_.size());
        }
    }

    /// @brief A list of values set by callback invocations.
    std::vector<int> invocations_;
};

/// @brief Verifies critical section callback maintenance:
/// catch invalid pairs, add pairs, remove pairs.
TEST_F(CriticalSectionCallbackTest, addAndRemove) {
    auto& mgr = MultiThreadingMgr::instance();

    // Cannot add with a blank name.
    ASSERT_THROW_MSG(mgr.addCriticalSectionCallbacks("", [](){}, [](){}, [](){}),
                     BadValue, "CSCallbackSetList - name cannot be empty");

    // Cannot add with an empty check callback.
    ASSERT_THROW_MSG(mgr.addCriticalSectionCallbacks("bad", nullptr, [](){}, [](){}),
                     BadValue, "CSCallbackSetList - check callback for bad cannot be empty");

    // Cannot add with an empty exit callback.
    ASSERT_THROW_MSG(mgr.addCriticalSectionCallbacks("bad", [](){}, nullptr, [](){}),
                     BadValue, "CSCallbackSetList - entry callback for bad cannot be empty");

    // Cannot add with an empty exit callback.
    ASSERT_THROW_MSG(mgr.addCriticalSectionCallbacks("bad", [](){}, [](){}, nullptr),
                     BadValue, "CSCallbackSetList - exit callback for bad cannot be empty");

    // Should be able to add foo.
    ASSERT_NO_THROW_LOG(mgr.addCriticalSectionCallbacks("foo", [](){}, [](){}, [](){}));

    // Should not be able to add foo twice.
    ASSERT_THROW_MSG(mgr.addCriticalSectionCallbacks("foo", [](){}, [](){}, [](){}),
                     BadValue, "CSCallbackSetList - callbacks for foo already exist");

    // Should be able to add bar.
    ASSERT_NO_THROW_LOG(mgr.addCriticalSectionCallbacks("bar", [](){}, [](){}, [](){}));

    // Should be able to remove foo.
    ASSERT_NO_THROW_LOG(mgr.removeCriticalSectionCallbacks("foo"));

    // Should be able to remove foo twice without issue.
    ASSERT_NO_THROW_LOG(mgr.removeCriticalSectionCallbacks("foo"));

    // Should be able to remove all without issue.
    ASSERT_NO_THROW_LOG(mgr.removeAllCriticalSectionCallbacks());
}

/// @brief Verifies that the critical section callbacks work.
TEST_F(CriticalSectionCallbackTest, invocations) {
    // get the thread pool instance
    auto& thread_pool = MultiThreadingMgr::instance().getThreadPool();
    // thread pool should be stopped
    EXPECT_EQ(thread_pool.size(), 0);

    // Add two sets of CriticalSection call backs.
    MultiThreadingMgr::instance().addCriticalSectionCallbacks("oneAndTwo",
         std::bind(&CriticalSectionCallbackTest::ignoredException, this),
         std::bind(&CriticalSectionCallbackTest::one, this),
         std::bind(&CriticalSectionCallbackTest::two, this));

    MultiThreadingMgr::instance().addCriticalSectionCallbacks("threeAndFour",
         std::bind(&CriticalSectionCallbackTest::ignoredException, this),
         std::bind(&CriticalSectionCallbackTest::three, this),
         std::bind(&CriticalSectionCallbackTest::four, this));

    // Apply multi-threading configuration with 16 threads and queue size 256.
    MultiThreadingMgr::instance().apply(true, 16, 256);

    // Make three passes over nested CriticalSections to ensure
    // callbacks execute at the appropriate times and we can do
    // so repeatedly.
    for (int i = 0; i < 3; ++i) {
        runCriticalSections({1 ,3}, {4, 2});
    }

    // Now remove the first set of callbacks.
    MultiThreadingMgr::instance().removeCriticalSectionCallbacks("oneAndTwo");

    // Retest CriticalSections.
    runCriticalSections({3}, {4});

    // Now remove the remaining callbacks.
    MultiThreadingMgr::instance().removeAllCriticalSectionCallbacks();

    // Retest CriticalSections.
    runCriticalSections({}, {});
}

/// @brief Verifies that the critical section callbacks work.
TEST_F(CriticalSectionCallbackTest, invocationsWithExceptions) {
    // get the thread pool instance
    auto& thread_pool = MultiThreadingMgr::instance().getThreadPool();
    // thread pool should be stopped
    EXPECT_EQ(thread_pool.size(), 0);

    // Apply multi-threading configuration with 16 threads and queue size 256.
    MultiThreadingMgr::instance().apply(true, 16, 256);

    // Add two sets of CriticalSection call backs.
    MultiThreadingMgr::instance().addCriticalSectionCallbacks("observed",
         std::bind(&CriticalSectionCallbackTest::observedException, this),
         std::bind(&CriticalSectionCallbackTest::one, this),
         std::bind(&CriticalSectionCallbackTest::two, this));

    MultiThreadingMgr::instance().addCriticalSectionCallbacks("ignored",
         std::bind(&CriticalSectionCallbackTest::ignoredException, this),
         std::bind(&CriticalSectionCallbackTest::three, this),
         std::bind(&CriticalSectionCallbackTest::four, this));

    // Make three passes over nested CriticalSections to ensure
    // callbacks execute at the appropriate times and we can do
    // so repeatedly.
    for (int i = 0; i < 3; ++i) {
        runCriticalSections({}, {}, true);
    }

    // Now remove the first set of callbacks.
    MultiThreadingMgr::instance().removeCriticalSectionCallbacks("observed");

    // Retest CriticalSections.
    runCriticalSections({3}, {4});

    // Now remove the remaining callbacks.
    MultiThreadingMgr::instance().removeAllCriticalSectionCallbacks();

    // Retest CriticalSections.
    runCriticalSections({}, {});
}