Debian Codegraph @

runtime/wtp.c

raw
1 /* wtp.c
2 *
3 * This file implements the worker thread pool (wtp) class.
4 *
5 * File begun on 2008-01-20 by RGerhards
6 *
7 * There is some in-depth documentation available in doc/dev_queue.html
8 * (and in the web doc set on https://www.rsyslog.com/doc/). Be sure to read it
9 * if you are getting acquainted to the object.
10 *
11 * Copyright 2008-2026 Rainer Gerhards and Adiscon GmbH.
12 *
13 * This file is part of the rsyslog runtime library.
14 *
15 * The rsyslog runtime library is free software: you can redistribute it and/or modify
16 * it under the terms of the GNU Lesser General Public License as published by
17 * the Free Software Foundation, either version 3 of the License, or
18 * (at your option) any later version.
19 *
20 * The rsyslog runtime library is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU Lesser General Public License for more details.
24 *
25 * You should have received a copy of the GNU Lesser General Public License
26 * along with the rsyslog runtime library. If not, see <http://www.gnu.org/licenses/>.
27 *
28 * A copy of the GPL can be found in the file "COPYING" in this distribution.
29 * A copy of the LGPL can be found in the file "COPYING.LESSER" in this distribution.
30 */
31 #include "config.h"
32
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <assert.h>
37 #include <signal.h>
38 #include <pthread.h>
39 #include <fcntl.h>
40 #include <unistd.h>
41 #include <errno.h>
42 #include <atomic.h>
43 #ifdef HAVE_SYS_PRCTL_H
44 #include <sys/prctl.h>
45 #endif
46
47 #include "rsyslog.h"
48 #include "stringbuf.h"
49 #include "srUtils.h"
50 #include "wtp.h"
51 #include "wti.h"
52 #include "obj.h"
53 #include "unicode-helper.h"
54 #include "glbl.h"
55 #include "errmsg.h"
56
57 /* static data */
58 DEFobjStaticHelpers;
59 DEFobjCurrIf(glbl)
60
61 /* forward-definitions */
62
63 /* methods */
64
65 /* get the header for debug messages
66 * The caller must NOT free or otherwise modify the returned string!
67 */
68 static uchar *wtpGetDbgHdr(wtp_t *pThis) {
69 ISOBJ_TYPE_assert(pThis, wtp);
70
71 if (pThis->pszDbgHdr == NULL)
72 return (uchar *)"wtp"; /* should not normally happen */
73 else
74 return pThis->pszDbgHdr;
75 }
76
77
78 /* Not implemented dummy function for constructor */
79 static rsRetVal NotImplementedDummy_voidp_int(__attribute__((unused)) void *p1, __attribute__((unused)) int p2) {
80 return RS_RET_NOT_IMPLEMENTED;
81 }
82 static rsRetVal NotImplementedDummy_voidp_intp(__attribute__((unused)) void *p1, __attribute__((unused)) int *p2) {
83 return RS_RET_NOT_IMPLEMENTED;
84 }
85 static rsRetVal NotImplementedDummy_voidp_voidp(__attribute__((unused)) void *p1, __attribute__((unused)) void *p2) {
86 return RS_RET_NOT_IMPLEMENTED;
87 }
88 static rsRetVal NotImplementedDummy_voidp_wti_tp(__attribute__((unused)) void *p1, __attribute__((unused)) wti_t *p2) {
89 return RS_RET_NOT_IMPLEMENTED;
90 }
91 /* Standard-Constructor for the wtp object
92 */
93 BEGINobjConstruct(wtp) /* be sure to specify the object type also in END macro! */
94 pthread_mutex_init(&pThis->mutWtp, NULL);
95 pthread_cond_init(&pThis->condThrdInitDone, NULL);
96 pthread_cond_init(&pThis->condThrdTrm, NULL);
97 pthread_attr_init(&pThis->attrThrd);
98 /* Set thread scheduling policy to default */
99 #ifdef HAVE_PTHREAD_SETSCHEDPARAM
100 pthread_attr_setschedpolicy(&pThis->attrThrd, default_thr_sched_policy);
101 pthread_attr_setschedparam(&pThis->attrThrd, &default_sched_param);
102 pthread_attr_setinheritsched(&pThis->attrThrd, PTHREAD_EXPLICIT_SCHED);
103 #endif
104 /* set all function pointers to "not implemented" dummy so that we can safely call them */
105 pThis->pfChkStopWrkr = (rsRetVal(*)(void *, int))NotImplementedDummy_voidp_int;
106 pThis->pfGetDeqBatchSize = (rsRetVal(*)(void *, int *))NotImplementedDummy_voidp_intp;
107 pThis->pfDoWork = (rsRetVal(*)(void *, void *))NotImplementedDummy_voidp_voidp;
108 pThis->pfObjProcessed = (rsRetVal(*)(void *, wti_t *))NotImplementedDummy_voidp_wti_tp;
109 INIT_ATOMIC_HELPER_MUT(pThis->mutCurNumWrkThrd);
110 INIT_ATOMIC_HELPER_MUT(pThis->mutWtpState);
111 ENDobjConstruct(wtp)
112
113
114 /* Construction finalizer
115 * rgerhards, 2008-01-17
116 */
117 rsRetVal wtpConstructFinalize(wtp_t *pThis) {
118 DEFiRet;
119 int i;
120 uchar pszBuf[64];
121 size_t lenBuf;
122 wti_t *pWti;
123
124 ISOBJ_TYPE_assert(pThis, wtp);
125
126 DBGPRINTF("%s: finalizing construction of worker thread pool (numworkerThreads %d)\n", wtpGetDbgHdr(pThis),
127 pThis->iNumWorkerThreads);
128 /* alloc and construct workers - this can only be done in finalizer as we previously do
129 * not know the max number of workers
130 */
131 CHKmalloc(pThis->pWrkr = malloc(sizeof(wti_t *) * pThis->iNumWorkerThreads));
132
133 for (i = 0; i < pThis->iNumWorkerThreads; ++i) {
134 CHKiRet(wtiConstruct(&pThis->pWrkr[i]));
135 pWti = pThis->pWrkr[i];
136 lenBuf = snprintf((char *)pszBuf, sizeof(pszBuf), "%.*s/w%d",
137 (int)(sizeof(pszBuf) - 6), /* leave 6 chars for \0, "/w" and number: */
138 wtpGetDbgHdr(pThis), i);
139 if (lenBuf >= sizeof(pszBuf)) {
140 LogError(0, RS_RET_INTERNAL_ERROR,
141 "%s:%d debug header too long: %zd - in "
142 "thory this cannot happen - truncating",
143 __FILE__, __LINE__, lenBuf);
144 lenBuf = sizeof(pszBuf) - 1;
145 pszBuf[lenBuf] = '\0';
146 }
147 CHKiRet(wtiSetDbgHdr(pWti, pszBuf, lenBuf));
148 CHKiRet(wtiSetpWtp(pWti, pThis));
149 CHKiRet(wtiConstructFinalize(pWti));
150 }
151
152
153 finalize_it:
154 RETiRet;
155 }
156
157
158 /* Destructor */
159 BEGINobjDestruct(wtp) /* be sure to specify the object type also in END and CODESTART macros! */
160 int i;
161 CODESTARTobjDestruct(wtp);
162 d_pthread_mutex_lock(&pThis->mutWtp); /* make sure nobody is still using the mutex */
163 assert(pThis->iCurNumWrkThrd == 0);
164
165 /* destruct workers */
166 for (i = 0; i < pThis->iNumWorkerThreads; ++i) wtiDestruct(&pThis->pWrkr[i]);
167
168 free(pThis->pWrkr);
169 pThis->pWrkr = NULL;
170
171 /* actual destruction */
172 d_pthread_mutex_unlock(&pThis->mutWtp);
173 pthread_cond_destroy(&pThis->condThrdTrm);
174 pthread_cond_destroy(&pThis->condThrdInitDone);
175 pthread_mutex_destroy(&pThis->mutWtp);
176 pthread_attr_destroy(&pThis->attrThrd);
177 DESTROY_ATOMIC_HELPER_MUT(pThis->mutCurNumWrkThrd);
178 DESTROY_ATOMIC_HELPER_MUT(pThis->mutWtpState);
179
180 free(pThis->pszDbgHdr);
181 ENDobjDestruct(wtp)
182
183
184 /* Set worker thread pool state. -- rgerhards, 2008-01-21
185 *
186 * This function is called from multiple contexts:
187 * 1. During shutdown (wtpShutdownAll, queue destructor)
188 * 2. During persistence mode changes (queuePersist)
189 *
190 * IMPORTANT: Uses atomic store because worker threads read wtpState atomically
191 * in wtpChkStopWrkr(). Mixing plain stores with atomic loads violates the C11
192 * memory model and creates undefined behavior.
193 *
194 * The atomic store ensures:
195 * - Immediate visibility to all worker threads
196 * - SHUTDOWN_IMMEDIATE is seen without delay
197 * - Proper memory barriers on all architectures (including ARM)
198 *
199 * rgerhards, 2008-01-21
200 */
201 rsRetVal wtpSetState(wtp_t *pThis, wtpState_t iNewState) {
202 ISOBJ_TYPE_assert(pThis, wtp);
203 ATOMIC_STORE_INT((int *)&pThis->wtpState, &pThis->mutWtpState, iNewState);
204 return RS_RET_OK;
205 }
206
207 /* join terminated worker threads */
208 static void ATTR_NONNULL() wtpJoinTerminatedWrkr(wtp_t *const pThis) {
209 int i;
210 for (i = 0; i < pThis->iNumWorkerThreads; ++i) {
211 wtiJoinThrd(pThis->pWrkr[i]);
212 }
213 }
214
215
216 /* check if the worker shall shutdown (1 = yes, 0 = no)
217 * Note: there may be two mutexes locked, the bLockUsrMutex is the one in our "user"
218 * (e.g. the queue clas)
219 * rgerhards, 2008-01-21
220 */
221 rsRetVal wtpChkStopWrkr(wtp_t *pThis, int bLockUsrMutex) {
222 DEFiRet;
223 wtpState_t wtpState;
224
225 ISOBJ_TYPE_assert(pThis, wtp);
226 /* we need a consistent value, but it doesn't really matter if it is changed
227 * right after the fetch - then we simply do one more iteration in the worker
228 */
229 wtpState = (wtpState_t)ATOMIC_FETCH_32BIT((int *)&pThis->wtpState, &pThis->mutWtpState);
230
231 if (wtpState == wtpState_SHUTDOWN_IMMEDIATE) {
232 ABORT_FINALIZE(RS_RET_TERMINATE_NOW);
233 } else if (wtpState == wtpState_SHUTDOWN) {
234 ABORT_FINALIZE(RS_RET_TERMINATE_WHEN_IDLE);
235 }
236
237 /* try customer handler if one was set and we do not yet have a definite result */
238 if (pThis->pfChkStopWrkr != NULL) {
239 iRet = pThis->pfChkStopWrkr(pThis->pUsr, bLockUsrMutex);
240 }
241
242 finalize_it:
243 RETiRet;
244 }
245
246
247 PRAGMA_DIAGNOSTIC_PUSH
248 PRAGMA_IGNORE_Wempty_body
249 /* Send a shutdown command to all workers and see if they terminate.
250 * A timeout may be specified. This function may also be called with
251 * the current number of workers being 0, in which case it does not
252 * shut down any worker.
253 * rgerhards, 2008-01-14
254 */
255 rsRetVal
256 ATTR_NONNULL() wtpShutdownAll(wtp_t *pThis, wtpState_t tShutdownCmd, struct timespec *ptTimeout) {
257 DEFiRet;
258 int bTimedOut;
259 int i;
260
261 ISOBJ_TYPE_assert(pThis, wtp);
262
263 /* lock mutex to prevent races (may otherwise happen during idle processing and such...) */
264 d_pthread_mutex_lock(pThis->pmutUsr);
265 wtpSetState(pThis, tShutdownCmd);
266 /* awake workers in retry loop */
267 for (i = 0; i < pThis->iNumWorkerThreads; ++i) {
268 wtpJoinTerminatedWrkr(pThis);
269 pthread_cond_signal(&pThis->pWrkr[i]->pcondBusy);
270 wtiWakeupThrd(pThis->pWrkr[i]);
271 }
272 d_pthread_mutex_unlock(pThis->pmutUsr);
273
274 /* wait for worker thread termination */
275 d_pthread_mutex_lock(&pThis->mutWtp);
276 pthread_cleanup_push(mutexCancelCleanup, &pThis->mutWtp);
277 bTimedOut = 0;
278 /* Use atomic read for consistency - iCurNumWrkThrd is updated atomically by
279 * worker threads. Even though we hold mutWtp, workers update this counter
280 * atomically, so we must read it atomically to ensure we see the latest value.
281 */
282 while (ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd) > 0 && !bTimedOut) {
283 wtpJoinTerminatedWrkr(pThis);
284 DBGPRINTF("%s: waiting %ldms on worker thread termination, %d still running\n", wtpGetDbgHdr(pThis),
285 timeoutVal(ptTimeout), ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd));
286
287 if (d_pthread_cond_timedwait(&pThis->condThrdTrm, &pThis->mutWtp, ptTimeout) != 0) {
288 DBGPRINTF("%s: timeout waiting on worker thread termination\n", wtpGetDbgHdr(pThis));
289 bTimedOut = 1; /* we exit the loop on timeout */
290 }
291
292 /* awake workers in retry loop */
293 for (i = 0; i < pThis->iNumWorkerThreads; ++i) {
294 wtiWakeupThrd(pThis->pWrkr[i]);
295 }
296 }
297 pthread_cleanup_pop(1);
298
299 if (bTimedOut) iRet = RS_RET_TIMED_OUT;
300
301 RETiRet;
302 }
303 PRAGMA_DIAGNOSTIC_POP
304
305
306 /* Unconditionally cancel all running worker threads.
307 * rgerhards, 2008-01-14
308 */
309 rsRetVal ATTR_NONNULL() wtpCancelAll(wtp_t *pThis, const uchar *const cancelobj) {
310 DEFiRet;
311 int i;
312
313 ISOBJ_TYPE_assert(pThis, wtp);
314
315 /* go through all workers and cancel those that are active */
316 for (i = 0; i < pThis->iNumWorkerThreads; ++i) {
317 wtiCancelThrd(pThis->pWrkr[i], cancelobj);
318 }
319
320 RETiRet;
321 }
322
323
324 /* this function contains shared code for both regular worker shutdown as
325 * well as shutdown via cancellation. We can not simply use pthread_cleanup_pop(1)
326 * as this introduces a race in the debug system (RETiRet system).
327 * rgerhards, 2009-10-26
328 */
329 static void wtpWrkrExecCleanup(wti_t *pWti) {
330 wtp_t *pThis;
331
332 ISOBJ_TYPE_assert(pWti, wti);
333 pThis = pWti->pWtp;
334 ISOBJ_TYPE_assert(pThis, wtp);
335
336 // TESTBENCH bughunt - remove when done! 2018-11-05 rgerhards
337 if (dbgTimeoutToStderr) {
338 fprintf(stderr, "rsyslog debug: %s: enter WrkrExecCleanup\n", wtiGetDbgHdr(pWti));
339 }
340 /* the order of the next two statements is important! */
341 wtiSetState(pWti, WRKTHRD_WAIT_JOIN);
342 ATOMIC_DEC(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd);
343
344 /* note: numWorkersNow is only for message generation, so we do not try
345 * hard to get it 100% accurate (as curently done, it is not).
346 */
347 const int numWorkersNow = ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd);
348 DBGPRINTF("%s: Worker thread %lx, terminated, num workers now %d\n", wtpGetDbgHdr(pThis), (unsigned long)pWti,
349 numWorkersNow);
350 if (numWorkersNow > 0) {
351 // TODO: did the thread ID experiment (pthread_self) work out? rgerhards, 2024-07-25
352 LogMsg(0, RS_RET_OPERATION_STATUS, LOG_INFO,
353 "%s: worker thread %lx (%" PRIuPTR ") terminated, now %d active worker threads", wtpGetDbgHdr(pThis),
354 (unsigned long)pWti, (uintptr_t)pthread_self(), numWorkersNow);
355 }
356 }
357
358
359 /* cancellation cleanup handler for executing worker decrements the worker counter.
360 * rgerhards, 2009-07-20
361 */
362 static void wtpWrkrExecCancelCleanup(void *arg) {
363 wti_t *pWti = (wti_t *)arg;
364 wtp_t *pThis;
365
366 ISOBJ_TYPE_assert(pWti, wti);
367 pThis = pWti->pWtp;
368 ISOBJ_TYPE_assert(pThis, wtp);
369 DBGPRINTF("%s: Worker thread %lx requested to be cancelled.\n", wtpGetDbgHdr(pThis), (unsigned long)pWti);
370
371 wtpWrkrExecCleanup(pWti);
372
373 pthread_cond_broadcast(&pThis->condThrdTrm); /* activate anyone waiting on thread shutdown */
374 }
375
376
377 /* wtp worker shell. This is started and calls into the actual
378 * wti worker.
379 * rgerhards, 2008-01-21
380 */
381 PRAGMA_DIAGNOSTIC_PUSH
382 PRAGMA_IGNORE_Wempty_body static void *wtpWorker(
383 void *arg) /* the arg is actually a wti object, even though we are in wtp! */
384 {
385 wti_t *pWti = (wti_t *)arg;
386 wtp_t *pThis;
387 sigset_t sigSet;
388 #if defined(HAVE_PRCTL) && defined(PR_SET_NAME)
389 uchar *pszDbgHdr;
390 uchar thrdName[32] = "rs:";
391 #endif
392
393 ISOBJ_TYPE_assert(pWti, wti);
394 pThis = pWti->pWtp;
395 ISOBJ_TYPE_assert(pThis, wtp);
396
397 /* block all signals except SIGTTIN and SIGSEGV */
398 sigfillset(&sigSet);
399 sigdelset(&sigSet, SIGTTIN);
400 sigdelset(&sigSet, SIGSEGV);
401 pthread_sigmask(SIG_BLOCK, &sigSet, NULL);
402
403 /* Avoid a startup race: cancellation can be requested very early during
404 * shutdown. If that happens before our cleanup handler is registered,
405 * the thread can exit without transitioning state to WAIT_JOIN.
406 * Keep cancellation disabled until cleanup registration is complete.
407 */
408 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
409 pthread_cleanup_push(wtpWrkrExecCancelCleanup, pWti);
410
411 #if defined(HAVE_PRCTL) && defined(PR_SET_NAME)
412 /* set thread name - we ignore if the call fails, has no harsh consequences... */
413 pszDbgHdr = wtpGetDbgHdr(pThis);
414 ustrncpy(thrdName + 3, pszDbgHdr, 20);
415 if (prctl(PR_SET_NAME, thrdName, 0, 0, 0) != 0) {
416 DBGPRINTF("prctl failed, not setting thread name for '%s'\n", wtpGetDbgHdr(pThis));
417 }
418 dbgOutputTID((char *)thrdName);
419 #endif
420
421 // TESTBENCH bughunt - remove when done! 2018-11-05 rgerhards
422 if (dbgTimeoutToStderr) {
423 fprintf(stderr, "rsyslog debug: %s: worker %p started\n", wtpGetDbgHdr(pThis), pThis);
424 }
425 /* let the parent know we're done with initialization */
426 d_pthread_mutex_lock(&pThis->mutWtp);
427 /* Startup invariant: once a worker is visible as RUNNING, cancellation
428 * cleanup is already installed and will transition it to WAIT_JOIN.
429 */
430 wtiSetState(pWti, WRKTHRD_RUNNING);
431 pthread_cond_broadcast(&pThis->condThrdInitDone);
432 d_pthread_mutex_unlock(&pThis->mutWtp);
433
434 wtiWorker(pWti);
435 pthread_cleanup_pop(0);
436 d_pthread_mutex_lock(&pThis->mutWtp);
437 pthread_cleanup_push(mutexCancelCleanup, &pThis->mutWtp);
438 wtpWrkrExecCleanup(pWti);
439
440 pthread_cond_broadcast(&pThis->condThrdTrm); /* activate anyone waiting on thread shutdown */
441 pthread_cleanup_pop(1); /* unlock mutex */
442 if (dbgTimeoutToStderr) {
443 fprintf(stderr, "rsyslog debug: %p: worker exiting\n", pWti);
444 }
445 pthread_exit(0);
446 return NULL; /* To suppress warning */
447 }
448 PRAGMA_DIAGNOSTIC_POP
449
450 /* start a new worker */
451 static rsRetVal ATTR_NONNULL() wtpStartWrkr(wtp_t *const pThis, const int permit_during_shutdown) {
452 wti_t *pWti;
453 int i;
454 int iState;
455 DEFiRet;
456
457 ISOBJ_TYPE_assert(pThis, wtp);
458
459 // TESTBENCH bughunt - remove when done! 2018-11-05 rgerhards
460 if (dbgTimeoutToStderr) {
461 fprintf(stderr, "%s: worker start requested, num workers currently %d\n", wtpGetDbgHdr(pThis),
462 ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd));
463 }
464
465 d_pthread_mutex_lock(&pThis->mutWtp);
466
467 /* Check state under mutex to prevent TOCTOU race where worker could be
468 * created during shutdown. Must hold mutWtp to ensure state doesn't change
469 * between check and worker creation.
470 *
471 * Note: An atomic read is required as wtpState is protected by its own
472 * lock (mutWtpState). This lock on mutWtp ensures the check and
473 * subsequent worker creation are an atomic unit, fixing the TOCTOU race.
474 */
475 const wtpState_t wtpState = (wtpState_t)ATOMIC_FETCH_32BIT((int *)&pThis->wtpState, &pThis->mutWtpState);
476 if (wtpState != wtpState_RUNNING && !permit_during_shutdown) {
477 d_pthread_mutex_unlock(&pThis->mutWtp);
478 DBGPRINTF("%s: worker start requested during shutdown - ignored\n", wtpGetDbgHdr(pThis));
479 if (dbgTimeoutToStderr) {
480 fprintf(stderr, "rsyslog debug: %s: worker start requested during shutdown - ignored\n",
481 wtpGetDbgHdr(pThis));
482 }
483 return RS_RET_ERR; /* exceptional case, but really makes sense here! */
484 }
485
486 wtpJoinTerminatedWrkr(pThis);
487 /* find free spot in thread table. */
488 for (i = 0; i < pThis->iNumWorkerThreads; ++i) {
489 if (wtiCASState(pThis->pWrkr[i], WRKTHRD_STOPPED, WRKTHRD_INITIALIZING) == RS_RET_OK) {
490 break;
491 }
492 }
493
494 if (i == pThis->iNumWorkerThreads) ABORT_FINALIZE(RS_RET_NO_MORE_THREADS);
495
496 if (i == 0 || pThis->toWrkShutdown == -1) {
497 wtiSetAlwaysRunning(pThis->pWrkr[i]);
498 }
499
500 pWti = pThis->pWrkr[i];
501 iState = pthread_create(&(pWti->thrdID), &pThis->attrThrd, wtpWorker, (void *)pWti);
502 if (iState != 0) {
503 wtiSetState(pWti, WRKTHRD_STOPPED);
504 LogError(iState, RS_RET_ERR, "%s: pthread_create failed while starting a worker", wtpGetDbgHdr(pThis));
505 ABORT_FINALIZE(RS_RET_ERR);
506 }
507 ATOMIC_INC(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd); /* we got one more! */
508
509 // TESTBENCH bughunt - remove when done! 2018-11-05 rgerhards
510 if (dbgTimeoutToStderr) {
511 fprintf(stderr, "%s: wrkr start initiated with state %d, num workers now %d\n", wtpGetDbgHdr(pThis), iState,
512 ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd));
513 }
514 DBGPRINTF("%s: started with state %d, num workers now %d\n", wtpGetDbgHdr(pThis), iState,
515 ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd));
516
517 /* wait for the new thread to initialize its signal mask and
518 * cancellation cleanup handler before proceeding
519 */
520 do {
521 d_pthread_cond_wait(&pThis->condThrdInitDone, &pThis->mutWtp);
522 } while ((iState = wtiGetState(pWti)) == WRKTHRD_INITIALIZING);
523 DBGPRINTF("%s: new worker finished initialization with state %d, num workers now %d\n", wtpGetDbgHdr(pThis), iState,
524 ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd));
525 // TESTBENCH bughunt - remove when done! 2018-11-05 rgerhards
526 if (dbgTimeoutToStderr) {
527 fprintf(stderr, "rsyslog debug: %s: started with state %d, num workers now %d\n", wtpGetDbgHdr(pThis), iState,
528 ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd));
529 }
530
531 finalize_it:
532 d_pthread_mutex_unlock(&pThis->mutWtp);
533 RETiRet;
534 }
535
536
537 /* set the number of worker threads that should be running. If less than currently running,
538 * a new worker may be started. Please note that there is no guarantee the number of workers
539 * said will be running after we exit this function. It is just a hint. If the number is
540 * higher than one, and no worker is started, the "busy" condition is signaled to awake a worker.
541 * So the caller can assume that there is at least one worker re-checking if there is "work to do"
542 * after this function call.
543 * Parameter "permit_during_shutdown" if true, permits worker starts while the system is
544 * in shutdown state. The prime use case for this is persisting disk queues in enqueue only
545 * mode, which is activated during shutdown.
546 */
547 rsRetVal ATTR_NONNULL() wtpAdviseMaxWorkers(wtp_t *const pThis, int nMaxWrkr, const int permit_during_shutdown) {
548 DEFiRet;
549 int nMissing; /* number workers missing to run */
550 int i, nRunning;
551
552 ISOBJ_TYPE_assert(pThis, wtp);
553
554 if (nMaxWrkr == 0) FINALIZE;
555
556 if (nMaxWrkr > pThis->iNumWorkerThreads) /* limit to configured maximum */
557 nMaxWrkr = pThis->iNumWorkerThreads;
558
559 nMissing = nMaxWrkr - ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd);
560
561 if (nMissing > 0) {
562 if (ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd) > 0) {
563 LogMsg(0, RS_RET_OPERATION_STATUS, LOG_INFO,
564 "%s: high activity - starting %d additional worker thread(s), "
565 "currently %d active worker threads.",
566 wtpGetDbgHdr(pThis), nMissing, ATOMIC_FETCH_32BIT(&pThis->iCurNumWrkThrd, &pThis->mutCurNumWrkThrd));
567 }
568 /* start the rqtd nbr of workers */
569 for (i = 0; i < nMissing; ++i) {
570 CHKiRet(wtpStartWrkr(pThis, permit_during_shutdown));
571 }
572 } else {
573 /* we have needed number of workers, but they may be sleeping */
574 for (i = 0, nRunning = 0; i < pThis->iNumWorkerThreads && nRunning < nMaxWrkr; ++i) {
575 if (wtiGetState(pThis->pWrkr[i]) != WRKTHRD_STOPPED) {
576 pthread_cond_signal(&pThis->pWrkr[i]->pcondBusy);
577 nRunning++;
578 }
579 }
580 }
581
582
583 finalize_it:
584 RETiRet;
585 }
586
587
588 /* some simple object access methods
589 * Note: the semicolons behind the macros are actually empty declarations. This is
590 * a work-around for clang-format's missing understanding of generative macros.
591 * Some compilers may flag this empty declarations by a warning. If so, we need
592 * to disable this warning. Alternatively, we could exclude this code from being
593 * reformatted by clang-format;
594 */
595 DEFpropSetMeth(wtp, toWrkShutdown, long);
596 DEFpropSetMeth(wtp, wtpState, wtpState_t);
597 DEFpropSetMeth(wtp, iNumWorkerThreads, int);
598 DEFpropSetMeth(wtp, pUsr, void *);
599 DEFpropSetMethPTR(wtp, pmutUsr, pthread_mutex_t);
600 DEFpropSetMethFP(wtp, pfChkStopWrkr, rsRetVal (*pVal)(void *, int));
601 DEFpropSetMethFP(wtp, pfRateLimiter, rsRetVal (*pVal)(void *));
602 DEFpropSetMethFP(wtp, pfGetDeqBatchSize, rsRetVal (*pVal)(void *, int *));
603 DEFpropSetMethFP(wtp, pfDoWork, rsRetVal (*pVal)(void *, void *));
604 DEFpropSetMethFP(wtp, pfObjProcessed, rsRetVal (*pVal)(void *, wti_t *));
605
606
607 /* set the debug header message
608 * The passed-in string is duplicated. So if the caller does not need
609 * it any longer, it must free it. Must be called only before object is finalized.
610 * rgerhards, 2008-01-09
611 */
612 rsRetVal wtpSetDbgHdr(wtp_t *pThis, uchar *pszMsg, size_t lenMsg) {
613 DEFiRet;
614
615 ISOBJ_TYPE_assert(pThis, wtp);
616 assert(pszMsg != NULL);
617
618 if (lenMsg < 1) ABORT_FINALIZE(RS_RET_PARAM_ERROR);
619
620 if (pThis->pszDbgHdr != NULL) {
621 free(pThis->pszDbgHdr);
622 pThis->pszDbgHdr = NULL;
623 }
624
625 if ((pThis->pszDbgHdr = malloc(lenMsg + 1)) == NULL) ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
626
627 memcpy(pThis->pszDbgHdr, pszMsg, lenMsg + 1); /* always think about the \0! */
628
629 finalize_it:
630 RETiRet;
631 }
632
633 /* dummy */
634 static rsRetVal wtpQueryInterface(interface_t __attribute__((unused)) * i) {
635 return RS_RET_NOT_IMPLEMENTED;
636 }
637
638 /* exit our class
639 */
640 BEGINObjClassExit(wtp, OBJ_IS_CORE_MODULE) /* CHANGE class also in END MACRO! */
641 CODESTARTObjClassExit(wtp);
642 /* release objects we no longer need */
643 objRelease(glbl, CORE_COMPONENT);
644 ENDObjClassExit(wtp)
645
646
647 /* Initialize the stream class. Must be called as the very first method
648 * before anything else is called inside this class.
649 * rgerhards, 2008-01-09
650 */
651 BEGINObjClassInit(wtp, 1, OBJ_IS_CORE_MODULE)
652 /* request objects we use */
653 CHKiRet(objUse(glbl, CORE_COMPONENT));
654 ENDObjClassInit(wtp)