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
// Copyright (C) 2019-2024 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 <util/multi_threading_mgr.h>

#include <boost/range/adaptor/reversed.hpp><--- Include file:  not found. Please note: Cppcheck does not need standard library headers to get proper results.

namespace isc {
namespace util {

MultiThreadingMgr::MultiThreadingMgr()
    : enabled_(false), critical_section_count_(0), thread_pool_size_(0) {
}

MultiThreadingMgr::~MultiThreadingMgr() {
}

MultiThreadingMgr&
MultiThreadingMgr::instance() {
    static MultiThreadingMgr manager;
    return (manager);
}

bool
MultiThreadingMgr::getMode() const {
    return (enabled_);
}

void
MultiThreadingMgr::setMode(bool enabled) {
    enabled_ = enabled;
}

void
MultiThreadingMgr::enterCriticalSection() {
    checkCallbacksPermissions();
    bool inside = isInCriticalSection();
    // Increment the counter to allow CS to be created in the registered
    // callbacks (in which case the new CS would not call callbacks again).
    // The counter must be updated regardless of the MT mode because the MT mode
    // can change between the constructor call and the destructor call.
    ++critical_section_count_;
    if (getMode() && !inside) {
        if (getThreadPoolSize()) {
            // Simply pause after waiting for started tasks to complete.
            thread_pool_.pause();
        }
        // Now it is safe to call callbacks which can also create other CSs.
        callEntryCallbacks();
    }
}

void
MultiThreadingMgr::exitCriticalSection() {
    // The number of CS destructors should match the number of CS constructors.
    // The case when counter is 0 is only possible if calling this function
    // explicitly, which is a programming error.
    if (!isInCriticalSection()) {
        isc_throw(InvalidOperation, "invalid value for critical section count");
    }
    // Decrement the counter to allow the check for last CS destructor which
    // would result in restarting the thread pool.
    // The counter must be updated regardless of the MT mode because the MT mode
    // can change between the constructor call and the destructor call.
    --critical_section_count_;
    if (getMode() && !isInCriticalSection()) {
        if (getThreadPoolSize()) {
            // If apply has been called, threads have never been started inside
            // a critical section, so start them now, otherwise just resume
            // paused threads.
            if (!thread_pool_.enabled()) {
                thread_pool_.start(getThreadPoolSize());
            } else {
                thread_pool_.resume();
            }
        }
        // Now it is safe to call callbacks which can also create other CSs.
        callExitCallbacks();
    }
}

bool
MultiThreadingMgr::isInCriticalSection() {
    return (critical_section_count_ != 0);
}

ThreadPool<std::function<void()>>&
MultiThreadingMgr::getThreadPool() {
    return thread_pool_;
}

uint32_t
MultiThreadingMgr::getThreadPoolSize() const {
    return (thread_pool_size_);
}

void
MultiThreadingMgr::setThreadPoolSize(uint32_t size) {
    thread_pool_size_ = size;
}

uint32_t
MultiThreadingMgr::getPacketQueueSize() {
    return (thread_pool_.getMaxQueueSize());
}

void
MultiThreadingMgr::setPacketQueueSize(uint32_t size) {
    thread_pool_.setMaxQueueSize(size);
}

uint32_t
MultiThreadingMgr::detectThreadCount() {
    return (std::thread::hardware_concurrency());
}

void
MultiThreadingMgr::apply(bool enabled, uint32_t thread_count, uint32_t queue_size) {
    // check the enabled flag
    if (enabled) {
        // check for auto scaling (enabled flag true but thread_count 0)
        if (!thread_count) {
            // might also return 0
            thread_count = MultiThreadingMgr::detectThreadCount();
        }
    } else {
        thread_count = 0;
        queue_size = 0;
    }
    // check enabled flag and explicit number of threads or system supports
    // hardware concurrency
    if (thread_count) {
        if (thread_pool_.size()) {
            thread_pool_.stop();
        }
        setThreadPoolSize(thread_count);
        setPacketQueueSize(queue_size);
        setMode(true);
        if (!isInCriticalSection()) {
            thread_pool_.start(thread_count);
        }
    } else {
        removeAllCriticalSectionCallbacks();
        thread_pool_.reset();
        setMode(false);
        setThreadPoolSize(thread_count);
        setPacketQueueSize(queue_size);
    }
}

void
MultiThreadingMgr::checkCallbacksPermissions() {
    if (getMode()) {
        for (auto const& cb : cs_callbacks_.getCallbackSets()) {
            try {
                (cb.check_cb_)();
            } catch (const isc::MultiThreadingInvalidOperation& ex) {
                // If any registered callback throws, the exception needs to be
                // propagated to the caller of the
                // @ref MultiThreadingCriticalSection constructor.
                // Because this function is called by the
                // @ref MultiThreadingCriticalSection constructor, throwing here
                // is safe.
                throw;
            } catch (...) {
                // We can't log it and throwing could be chaos.
                // We'll swallow it and tell people their callbacks
                // must be exception-proof
            }
        }
    }
}

void
MultiThreadingMgr::callEntryCallbacks() {
    if (getMode()) {
        auto const& callbacks = cs_callbacks_.getCallbackSets();
        for (auto const& cb_it : callbacks) {
            try {
                (cb_it.entry_cb_)();
            } catch (...) {
                // We can't log it and throwing could be chaos.
                // We'll swallow it and tell people their callbacks
                // must be exception-proof
            }
        }
    }
}

void
MultiThreadingMgr::callExitCallbacks() {
    if (getMode()) {
        auto const& callbacks = cs_callbacks_.getCallbackSets();
        for (auto const& cb_it : boost::adaptors::reverse(callbacks)) {
            try {
                (cb_it.exit_cb_)();
            } catch (...) {
                // We can't log it and throwing could be chaos.
                // We'll swallow it and tell people their callbacks
                // must be exception-proof
                // Because this function is called by the
                // @ref MultiThreadingCriticalSection destructor, throwing here
                // is not safe and will cause the process to crash.
            }
        }
    }
}

void
MultiThreadingMgr::addCriticalSectionCallbacks(const std::string& name,
                                               const CSCallbackSet::Callback& check_cb,
                                               const CSCallbackSet::Callback& entry_cb,
                                               const CSCallbackSet::Callback& exit_cb) {
    cs_callbacks_.addCallbackSet(name, check_cb, entry_cb, exit_cb);
}

void
MultiThreadingMgr::removeCriticalSectionCallbacks(const std::string& name) {
    cs_callbacks_.removeCallbackSet(name);
}

void
MultiThreadingMgr::removeAllCriticalSectionCallbacks() {
    cs_callbacks_.removeAll();
}

MultiThreadingCriticalSection::MultiThreadingCriticalSection() {
    MultiThreadingMgr::instance().enterCriticalSection();
}

MultiThreadingCriticalSection::~MultiThreadingCriticalSection() {
    MultiThreadingMgr::instance().exitCriticalSection();
}

MultiThreadingLock::MultiThreadingLock(std::mutex& mutex) {
    if (MultiThreadingMgr::instance().getMode()) {
        lock_ = std::unique_lock<std::mutex>(mutex);
    }
}

void
CSCallbackSetList::addCallbackSet(const std::string& name,
                                  const CSCallbackSet::Callback& check_cb,
                                  const CSCallbackSet::Callback& entry_cb,
                                  const CSCallbackSet::Callback& exit_cb) {
    if (name.empty()) {
        isc_throw(BadValue, "CSCallbackSetList - name cannot be empty");
    }

    if (!check_cb) {
        isc_throw(BadValue, "CSCallbackSetList - check callback for " << name
                  << " cannot be empty");
    }

    if (!entry_cb) {
        isc_throw(BadValue, "CSCallbackSetList - entry callback for " << name
                  << " cannot be empty");
    }

    if (!exit_cb) {
        isc_throw(BadValue, "CSCallbackSetList - exit callback for " << name
                  << " cannot be empty");
    }

    for (auto const& callback : cb_sets_) {
        if (callback.name_ == name) {
            isc_throw(BadValue, "CSCallbackSetList - callbacks for " << name
                      << " already exist");
        }
    }

    cb_sets_.push_back(CSCallbackSet(name, check_cb, entry_cb, exit_cb));
}

void
CSCallbackSetList::removeCallbackSet(const std::string& name) {
    for (auto it = cb_sets_.begin(); it != cb_sets_.end(); ++it) {
        if ((*it).name_ == name) {<--- Consider using std::find_if algorithm instead of a raw loop.
            cb_sets_.erase(it);
            break;
        }
    }
}

void
CSCallbackSetList::removeAll() {
    cb_sets_.clear();
}

const std::list<CSCallbackSet>&
CSCallbackSetList::getCallbackSets() {
    return (cb_sets_);
}

}  // namespace util
}  // namespace isc