Debian Codegraph @

runtime/dynstats.c

raw
1 /*
2 * This file is part of the rsyslog runtime library.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 * -or-
10 * see COPYING.ASL20 in the source distribution
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18 #include "config.h"
19 #include <stdlib.h>
20 #include <string.h>
21 #include <errno.h>
22 #include <sys/types.h>
23 #include <assert.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <json.h>
27 #include <sys/stat.h>
28
29 #include "rsyslog.h"
30 #include "srUtils.h"
31 #include "errmsg.h"
32 #include "rsconf.h"
33 #include "datetime.h"
34 #include "unicode-helper.h"
35 #include "hashtable_itr.h"
36 #include <sys/queue.h>
37
38 /* definitions for objects we access */
39 DEFobjStaticHelpers;
40 DEFobjCurrIf(statsobj) DEFobjCurrIf(datetime)
41
42 #define DYNSTATS_PARAM_NAME "name"
43 #define DYNSTATS_PARAM_RESETTABLE "resettable"
44 #define DYNSTATS_PARAM_MAX_CARDINALITY "maxCardinality"
45 #define DYNSTATS_PARAM_UNUSED_METRIC_LIFE "unusedMetricLife" /* in seconds */
46 #define DYNSTATS_PARAM_PERSISTSTATEINTERVAL "persistStateInterval"
47 #define DYNSTATS_PARAM_PERSISTSTATE_TIME_INTERVAL "persistStateTimeInterval"
48 #define DYNSTATS_PARAM_STATEFILE_DIRECTORY "statefile.directory"
49
50 #define DYNSTATS_DEFAULT_RESETTABILITY 1
51 #define DYNSTATS_DEFAULT_MAX_CARDINALITY 2000
52 #define DYNSTATS_DEFAULT_UNUSED_METRIC_LIFE 3600 /* seconds */
53 #define DYNSTATS_DEFAULT_PERSISTSTATEINTERVAL 0 /* seconds, default is 0, or never */
54 #define DYNSTATS_DEFAULT_PERSISTSTATE_TIME_INTERVAL 0 /* seconds, default is 0, or never */
55
56 #define DYNSTATS_MAX_BUCKET_NS_METRIC_LENGTH 100
57 #define DYNSTATS_METRIC_NAME_SEPARATOR '.'
58 #define DYNSTATS_HASHTABLE_SIZE_OVERPROVISIONING 1.25
59 #define DYNSTATS_BUCKET_PERSIST_NAME "name"
60 #define DYNSTATS_BUCKET_PERSIST_VALUES_NAME "values"
61
62 static struct cnfparamdescr modpdescr[] = {
63 {DYNSTATS_PARAM_NAME, eCmdHdlrString, CNFPARAM_REQUIRED},
64 {DYNSTATS_PARAM_RESETTABLE, eCmdHdlrBinary, 0},
65 {DYNSTATS_PARAM_MAX_CARDINALITY, eCmdHdlrPositiveInt, 0},
66 {DYNSTATS_PARAM_UNUSED_METRIC_LIFE, eCmdHdlrPositiveInt, 0}, /* in minutes */
67 {DYNSTATS_PARAM_PERSISTSTATEINTERVAL, eCmdHdlrPositiveInt, 0},
68 {DYNSTATS_PARAM_PERSISTSTATE_TIME_INTERVAL, eCmdHdlrPositiveInt, 0},
69 {DYNSTATS_PARAM_STATEFILE_DIRECTORY, eCmdHdlrString, 0}};
70
71 static struct cnfparamblk modpblk = {CNFPARAMBLK_VERSION, sizeof(modpdescr) / sizeof(struct cnfparamdescr), modpdescr};
72
73 static rsRetVal dynstats_addNewCtr(dynstats_bucket_t *b,
74 const uchar *metric,
75 uint8_t doInitialIncrement,
76 uint64_t doInitialOffset);
77 static int getFullStateFileName(dynstats_bucket_t *b, uchar *pszstatefile, uchar *pszout, int buflen);
78 static uchar *getStateFileName(const dynstats_bucket_t *const pbucket,
79 uchar *const __restrict__ buf,
80 const size_t lenbuf) ATTR_NONNULL(1, 2);
81 static rsRetVal persistBucketState(dynstats_bucket_t *b, sbool useWorker) ATTR_NONNULL(1);
82 static rsRetVal initFileWriteWorker(dynstats_buckets_t *bkts);
83 static rsRetVal enqueueFileWriteTask(dynstats_bucket_t *b, const char *file_name, const char *content);
84 static void startFileWriteWorker(dynstats_buckets_t *bkts);
85 static void stopFileWriteWorker(dynstats_buckets_t *bkts);
86 static void destroyFileWriteWorker(dynstats_buckets_t *bkts);
87
88 rsRetVal dynstatsClassInit(void) {
89 DEFiRet;
90 CHKiRet(objGetObjInterface(&obj));
91 CHKiRet(objUse(statsobj, CORE_COMPONENT));
92 CHKiRet(objUse(datetime, CORE_COMPONENT));
93 finalize_it:
94 RETiRet;
95 }
96
97 static void dynstats_destroyCtr(dynstats_ctr_t *ctr) {
98 statsobj.DestructUnlinkedCounter(ctr->pCtr);
99 free(ctr->metric);
100 free(ctr);
101 }
102
103 static void /* assumes exclusive access to bucket */
104 dynstats_destroyCountersIn(dynstats_bucket_t *b, htable *table, dynstats_ctr_t *ctrs) {
105 dynstats_ctr_t *ctr;
106 int ctrs_purged = 0;
107 hashtable_destroy(table, 0);
108 while (ctrs != NULL) {
109 ctr = ctrs;
110 ctrs = ctrs->next;
111 dynstats_destroyCtr(ctr);
112 ctrs_purged++;
113 }
114 STATSCOUNTER_ADD(b->ctrMetricsPurged, b->mutCtrMetricsPurged, ctrs_purged);
115 ATOMIC_SUB_unsigned(&b->metricCount, ctrs_purged, &b->mutMetricCount);
116 }
117
118 static void /* assumes exclusive access to bucket */
119 dynstats_destroyCounters(dynstats_bucket_t *b) {
120 statsobj.UnlinkAllCounters(b->stats);
121 dynstats_destroyCountersIn(b, b->table, b->ctrs);
122 }
123
124 static void dynstats_destroyBucket(dynstats_bucket_t *b) {
125 dynstats_buckets_t *bkts;
126 sbool need_persist = 0;
127
128 if (b == NULL) {
129 return;
130 }
131
132 bkts = b->bkts;
133 if (bkts == NULL) {
134 LogError(0, RS_RET_INTERNAL_ERROR, "dynstats: bucket '%s' has no parent buckets structure, cannot destroy.",
135 (char *)b->name);
136 return;
137 }
138
139 pthread_rwlock_rdlock(&b->lock);
140 need_persist =
141 (b->persist_state_write_count_interval || b->persist_state_interval_secs || b->persist_expiration_time);
142 pthread_rwlock_unlock(&b->lock);
143
144 /* Persist state BEFORE taking lock for destruction to avoid holding lock during I/O.
145 * At this point the worker is stopped and this bucket is removed from the list,
146 * so no other threads should be accessing it.
147 */
148 if (need_persist) {
149 pthread_rwlock_wrlock(&b->lock);
150 persistBucketState(b, 0);
151 pthread_rwlock_unlock(&b->lock);
152 }
153
154 pthread_rwlock_wrlock(&b->lock);
155 dynstats_destroyCounters(b);
156 dynstats_destroyCountersIn(b, b->survivor_table, b->survivor_ctrs);
157 statsobj.DestructCounter(b->stats, b->pCtrFlushedBytes);
158 statsobj.DestructCounter(b->stats, b->pCtrFlushed);
159 statsobj.DestructCounter(b->stats, b->pCtrFlushedErrors);
160 statsobj.Destruct(&b->stats);
161 free(b->name);
162 free(b->state_file_directory);
163 pthread_rwlock_unlock(&b->lock);
164 pthread_rwlock_destroy(&b->lock);
165 pthread_mutex_destroy(&b->mutMetricCount);
166 statsobj.DestructCounter(bkts->global_stats, b->pOpsOverflowCtr);
167 statsobj.DestructCounter(bkts->global_stats, b->pNewMetricAddCtr);
168 statsobj.DestructCounter(bkts->global_stats, b->pNoMetricCtr);
169 statsobj.DestructCounter(bkts->global_stats, b->pMetricsPurgedCtr);
170 statsobj.DestructCounter(bkts->global_stats, b->pOpsIgnoredCtr);
171 statsobj.DestructCounter(bkts->global_stats, b->pPurgeTriggeredCtr);
172 free(b);
173 }
174
175 /**
176 * @brief Build one bucket meta-counter name and register it.
177 *
178 * Uses the caller-provided `metric_name_buff` layout:
179 * `"<bucket-name>.<suffix>"`, where `metric_suffix` points right after
180 * the separator. The suffix copy is bounded and explicitly NUL-terminated.
181 *
182 * @param global_stats global dynstats stats object that owns the entry
183 * @param metric_name_buff mutable full-name buffer reused across calls
184 * @param metric_suffix write position for the suffix inside the buffer
185 * @param suffix_literal counter suffix to append (e.g. "ops_overflow")
186 * @param counter caller-owned counter storage to register
187 * @param counter_ref out: created stats counter handle
188 *
189 * @note `statsobj.AddManagedCounter()` duplicates the counter name, so
190 * `metric_name_buff` only needs to remain valid for the duration of this call.
191 */
192 static rsRetVal dynstats_addBucketMetaCounter(statsobj_t *global_stats,
193 uchar *metric_name_buff,
194 uchar *metric_suffix,
195 const uchar *suffix_literal,
196 intctr_t *counter,
197 ctr_t **counter_ref) {
198 ustrncpy(metric_suffix, suffix_literal, DYNSTATS_MAX_BUCKET_NS_METRIC_LENGTH);
199 /* Clamp at fixed boundary in case source length reaches/exceeds max copy width. */
200 metric_suffix[DYNSTATS_MAX_BUCKET_NS_METRIC_LENGTH] = '\0';
201 return statsobj.AddManagedCounter(global_stats, metric_name_buff, ctrType_IntCtr, CTR_FLAG_RESETTABLE, counter,
202 counter_ref, 1);
203 }
204
205 /**
206 * @brief Register the built-in meta counters for one dynstats bucket.
207 *
208 * This creates and registers counters like `ops_overflow`, `new_metric_add`,
209 * and related operational metrics under the global dynstats stats object.
210 *
211 * @param bkts dynstats bucket collection that owns the global stats object
212 * @param b bucket that owns the counter storage and resulting refs
213 * @param name bucket name used as metric-name prefix
214 *
215 * @note Counter names are generated once during bucket creation time.
216 */
217 static rsRetVal dynstats_addBucketMetrics(dynstats_buckets_t *bkts, dynstats_bucket_t *b, const uchar *name) {
218 uchar *metric_name_buff, *metric_suffix;
219 const uchar *suffix_literal;
220 size_t name_len;
221 DEFiRet;
222
223 name_len = ustrlen(name);
224 /* Layout: "<name>" + '.' + <suffix up to MAX> + '\0' => +2 avoids off-by-one overflow. */
225 CHKmalloc(metric_name_buff = malloc(name_len + DYNSTATS_MAX_BUCKET_NS_METRIC_LENGTH + 2));
226
227 /* Name generation algorithm:
228 * 1) Seed reusable buffer with "<bucket-name>\0".
229 * 2) Move to the end and append '.' once.
230 * 3) For each suffix, overwrite only the suffix segment and terminate.
231 * This avoids repeated full-string formatting and keeps bounds explicit.
232 */
233 memcpy(metric_name_buff, name, name_len + 1);
234 metric_suffix = metric_name_buff + name_len;
235 *metric_suffix = DYNSTATS_METRIC_NAME_SEPARATOR;
236 metric_suffix++;
237
238 suffix_literal = UCHAR_CONSTANT("ops_overflow");
239 STATSCOUNTER_INIT(b->ctrOpsOverflow, b->mutCtrOpsOverflow);
240 CHKiRet(dynstats_addBucketMetaCounter(bkts->global_stats, metric_name_buff, metric_suffix, suffix_literal,
241 &(b->ctrOpsOverflow), &b->pOpsOverflowCtr));
242
243 suffix_literal = UCHAR_CONSTANT("new_metric_add");
244 STATSCOUNTER_INIT(b->ctrNewMetricAdd, b->mutCtrNewMetricAdd);
245 CHKiRet(dynstats_addBucketMetaCounter(bkts->global_stats, metric_name_buff, metric_suffix, suffix_literal,
246 &(b->ctrNewMetricAdd), &b->pNewMetricAddCtr));
247
248 suffix_literal = UCHAR_CONSTANT("no_metric");
249 STATSCOUNTER_INIT(b->ctrNoMetric, b->mutCtrNoMetric);
250 CHKiRet(dynstats_addBucketMetaCounter(bkts->global_stats, metric_name_buff, metric_suffix, suffix_literal,
251 &(b->ctrNoMetric), &b->pNoMetricCtr));
252
253 suffix_literal = UCHAR_CONSTANT("metrics_purged");
254 STATSCOUNTER_INIT(b->ctrMetricsPurged, b->mutCtrMetricsPurged);
255 CHKiRet(dynstats_addBucketMetaCounter(bkts->global_stats, metric_name_buff, metric_suffix, suffix_literal,
256 &(b->ctrMetricsPurged), &b->pMetricsPurgedCtr));
257
258 suffix_literal = UCHAR_CONSTANT("ops_ignored");
259 STATSCOUNTER_INIT(b->ctrOpsIgnored, b->mutCtrOpsIgnored);
260 CHKiRet(dynstats_addBucketMetaCounter(bkts->global_stats, metric_name_buff, metric_suffix, suffix_literal,
261 &(b->ctrOpsIgnored), &b->pOpsIgnoredCtr));
262
263 suffix_literal = UCHAR_CONSTANT("purge_triggered");
264 STATSCOUNTER_INIT(b->ctrPurgeTriggered, b->mutCtrPurgeTriggered);
265 CHKiRet(dynstats_addBucketMetaCounter(bkts->global_stats, metric_name_buff, metric_suffix, suffix_literal,
266 &(b->ctrPurgeTriggered), &b->pPurgeTriggeredCtr));
267
268 finalize_it:
269 free(metric_name_buff);
270 if (iRet != RS_RET_OK) {
271 if (b->pOpsOverflowCtr != NULL) {
272 statsobj.DestructCounter(bkts->global_stats, b->pOpsOverflowCtr);
273 }
274 if (b->pNewMetricAddCtr != NULL) {
275 statsobj.DestructCounter(bkts->global_stats, b->pNewMetricAddCtr);
276 }
277 if (b->pNoMetricCtr != NULL) {
278 statsobj.DestructCounter(bkts->global_stats, b->pNoMetricCtr);
279 }
280 if (b->pMetricsPurgedCtr != NULL) {
281 statsobj.DestructCounter(bkts->global_stats, b->pMetricsPurgedCtr);
282 }
283 if (b->pOpsIgnoredCtr != NULL) {
284 statsobj.DestructCounter(bkts->global_stats, b->pOpsIgnoredCtr);
285 }
286 if (b->pPurgeTriggeredCtr != NULL) {
287 statsobj.DestructCounter(bkts->global_stats, b->pPurgeTriggeredCtr);
288 }
289 }
290 RETiRet;
291 }
292
293 static void no_op_free(void __attribute__((unused)) * ignore) {}
294
295 static rsRetVal /* assumes exclusive access to bucket */
296 dynstats_rebuildSurvivorTable(dynstats_bucket_t *b) {
297 htable *survivor_table = NULL;
298 htable *new_table = NULL;
299 size_t htab_sz;
300 DEFiRet;
301
302 htab_sz = (size_t)(DYNSTATS_HASHTABLE_SIZE_OVERPROVISIONING * b->maxCardinality + 1);
303 if (b->table == NULL) {
304 CHKmalloc(survivor_table = create_hashtable(htab_sz, hash_from_string, key_equals_string, no_op_free));
305 }
306 CHKmalloc(new_table = create_hashtable(htab_sz, hash_from_string, key_equals_string, no_op_free));
307 statsobj.UnlinkAllCounters(b->stats);
308 if (b->survivor_table != NULL) {
309 dynstats_destroyCountersIn(b, b->survivor_table, b->survivor_ctrs);
310 }
311 b->survivor_table = (b->table == NULL) ? survivor_table : b->table;
312 b->survivor_ctrs = b->ctrs;
313 b->table = new_table;
314 b->ctrs = NULL;
315 finalize_it:
316 if (iRet != RS_RET_OK) {
317 LogError(errno, RS_RET_INTERNAL_ERROR,
318 "error trying to evict "
319 "TTL-expired metrics of dyn-stats bucket named: %s",
320 b->name);
321 if (new_table == NULL) {
322 LogError(errno, RS_RET_INTERNAL_ERROR,
323 "error trying to "
324 "initialize hash-table for dyn-stats bucket named: %s",
325 b->name);
326 } else {
327 assert(0); /* "can" not happen -- triggers Coverity CID 184307:
328 hashtable_destroy(new_table, 0);
329 We keep this as guard should code above change in the future */
330 }
331 if (b->table == NULL) {
332 if (survivor_table == NULL) {
333 LogError(errno, RS_RET_INTERNAL_ERROR,
334 "error trying to initialize "
335 "ttl-survivor hash-table for dyn-stats bucket named: %s",
336 b->name);
337 } else {
338 hashtable_destroy(survivor_table, 0);
339 }
340 }
341 }
342 RETiRet;
343 }
344
345 static rsRetVal dynstats_resetBucket(dynstats_bucket_t *b) {
346 DEFiRet;
347 pthread_rwlock_wrlock(&b->lock);
348 CHKiRet(dynstats_rebuildSurvivorTable(b));
349 STATSCOUNTER_INC(b->ctrPurgeTriggered, b->mutCtrPurgeTriggered);
350 timeoutComp(&b->metricCleanupTimeout, b->unusedMetricLife);
351 finalize_it:
352 pthread_rwlock_unlock(&b->lock);
353 RETiRet;
354 }
355
356 static void dynstats_resetIfExpired(dynstats_bucket_t *b) {
357 long timeout;
358 pthread_rwlock_rdlock(&b->lock);
359 timeout = timeoutVal(&b->metricCleanupTimeout);
360 pthread_rwlock_unlock(&b->lock);
361 if (timeout == 0) {
362 LogMsg(0, RS_RET_TIMED_OUT, LOG_INFO, "dynstats: bucket '%s' is being reset", b->name);
363 dynstats_resetBucket(b);
364 }
365 }
366
367 static void dynstats_readCallback(statsobj_t __attribute__((unused)) * ignore, void *b) {
368 dynstats_buckets_t *bkts;
369 bkts = &runConf->dynstats_buckets;
370
371 pthread_rwlock_rdlock(&bkts->lock);
372 dynstats_resetIfExpired((dynstats_bucket_t *)b);
373 pthread_rwlock_unlock(&bkts->lock);
374 }
375
376 static rsRetVal dynstats_initNewBucketStats(dynstats_bucket_t *b) {
377 DEFiRet;
378
379 CHKiRet(statsobj.Construct(&b->stats));
380 CHKiRet(statsobj.SetOrigin(b->stats, UCHAR_CONSTANT("dynstats.bucket")));
381 CHKiRet(statsobj.SetName(b->stats, b->name));
382 CHKiRet(statsobj.SetReportingNamespace(b->stats, UCHAR_CONSTANT("values")));
383
384 char bucket_stat_name[512];
385 int bufsize = sizeof(bucket_stat_name);
386 int rc;
387 rc = snprintf(bucket_stat_name, bufsize, "%s_%s", b->name, "flushed_bytes");
388 if (rc < 0 || rc >= bufsize) {
389 LogError(0, RS_RET_INTERNAL_ERROR, "dynstats: buffer too small for stat name");
390 ABORT_FINALIZE(RS_RET_INTERNAL_ERROR);
391 }
392 STATSCOUNTER_INIT(b->ctrFlushedBytes, b->mutCtrFlushedBytes);
393 CHKiRet(statsobj.AddManagedCounter(b->stats, (uchar *)bucket_stat_name, ctrType_IntCtr, CTR_FLAG_RESETTABLE,
394 &b->ctrFlushedBytes, &b->pCtrFlushedBytes, 0));
395
396 rc = snprintf(bucket_stat_name, bufsize, "%s_%s", b->name, "flushed_counts");
397 if (rc < 0 || rc >= bufsize) {
398 LogError(0, RS_RET_INTERNAL_ERROR, "dynstats: buffer too small for stat name");
399 ABORT_FINALIZE(RS_RET_INTERNAL_ERROR);
400 }
401 STATSCOUNTER_INIT(b->ctrFlushed, b->mutCtrFlushed);
402 CHKiRet(statsobj.AddManagedCounter(b->stats, (uchar *)bucket_stat_name, ctrType_IntCtr, CTR_FLAG_RESETTABLE,
403 &b->ctrFlushed, &b->pCtrFlushed, 0));
404
405 rc = snprintf(bucket_stat_name, bufsize, "%s_%s", b->name, "flush_errors");
406 if (rc < 0 || rc >= bufsize) {
407 LogError(0, RS_RET_INTERNAL_ERROR, "dynstats: buffer too small for stat name");
408 ABORT_FINALIZE(RS_RET_INTERNAL_ERROR);
409 }
410 STATSCOUNTER_INIT(b->ctrFlushedErrors, b->mutCtrFlushedErrors);
411 CHKiRet(statsobj.AddManagedCounter(b->stats, (uchar *)bucket_stat_name, ctrType_IntCtr, CTR_FLAG_RESETTABLE,
412 &b->ctrFlushedErrors, &b->pCtrFlushedErrors, 0));
413
414 statsobj.SetReadNotifier(b->stats, dynstats_readCallback, b);
415 CHKiRet(statsobj.ConstructFinalize(b->stats));
416
417 finalize_it:
418 RETiRet;
419 }
420
421 /* try to open a file which has a state file. If the state file does not
422 * exist or cannot be read, an error is returned.
423 */
424 static rsRetVal ATTR_NONNULL(1) loadPersistedState(dynstats_bucket_t *b) {
425 DEFiRet;
426 struct stat stat_buf;
427 uchar statefile[MAXFNAME];
428 uchar state_file_path[MAXFNAME];
429 json_object *json_obj = NULL;
430
431 uchar *const state_file_name = getStateFileName(b, statefile, sizeof(statefile));
432 assert(state_file_name);
433 /* Get full path and file name */
434 if (getFullStateFileName(b, state_file_name, state_file_path, sizeof(state_file_path)) == -1) {
435 ABORT_FINALIZE(RS_RET_ERR);
436 }
437 DBGPRINTF("opening statefile for '%s', state file '%s'\n", b->name, state_file_path);
438
439 /* check if the file exists */
440 if (stat((char *)state_file_path, &stat_buf) == -1) {
441 LogMsg(0, RS_RET_FILE_NOT_FOUND, LOG_INFO, "dyn_stats: warning state file doesn't exist: '%s'",
442 state_file_path);
443 ABORT_FINALIZE(RS_RET_FILE_NOT_FOUND);
444 }
445
446 json_obj = fjson_object_from_file((const char *)state_file_path);
447 if (!json_obj) {
448 LogMsg(0, RS_RET_JSON_UNUSABLE, LOG_INFO, "dyn_stats: error couldn't read json from file: '%s'",
449 state_file_path);
450 ABORT_FINALIZE(RS_RET_JSON_UNUSABLE);
451 }
452
453 /* expected json format
454 * { "name": "bucketname", "values": { "foo": "1" } }
455 */
456
457 json_object *json_obj_metrics = NULL;
458 if (json_object_object_get_ex(json_obj, DYNSTATS_BUCKET_PERSIST_VALUES_NAME, &json_obj_metrics)) {
459 struct json_object_iterator it, itEnd;
460 for (it = json_object_iter_begin(json_obj_metrics), itEnd = json_object_iter_end(json_obj_metrics);
461 !json_object_iter_equal(&it, &itEnd); json_object_iter_next(&it)) {
462 const uchar *metric = (const uchar *)json_object_iter_peek_name(&it);
463 if (metric == NULL) {
464 continue;
465 }
466 json_object *val_obj = json_object_iter_peek_value(&it);
467 if (val_obj == NULL) {
468 continue;
469 }
470 if (!json_object_is_type(val_obj, json_type_int)) {
471 LogError(0, RS_RET_JSON_UNUSABLE,
472 "dynstats: state file '%s' contains non-integer value for metric '%s'", state_file_path,
473 metric);
474 continue;
475 }
476 int64_t val_signed = json_object_get_int64(val_obj);
477 if (val_signed < 0) {
478 LogError(0, RS_RET_JSON_UNUSABLE,
479 "dynstats: state file '%s' contains negative value %lld for metric '%s' - ignoring",
480 state_file_path, (long long)val_signed, metric);
481 continue;
482 }
483 uint64_t val = (uint64_t)val_signed;
484 // now add the counter to the bucket with offset
485 rsRetVal iRetCtr = dynstats_addNewCtr(b, metric, 0, val);
486 if (iRetCtr != RS_RET_OK) {
487 LogError(0, iRetCtr, "dynstats: failed to add metric '%s' from state file", metric);
488 }
489 }
490 }
491
492 finalize_it:
493 if (json_obj != NULL) {
494 json_object_put(json_obj);
495 }
496 RETiRet;
497 }
498
499 static rsRetVal dynstats_openStateFile(dynstats_bucket_t *b) {
500 DEFiRet;
501
502 CHKiRet(loadPersistedState(b));
503
504 finalize_it:
505 RETiRet;
506 }
507
508 /**
509 * @brief Create and initialize a dynstats bucket from configuration values.
510 *
511 * The function allocates bucket state, initializes runtime/stat structures,
512 * registers per-bucket meta counters, optionally loads persisted state, and
513 * links the bucket into the active dynstats list.
514 *
515 * @param name bucket name
516 * @param resettable whether bucket counters are resettable
517 * @param maxCardinality maximum tracked metric keys in bucket
518 * @param unusedMetricLife metric TTL in seconds
519 * @param persistStateInterval persist after this many updates (0 disables)
520 * @param persistStateTimeInterval persist after this many seconds (0 disables)
521 * @param stateFileDirectory optional directory for state files
522 */
523 static rsRetVal dynstats_newBucket(const uchar *name,
524 uint8_t resettable,
525 uint32_t maxCardinality,
526 uint32_t unusedMetricLife,
527 uint32_t persistStateInterval,
528 uint32_t persistStateTimeInterval,
529 const uchar *stateFileDirectory) {
530 dynstats_bucket_t *b;
531 dynstats_buckets_t *bkts;
532 uint8_t lock_initialized, metric_count_mutex_initialized;
533 pthread_rwlockattr_t bucket_lock_attr;
534 DEFiRet;
535
536 lock_initialized = metric_count_mutex_initialized = 0;
537 b = NULL;
538
539 bkts = &loadConf->dynstats_buckets;
540
541 if (bkts->initialized) {
542 CHKmalloc(b = calloc(1, sizeof(dynstats_bucket_t)));
543 b->bkts = bkts;
544 b->resettable = resettable;
545 b->maxCardinality = maxCardinality;
546 b->unusedMetricLife = 1000 * unusedMetricLife;
547 b->persist_state_write_count_interval = persistStateInterval;
548 b->persist_state_interval_secs = persistStateTimeInterval;
549 b->n_updates = 0;
550 CHKmalloc(b->name = ustrdup(name));
551 if (stateFileDirectory) {
552 CHKmalloc(b->state_file_directory = ustrdup(stateFileDirectory));
553 }
554
555 pthread_rwlockattr_init(&bucket_lock_attr);
556 #ifdef HAVE_PTHREAD_RWLOCKATTR_SETKIND_NP
557 pthread_rwlockattr_setkind_np(&bucket_lock_attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
558 #endif
559
560 pthread_rwlock_init(&b->lock, &bucket_lock_attr);
561 lock_initialized = 1;
562 pthread_mutex_init(&b->mutMetricCount, NULL);
563 metric_count_mutex_initialized = 1;
564
565 CHKiRet(dynstats_initNewBucketStats(b));
566
567 CHKiRet(dynstats_resetBucket(b));
568
569 CHKiRet(dynstats_addBucketMetrics(bkts, b, name));
570
571 if (b && (b->persist_state_write_count_interval || b->persist_state_interval_secs)) {
572 time_t now;
573 rsRetVal rc = dynstats_openStateFile(b);
574 if (rc != RS_RET_OK) {
575 LogMsg(0, rc, LOG_INFO,
576 "dynstats: openStateFile failed - "
577 "there should be messages before this one with the reason.\n");
578 }
579 if (datetime.GetTime(&now) == -1) {
580 ABORT_FINALIZE(RS_RET_INVLD_TIME);
581 }
582 pthread_rwlock_wrlock(&b->lock);
583 if (persistStateTimeInterval > 0) {
584 b->persist_expiration_time = now + persistStateTimeInterval;
585 }
586 pthread_rwlock_unlock(&b->lock);
587
588 /* Start the file write worker if not already started */
589 startFileWriteWorker(bkts);
590 }
591
592 pthread_rwlock_wrlock(&bkts->lock);
593 if (bkts->list == NULL) {
594 bkts->list = b;
595 } else {
596 b->next = bkts->list;
597 bkts->list = b;
598 }
599 pthread_rwlock_unlock(&bkts->lock);
600 } else {
601 LogError(0, RS_RET_INTERNAL_ERROR,
602 "dynstats: bucket creation failed, as "
603 "global-initialization of buckets was unsuccessful");
604 ABORT_FINALIZE(RS_RET_INTERNAL_ERROR);
605 }
606 finalize_it:
607 if (iRet != RS_RET_OK) {
608 if (b != NULL) {
609 if (lock_initialized) {
610 if (!metric_count_mutex_initialized) {
611 pthread_mutex_init(&b->mutMetricCount, NULL);
612 }
613 dynstats_destroyBucket(b);
614 } else {
615 free(b->name);
616 free(b->state_file_directory);
617 free(b);
618 }
619 }
620 }
621 RETiRet;
622 }
623
624 /**
625 * @brief Process one `dyn_stats` config object and create the bucket.
626 *
627 * Parses config parameters, applies defaults, and forwards the normalized
628 * values to `dynstats_newBucket()`.
629 *
630 * @param o parsed config object for dynstats bucket creation
631 */
632 rsRetVal dynstats_processCnf(struct cnfobj *o) {
633 struct cnfparamvals *pvals;
634 short i;
635 uchar *name = NULL;
636 uchar *stateFileDirectory = NULL;
637 uint8_t resettable = DYNSTATS_DEFAULT_RESETTABILITY;
638 uint32_t maxCardinality = DYNSTATS_DEFAULT_MAX_CARDINALITY;
639 uint32_t unusedMetricLife = DYNSTATS_DEFAULT_UNUSED_METRIC_LIFE;
640 uint32_t persistStateInterval = DYNSTATS_DEFAULT_PERSISTSTATEINTERVAL;
641 uint32_t persistStateTimeInterval = DYNSTATS_DEFAULT_PERSISTSTATE_TIME_INTERVAL;
642 DEFiRet;
643
644 pvals = nvlstGetParams(o->nvlst, &modpblk, NULL);
645 if (pvals == NULL) {
646 ABORT_FINALIZE(RS_RET_MISSING_CNFPARAMS);
647 }
648
649 for (i = 0; i < modpblk.nParams; ++i) {
650 if (!pvals[i].bUsed) continue;
651 if (!strcmp(modpblk.descr[i].name, DYNSTATS_PARAM_NAME)) {
652 CHKmalloc(name = (uchar *)es_str2cstr(pvals[i].val.d.estr, NULL));
653 } else if (!strcmp(modpblk.descr[i].name, DYNSTATS_PARAM_RESETTABLE)) {
654 resettable = (pvals[i].val.d.n != 0);
655 } else if (!strcmp(modpblk.descr[i].name, DYNSTATS_PARAM_MAX_CARDINALITY)) {
656 maxCardinality = (uint32_t)pvals[i].val.d.n;
657 } else if (!strcmp(modpblk.descr[i].name, DYNSTATS_PARAM_UNUSED_METRIC_LIFE)) {
658 unusedMetricLife = (uint32_t)pvals[i].val.d.n;
659 } else if (!strcmp(modpblk.descr[i].name, DYNSTATS_PARAM_PERSISTSTATEINTERVAL)) {
660 persistStateInterval = (uint32_t)pvals[i].val.d.n;
661 } else if (!strcmp(modpblk.descr[i].name, DYNSTATS_PARAM_PERSISTSTATE_TIME_INTERVAL)) {
662 persistStateTimeInterval = (uint32_t)pvals[i].val.d.n;
663 } else if (!strcmp(modpblk.descr[i].name, DYNSTATS_PARAM_STATEFILE_DIRECTORY)) {
664 CHKmalloc(stateFileDirectory = (uchar *)es_str2cstr(pvals[i].val.d.estr, NULL));
665 } else {
666 dbgprintf(
667 "dyn_stats: program error, non-handled "
668 "param '%s'\n",
669 modpblk.descr[i].name);
670 }
671 }
672 if (name != NULL) {
673 CHKiRet(dynstats_newBucket(name, resettable, maxCardinality, unusedMetricLife, persistStateInterval,
674 persistStateTimeInterval, stateFileDirectory));
675 }
676
677 finalize_it:
678 free(name);
679 free(stateFileDirectory);
680 cnfparamvalsDestruct(pvals, &modpblk);
681 RETiRet;
682 }
683
684 rsRetVal dynstats_initCnf(dynstats_buckets_t *bkts) {
685 DEFiRet;
686
687 bkts->initialized = 0;
688
689 bkts->list = NULL;
690 CHKiRet(statsobj.Construct(&bkts->global_stats));
691 CHKiRet(statsobj.SetOrigin(bkts->global_stats, UCHAR_CONSTANT("dynstats")));
692 CHKiRet(statsobj.SetName(bkts->global_stats, UCHAR_CONSTANT("global")));
693 CHKiRet(statsobj.SetReportingNamespace(bkts->global_stats, UCHAR_CONSTANT("values")));
694 CHKiRet(statsobj.ConstructFinalize(bkts->global_stats));
695 pthread_rwlock_init(&bkts->lock, NULL);
696
697 bkts->initialized = 1;
698 bkts->wrkrStarted = 0;
699 CHKiRet(initFileWriteWorker(bkts));
700
701 finalize_it:
702 if (iRet != RS_RET_OK) {
703 statsobj.Destruct(&bkts->global_stats);
704 }
705 RETiRet;
706 }
707
708 void dynstats_destroyAllBuckets(rsconf_t *cnf) {
709 dynstats_buckets_t *bkts;
710 dynstats_bucket_t *b;
711 if (cnf == NULL) {
712 return;
713 }
714 bkts = &cnf->dynstats_buckets;
715 if (bkts->initialized) {
716 pthread_mutex_lock(&bkts->work_q.mut);
717 if (bkts->wrkrStarted) {
718 pthread_mutex_unlock(&bkts->work_q.mut);
719 stopFileWriteWorker(bkts);
720 } else {
721 pthread_mutex_unlock(&bkts->work_q.mut);
722 }
723 pthread_rwlock_wrlock(&bkts->lock);
724 while (1) {
725 b = bkts->list;
726 if (b == NULL) {
727 break;
728 } else {
729 bkts->list = b->next;
730 dynstats_destroyBucket(b);
731 }
732 }
733 statsobj.Destruct(&bkts->global_stats);
734 pthread_rwlock_unlock(&bkts->lock);
735 pthread_rwlock_destroy(&bkts->lock);
736 destroyFileWriteWorker(bkts);
737 }
738 }
739
740 dynstats_bucket_t *dynstats_findBucket(const uchar *name) {
741 dynstats_buckets_t *bkts;
742 dynstats_bucket_t *b;
743 bkts = &loadConf->dynstats_buckets;
744 if (bkts->initialized) {
745 pthread_rwlock_rdlock(&bkts->lock);
746 b = bkts->list;
747 while (b != NULL) {
748 if (!ustrcmp(name, b->name)) {
749 break;
750 }
751 b = b->next;
752 }
753 pthread_rwlock_unlock(&bkts->lock);
754 } else {
755 b = NULL;
756 LogError(0, RS_RET_INTERNAL_ERROR,
757 "dynstats: bucket lookup failed, as global-initialization "
758 "of buckets was unsuccessful");
759 }
760
761 return b;
762 }
763
764 static rsRetVal dynstats_createCtr(dynstats_bucket_t *b, const uchar *metric, dynstats_ctr_t **ctr) {
765 DEFiRet;
766
767 CHKmalloc(*ctr = calloc(1, sizeof(dynstats_ctr_t)));
768 CHKmalloc((*ctr)->metric = ustrdup(metric));
769 STATSCOUNTER_INIT((*ctr)->ctr, (*ctr)->mutCtr);
770 CHKiRet(statsobj.AddManagedCounter(b->stats, metric, ctrType_IntCtr,
771 b->resettable ? CTR_FLAG_MUST_RESET : CTR_FLAG_NONE, &(*ctr)->ctr, &(*ctr)->pCtr,
772 0));
773 finalize_it:
774 if (iRet != RS_RET_OK) {
775 if ((*ctr) != NULL) {
776 free((*ctr)->metric);
777 free(*ctr);
778 *ctr = NULL;
779 }
780 }
781 RETiRet;
782 }
783
784 /* not supported in older platforms - disable */
785 #ifndef O_CLOEXEC
786 #define O_CLOEXEC 0
787 #endif
788 #ifndef O_NOFOLLOW
789 #define O_NOFOLLOW 0
790 #endif
791 /*
792 * Helper function adapted from imfile of the same name - possible candidate for refactor.
793 * Updates configured state file with the state of the specified bucket
794 */
795 static rsRetVal ATTR_NONNULL(1) writeStateFile(dynstats_bucket_t *b, const char *file_name, const char *content) {
796 assert(b);
797 const size_t toWrite = strlen(content);
798 ssize_t w = 0;
799 int fd = -1;
800 char *tmp_file_name = NULL;
801 DEFiRet;
802
803 /* Create temp file name */
804 size_t name_len = strlen(file_name);
805 CHKmalloc(tmp_file_name = malloc(name_len + 5)); /* .tmp + null */
806 snprintf(tmp_file_name, name_len + 5, "%s.tmp", file_name);
807
808 fd = open(tmp_file_name, O_CLOEXEC | O_NOCTTY | O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW, 0600);
809 if (fd < 0) {
810 LogError(errno, RS_RET_IO_ERROR,
811 "dynstats: cannot open state file '%s' for "
812 "persisting file state - some data will probably be duplicated "
813 "on next startup",
814 tmp_file_name);
815 ABORT_FINALIZE(RS_RET_IO_ERROR);
816 }
817
818 /* note: write is buffered; actual sync happens via atomicWriteStateFile */
819 w = write(fd, content, toWrite);
820 if (w != (ssize_t)toWrite) {
821 LogError(errno, RS_RET_IO_ERROR,
822 "dynstats: partial write to state file '%s' "
823 "this may cause trouble in the future. We will try to delete the "
824 "state file, as this provides most consistent state",
825 tmp_file_name);
826 unlink(tmp_file_name);
827 ABORT_FINALIZE(RS_RET_IO_ERROR);
828 }
829
830 /* Sync to disk to ensure data is safe before rename */
831 if (fsync(fd) != 0) {
832 LogError(errno, RS_RET_IO_ERROR, "dynstats: fsync failed for '%s'", tmp_file_name);
833 unlink(tmp_file_name);
834 ABORT_FINALIZE(RS_RET_IO_ERROR);
835 }
836
837 if (close(fd) != 0) {
838 LogError(errno, RS_RET_IO_ERROR, "dynstats: close failed for '%s'", tmp_file_name);
839 unlink(tmp_file_name);
840 fd = -1;
841 ABORT_FINALIZE(RS_RET_IO_ERROR);
842 }
843 fd = -1;
844
845 if (rename(tmp_file_name, file_name) != 0) {
846 LogError(errno, RS_RET_IO_ERROR, "dynstats: rename failed from '%s' to '%s'", tmp_file_name, file_name);
847 unlink(tmp_file_name);
848 ABORT_FINALIZE(RS_RET_IO_ERROR);
849 }
850
851 finalize_it:
852 if (fd >= 0) {
853 close(fd);
854 }
855 free(tmp_file_name);
856
857 if (iRet == RS_RET_IO_ERROR) {
858 STATSCOUNTER_INC(b->ctrFlushedErrors, b->mutCtrFlushedErrors);
859 }
860 if (iRet == RS_RET_OK) {
861 STATSCOUNTER_ADD(b->ctrFlushedBytes, b->mutCtrFlushedBytes, w);
862 STATSCOUNTER_INC(b->ctrFlushed, b->mutCtrFlushed);
863 }
864 RETiRet;
865 }
866
867 static const uchar *getStateFileDir(dynstats_bucket_t *b) {
868 const uchar *wrkdir;
869 assert(b != NULL);
870 if (b->state_file_directory == NULL) {
871 rsconf_t *cnf = (runConf != NULL) ? runConf : loadConf;
872 wrkdir = glblGetWorkDirRaw(cnf);
873 } else {
874 wrkdir = b->state_file_directory;
875 }
876 return (wrkdir);
877 }
878
879 /*
880 * Helper function to combine statefile and workdir
881 */
882 static int getFullStateFileName(dynstats_bucket_t *b, uchar *pszstatefile, uchar *pszout, int buflen) {
883 int lenout;
884 const uchar *pszworkdir;
885
886 /* Get Raw Workdir, if it is NULL we need to propper handle it */
887 pszworkdir = getStateFileDir(b);
888
889 /* Construct file name */
890 lenout = snprintf((char *)pszout, buflen, "%s/%s", (char *)(pszworkdir == NULL ? "." : (char *)pszworkdir),
891 (char *)pszstatefile);
892
893 if (lenout >= buflen) {
894 LogError(0, RS_RET_ERR, "dynstats: state file path too long for bucket '%s'", (char *)b->name);
895 return -1;
896 }
897
898 /* return out length */
899 return lenout;
900 }
901
902 /* this generates a state file name suitable for the given file. To avoid
903 * malloc calls, it must be passed a buffer which should be MAXFNAME large.
904 * Note: the buffer is not necessarily populated ... always ONLY use the
905 * RETURN VALUE!
906 * This function is guranteed to work only on config data and DOES NOT
907 * open or otherwise modify disk file state.
908 */
909 static uchar *ATTR_NONNULL(1, 2)
910 getStateFileName(const dynstats_bucket_t *const pbucket, uchar *const __restrict__ buf, const size_t lenbuf) {
911 DBGPRINTF("getStateFileName for '%s'\n", pbucket->name);
912 if (strchr((const char *)pbucket->name, '/') != NULL) {
913 /* Basic path traversal protection - bucket names should not contain slashes */
914 char sanitized_name[MAXFNAME];
915 strncpy(sanitized_name, (const char *)pbucket->name, sizeof(sanitized_name) - 1);
916 sanitized_name[sizeof(sanitized_name) - 1] = '\0';
917 for (char *p = sanitized_name; *p; p++) {
918 if (*p == '/') *p = '_';
919 }
920 snprintf((char *)buf, lenbuf, "dynstats-state:%s", sanitized_name);
921 LogMsg(0, RS_RET_OK, LOG_WARNING,
922 "dynstats: bucket name '%s' contains slashes, "
923 "sanitized to '%s' for state file",
924 pbucket->name, sanitized_name);
925 } else {
926 snprintf((char *)buf, lenbuf, "dynstats-state:%s", pbucket->name);
927 }
928 DBGPRINTF("getStateFileName: state file name now is %s\n", buf);
929 return buf;
930 }
931
932 /* This function persists dynstats_bucket_t data, which for the time being:
933 * metric bucket counters
934 */
935 static rsRetVal ATTR_NONNULL(1) persistBucketState(dynstats_bucket_t *b, sbool useWorker) {
936 DEFiRet;
937 uchar statefile[MAXFNAME];
938 uchar statefname[MAXFNAME];
939 struct json_object *jval = NULL;
940 struct json_object *json = NULL;
941 struct json_object *json_bucket_values = NULL;
942
943 assert(b->name);
944 uchar *const statefn = getStateFileName(b, statefile, sizeof(statefile));
945 /* Get full path and file name */
946 if (getFullStateFileName(b, statefn, statefname, sizeof(statefname)) == -1) {
947 ABORT_FINALIZE(RS_RET_ERR);
948 }
949 DBGPRINTF("persisting state for '%s', state file '%s'\n", b->name, statefname);
950
951 CHKmalloc(json = json_object_new_object());
952 jval = json_object_new_string((char *)b->name);
953 if (jval == NULL) {
954 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
955 }
956 json_object_object_add(json, DYNSTATS_BUCKET_PERSIST_NAME, jval);
957
958 // walk the hashtable and create a val for each
959 CHKmalloc(json_bucket_values = json_object_new_object());
960 json_object_object_add(json, DYNSTATS_BUCKET_PERSIST_VALUES_NAME, json_bucket_values);
961
962 if (b->table != NULL && hashtable_count(b->table) > 0) {
963 struct hashtable_itr *itr = hashtable_iterator(b->table);
964 if (itr == NULL) {
965 LogError(0, RS_RET_OUT_OF_MEMORY, "dynstats: failed to allocate hashtable iterator");
966 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
967 }
968 dynstats_ctr_t *pctr = NULL;
969 do {
970 pctr = (dynstats_ctr_t *)hashtable_iterator_value(itr);
971 jval = json_object_new_int64(pctr->ctr);
972 if (jval == NULL) {
973 free(itr);
974 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
975 }
976 json_object_object_add(json_bucket_values, (const char *)pctr->metric, jval);
977 } while (hashtable_iterator_advance(itr));
978 free(itr);
979 }
980
981 const char *jstr = json_object_to_json_string_ext(json, JSON_C_TO_STRING_PLAIN);
982 if (jstr == NULL) {
983 LogError(0, RS_RET_OUT_OF_MEMORY, "dynstats: failed to serialize JSON");
984 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
985 }
986 if (useWorker) {
987 CHKiRet(enqueueFileWriteTask(b, (const char *)statefname, jstr));
988 } else {
989 CHKiRet(writeStateFile(b, (const char *)statefname, jstr));
990 }
991
992 finalize_it:
993 if (iRet != RS_RET_OK) {
994 LogError(0, iRet,
995 "dynstats: could not persist state "
996 "file %s - data may be repeated on next "
997 "startup. Is WorkDirectory set?",
998 statefname);
999 }
1000 if (json) {
1001 json_object_put(json);
1002 }
1003
1004 RETiRet;
1005 }
1006
1007 #if defined(__GNUC__) && !defined(__clang__)
1008 #pragma GCC diagnostic push
1009 #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" /* TODO: how can we fix these warnings? */
1010 #endif
1011 static rsRetVal dynstats_addNewCtr(dynstats_bucket_t *b,
1012 const uchar *metric,
1013 uint8_t doInitialIncrement,
1014 uint64_t doInitialOffset) {
1015 dynstats_ctr_t *ctr;
1016 dynstats_ctr_t *found_ctr, *survivor_ctr, *effective_ctr = NULL;
1017 int created;
1018 uchar *copy_of_key = NULL;
1019 DEFiRet;
1020
1021 created = 0;
1022 ctr = NULL;
1023
1024 if ((unsigned)ATOMIC_FETCH_32BIT_unsigned(&b->metricCount, &b->mutMetricCount) >= b->maxCardinality) {
1025 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
1026 }
1027
1028 CHKiRet(dynstats_createCtr(b, metric, &ctr));
1029
1030 pthread_rwlock_wrlock(&b->lock);
1031 found_ctr = (dynstats_ctr_t *)hashtable_search(b->table, ctr->metric);
1032 if (found_ctr != NULL) {
1033 if (doInitialIncrement) {
1034 STATSCOUNTER_INC(found_ctr->ctr, found_ctr->mutCtr);
1035 }
1036 } else {
1037 copy_of_key = ustrdup(ctr->metric);
1038 if (copy_of_key != NULL) {
1039 survivor_ctr = (dynstats_ctr_t *)hashtable_search(b->survivor_table, ctr->metric);
1040 if (survivor_ctr == NULL) {
1041 effective_ctr = ctr;
1042 } else {
1043 effective_ctr = survivor_ctr;
1044 if (survivor_ctr->prev != NULL) {
1045 survivor_ctr->prev->next = survivor_ctr->next;
1046 }
1047 if (survivor_ctr->next != NULL) {
1048 survivor_ctr->next->prev = survivor_ctr->prev;
1049 }
1050 if (survivor_ctr == b->survivor_ctrs) {
1051 b->survivor_ctrs = survivor_ctr->next;
1052 }
1053 }
1054 if ((created = hashtable_insert(b->table, copy_of_key, effective_ctr))) {
1055 statsobj.AddPreCreatedCtr(b->stats, effective_ctr->pCtr);
1056 }
1057 }
1058 if (created) {
1059 if (b->ctrs != NULL) {
1060 b->ctrs->prev = effective_ctr;
1061 }
1062 effective_ctr->prev = NULL;
1063 effective_ctr->next = b->ctrs;
1064 b->ctrs = effective_ctr;
1065 if (doInitialIncrement) {
1066 STATSCOUNTER_INC(effective_ctr->ctr, effective_ctr->mutCtr);
1067 }
1068 if (doInitialOffset) {
1069 // doInitialOffset regardless of the state of GatherStats
1070 effective_ctr->ctr += doInitialOffset;
1071 }
1072 }
1073 }
1074 pthread_rwlock_unlock(&b->lock);
1075
1076 if (found_ctr != NULL) {
1077 // ignore
1078 } else if (created && (effective_ctr != survivor_ctr)) {
1079 ATOMIC_INC(&b->metricCount, &b->mutMetricCount);
1080 STATSCOUNTER_INC(b->ctrNewMetricAdd, b->mutCtrNewMetricAdd);
1081 } else if (!created) {
1082 if (copy_of_key != NULL) {
1083 free(copy_of_key);
1084 }
1085 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
1086 }
1087
1088 finalize_it:
1089 if (((!created) || (effective_ctr != ctr)) && (ctr != NULL)) {
1090 dynstats_destroyCtr(ctr);
1091 }
1092 RETiRet;
1093 }
1094 #if defined(__GNUC__) && !defined(__clang__)
1095 #pragma GCC diagnostic pop
1096 #endif
1097
1098 static sbool dynstats_shouldPersist(dynstats_bucket_t *b, time_t now) {
1099 sbool shouldPersist = FALSE;
1100 time_t expire;
1101 if (b->persist_state_write_count_interval > 0) {
1102 if (ATOMIC_INC_AND_FETCH_unsigned(&b->n_updates, &b->mutMetricCount) >= b->persist_state_write_count_interval) {
1103 shouldPersist = TRUE;
1104 }
1105 }
1106
1107 #ifdef HAVE_ATOMIC_BUILTINS64
1108 expire = (time_t)__sync_fetch_and_add((uint64_t *)&b->persist_expiration_time, 0);
1109 #else
1110 pthread_rwlock_rdlock(&b->lock);
1111 expire = b->persist_expiration_time;
1112 pthread_rwlock_unlock(&b->lock);
1113 #endif
1114
1115 if (!shouldPersist && expire && now >= expire) {
1116 shouldPersist = TRUE;
1117 }
1118 return shouldPersist;
1119 }
1120
1121 static sbool dynstats_shouldPersistLocked(dynstats_bucket_t *b, time_t now) {
1122 if (b->persist_state_write_count_interval > 0 &&
1123 (uint32_t)ATOMIC_FETCH_32BIT_unsigned(&b->n_updates, &b->mutMetricCount) >=
1124 b->persist_state_write_count_interval) {
1125 return TRUE;
1126 }
1127 if (b->persist_expiration_time && now >= b->persist_expiration_time) {
1128 return TRUE;
1129 }
1130 return FALSE;
1131 }
1132
1133 rsRetVal dynstats_inc(dynstats_bucket_t *b, uchar *metric) {
1134 dynstats_ctr_t *ctr = NULL;
1135 DEFiRet;
1136
1137 if (!GatherStats) {
1138 FINALIZE;
1139 }
1140
1141 if (ustrlen(metric) == 0) {
1142 STATSCOUNTER_INC(b->ctrNoMetric, b->mutCtrNoMetric);
1143 FINALIZE;
1144 }
1145
1146 if (pthread_rwlock_tryrdlock(&b->lock) == 0) {
1147 ctr = (dynstats_ctr_t *)hashtable_search(b->table, metric);
1148 if (ctr != NULL) {
1149 STATSCOUNTER_INC(ctr->ctr, ctr->mutCtr);
1150 }
1151 pthread_rwlock_unlock(&b->lock);
1152 } else {
1153 ABORT_FINALIZE(RS_RET_NOENTRY);
1154 }
1155
1156 if (ctr == NULL) {
1157 CHKiRet(dynstats_addNewCtr(b, metric, 1, 0));
1158 }
1159
1160 if (b->persist_state_write_count_interval == 0 && b->persist_state_interval_secs == 0) {
1161 FINALIZE;
1162 }
1163
1164 time_t now;
1165 if (datetime.GetTime(&now) != -1) {
1166 if (dynstats_shouldPersist(b, now)) {
1167 pthread_rwlock_wrlock(&b->lock);
1168 if (dynstats_shouldPersistLocked(b, now)) {
1169 rsRetVal persist_ret = persistBucketState(b, 1);
1170 if (persist_ret == RS_RET_OK) {
1171 if (b->persist_state_write_count_interval) {
1172 ATOMIC_SUB_unsigned(&b->n_updates, b->persist_state_write_count_interval, &b->mutMetricCount);
1173 }
1174 if (b->persist_state_interval_secs) {
1175 b->persist_expiration_time = now + b->persist_state_interval_secs;
1176 }
1177 }
1178 }
1179 pthread_rwlock_unlock(&b->lock);
1180 }
1181 }
1182
1183 finalize_it:
1184 if (iRet != RS_RET_OK) {
1185 if (iRet == RS_RET_NOENTRY) {
1186 /* NOTE: this is not tested (because it requires very strong orchestration to
1187 guarantee contended lock for testing) */
1188 STATSCOUNTER_INC(b->ctrOpsIgnored, b->mutCtrOpsIgnored);
1189 } else {
1190 STATSCOUNTER_INC(b->ctrOpsOverflow, b->mutCtrOpsOverflow);
1191 }
1192 }
1193 RETiRet;
1194 }
1195
1196 typedef struct file_write_entry_s {
1197 STAILQ_ENTRY(file_write_entry_s) link;
1198 const char *name;
1199 const char *content;
1200 dynstats_bucket_t *bucket;
1201 } file_write_entry_t;
1202
1203
1204 static void processWorkItem(file_write_entry_t *task) {
1205 // write out the file
1206 /* NOTE: accessing task->bucket is safe here because stopFileWriteWorker()
1207 * is called before dynstats_destroyBucket() in dynstats_destroyAllBuckets(),
1208 * which ensures the worker thread has finished processing all pending tasks
1209 * before any bucket is freed.
1210 */
1211 DBGPRINTF("dynstats: worker processing - '%s', '%.100s'\n", task->name, task->content);
1212 writeStateFile(task->bucket, task->name, task->content);
1213 }
1214
1215 static void destroyFileWriteTask(file_write_entry_t *task) {
1216 free((void *)task->name);
1217 free((void *)task->content);
1218 free(task);
1219 }
1220
1221 static void *fileWriteWorker(void *data) {
1222 dynstats_buckets_t *bkts = (dynstats_buckets_t *)data;
1223 if (!bkts) {
1224 return NULL;
1225 }
1226
1227 pthread_mutex_lock(&bkts->work_q.mut);
1228 ++bkts->wrkrRunning;
1229 pthread_mutex_unlock(&bkts->work_q.mut);
1230
1231 file_write_entry_t *task;
1232 while (1) {
1233 task = NULL;
1234 pthread_mutex_lock(&bkts->work_q.mut);
1235 if (bkts->work_q.size == 0) {
1236 --bkts->wrkrRunning;
1237 if (bkts->wrkrTermState == 1) {
1238 pthread_mutex_unlock(&bkts->work_q.mut);
1239 break;
1240 } else {
1241 DBGPRINTF("dynstats: worker %llu waiting on new work items\n", (unsigned long long)bkts->wrkrInfo.tid);
1242 pthread_cond_wait(&bkts->work_q.wakeup_worker, &bkts->work_q.mut);
1243 DBGPRINTF("dynstats: worker %llu awoken\n", (unsigned long long)bkts->wrkrInfo.tid);
1244 /* Check termination flag after waking up */
1245 if (bkts->wrkrTermState == 1) {
1246 pthread_mutex_unlock(&bkts->work_q.mut);
1247 break;
1248 }
1249 }
1250 ++bkts->wrkrRunning;
1251 }
1252 if (bkts->work_q.size > 0) {
1253 task = STAILQ_FIRST(&bkts->work_q.q);
1254 STAILQ_REMOVE_HEAD(&bkts->work_q.q, link);
1255 bkts->work_q.size--;
1256 }
1257 pthread_mutex_unlock(&bkts->work_q.mut);
1258
1259 if (task != NULL) {
1260 processWorkItem(task);
1261 destroyFileWriteTask(task);
1262 }
1263 }
1264 return NULL;
1265 }
1266
1267 static rsRetVal initFileWriteWorker(dynstats_buckets_t *bkts) {
1268 DEFiRet;
1269 CHKiConcCtrl(pthread_mutex_init(&bkts->work_q.mut, NULL));
1270 CHKiConcCtrl(pthread_cond_init(&bkts->work_q.wakeup_worker, NULL));
1271 STAILQ_INIT(&bkts->work_q.q);
1272 bkts->work_q.size = 0;
1273 bkts->work_q.ctrMaxSz = 0;
1274 CHKiRet(statsobj.Construct(&bkts->work_q.stats));
1275 CHKiRet(statsobj.SetName(bkts->work_q.stats, (uchar *)"file-write-worker"));
1276 CHKiRet(statsobj.SetOrigin(bkts->work_q.stats, (uchar *)"dynstats"));
1277 STATSCOUNTER_INIT(bkts->work_q.ctrEnq, bkts->work_q.mutCtrEnq);
1278 CHKiRet(statsobj.AddCounter(bkts->work_q.stats, UCHAR_CONSTANT("enqueued"), ctrType_IntCtr, CTR_FLAG_RESETTABLE,
1279 &bkts->work_q.ctrEnq));
1280 CHKiRet(statsobj.AddCounter(bkts->work_q.stats, UCHAR_CONSTANT("maxqsize"), ctrType_Int, CTR_FLAG_NONE,
1281 &bkts->work_q.ctrMaxSz));
1282 CHKiRet(statsobj.ConstructFinalize(bkts->work_q.stats));
1283 finalize_it:
1284 RETiRet;
1285 }
1286
1287 static void ATTR_NONNULL(1) destroyFileWriteWorker(dynstats_buckets_t *bkts) {
1288 file_write_entry_t *task;
1289 if (bkts->work_q.stats != NULL) {
1290 statsobj.Destruct(&bkts->work_q.stats);
1291 }
1292 pthread_mutex_lock(&bkts->work_q.mut);
1293 while (!STAILQ_EMPTY(&bkts->work_q.q)) {
1294 task = STAILQ_FIRST(&bkts->work_q.q);
1295 STAILQ_REMOVE_HEAD(&bkts->work_q.q, link);
1296 LogError(0, RS_RET_INTERNAL_ERROR,
1297 "dynstats: discarded enqueued io-work to allow shutdown "
1298 "- ignored");
1299 destroyFileWriteTask(task);
1300 }
1301 bkts->work_q.size = 0;
1302 pthread_mutex_unlock(&bkts->work_q.mut);
1303 pthread_cond_destroy(&bkts->work_q.wakeup_worker);
1304 pthread_mutex_destroy(&bkts->work_q.mut);
1305 }
1306
1307 static rsRetVal ATTR_NONNULL(1) enqueueFileWriteTask(dynstats_bucket_t *b, const char *file_name, const char *content) {
1308 file_write_entry_t *task;
1309 dynstats_buckets_t *bkts;
1310 DEFiRet;
1311
1312 assert(b != NULL);
1313 bkts = b->bkts;
1314 if (!bkts) {
1315 FINALIZE;
1316 }
1317
1318 CHKmalloc(task = malloc(sizeof(file_write_entry_t)));
1319 task->bucket = b;
1320 task->name = strdup(file_name);
1321 task->content = strdup(content);
1322
1323 if (task->name == NULL || task->content == NULL) {
1324 if (task->name) free((void *)task->name);
1325 if (task->content) free((void *)task->content);
1326 free(task);
1327 task =
1328 NULL; /* Prevent double-free in error handler if it existed, though here finalize handles NULL task check */
1329 ABORT_FINALIZE(RS_RET_OUT_OF_MEMORY);
1330 }
1331
1332 pthread_mutex_lock(&bkts->work_q.mut);
1333 STAILQ_INSERT_TAIL(&bkts->work_q.q, task, link);
1334 bkts->work_q.size++;
1335 STATSCOUNTER_INC(bkts->work_q.ctrEnq, bkts->work_q.mutCtrEnq);
1336 STATSCOUNTER_SETMAX_NOMUT(bkts->work_q.ctrMaxSz, bkts->work_q.size);
1337 if (bkts->work_q.size == 1) {
1338 pthread_cond_signal(&bkts->work_q.wakeup_worker);
1339 }
1340 pthread_mutex_unlock(&bkts->work_q.mut);
1341
1342 finalize_it:
1343 if (iRet != RS_RET_OK) {
1344 if (task == NULL) {
1345 LogError(0, iRet, "dynstats: couldn't allocate memory to enqueue io-request - ignored");
1346 }
1347 }
1348 RETiRet;
1349 }
1350
1351 static void startFileWriteWorker(dynstats_buckets_t *bkts) {
1352 pthread_mutex_lock(&bkts->work_q.mut); /* locking to keep Coverity happy */
1353 if (bkts->wrkrStarted) {
1354 pthread_mutex_unlock(&bkts->work_q.mut);
1355 return;
1356 }
1357 bkts->wrkrRunning = 0;
1358 bkts->wrkrTermState = 0;
1359 bkts->wrkrStarted = 1;
1360 int ret = pthread_create(&bkts->wrkrInfo.tid, NULL, fileWriteWorker, bkts);
1361 if (ret != 0) {
1362 bkts->wrkrStarted = 0;
1363 pthread_mutex_unlock(&bkts->work_q.mut);
1364 LogError(ret, RS_RET_INTERNAL_ERROR, "dynstats: failed to create worker thread");
1365 return;
1366 }
1367 pthread_mutex_unlock(&bkts->work_q.mut);
1368 DBGPRINTF("dynstats: worker started tid: %llu workers\n", (unsigned long long)bkts->wrkrInfo.tid);
1369 }
1370
1371 static void ATTR_NONNULL(1) stopFileWriteWorker(dynstats_buckets_t *bkts) {
1372 DBGPRINTF("dynstats: stopping worker pool\n");
1373 pthread_mutex_lock(&bkts->work_q.mut);
1374 bkts->wrkrTermState = 1;
1375 pthread_cond_broadcast(&bkts->work_q.wakeup_worker); /* awake wrkr if not running */
1376 pthread_mutex_unlock(&bkts->work_q.mut);
1377 pthread_join(bkts->wrkrInfo.tid, NULL);
1378 DBGPRINTF("dynstats: info: worker stopped\n");
1379 }