forked from rsyslog/rsyslog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
action.c
2406 lines (2149 loc) · 84.1 KB
/
action.c
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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* action.c
*
* Implementation of the action object.
*
* File begun on 2007-08-06 by RGerhards (extracted from syslogd.c)
*
* Some notes on processing (this hopefully makes it easier to find
* the right code in question): For performance reasons, this module
* uses different methods of message submission based on the user-selected
* configuration. This code is similar, but can not be abstracted because
* of the performance-affecting differences in it. As such, it is often
* necessary to triple-check that everything works well in *all* modes.
* The different modes (and calling sequence) are:
*
* if set iExecEveryNthOccur > 1 || iSecsExecOnceInterval
* - doSubmitToActionQComplex
* handles mark message reduction, but in essence calls
* - actionWriteToAction
* - doSubmitToActionQ
* (now queue engine processing)
* if(pThis->bWriteAllMarkMsgs == RSFALSE)
* - doSubmitToActionQNotAllMark
* - doSubmitToActionQ (and from here like in the else case below!)
* else
* - doSubmitToActionQ
* - qqueueEnqObj
* (now queue engine processing)
*
* Note that bWriteAllMakrMsgs on or off creates almost the same processing.
* The difference ist that if WriteAllMarkMsgs is not set, we need to
* preprocess the batch and drop mark messages which are not yet due for
* writing.
*
* After dequeue, processing is as follows:
* - processBatchMain
* - processMsgMain (direct entry for DIRECT queue!)
* - ...
*
* MORE ON PROCESSING, QUEUES and FILTERING
* All filtering needs to be done BEFORE messages are enqueued to an
* action. In previous code, part of the filtering was done at the
* "remote end" of the action queue, which lead to problems in
* non-direct mode (because then things run asynchronously). In order
* to solve this problem once and for all, I have changed the code so
* that all filtering is done before enq, and processing on the
* dequeue side of action processing now always executes whatever is
* enqueued. This is the only way to handle things consistently and
* (as much as possible) in a queue-type agnostic way. However, it is
* a rather radical change, which I unfortunately needed to make from
* stable version 5.8.1 to 5.8.2. If new problems pop up, you now know
* what may be their cause. In any case, the way it is done now is the
* only correct one.
* A problem is that, under fortunate conditions, we use the current
* batch for the output system as well. This is very good from a performance
* point of view, but makes the distinction between enq and deq side of
* the queue a bit hard. The current idea is that the filter condition
* alone is checked at the deq side of the queue (seems to be unavoidable
* to do it that way), but all other complex conditons (like failover
* handling) go into the computation of the filter condition. For
* non-direct queues, we still enqueue only what is acutally necessary.
* Note that in this case the rest of the code must ensure that the filter
* is set to "true". While this is not perfect and not as simple as
* we would like to see it, it looks like the best way to tackle that
* beast.
* rgerhards, 2011-06-15
*
* Copyright 2007-2022 Rainer Gerhards and Adiscon GmbH.
*
* This file is part of rsyslog.
*
* Rsyslog is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Rsyslog is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Rsyslog. If not, see <http://www.gnu.org/licenses/>.
*
* A copy of the GPL can be found in the file "COPYING" in this distribution.
*/
#include "config.h"
#include <stdio.h>
#include <assert.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <json.h>
#include "rsyslog.h"
#include "dirty.h"
#include "template.h"
#include "action.h"
#include "modules.h"
#include "cfsysline.h"
#include "srUtils.h"
#include "errmsg.h"
#include "batch.h"
#include "wti.h"
#include "rsconf.h"
#include "datetime.h"
#include "unicode-helper.h"
#include "atomic.h"
#include "ruleset.h"
#include "parserif.h"
#include "statsobj.h"
/* AIXPORT : cs renamed to legacy_cs as clashes with libpthreads variable in complete file*/
#ifdef _AIX
#define cs legacy_cs
#endif
PRAGMA_INGORE_Wswitch_enum
#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif
#define NO_TIME_PROVIDED 0 /* indicate we do not provide any cached time */
/* forward definitions */
static rsRetVal ATTR_NONNULL() processBatchMain(void *pVoid, batch_t *pBatch, wti_t * const pWti);
static rsRetVal doSubmitToActionQ(action_t * const pAction, wti_t * const pWti, smsg_t*);
static rsRetVal doSubmitToActionQComplex(action_t * const pAction, wti_t * const pWti, smsg_t*);
static rsRetVal doSubmitToActionQNotAllMark(action_t * const pAction, wti_t * const pWti, smsg_t*);
static void ATTR_NONNULL() actionSuspend(action_t * const pThis, wti_t * const pWti);
static void ATTR_NONNULL() actionRetry(action_t * const pThis, wti_t * const pWti);
/* object static data (once for all instances) */
DEFobjCurrIf(obj)
DEFobjCurrIf(datetime)
DEFobjCurrIf(module)
DEFobjCurrIf(statsobj)
DEFobjCurrIf(ruleset)
typedef struct configSettings_s {
int bActExecWhenPrevSusp; /* execute action only when previous one was suspended? */
int bActionWriteAllMarkMsgs; /* should all mark messages be unconditionally written? */
int iActExecOnceInterval; /* execute action once every nn seconds */
int iActExecEveryNthOccur; /* execute action every n-th occurrence (0,1=always) */
time_t iActExecEveryNthOccurTO; /* timeout for n-occurrence setting (in seconds, 0=never) */
int glbliActionResumeInterval;
int glbliActionResumeRetryCount; /* how often should suspended actions be retried? */
int bActionRepMsgHasMsg; /* last messsage repeated... has msg fragment in it */
uchar *pszActionName; /* short name for the action */
/* action queue and its configuration parameters */
queueType_t ActionQueType; /* type of the main message queue above */
int iActionQueueSize; /* size of the main message queue above */
int iActionQueueDeqBatchSize; /* batch size for action queues */
int iActionQHighWtrMark; /* high water mark for disk-assisted queues */
int iActionQLowWtrMark; /* low water mark for disk-assisted queues */
int iActionQDiscardMark; /* begin to discard messages */
int iActionQDiscardSeverity;
/* by default, discard nothing to prevent unintentional loss */
int iActionQueueNumWorkers; /* number of worker threads for the mm queue above */
uchar *pszActionQFName; /* prefix for the main message queue file */
int64 iActionQueMaxFileSize;
int iActionQPersistUpdCnt; /* persist queue info every n updates */
int bActionQSyncQeueFiles; /* sync queue files */
int iActionQtoQShutdown; /* queue shutdown */
int iActionQtoActShutdown; /* action shutdown (in phase 2) */
int iActionQtoEnq; /* timeout for queue enque */
int iActionQtoWrkShutdown; /* timeout for worker thread shutdown */
int iActionQWrkMinMsgs; /* minimum messages per worker needed to start a new one */
int bActionQSaveOnShutdown; /* save queue on shutdown (when DA enabled)? */
int64 iActionQueMaxDiskSpace; /* max disk space allocated 0 ==> unlimited */
int iActionQueueDeqSlowdown; /* dequeue slowdown (simple rate limiting) */
int iActionQueueDeqtWinFromHr; /* hour begin of time frame when queue is to be dequeued */
int iActionQueueDeqtWinToHr; /* hour begin of time frame when queue is to be dequeued */
} configSettings_t;
static configSettings_t cs; /* our current config settings */
/* tables for interfacing with the v6 config system */
static struct cnfparamdescr cnfparamdescr[] = {
{ "name", eCmdHdlrGetWord, 0 }, /* legacy: actionname */
{ "type", eCmdHdlrString, CNFPARAM_REQUIRED }, /* legacy: actionname */
{ "action.errorfile", eCmdHdlrString, 0 },
{ "action.errorfile.maxsize", eCmdHdlrInt, 0 },
{ "action.writeallmarkmessages", eCmdHdlrBinary, 0 }, /* legacy: actionwriteallmarkmessages */
{ "action.execonlyeverynthtime", eCmdHdlrInt, 0 }, /* legacy: actionexeconlyeverynthtime */
{ "action.execonlyeverynthtimetimeout", eCmdHdlrInt, 0 }, /* legacy: actionexeconlyeverynthtimetimeout */
{ "action.execonlyonceeveryinterval", eCmdHdlrInt, 0 }, /* legacy: actionexeconlyonceeveryinterval */
{ "action.execonlywhenpreviousissuspended", eCmdHdlrBinary, 0 },
/* legacy: actionexeconlywhenpreviousissuspended */
{ "action.repeatedmsgcontainsoriginalmsg", eCmdHdlrBinary, 0 }, /* legacy: repeatedmsgcontainsoriginalmsg */
{ "action.resumeretrycount", eCmdHdlrInt, 0 }, /* legacy: actionresumeretrycount */
{ "action.reportsuspension", eCmdHdlrBinary, 0 },
{ "action.reportsuspensioncontinuation", eCmdHdlrBinary, 0 },
{ "action.resumeintervalmax", eCmdHdlrPositiveInt, 0 },
{ "action.resumeinterval", eCmdHdlrInt, 0 },
{ "action.externalstate.file", eCmdHdlrString, 0 },
{ "action.copymsg", eCmdHdlrBinary, 0 }
};
static struct cnfparamblk pblk =
{ CNFPARAMBLK_VERSION,
sizeof(cnfparamdescr)/sizeof(struct cnfparamdescr),
cnfparamdescr
};
/* primarily a helper for debug purposes, get human-readble name of state */
/* currently not needed, but may be useful in the future! */
#if 0
static const char *
batchState2String(const batch_state_t state)
{
switch(state) {
case BATCH_STATE_RDY:
return "BATCH_STATE_RDY";
case BATCH_STATE_BAD:
return "BATCH_STATE_BAD";
case BATCH_STATE_SUB:
return "BATCH_STATE_SUB";
case BATCH_STATE_COMM:
return "BATCH_STATE_COMM";
case BATCH_STATE_DISC:
return "BATCH_STATE_DISC";
default:
return "ERROR, batch state not known!";
}
}
#endif // #if 0
/* ------------------------------ methods ------------------------------ */
/* This function returns the "current" time for this action. Current time
* is not necessarily real-time. In order to enhance performance, current
* system time is obtained the first time an action needs to know the time
* and then kept cached inside the action structure. Later requests will
* always return that very same time. Wile not totally accurate, it is far
* accurate in most cases and considered "acurate enough" for all cases.
* When changing the threading model, please keep in mind that this
* logic needs to be changed should we once allow more than one parallel
* call into the same action (object). As this is currently not supported,
* we simply cache the time inside the action object itself, after it
* is under mutex protection.
* Side-note: the value -1 is used as tActNow, because it also is the
* error return value of time(). So we would do a retry with the next
* invocation if time() failed. Then, of course, we would probably already
* be in trouble, but for the sake of performance we accept this very,
* very slight risk.
* This logic has been added as part of an overall performance improvment
* effort inspired by David Lang. -- rgerhards, 2008-09-16
* Note: this function does not use the usual iRet call conventions
* because that would provide little to no benefit but complicate things
* a lot. So we simply return the system time.
*/
static time_t
getActNow(action_t * const pThis)
{
assert(pThis != NULL);
if(pThis->tActNow == -1) {
pThis->tActNow = datetime.GetTime(NULL); /* good time call - the only one done */
if(pThis->tLastExec > pThis->tActNow) {
/* if we are traveling back in time, reset tLastExec */
pThis->tLastExec = (time_t) 0;
}
}
return pThis->tActNow;
}
/* resets action queue parameters to their default values. This happens
* after each action has been created in order to prevent any wild defaults
* to be used. It is somewhat against the original spirit of the config file
* reader, but I think it is a good thing to do.
* rgerhards, 2008-01-29
*/
static rsRetVal
actionResetQueueParams(void)
{
DEFiRet;
cs.ActionQueType = QUEUETYPE_DIRECT; /* type of the main message queue above */
cs.iActionQueueSize = 1000; /* size of the main message queue above */
cs.iActionQueueDeqBatchSize = 16; /* default batch size */
cs.iActionQHighWtrMark = -1; /* high water mark for disk-assisted queues */
cs.iActionQLowWtrMark = -1; /* low water mark for disk-assisted queues */
cs.iActionQDiscardMark = 980; /* begin to discard messages */
cs.iActionQDiscardSeverity = 8; /* discard warning and above */
cs.iActionQueueNumWorkers = 1; /* number of worker threads for the mm queue above */
cs.iActionQueMaxFileSize = 1024*1024;
cs.iActionQPersistUpdCnt = 0; /* persist queue info every n updates */
cs.bActionQSyncQeueFiles = 0;
cs.iActionQtoQShutdown = 0; /* queue shutdown */
cs.iActionQtoActShutdown = 1000; /* action shutdown (in phase 2) */
cs.iActionQtoEnq = 50; /* timeout for queue enque */
cs.iActionQtoWrkShutdown = 60000; /* timeout for worker thread shutdown */
cs.iActionQWrkMinMsgs = -1; /* minimum messages per worker needed to start a new one */
cs.bActionQSaveOnShutdown = 1; /* save queue on shutdown (when DA enabled)? */
cs.iActionQueMaxDiskSpace = 0;
cs.iActionQueueDeqSlowdown = 0;
cs.iActionQueueDeqtWinFromHr = 0;
cs.iActionQueueDeqtWinToHr = 25; /* 25 disables time windowed dequeuing */
cs.glbliActionResumeRetryCount = 0; /* I guess it is smart to reset this one, too */
free(cs.pszActionQFName);
cs.pszActionQFName = NULL; /* prefix for the main message queue file */
RETiRet;
}
/* free action worker data table
*/
static void freeWrkrDataTable(action_t * const pThis)
{
int freeSpot;
for(freeSpot = 0; freeSpot < pThis->wrkrDataTableSize; ++freeSpot) {
if(pThis->wrkrDataTable[freeSpot] != NULL) {
pThis->pMod->mod.om.freeWrkrInstance(pThis->wrkrDataTable[freeSpot]);
pThis->wrkrDataTable[freeSpot] = NULL;
}
}
free(pThis->wrkrDataTable);
return;
}
/* destructs an action descriptor object
* rgerhards, 2007-08-01
*/
rsRetVal actionDestruct(action_t * const pThis)
{
DEFiRet;
assert(pThis != NULL);
if(!strcmp((char*)modGetName(pThis->pMod), "builtin:omdiscard")) {
/* discard actions will be optimized out */
FINALIZE;
}
if(pThis->pQueue != NULL) {
qqueueDestruct(&pThis->pQueue);
}
/* destroy stats object, if we have one (may not always be
* be the case, e.g. if turned off)
*/
if(pThis->statsobj != NULL)
statsobj.Destruct(&pThis->statsobj);
if(pThis->pModData != NULL)
pThis->pMod->freeInstance(pThis->pModData);
if(pThis->fdErrFile != -1)
close(pThis->fdErrFile);
pthread_mutex_destroy(&pThis->mutErrFile);
pthread_mutex_destroy(&pThis->mutAction);
pthread_mutex_destroy(&pThis->mutWrkrDataTable);
free((void*)pThis->pszErrFile);
free((void*)pThis->pszExternalStateFile);
free(pThis->pszName);
free(pThis->ppTpl);
free(pThis->peParamPassing);
freeWrkrDataTable(pThis);
finalize_it:
free(pThis);
RETiRet;
}
/* Disable action, this means it will never again be usable
* until rsyslog is reloaded. Use only as a last resort, but
* depends on output module.
* rgerhards, 2007-08-02
*/
static inline void
actionDisable(action_t *__restrict__ const pThis)
{
pThis->bDisabled = 1;
}
/* create a new action descriptor object
* rgerhards, 2007-08-01
* Note that it is vital to set proper initial values as the v6 config
* system depends on these!
*/
rsRetVal actionConstruct(action_t **ppThis)
{
DEFiRet;
action_t *pThis;
assert(ppThis != NULL);
CHKmalloc(pThis = (action_t*) calloc(1, sizeof(action_t)));
pThis->iResumeInterval = 30;
pThis->iResumeIntervalMax = 1800; /* max interval default is half an hour */
pThis->iResumeRetryCount = 0;
pThis->pszName = NULL;
pThis->pszErrFile = NULL;
pThis->maxErrFileSize = 0;
pThis->currentErrFileSize = 0;
pThis->pszExternalStateFile = NULL;
pThis->fdErrFile = -1;
pThis->bWriteAllMarkMsgs = 1;
pThis->iExecEveryNthOccur = 0;
pThis->iExecEveryNthOccurTO = 0;
pThis->iSecsExecOnceInterval = 0;
pThis->bExecWhenPrevSusp = 0;
pThis->bRepMsgHasMsg = 0;
pThis->bDisabled = 0;
pThis->isTransactional = 0;
pThis->bReportSuspension = -1; /* indicate "not yet set" */
pThis->bReportSuspensionCont = -1; /* indicate "not yet set" */
pThis->bCopyMsg = 0;
pThis->tLastOccur = datetime.GetTime(NULL); /* done once per action on startup only */
pThis->iActionNbr = loadConf->actions.iActionNbr;
pthread_mutex_init(&pThis->mutErrFile, NULL);
pthread_mutex_init(&pThis->mutAction, NULL);
pthread_mutex_init(&pThis->mutWrkrDataTable, NULL);
INIT_ATOMIC_HELPER_MUT(pThis->mutCAS);
/* indicate we have a new action */
loadConf->actions.iActionNbr++;
finalize_it:
*ppThis = pThis;
RETiRet;
}
/* action construction finalizer
*/
rsRetVal
actionConstructFinalize(action_t *__restrict__ const pThis, struct nvlst *lst)
{
DEFiRet;
uchar pszAName[64]; /* friendly name of our action */
if(!strcmp((char*)modGetName(pThis->pMod), "builtin:omdiscard")) {
/* discard actions will be optimized out */
FINALIZE;
}
/* generate a friendly name for us action stats */
if(pThis->pszName == NULL) {
snprintf((char*) pszAName, sizeof(pszAName), "action-%d-%s",
pThis->iActionNbr, pThis->pMod->pszName);
pThis->pszName = ustrdup(pszAName);
}
/* cache transactional attribute */
pThis->isTransactional = pThis->pMod->mod.om.supportsTX;
if(pThis->isTransactional) {
int i;
for(i = 0 ; i < pThis->iNumTpls ; ++i) {
if(pThis->peParamPassing[i] != ACT_STRING_PASSING) {
LogError(0, RS_RET_INVLD_OMOD, "action '%s'(%d) is transactional but "
"parameter %d "
"uses invalid parameter passing mode -- disabling "
"action. This is probably caused by a pre-v7 "
"output module that needs upgrade.",
pThis->pszName, pThis->iActionNbr, i);
actionDisable(pThis);
ABORT_FINALIZE(RS_RET_INVLD_OMOD);
}
}
}
/* support statistics gathering */
CHKiRet(statsobj.Construct(&pThis->statsobj));
CHKiRet(statsobj.SetName(pThis->statsobj, pThis->pszName));
CHKiRet(statsobj.SetOrigin(pThis->statsobj, (uchar*)"core.action"));
STATSCOUNTER_INIT(pThis->ctrProcessed, pThis->mutCtrProcessed);
CHKiRet(statsobj.AddCounter(pThis->statsobj, UCHAR_CONSTANT("processed"),
ctrType_IntCtr, CTR_FLAG_RESETTABLE, &pThis->ctrProcessed));
STATSCOUNTER_INIT(pThis->ctrFail, pThis->mutCtrFail);
CHKiRet(statsobj.AddCounter(pThis->statsobj, UCHAR_CONSTANT("failed"),
ctrType_IntCtr, CTR_FLAG_RESETTABLE, &pThis->ctrFail));
STATSCOUNTER_INIT(pThis->ctrSuspend, pThis->mutCtrSuspend);
CHKiRet(statsobj.AddCounter(pThis->statsobj, UCHAR_CONSTANT("suspended"),
ctrType_IntCtr, CTR_FLAG_RESETTABLE, &pThis->ctrSuspend));
STATSCOUNTER_INIT(pThis->ctrSuspendDuration, pThis->mutCtrSuspendDuration);
CHKiRet(statsobj.AddCounter(pThis->statsobj, UCHAR_CONSTANT("suspended.duration"),
ctrType_IntCtr, 0, &pThis->ctrSuspendDuration));
STATSCOUNTER_INIT(pThis->ctrResume, pThis->mutCtrResume);
CHKiRet(statsobj.AddCounter(pThis->statsobj, UCHAR_CONSTANT("resumed"),
ctrType_IntCtr, CTR_FLAG_RESETTABLE, &pThis->ctrResume));
CHKiRet(statsobj.ConstructFinalize(pThis->statsobj));
/* create our queue */
/* generate a friendly name for the queue */
snprintf((char*) pszAName, sizeof(pszAName), "%s queue",
pThis->pszName);
/* now check if we can run the action in "firehose mode" during stage one of
* its processing (that is before messages are enqueued into the action q).
* This is only possible if some features, which require strict sequence, are
* not used. Thankfully, that is usually the case. The benefit of firehose
* mode is much faster processing (and simpler code) -- rgerhards, 2010-06-08
*/
if( pThis->iExecEveryNthOccur > 1
|| pThis->iSecsExecOnceInterval
) {
DBGPRINTF("info: firehose mode disabled for action because "
"iExecEveryNthOccur=%d, iSecsExecOnceInterval=%d\n",
pThis->iExecEveryNthOccur, pThis->iSecsExecOnceInterval);
pThis->submitToActQ = doSubmitToActionQComplex;
} else if(pThis->bWriteAllMarkMsgs) {
/* full firehose submission mode, default case*/
pThis->submitToActQ = doSubmitToActionQ;
} else {
/* nearly full-speed submission mode */
pThis->submitToActQ = doSubmitToActionQNotAllMark;
}
/* create queue */
/* action queues always (for now) have just one worker. This may change when
* we begin to implement an interface the enable output modules to request
* to be run on multiple threads. So far, this is forbidden by the interface
* spec. -- rgerhards, 2008-01-30
*/
CHKiRet(qqueueConstruct(&pThis->pQueue, cs.ActionQueType, 1, cs.iActionQueueSize,
processBatchMain));
obj.SetName((obj_t*) pThis->pQueue, pszAName);
qqueueSetpAction(pThis->pQueue, pThis);
if(lst == NULL) { /* use legacy params? */
/* ... set some properties ... */
# define setQPROP(func, directive, data) \
CHKiRet_Hdlr(func(pThis->pQueue, data)) { \
LogError(0, NO_ERRCODE, "Invalid " #directive ", \
error %d. Ignored, running with default setting", iRet); \
}
# define setQPROPstr(func, directive, data) \
CHKiRet_Hdlr(func(pThis->pQueue, data, (data == NULL)? 0 : strlen((char*) data))) { \
LogError(0, NO_ERRCODE, "Invalid " #directive ", \
error %d. Ignored, running with default setting", iRet); \
}
setQPROP(qqueueSetsizeOnDiskMax, "$ActionQueueMaxDiskSpace", cs.iActionQueMaxDiskSpace);
setQPROP(qqueueSetiDeqBatchSize, "$ActionQueueDequeueBatchSize", cs.iActionQueueDeqBatchSize);
setQPROP(qqueueSetMaxFileSize, "$ActionQueueFileSize", cs.iActionQueMaxFileSize);
setQPROPstr(qqueueSetFilePrefix, "$ActionQueueFileName", cs.pszActionQFName);
setQPROP(qqueueSetiPersistUpdCnt, "$ActionQueueCheckpointInterval", cs.iActionQPersistUpdCnt);
setQPROP(qqueueSetbSyncQueueFiles, "$ActionQueueSyncQueueFiles", cs.bActionQSyncQeueFiles);
setQPROP(qqueueSettoQShutdown, "$ActionQueueTimeoutShutdown", cs.iActionQtoQShutdown );
setQPROP(qqueueSettoActShutdown, "$ActionQueueTimeoutActionCompletion", cs.iActionQtoActShutdown);
setQPROP(qqueueSettoWrkShutdown, "$ActionQueueWorkerTimeoutThreadShutdown", cs.iActionQtoWrkShutdown);
setQPROP(qqueueSettoEnq, "$ActionQueueTimeoutEnqueue", cs.iActionQtoEnq);
setQPROP(qqueueSetiHighWtrMrk, "$ActionQueueHighWaterMark", cs.iActionQHighWtrMark);
setQPROP(qqueueSetiLowWtrMrk, "$ActionQueueLowWaterMark", cs.iActionQLowWtrMark);
setQPROP(qqueueSetiDiscardMrk, "$ActionQueueDiscardMark", cs.iActionQDiscardMark);
setQPROP(qqueueSetiDiscardSeverity, "$ActionQueueDiscardSeverity", cs.iActionQDiscardSeverity);
setQPROP(qqueueSetiMinMsgsPerWrkr, "$ActionQueueWorkerThreadMinimumMessages", cs.iActionQWrkMinMsgs);
setQPROP(qqueueSetiNumWorkerThreads, "$ActionQueueWorkerThreads", cs.iActionQueueNumWorkers);
setQPROP(qqueueSetbSaveOnShutdown, "$ActionQueueSaveOnShutdown", cs.bActionQSaveOnShutdown);
setQPROP(qqueueSetiDeqSlowdown, "$ActionQueueDequeueSlowdown", cs.iActionQueueDeqSlowdown);
setQPROP(qqueueSetiDeqtWinFromHr, "$ActionQueueDequeueTimeBegin", cs.iActionQueueDeqtWinFromHr);
setQPROP(qqueueSetiDeqtWinToHr, "$ActionQueueDequeueTimeEnd", cs.iActionQueueDeqtWinToHr);
} else {
/* we have v6-style config params */
qqueueSetDefaultsActionQueue(pThis->pQueue);
qqueueApplyCnfParam(pThis->pQueue, lst);
}
qqueueCorrectParams(pThis->pQueue);
# undef setQPROP
# undef setQPROPstr
qqueueDbgPrint(pThis->pQueue);
DBGPRINTF("Action %p: queue %p created\n", pThis, pThis->pQueue);
if(pThis->bUsesMsgPassingMode && pThis->pQueue->qType != QUEUETYPE_DIRECT) {
parser_warnmsg("module %s with message passing mode uses "
"non-direct queue. This most probably leads to undesired "
"results. For message modificaton modules (mm*), this means "
"that they will have no effect - "
"see https://www.rsyslog.com/mm-no-queue/", (char*)modGetName(pThis->pMod));
}
/* and now reset the queue params (see comment in its function header!) */
actionResetQueueParams();
finalize_it:
RETiRet;
}
/* set the global resume interval
*/
rsRetVal actionSetGlobalResumeInterval(int iNewVal)
{
cs.glbliActionResumeInterval = iNewVal;
return RS_RET_OK;
}
/* returns the action state name in human-readable form
* returned string must not be modified.
* rgerhards, 2009-05-07
*/
static uchar *getActStateName(action_t * const pThis, wti_t * const pWti)
{
switch(getActionState(pWti, pThis)) {
case ACT_STATE_RDY:
return (uchar*) "rdy";
case ACT_STATE_ITX:
return (uchar*) "itx";
case ACT_STATE_RTRY:
return (uchar*) "rtry";
case ACT_STATE_SUSP:
return (uchar*) "susp";
case ACT_STATE_DATAFAIL:
return (uchar*) "datafail";
default:
return (uchar*) "ERROR/UNKNWON";
}
}
/* returns a suitable return code based on action state
* rgerhards, 2009-05-07
*/
static rsRetVal getReturnCode(action_t * const pThis, wti_t * const pWti)
{
DEFiRet;
switch(getActionState(pWti, pThis)) {
case ACT_STATE_RDY:
iRet = RS_RET_OK;
break;
case ACT_STATE_ITX:
if(pWti->actWrkrInfo[pThis->iActionNbr].bHadAutoCommit) {
pWti->actWrkrInfo[pThis->iActionNbr].bHadAutoCommit = 0; /* auto-reset */
iRet = RS_RET_PREVIOUS_COMMITTED;
} else {
iRet = RS_RET_DEFER_COMMIT;
}
break;
case ACT_STATE_RTRY:
iRet = RS_RET_SUSPENDED;
break;
case ACT_STATE_SUSP:
iRet = RS_RET_ACTION_FAILED;
break;
case ACT_STATE_DATAFAIL:
iRet = RS_RET_DATAFAIL;
break;
default:
DBGPRINTF("Invalid action engine state %u, program error\n",
getActionState(pWti, pThis));
iRet = RS_RET_ERR;
break;
}
RETiRet;
}
/* set the action to a new state
* rgerhards, 2007-08-02
*/
static void
actionSetState(action_t * const pThis, wti_t * const pWti, uint8_t newState)
{
setActionState(pWti, pThis, newState);
DBGPRINTF("action[%s] transitioned to state: %s\n",
pThis->pszName, getActStateName(pThis, pWti));
}
/* Handles the transient commit state. So far, this is
* mostly a dummy...
* rgerhards, 2007-08-02
*/
static void actionCommitted(action_t * const pThis, wti_t * const pWti)
{
actionSetState(pThis, pWti, ACT_STATE_RDY);
}
/* set action state according to external state file (if configured)
*/
static rsRetVal ATTR_NONNULL()
checkExternalStateFile(action_t *const pThis, wti_t *const pWti)
{
char filebuf[1024];
int fd = -1;
int r;
DEFiRet;
DBGPRINTF("checking external state file\n");
if(pThis->pszExternalStateFile == NULL) {
FINALIZE;
}
fd = open(pThis->pszExternalStateFile, O_RDONLY|O_CLOEXEC);
if(fd == -1) {
dbgprintf("could not read external state file\n");
FINALIZE;
}
r = read(fd, filebuf, sizeof(filebuf) - 1);
if(r < 1) {
dbgprintf("checkExternalStateFile read() returned %d\n", r);
FINALIZE;
}
filebuf[r] = '\0';
dbgprintf("external state file content: '%s'\n", filebuf);
/* trim trailing whitespace */
for(int j = r-1 ; j > 0 ; --j) {
if(filebuf[j] == '\n' || filebuf[j] == '\t' || filebuf[j] == ' ') {
filebuf[j] = '\0';
} else {
break;
}
}
if(!strcmp(filebuf, "SUSPENDED")) {
LogMsg(0, RS_RET_SUSPENDED, LOG_WARNING,
"action '%s' suspended (module '%s') by external state file",
pThis->pszName, pThis->pMod->pszName);
actionRetry(pThis, pWti);
ABORT_FINALIZE(RS_RET_SUSPENDED);
}
finalize_it:
if(fd != -1) {
close(fd);
}
DBGPRINTF("done checking external state file, iRet=%d\n", iRet);
RETiRet;
}
/* we need to defer setting the action's own bReportSuspension state until
* after the full config has been processed. So the most simple case to do
* that is here. It's not a performance problem, as it happens infrequently.
* it's not a threading race problem, as always the same value will be written.
* As we need to do this in several places, we have moved the code to its own
* helper function.
*/
static void
setSuspendMessageConfVars(action_t *__restrict__ const pThis)
{
if(pThis->bReportSuspension == -1)
pThis->bReportSuspension = runConf->globals.bActionReportSuspension;
if(pThis->bReportSuspensionCont == -1) {
pThis->bReportSuspensionCont = runConf->globals.bActionReportSuspensionCont;
if(pThis->bReportSuspensionCont == -1)
pThis->bReportSuspensionCont = 1;
}
}
/* set action to "rtry" state.
* rgerhards, 2007-08-02
*/
static void ATTR_NONNULL() actionRetry(action_t * const pThis, wti_t * const pWti)
{
setSuspendMessageConfVars(pThis);
actionSetState(pThis, pWti, ACT_STATE_RTRY);
if(pThis->bReportSuspension) {
LogMsg(0, RS_RET_SUSPENDED, LOG_WARNING,
"action '%s' suspended (module '%s'), retry %d. There should "
"be messages before this one giving the reason for suspension.",
pThis->pszName, pThis->pMod->pszName,
getActionNbrResRtry(pWti, pThis));
}
incActionResumeInRow(pWti, pThis);
}
/* Suspend action, this involves changing the action state as well
* as setting the next retry time.
* if we have more than 10 retries, we prolong the
* retry interval. If something is really stalled, it will
* get re-tried only very, very seldom - but that saves
* CPU time. TODO: maybe a config option for that?
* rgerhards, 2007-08-02
*/
static void ATTR_NONNULL()
actionSuspend(action_t * const pThis, wti_t * const pWti)
{
time_t ttNow;
int suspendDuration;
char timebuf[32];
DBGPRINTF("actionSuspend: enter\n");
setSuspendMessageConfVars(pThis);
/* note: we can NOT use a cached timestamp, as time may have evolved
* since caching, and this would break logic (and it actually did so!)
*/
datetime.GetTime(&ttNow);
suspendDuration = pThis->iResumeInterval * (getActionNbrResRtry(pWti, pThis) / 10 + 1);
if(pThis->iResumeIntervalMax > 0 && suspendDuration > pThis->iResumeIntervalMax) {
suspendDuration = pThis->iResumeIntervalMax;
}
pThis->ttResumeRtry = ttNow + suspendDuration;
actionSetState(pThis, pWti, ACT_STATE_SUSP);
pThis->ctrSuspendDuration += suspendDuration;
if(getActionNbrResRtry(pWti, pThis) == 0) {
STATSCOUNTER_INC(pThis->ctrSuspend, pThis->mutCtrSuspend);
}
if( pThis->bReportSuspensionCont
|| (pThis->bReportSuspension && getActionNbrResRtry(pWti, pThis) == 0) ) {
ctime_r(&pThis->ttResumeRtry, timebuf);
timebuf[strlen(timebuf)-1] = '\0'; /* strip LF */
LogMsg(0, RS_RET_SUSPENDED, LOG_WARNING,
"action '%s' suspended (module '%s'), next retry is %s, retry nbr %d. "
"There should be messages before this one giving the reason for suspension.",
pThis->pszName, pThis->pMod->pszName, timebuf,
getActionNbrResRtry(pWti, pThis));
}
DBGPRINTF("action '%s' suspended, earliest retry=%lld (now %lld), iNbrResRtry %d, "
"duration %d\n",
pThis->pszName, (long long) pThis->ttResumeRtry, (long long) ttNow,
getActionNbrResRtry(pWti, pThis), suspendDuration);
}
/* actually do retry processing. Note that the function receives a timestamp so
* that we do not need to call the (expensive) time() API.
* Note that we do the full retry processing here, doing the configured number of
* iterations. -- rgerhards, 2009-05-07
* We need to guard against module which always return RS_RET_OK from their tryResume()
* entry point. This is invalid, but has harsh consequences: it will cause the rsyslog
* engine to go into a tight loop. That obviously is not acceptable. As such, we track the
* count of iterations that a tryResume returning RS_RET_OK is immediately followed by
* an unsuccessful call to doAction(). If that happens more than 10 times, we assume
* the return acutally is a RS_RET_SUSPENDED. In order to go through the various
* resumption stages, we do this for every 10 requests. This magic number 10 may
* not be the most appropriate, but it should be thought of a "if nothing else helps"
* kind of facility: in the first place, the module should return a proper indication
* of its inability to recover. -- rgerhards, 2010-04-26.
*/
static rsRetVal ATTR_NONNULL()
actionDoRetry(action_t * const pThis, wti_t * const pWti)
{
int iRetries;
int iSleepPeriod;
int bTreatOKasSusp;
DEFiRet;
assert(pThis != NULL);
iRetries = 0;
while((*pWti->pbShutdownImmediate == 0) && getActionState(pWti, pThis) == ACT_STATE_RTRY) {
DBGPRINTF("actionDoRetry: %s enter loop, iRetries=%d, ResumeInRow %d\n",
pThis->pszName, iRetries, getActionResumeInRow(pWti, pThis));
iRet = pThis->pMod->tryResume(pWti->actWrkrInfo[pThis->iActionNbr].actWrkrData);
DBGPRINTF("actionDoRetry: %s action->tryResume returned %d\n", pThis->pszName, iRet);
if((getActionResumeInRow(pWti, pThis) > 9) && (getActionResumeInRow(pWti, pThis) % 10 == 0)) {
bTreatOKasSusp = 1;
setActionResumeInRow(pWti, pThis, 0);
iRet = RS_RET_SUSPENDED;
} else {
bTreatOKasSusp = 0;
}
if((iRet == RS_RET_OK) && (!bTreatOKasSusp)) {
DBGPRINTF("actionDoRetry: %s had success RDY again (iRet=%d)\n",
pThis->pszName, iRet);
STATSCOUNTER_INC(pThis->ctrResume, pThis->mutCtrResume);
if(pThis->bReportSuspension) {
LogMsg(0, RS_RET_RESUMED, LOG_INFO, "action '%s' "
"resumed (module '%s')",
pThis->pszName, pThis->pMod->pszName);
}
actionSetState(pThis, pWti, ACT_STATE_RDY);
} else if(iRet == RS_RET_SUSPENDED || bTreatOKasSusp) {
/* max retries reached? */
DBGPRINTF("actionDoRetry: %s check for max retries, iResumeRetryCount "
"%d, iRetries %d\n",
pThis->pszName, pThis->iResumeRetryCount, iRetries);
if((pThis->iResumeRetryCount != -1 && iRetries >= pThis->iResumeRetryCount)) {
actionSuspend(pThis, pWti);
if(getActionNbrResRtry(pWti, pThis) < 20)
incActionNbrResRtry(pWti, pThis);
} else {
++iRetries;
iSleepPeriod = pThis->iResumeInterval;
DBGPRINTF("actionDoRetry: sleeping now %d seconds\n", iSleepPeriod);
srSleep(iSleepPeriod, 0);
if(*pWti->pbShutdownImmediate) {
ABORT_FINALIZE(RS_RET_FORCE_TERM);
}
}
} else if(iRet == RS_RET_DISABLE_ACTION) {
actionDisable(pThis);
}
}
if(getActionState(pWti, pThis) == ACT_STATE_RDY) {
setActionNbrResRtry(pWti, pThis, 0);
}
finalize_it:
RETiRet;
}
/* special retry handling if disabled via file: simply wait for the file
* to indicate whether or not it is ready again
*/
static rsRetVal ATTR_NONNULL()
actionDoRetry_extFile(action_t *const pThis, wti_t *const pWti)
{
int iRetries;
int iSleepPeriod;
DEFiRet;
assert(pThis != NULL);
DBGPRINTF("actionDoRetry_extFile: enter, actionState: %d\n",getActionState(pWti, pThis));
iRetries = 0;
while((*pWti->pbShutdownImmediate == 0) && getActionState(pWti, pThis) == ACT_STATE_RTRY) {
DBGPRINTF("actionDoRetry_extFile: %s enter loop, iRetries=%d, ResumeInRow %d\n",
pThis->pszName, iRetries, getActionResumeInRow(pWti, pThis));
iRet = checkExternalStateFile(pThis, pWti);
DBGPRINTF("actionDoRetry_extFile: %s checkExternalStateFile returned %d\n", pThis->pszName, iRet);
if(iRet == RS_RET_OK) {
DBGPRINTF("actionDoRetry_extFile: %s had success RDY again (iRet=%d)\n",
pThis->pszName, iRet);
if(pThis->bReportSuspension) {
LogMsg(0, RS_RET_RESUMED, LOG_INFO, "action '%s' "
"resumed (module '%s') via external state file",
pThis->pszName, pThis->pMod->pszName);
}
actionSetState(pThis, pWti, ACT_STATE_RDY);
} else if(iRet == RS_RET_SUSPENDED) {
/* max retries reached? */
DBGPRINTF("actionDoRetry_extFile: %s check for max retries, iResumeRetryCount "
"%d, iRetries %d\n",
pThis->pszName, pThis->iResumeRetryCount, iRetries);
if((pThis->iResumeRetryCount != -1 && iRetries >= pThis->iResumeRetryCount)) {
DBGPRINTF("actionDoRetry_extFile: did not work out, suspending\n");
actionSuspend(pThis, pWti);
pWti->execState.bPrevWasSuspended = 1;
if(getActionNbrResRtry(pWti, pThis) < 20)
incActionNbrResRtry(pWti, pThis);
} else {
++iRetries;
iSleepPeriod = pThis->iResumeInterval;
srSleep(iSleepPeriod, 0);
if(*pWti->pbShutdownImmediate) {
ABORT_FINALIZE(RS_RET_FORCE_TERM);
}
}
} else if(iRet == RS_RET_DISABLE_ACTION) {
actionDisable(pThis);
}
}
if(getActionState(pWti, pThis) == ACT_STATE_RDY) {
setActionNbrResRtry(pWti, pThis, 0);
}
finalize_it:
RETiRet;
}
static rsRetVal
actionCheckAndCreateWrkrInstance(action_t * const pThis, const wti_t *const pWti)
{
int locked = 0;
DEFiRet;
if(pWti->actWrkrInfo[pThis->iActionNbr].actWrkrData == NULL) {
DBGPRINTF("wti %p: we need to create a new action worker instance for "
"action %d\n", pWti, pThis->iActionNbr);
CHKiRet(pThis->pMod->mod.om.createWrkrInstance(&(pWti->actWrkrInfo[pThis->iActionNbr].actWrkrData),
pThis->pModData));
pWti->actWrkrInfo[pThis->iActionNbr].pAction = pThis;
setActionState(pWti, pThis, ACT_STATE_RDY); /* action is enabled */
/* maintain worker data table -- only needed if wrkrHUP is requested! */
pthread_mutex_lock(&pThis->mutWrkrDataTable);
locked = 1;
int freeSpot;
for(freeSpot = 0 ; freeSpot < pThis->wrkrDataTableSize ; ++freeSpot)
if(pThis->wrkrDataTable[freeSpot] == NULL)
break;