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
|
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
#include "base/workqueue.hpp"
#include "base/utility.hpp"
#include "base/logger.hpp"
#include "base/convert.hpp"
#include "base/application.hpp"
#include "base/exception.hpp"
#include <boost/thread/tss.hpp>
#include <math.h>
using namespace icinga;
std::atomic<int> WorkQueue::m_NextID(1);
boost::thread_specific_ptr<WorkQueue *> l_ThreadWorkQueue;
WorkQueue::WorkQueue(size_t maxItems, int threadCount, LogSeverity statsLogLevel)
: m_ID(m_NextID++), m_ThreadCount(threadCount), m_MaxItems(maxItems),
m_TaskStats(15 * 60), m_StatsLogLevel(statsLogLevel)
{
/* Initialize logger. */
m_StatusTimerTimeout = Utility::GetTime();
m_StatusTimer = Timer::Create();
m_StatusTimer->SetInterval(10);
m_StatusTimer->OnTimerExpired.connect([this](const Timer * const&) { StatusTimerHandler(); });
m_StatusTimer->Start();
}
WorkQueue::~WorkQueue()
{
m_StatusTimer->Stop(true);
Join(true);
}
void WorkQueue::SetName(const String& name)
{
m_Name = name;
}
String WorkQueue::GetName() const
{
return m_Name;
}
std::unique_lock<std::mutex> WorkQueue::AcquireLock()
{
return std::unique_lock<std::mutex>(m_Mutex);
}
/**
* Enqueues a task. Tasks are guaranteed to be executed in the order
* they were enqueued in except if there is more than one worker thread.
*/
void WorkQueue::EnqueueUnlocked(std::unique_lock<std::mutex>& lock, std::function<void ()>&& function, WorkQueuePriority priority)
{
if (!m_Spawned) {
Log(LogNotice, "WorkQueue")
<< "Spawning WorkQueue threads for '" << m_Name << "'";
for (int i = 0; i < m_ThreadCount; i++) {
m_Threads.create_thread([this]() { WorkerThreadProc(); });
}
m_Spawned = true;
}
bool wq_thread = IsWorkerThread();
if (!wq_thread) {
while (m_Tasks.size() >= m_MaxItems && m_MaxItems != 0)
m_CVFull.wait(lock);
}
m_Tasks.emplace(std::move(function), priority, ++m_NextTaskID);
m_CVEmpty.notify_one();
}
/**
* Enqueues a task. Tasks are guaranteed to be executed in the order
* they were enqueued in except if there is more than one worker thread or when
* allowInterleaved is true in which case the new task might be run
* immediately if it's being enqueued from within the WorkQueue thread.
*/
void WorkQueue::Enqueue(std::function<void ()>&& function, WorkQueuePriority priority,
bool allowInterleaved)
{
bool wq_thread = IsWorkerThread();
if (wq_thread && allowInterleaved) {
function();
return;
}
auto lock = AcquireLock();
EnqueueUnlocked(lock, std::move(function), priority);
}
/**
* Waits until all currently enqueued tasks have completed. This only works reliably
* when no other thread is enqueuing new tasks when this method is called.
*
* @param stop Whether to stop the worker threads
*/
void WorkQueue::Join(bool stop)
{
std::unique_lock<std::mutex> lock(m_Mutex);
while (m_Processing || !m_Tasks.empty())
m_CVStarved.wait(lock);
if (stop) {
m_Stopped = true;
m_CVEmpty.notify_all();
lock.unlock();
m_Threads.join_all();
m_Spawned = false;
Log(LogNotice, "WorkQueue")
<< "Stopped WorkQueue threads for '" << m_Name << "'";
}
}
/**
* Checks whether the calling thread is one of the worker threads
* for this work queue.
*
* @returns true if called from one of the worker threads, false otherwise
*/
bool WorkQueue::IsWorkerThread() const
{
WorkQueue **pwq = l_ThreadWorkQueue.get();
if (!pwq)
return false;
return *pwq == this;
}
void WorkQueue::SetExceptionCallback(const ExceptionCallback& callback)
{
m_ExceptionCallback = callback;
}
/**
* Checks whether any exceptions have occurred while executing tasks for this
* work queue. When a custom exception callback is set this method will always
* return false.
*/
bool WorkQueue::HasExceptions() const
{
std::unique_lock<std::mutex> lock(m_Mutex);
return !m_Exceptions.empty();
}
/**
* Returns all exceptions which have occurred for tasks in this work queue. When a
* custom exception callback is set this method will always return an empty list.
*/
std::vector<boost::exception_ptr> WorkQueue::GetExceptions() const
{
std::unique_lock<std::mutex> lock(m_Mutex);
return m_Exceptions;
}
void WorkQueue::ReportExceptions(const String& facility, bool verbose) const
{
std::vector<boost::exception_ptr> exceptions = GetExceptions();
for (const auto& eptr : exceptions) {
Log(LogCritical, facility)
<< DiagnosticInformation(eptr, verbose);
}
Log(LogCritical, facility)
<< exceptions.size() << " error" << (exceptions.size() != 1 ? "s" : "");
}
size_t WorkQueue::GetLength() const
{
std::unique_lock<std::mutex> lock(m_Mutex);
return m_Tasks.size();
}
void WorkQueue::StatusTimerHandler()
{
std::unique_lock<std::mutex> lock(m_Mutex);
ASSERT(!m_Name.IsEmpty());
size_t pending = m_Tasks.size();
double now = Utility::GetTime();
double gradient = (pending - m_PendingTasks) / (now - m_PendingTasksTimestamp);
double timeToZero = pending / gradient;
String timeInfo;
if (pending > GetTaskCount(5)) {
timeInfo = " empty in ";
if (timeToZero < 0 || std::isinf(timeToZero))
timeInfo += "infinite time, your task handler isn't able to keep up";
else
timeInfo += Utility::FormatDuration(timeToZero);
}
m_PendingTasks = pending;
m_PendingTasksTimestamp = now;
/* Log if there are pending items, or 5 minute timeout is reached. */
if (pending > 0 || m_StatusTimerTimeout < now) {
Log(m_StatsLogLevel, "WorkQueue")
<< "#" << m_ID << " (" << m_Name << ") "
<< "items: " << pending << ", "
<< "rate: " << std::setw(2) << GetTaskCount(60) / 60.0 << "/s "
<< "(" << GetTaskCount(60) << "/min " << GetTaskCount(60 * 5) << "/5min " << GetTaskCount(60 * 15) << "/15min);"
<< timeInfo;
}
/* Reschedule next log entry in 5 minutes. */
if (m_StatusTimerTimeout < now) {
m_StatusTimerTimeout = now + 60 * 5;
}
}
void WorkQueue::RunTaskFunction(const TaskFunction& func)
{
try {
func();
} catch (const std::exception&) {
boost::exception_ptr eptr = boost::current_exception();
{
std::unique_lock<std::mutex> mutex(m_Mutex);
if (!m_ExceptionCallback)
m_Exceptions.push_back(eptr);
}
if (m_ExceptionCallback)
m_ExceptionCallback(eptr);
}
}
void WorkQueue::WorkerThreadProc()
{
std::ostringstream idbuf;
idbuf << "WQ #" << m_ID;
Utility::SetThreadName(idbuf.str());
l_ThreadWorkQueue.reset(new WorkQueue *(this));
std::unique_lock<std::mutex> lock(m_Mutex);
for (;;) {
while (m_Tasks.empty() && !m_Stopped)
m_CVEmpty.wait(lock);
if (m_Stopped)
break;
if (m_Tasks.size() >= m_MaxItems && m_MaxItems != 0)
m_CVFull.notify_all();
Task task = m_Tasks.top();
m_Tasks.pop();
m_Processing++;
lock.unlock();
RunTaskFunction(task.Function);
/* clear the task so whatever other resources it holds are released _before_ we re-acquire the mutex */
task = Task();
IncreaseTaskCount();
lock.lock();
m_Processing--;
if (m_Tasks.empty())
m_CVStarved.notify_all();
}
}
void WorkQueue::IncreaseTaskCount()
{
m_TaskStats.InsertValue(Utility::GetTime(), 1);
}
size_t WorkQueue::GetTaskCount(RingBuffer::SizeType span)
{
return m_TaskStats.UpdateAndGetValues(Utility::GetTime(), span);
}
bool icinga::operator<(const Task& a, const Task& b)
{
if (a.Priority < b.Priority)
return true;
if (a.Priority == b.Priority) {
if (a.ID > b.ID)
return true;
else
return false;
}
return false;
}
|