suricata
counters.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2015 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Anoop Saldanha <anoopsaldanha@gmail.com>
22  * \author Victor Julien <victor@inliniac.net>
23  *
24  * Engine stats API
25  */
26 
27 #include "suricata-common.h"
28 #include "suricata.h"
29 #include "counters.h"
30 #include "threadvars.h"
31 #include "tm-threads.h"
32 #include "conf.h"
33 #include "util-time.h"
34 #include "util-unittest.h"
35 #include "util-debug.h"
36 #include "util-byte.h"
37 #include "util-privs.h"
38 #include "util-signal.h"
39 #include "unix-manager.h"
40 #include "runmodes.h"
41 
42 #include "output.h"
43 #include "output-stats.h"
44 #include "output-json-stats.h"
45 
46 /* Time interval for syncing the local counters with the global ones */
47 #define STATS_WUT_TTS 3
48 
49 /* Time interval at which the mgmt thread o/p the stats */
50 #define STATS_MGMTT_TTS 8
51 
52 /**
53  * \brief Different kinds of qualifier that can be used to modify the behaviour
54  * of the counter to be registered
55  */
56 enum {
61 
63 };
64 
65 /**
66  * \brief per thread store of counters
67  */
68 typedef struct StatsThreadStore_ {
69  /** thread name used in output */
70  const char *name;
71 
73 
75  uint32_t size;
76 
79 
80 /**
81  * \brief Holds the output interface context for the counter api
82  */
83 typedef struct StatsGlobalContext_ {
84  /** list of thread stores: one per thread plus one global */
87  int sts_cnt;
88 
90 
93 
94 static void *stats_thread_data = NULL;
95 static StatsGlobalContext *stats_ctx = NULL;
96 static time_t stats_start_time;
97 /** refresh interval in seconds */
98 static uint32_t stats_tts = STATS_MGMTT_TTS;
99 /** is the stats counter enabled? */
100 static char stats_enabled = TRUE;
101 
102 /**< add decoder events as stats? enabled by default */
104 const char *stats_decoder_events_prefix = "decoder.event";
105 /**< add stream events as stats? disabled by default */
106 bool stats_stream_events = false;
107 
108 static int StatsOutput(ThreadVars *tv);
109 static int StatsThreadRegister(const char *thread_name, StatsPublicThreadContext *);
111 
112 /** stats table is filled each interval and passed to the
113  * loggers. Initialized at first use. */
114 static StatsTable stats_table = { NULL, NULL, 0, 0, 0, {0 , 0}};
115 static SCMutex stats_table_mutex = SCMUTEX_INITIALIZER;
116 static int stats_loggers_active = 1;
117 
118 static uint16_t counters_global_id = 0;
119 
120 bool StatsEnabled(void)
121 {
122  return (stats_enabled == TRUE);
123 }
124 
125 static void StatsPublicThreadContextInit(StatsPublicThreadContext *t)
126 {
127  SCMutexInit(&t->m, NULL);
128 }
129 
130 static void StatsPublicThreadContextCleanup(StatsPublicThreadContext *t)
131 {
132  SCMutexLock(&t->m);
134  t->head = NULL;
135  t->perf_flag = 0;
136  t->curr_id = 0;
137  SCMutexUnlock(&t->m);
138  SCMutexDestroy(&t->m);
139 }
140 
141 /**
142  * \brief Adds a value of type uint64_t to the local counter.
143  *
144  * \param id ID of the counter as set by the API
145  * \param pca Counter array that holds the local counter for this TM
146  * \param x Value to add to this local counter
147  */
148 void StatsAddUI64(ThreadVars *tv, uint16_t id, uint64_t x)
149 {
151 #if defined (UNITTESTS) || defined (FUZZ)
152  if (pca->initialized == 0)
153  return;
154 #endif
155 #ifdef DEBUG
156  BUG_ON ((id < 1) || (id > pca->size));
157 #endif
158  pca->head[id].value += x;
159  pca->head[id].updates++;
160  return;
161 }
162 
163 /**
164  * \brief Increments the local counter
165  *
166  * \param id Index of the counter in the counter array
167  * \param pca Counter array that holds the local counters for this TM
168  */
169 void StatsIncr(ThreadVars *tv, uint16_t id)
170 {
172 #if defined (UNITTESTS) || defined (FUZZ)
173  if (pca->initialized == 0)
174  return;
175 #endif
176 #ifdef DEBUG
177  BUG_ON ((id < 1) || (id > pca->size));
178 #endif
179  pca->head[id].value++;
180  pca->head[id].updates++;
181  return;
182 }
183 
184 /**
185  * \brief Sets a value of type double to the local counter
186  *
187  * \param id Index of the local counter in the counter array
188  * \param pca Pointer to the StatsPrivateThreadContext
189  * \param x The value to set for the counter
190  */
191 void StatsSetUI64(ThreadVars *tv, uint16_t id, uint64_t x)
192 {
194 #if defined (UNITTESTS) || defined (FUZZ)
195  if (pca->initialized == 0)
196  return;
197 #endif
198 #ifdef DEBUG
199  BUG_ON ((id < 1) || (id > pca->size));
200 #endif
201 
202  if ((pca->head[id].pc->type == STATS_TYPE_MAXIMUM) &&
203  (x > pca->head[id].value)) {
204  pca->head[id].value = x;
205  } else if (pca->head[id].pc->type == STATS_TYPE_NORMAL) {
206  pca->head[id].value = x;
207  }
208 
209  pca->head[id].updates++;
210 
211  return;
212 }
213 
214 static ConfNode *GetConfig(void) {
215  ConfNode *stats = ConfGetNode("stats");
216  if (stats != NULL)
217  return stats;
218 
219  ConfNode *root = ConfGetNode("outputs");
220  ConfNode *node = NULL;
221  if (root != NULL) {
222  TAILQ_FOREACH(node, &root->head, next) {
223  if (strcmp(node->val, "stats") == 0) {
224  return node->head.tqh_first;
225  }
226  }
227  }
228  return NULL;
229 }
230 
231 /**
232  * \brief Initializes stats context
233  */
234 static void StatsInitCtxPreOutput(void)
235 {
236  SCEnter();
237  ConfNode *stats = GetConfig();
238  if (stats != NULL) {
239  const char *enabled = ConfNodeLookupChildValue(stats, "enabled");
240  if (enabled != NULL && ConfValIsFalse(enabled)) {
241  stats_enabled = FALSE;
242  SCLogDebug("Stats module has been disabled");
243  SCReturn;
244  }
245  /* warn if we are using legacy config to enable stats */
246  ConfNode *gstats = ConfGetNode("stats");
247  if (gstats == NULL) {
248  SCLogWarning(SC_ERR_STATS_LOG_GENERIC, "global stats config is missing. "
249  "Stats enabled through legacy stats.log. "
250  "See %s/configuration/suricata-yaml.html#stats", GetDocURL());
251  }
252 
253  const char *interval = ConfNodeLookupChildValue(stats, "interval");
254  if (interval != NULL)
255  if (StringParseUint32(&stats_tts, 10, 0, interval) < 0) {
256  SCLogWarning(SC_ERR_INVALID_VALUE, "Invalid value for "
257  "interval: \"%s\". Resetting to %d.", interval,
259  stats_tts = STATS_MGMTT_TTS;
260  }
261 
262  int b;
263  int ret = ConfGetChildValueBool(stats, "decoder-events", &b);
264  if (ret) {
265  stats_decoder_events = (b == 1);
266  }
267  ret = ConfGetChildValueBool(stats, "stream-events", &b);
268  if (ret) {
269  stats_stream_events = (b == 1);
270  }
271 
272  const char *prefix = NULL;
273  if (ConfGet("stats.decoder-events-prefix", &prefix) != 1) {
274  prefix = "decoder.event";
275  }
277  }
278  SCReturn;
279 }
280 
281 static void StatsInitCtxPostOutput(void)
282 {
283  SCEnter();
284  /* Store the engine start time */
285  time(&stats_start_time);
286 
287  /* init the lock used by StatsThreadStore */
288  if (SCMutexInit(&stats_ctx->sts_lock, NULL) != 0) {
289  FatalError(SC_ERR_FATAL, "error initializing sts mutex");
290  }
291 
292  if (stats_enabled && !OutputStatsLoggersRegistered()) {
293  stats_loggers_active = 0;
294 
295  /* if the unix command socket is enabled we do the background
296  * stats sync just in case someone runs 'dump-counters' */
297  if (!ConfUnixSocketIsEnable()) {
298  SCLogWarning(SC_WARN_NO_STATS_LOGGERS, "stats are enabled but no loggers are active");
299  stats_enabled = FALSE;
300  SCReturn;
301  }
302  }
303 
304  SCReturn;
305 }
306 
307 /**
308  * \brief Releases the resources alloted to the output context of the
309  * Stats API
310  */
311 static void StatsReleaseCtx(void)
312 {
313  if (stats_ctx == NULL) {
314  SCLogDebug("Counter module has been disabled");
315  return;
316  }
317 
318  StatsThreadStore *sts = NULL;
319  StatsThreadStore *temp = NULL;
320  sts = stats_ctx->sts;
321 
322  while (sts != NULL) {
323  if (sts->head != NULL)
324  SCFree(sts->head);
325 
326  temp = sts->next;
327  SCFree(sts);
328  sts = temp;
329  }
330 
331  if (stats_ctx->counters_id_hash != NULL) {
332  HashTableFree(stats_ctx->counters_id_hash);
333  stats_ctx->counters_id_hash = NULL;
334  counters_global_id = 0;
335  }
336 
337  StatsPublicThreadContextCleanup(&stats_ctx->global_counter_ctx);
338  SCFree(stats_ctx);
339  stats_ctx = NULL;
340 
341  SCMutexLock(&stats_table_mutex);
342  /* free stats table */
343  if (stats_table.tstats != NULL) {
344  SCFree(stats_table.tstats);
345  stats_table.tstats = NULL;
346  }
347 
348  if (stats_table.stats != NULL) {
349  SCFree(stats_table.stats);
350  stats_table.stats = NULL;
351  }
352  memset(&stats_table, 0, sizeof(stats_table));
353  SCMutexUnlock(&stats_table_mutex);
354 
355  return;
356 }
357 
358 /**
359  * \brief management thread. This thread is responsible for writing the stats
360  *
361  * \param arg thread var
362  *
363  * \retval NULL This is the value that is always returned
364  */
365 static void *StatsMgmtThread(void *arg)
366 {
367  ThreadVars *tv_local = (ThreadVars *)arg;
368 
369  /* Set the thread name */
370  if (SCSetThreadName(tv_local->name) < 0) {
371  SCLogWarning(SC_ERR_THREAD_INIT, "Unable to set thread name");
372  }
373 
374  if (tv_local->thread_setup_flags != 0)
375  TmThreadSetupOptions(tv_local);
376 
377  /* Set the threads capability */
378  tv_local->cap_flags = 0;
379  SCDropCaps(tv_local);
380 
381  if (stats_ctx == NULL) {
382  SCLogError(SC_ERR_STATS_NOT_INIT, "Stats API not init"
383  "StatsInitCounterApi() has to be called first");
385  return NULL;
386  }
387 
389  BUG_ON(tm->ThreadInit == NULL);
390  int r = tm->ThreadInit(tv_local, NULL, &stats_thread_data);
391  if (r != 0 || stats_thread_data == NULL) {
392  SCLogError(SC_ERR_THREAD_INIT, "Stats API "
393  "ThreadInit failed");
395  return NULL;
396  }
397  SCLogDebug("stats_thread_data %p", &stats_thread_data);
398 
399  TmThreadsSetFlag(tv_local, THV_INIT_DONE);
400  while (1) {
401  if (TmThreadsCheckFlag(tv_local, THV_PAUSE)) {
402  TmThreadsSetFlag(tv_local, THV_PAUSED);
403  TmThreadTestThreadUnPaused(tv_local);
404  TmThreadsUnsetFlag(tv_local, THV_PAUSED);
405  }
406 
407  struct timeval cur_timev;
408  gettimeofday(&cur_timev, NULL);
409  struct timespec cond_time = FROM_TIMEVAL(cur_timev);
410  cond_time.tv_sec += (stats_tts);
411 
412  /* wait for the set time, or until we are woken up by
413  * the shutdown procedure */
414  SCCtrlMutexLock(tv_local->ctrl_mutex);
415  SCCtrlCondTimedwait(tv_local->ctrl_cond, tv_local->ctrl_mutex, &cond_time);
416  SCCtrlMutexUnlock(tv_local->ctrl_mutex);
417 
418  SCMutexLock(&stats_table_mutex);
419  StatsOutput(tv_local);
420  SCMutexUnlock(&stats_table_mutex);
421 
422  if (TmThreadsCheckFlag(tv_local, THV_KILL)) {
423  break;
424  }
425  }
426 
428  TmThreadWaitForFlag(tv_local, THV_DEINIT);
429 
430  r = tm->ThreadDeinit(tv_local, stats_thread_data);
431  if (r != TM_ECODE_OK) {
432  SCLogError(SC_ERR_THREAD_DEINIT, "Stats Counter API "
433  "ThreadDeinit failed");
434  }
435 
436  TmThreadsSetFlag(tv_local, THV_CLOSED);
437  return NULL;
438 }
439 
440 /**
441  * \brief Wake up thread. This thread wakes up every TTS(time to sleep) seconds
442  * and sets the flag for every ThreadVars' StatsPublicThreadContext
443  *
444  * \param arg is NULL always
445  *
446  * \retval NULL This is the value that is always returned
447  */
448 static void *StatsWakeupThread(void *arg)
449 {
450  ThreadVars *tv_local = (ThreadVars *)arg;
451 
452  /* Set the thread name */
453  if (SCSetThreadName(tv_local->name) < 0) {
454  SCLogWarning(SC_ERR_THREAD_INIT, "Unable to set thread name");
455  }
456 
457  if (tv_local->thread_setup_flags != 0)
458  TmThreadSetupOptions(tv_local);
459 
460  /* Set the threads capability */
461  tv_local->cap_flags = 0;
462  SCDropCaps(tv_local);
463 
464  if (stats_ctx == NULL) {
465  SCLogError(SC_ERR_STATS_NOT_INIT, "Stats API not init"
466  "StatsInitCounterApi() has to be called first");
468  return NULL;
469  }
470 
471  TmThreadsSetFlag(tv_local, THV_INIT_DONE);
472  while (1) {
473  if (TmThreadsCheckFlag(tv_local, THV_PAUSE)) {
474  TmThreadsSetFlag(tv_local, THV_PAUSED);
475  TmThreadTestThreadUnPaused(tv_local);
476  TmThreadsUnsetFlag(tv_local, THV_PAUSED);
477  }
478 
479  struct timeval cur_timev;
480  gettimeofday(&cur_timev, NULL);
481  struct timespec cond_time = FROM_TIMEVAL(cur_timev);
482  cond_time.tv_sec += STATS_WUT_TTS;
483 
484  /* wait for the set time, or until we are woken up by
485  * the shutdown procedure */
486  SCCtrlMutexLock(tv_local->ctrl_mutex);
487  SCCtrlCondTimedwait(tv_local->ctrl_cond, tv_local->ctrl_mutex, &cond_time);
488  SCCtrlMutexUnlock(tv_local->ctrl_mutex);
489 
492  while (tv != NULL) {
493  if (tv->perf_public_ctx.head == NULL) {
494  tv = tv->next;
495  continue;
496  }
497 
498  /* assuming the assignment of an int to be atomic, and even if it's
499  * not, it should be okay */
501 
502  if (tv->inq != NULL) {
503  PacketQueue *q = tv->inq->pq;
504  SCCondSignal(&q->cond_q);
505  }
506 
507  tv = tv->next;
508  }
509 
510  /* mgt threads for flow manager */
511  tv = tv_root[TVT_MGMT];
512  while (tv != NULL) {
513  if (tv->perf_public_ctx.head == NULL) {
514  tv = tv->next;
515  continue;
516  }
517 
518  /* assuming the assignment of an int to be atomic, and even if it's
519  * not, it should be okay */
521 
522  tv = tv->next;
523  }
525 
526  if (TmThreadsCheckFlag(tv_local, THV_KILL)) {
527  break;
528  }
529  }
530 
532  TmThreadWaitForFlag(tv_local, THV_DEINIT);
533  TmThreadsSetFlag(tv_local, THV_CLOSED);
534  return NULL;
535 }
536 
537 /**
538  * \brief Releases a counter
539  *
540  * \param pc Pointer to the StatsCounter to be freed
541  */
542 static void StatsReleaseCounter(StatsCounter *pc)
543 {
544  if (pc != NULL) {
545  SCFree(pc);
546  }
547 
548  return;
549 }
550 
551 /**
552  * \brief Registers a counter.
553  *
554  * \param name Name of the counter, to be registered
555  * \param tm_name Thread module to which this counter belongs
556  * \param pctx StatsPublicThreadContext for this tm-tv instance
557  * \param type_q Qualifier describing the type of counter to be registered
558  *
559  * \retval the counter id for the newly registered counter, or the already
560  * present counter on success
561  * \retval 0 on failure
562  */
563 static uint16_t StatsRegisterQualifiedCounter(const char *name, const char *tm_name,
565  int type_q, uint64_t (*Func)(void))
566 {
567  StatsCounter **head = &pctx->head;
568  StatsCounter *temp = NULL;
569  StatsCounter *prev = NULL;
570  StatsCounter *pc = NULL;
571 
572  if (name == NULL || pctx == NULL) {
573  SCLogDebug("Counter name, StatsPublicThreadContext NULL");
574  return 0;
575  }
576 
577  temp = prev = *head;
578  while (temp != NULL) {
579  prev = temp;
580 
581  if (strcmp(name, temp->name) == 0) {
582  break;
583  }
584 
585  temp = temp->next;
586  }
587 
588  /* We already have a counter registered by this name */
589  if (temp != NULL)
590  return(temp->id);
591 
592  /* if we reach this point we don't have a counter registered by this name */
593  if ( (pc = SCMalloc(sizeof(StatsCounter))) == NULL)
594  return 0;
595  memset(pc, 0, sizeof(StatsCounter));
596 
597  /* assign a unique id to this StatsCounter. The id is local to this
598  * thread context. Please note that the id start from 1, and not 0 */
599  pc->id = ++(pctx->curr_id);
600  pc->name = name;
601  pc->type = type_q;
602  pc->Func = Func;
603 
604  /* we now add the counter to the list */
605  if (prev == NULL)
606  *head = pc;
607  else
608  prev->next = pc;
609 
610  return pc->id;
611 }
612 
613 /**
614  * \brief Copies the StatsCounter value from the local counter present in the
615  * StatsPrivateThreadContext to its corresponding global counterpart. Used
616  * internally by StatsUpdateCounterArray()
617  *
618  * \param pcae Pointer to the StatsPrivateThreadContext which holds the local
619  * versions of the counters
620  */
621 static void StatsCopyCounterValue(StatsLocalCounter *pcae)
622 {
623  StatsCounter *pc = pcae->pc;
624 
625  pc->value = pcae->value;
626  pc->updates = pcae->updates;
627  return;
628 }
629 
630 /**
631  * \brief The output interface for the Stats API
632  */
633 static int StatsOutput(ThreadVars *tv)
634 {
635  const StatsThreadStore *sts = NULL;
636  const StatsCounter *pc = NULL;
637  void *td = stats_thread_data;
638 
639  if (counters_global_id == 0)
640  return -1;
641 
642  if (stats_table.nstats == 0) {
643  StatsThreadRegister("Global", &stats_ctx->global_counter_ctx);
644 
645  uint32_t nstats = counters_global_id;
646 
647  stats_table.nstats = nstats;
648  stats_table.stats = SCCalloc(stats_table.nstats, sizeof(StatsRecord));
649  if (stats_table.stats == NULL) {
650  stats_table.nstats = 0;
651  SCLogError(SC_ERR_MEM_ALLOC, "could not alloc memory for stats");
652  return -1;
653  }
654 
655  stats_table.ntstats = stats_ctx->sts_cnt;
656  uint32_t array_size = stats_table.nstats * sizeof(StatsRecord);
657  stats_table.tstats = SCCalloc(stats_table.ntstats, array_size);
658  if (stats_table.tstats == NULL) {
659  stats_table.ntstats = 0;
660  SCLogError(SC_ERR_MEM_ALLOC, "could not alloc memory for stats");
661  return -1;
662  }
663 
664  stats_table.start_time = stats_start_time;
665  }
666 
667  const uint16_t max_id = counters_global_id;
668  if (max_id == 0)
669  return -1;
670 
671  /** temporary local table to merge the per thread counters,
672  * especially needed for the average counters */
673  struct CountersMergeTable {
674  int type;
675  uint64_t value;
676  uint64_t updates;
677  } merge_table[max_id];
678  memset(&merge_table, 0x00,
679  max_id * sizeof(struct CountersMergeTable));
680 
681  int thread = stats_ctx->sts_cnt - 1;
682  StatsRecord *table = stats_table.stats;
683 
684  /* Loop through the thread counter stores. The global counters
685  * are in a separate store inside this list. */
686  sts = stats_ctx->sts;
687  SCLogDebug("sts %p", sts);
688  while (sts != NULL) {
689  BUG_ON(thread < 0);
690 
691  SCLogDebug("Thread %d %s ctx %p", thread, sts->name, sts->ctx);
692 
693  /* temporary table for quickly storing the counters for this
694  * thread store, so that we can post process them outside
695  * of the thread store lock */
696  struct CountersMergeTable thread_table[max_id];
697  memset(&thread_table, 0x00,
698  max_id * sizeof(struct CountersMergeTable));
699 
700  SCMutexLock(&sts->ctx->m);
701  pc = sts->ctx->head;
702  while (pc != NULL) {
703  SCLogDebug("Counter %s (%u:%u) value %"PRIu64,
704  pc->name, pc->id, pc->gid, pc->value);
705 
706  thread_table[pc->gid].type = pc->type;
707  switch (pc->type) {
708  case STATS_TYPE_FUNC:
709  if (pc->Func != NULL)
710  thread_table[pc->gid].value = pc->Func();
711  break;
712  case STATS_TYPE_AVERAGE:
713  default:
714  thread_table[pc->gid].value = pc->value;
715  break;
716  }
717  thread_table[pc->gid].updates = pc->updates;
718  table[pc->gid].name = pc->name;
719 
720  pc = pc->next;
721  }
722  SCMutexUnlock(&sts->ctx->m);
723 
724  /* update merge table */
725  for (uint16_t c = 0; c < max_id; c++) {
726  struct CountersMergeTable *e = &thread_table[c];
727  /* thread only sets type if it has a counter
728  * of this type. */
729  if (e->type == 0)
730  continue;
731 
732  switch (e->type) {
733  case STATS_TYPE_MAXIMUM:
734  if (e->value > merge_table[c].value)
735  merge_table[c].value = e->value;
736  break;
737  case STATS_TYPE_FUNC:
738  merge_table[c].value = e->value;
739  break;
740  case STATS_TYPE_AVERAGE:
741  default:
742  merge_table[c].value += e->value;
743  break;
744  }
745  merge_table[c].updates += e->updates;
746  merge_table[c].type = e->type;
747  }
748 
749  /* update per thread stats table */
750  for (uint16_t c = 0; c < max_id; c++) {
751  struct CountersMergeTable *e = &thread_table[c];
752  /* thread only sets type if it has a counter
753  * of this type. */
754  if (e->type == 0)
755  continue;
756 
757  uint32_t offset = (thread * stats_table.nstats) + c;
758  StatsRecord *r = &stats_table.tstats[offset];
759  /* xfer previous value to pvalue and reset value */
760  r->pvalue = r->value;
761  r->value = 0;
762  r->name = table[c].name;
763  r->tm_name = sts->name;
764 
765  switch (e->type) {
766  case STATS_TYPE_AVERAGE:
767  if (e->value > 0 && e->updates > 0) {
768  r->value = (uint64_t)(e->value / e->updates);
769  }
770  break;
771  default:
772  r->value = e->value;
773  break;
774  }
775  }
776 
777  sts = sts->next;
778  thread--;
779  }
780 
781  /* transfer 'merge table' to final stats table */
782  for (uint16_t x = 0; x < max_id; x++) {
783  /* xfer previous value to pvalue and reset value */
784  table[x].pvalue = table[x].value;
785  table[x].value = 0;
786  table[x].tm_name = "Total";
787 
788  struct CountersMergeTable *m = &merge_table[x];
789  switch (m->type) {
790  case STATS_TYPE_MAXIMUM:
791  if (m->value > table[x].value)
792  table[x].value = m->value;
793  break;
794  case STATS_TYPE_AVERAGE:
795  if (m->value > 0 && m->updates > 0) {
796  table[x].value = (uint64_t)(m->value / m->updates);
797  }
798  break;
799  default:
800  table[x].value += m->value;
801  break;
802  }
803  }
804 
805  /* invoke logger(s) */
806  if (stats_loggers_active) {
807  OutputStatsLog(tv, td, &stats_table);
808  }
809  return 1;
810 }
811 
812 #ifdef BUILD_UNIX_SOCKET
813 /** \brief callback for getting stats into unix socket
814  */
815 TmEcode StatsOutputCounterSocket(json_t *cmd,
816  json_t *answer, void *data)
817 {
818  json_t *message = NULL;
819  TmEcode r = TM_ECODE_OK;
820 
821  if (!stats_enabled) {
822  r = TM_ECODE_FAILED;
823  message = json_string("stats are disabled in the config");
824  } else {
825  SCMutexLock(&stats_table_mutex);
826  if (stats_table.start_time == 0) {
827  r = TM_ECODE_FAILED;
828  message = json_string("stats not yet synchronized");
829  } else {
830  message = StatsToJSON(&stats_table, JSON_STATS_TOTALS|JSON_STATS_THREADS);
831  }
832  SCMutexUnlock(&stats_table_mutex);
833  }
834  json_object_set_new(answer, "message", message);
835  return r;
836 }
837 #endif /* BUILD_UNIX_SOCKET */
838 
839 static void StatsLogSummary(void)
840 {
841  uint64_t alerts = 0;
842  SCMutexLock(&stats_table_mutex);
843  if (stats_table.start_time != 0) {
844  const StatsTable *st = &stats_table;
845  for (uint32_t u = 0; u < st->nstats; u++) {
846  const char *name = st->stats[u].name;
847  if (name == NULL || strcmp(name, "detect.alert") != 0)
848  continue;
849  alerts = st->stats[u].value;
850  break;
851  }
852  }
853  SCMutexUnlock(&stats_table_mutex);
854  SCLogInfo("Alerts: %"PRIu64, alerts);
855 }
856 
857 /**
858  * \brief Initializes the perf counter api. Things are hard coded currently.
859  * More work to be done when we implement multiple interfaces
860  */
861 void StatsInit(void)
862 {
863  BUG_ON(stats_ctx != NULL);
864  if ( (stats_ctx = SCMalloc(sizeof(StatsGlobalContext))) == NULL) {
866  "Fatal error encountered in StatsInitCtx. Exiting...");
867  }
868  memset(stats_ctx, 0, sizeof(StatsGlobalContext));
869 
870  StatsPublicThreadContextInit(&stats_ctx->global_counter_ctx);
871 }
872 
874 {
875  StatsInitCtxPreOutput();
876 }
877 
879 {
880  StatsInitCtxPostOutput();
881 }
882 
883 
884 /**
885  * \brief Spawns the wakeup, and the management thread used by the stats api
886  *
887  * The threads use the condition variable in the thread vars to control
888  * their wait loops to make sure the main thread can quickly kill them.
889  */
891 {
892  SCEnter();
893 
894  if (!stats_enabled) {
895  SCReturn;
896  }
897 
898  ThreadVars *tv_wakeup = NULL;
899  ThreadVars *tv_mgmt = NULL;
900 
901  /* spawn the stats wakeup thread */
903  StatsWakeupThread, 1);
904  if (tv_wakeup == NULL) {
905  FatalError(SC_ERR_FATAL, "TmThreadCreateMgmtThread "
906  "failed");
907  }
908 
909  if (TmThreadSpawn(tv_wakeup) != 0) {
910  FatalError(SC_ERR_FATAL, "TmThreadSpawn failed for "
911  "StatsWakeupThread");
912  }
913 
914  /* spawn the stats mgmt thread */
916  StatsMgmtThread, 1);
917  if (tv_mgmt == NULL) {
918  FatalError(SC_ERR_FATAL, "TmThreadCreateMgmtThread failed");
919  }
920 
921  if (TmThreadSpawn(tv_mgmt) != 0) {
922  FatalError(SC_ERR_FATAL, "TmThreadSpawn failed for "
923  "StatsWakeupThread");
924  }
925 
926  SCReturn;
927 }
928 
929 /**
930  * \brief Registers a normal, unqualified counter
931  *
932  * \param name Name of the counter, to be registered
933  * \param tv Pointer to the ThreadVars instance for which the counter would
934  * be registered
935  *
936  * \retval id Counter id for the newly registered counter, or the already
937  * present counter
938  */
939 uint16_t StatsRegisterCounter(const char *name, struct ThreadVars_ *tv)
940 {
941  uint16_t id = StatsRegisterQualifiedCounter(name,
944  STATS_TYPE_NORMAL, NULL);
945  return id;
946 }
947 
948 /**
949  * \brief Registers a counter, whose value holds the average of all the values
950  * assigned to it.
951  *
952  * \param name Name of the counter, to be registered
953  * \param tv Pointer to the ThreadVars instance for which the counter would
954  * be registered
955  *
956  * \retval id Counter id for the newly registered counter, or the already
957  * present counter
958  */
959 uint16_t StatsRegisterAvgCounter(const char *name, struct ThreadVars_ *tv)
960 {
961  uint16_t id = StatsRegisterQualifiedCounter(name,
964  STATS_TYPE_AVERAGE, NULL);
965  return id;
966 }
967 
968 /**
969  * \brief Registers a counter, whose value holds the maximum of all the values
970  * assigned to it.
971  *
972  * \param name Name of the counter, to be registered
973  * \param tv Pointer to the ThreadVars instance for which the counter would
974  * be registered
975  *
976  * \retval the counter id for the newly registered counter, or the already
977  * present counter
978  */
979 uint16_t StatsRegisterMaxCounter(const char *name, struct ThreadVars_ *tv)
980 {
981  uint16_t id = StatsRegisterQualifiedCounter(name,
984  STATS_TYPE_MAXIMUM, NULL);
985  return id;
986 }
987 
988 /**
989  * \brief Registers a counter, which represents a global value
990  *
991  * \param name Name of the counter, to be registered
992  * \param Func Function Pointer returning a uint64_t
993  *
994  * \retval id Counter id for the newly registered counter, or the already
995  * present counter
996  */
997 uint16_t StatsRegisterGlobalCounter(const char *name, uint64_t (*Func)(void))
998 {
999 #if defined (UNITTESTS) || defined (FUZZ)
1000  if (stats_ctx == NULL)
1001  return 0;
1002 #else
1003  BUG_ON(stats_ctx == NULL);
1004 #endif
1005  uint16_t id = StatsRegisterQualifiedCounter(name, NULL,
1006  &(stats_ctx->global_counter_ctx),
1008  Func);
1009  return id;
1010 }
1011 
1012 typedef struct CountersIdType_ {
1013  uint16_t id;
1014  const char *string;
1016 
1017 static uint32_t CountersIdHashFunc(HashTable *ht, void *data, uint16_t datalen)
1018 {
1019  CountersIdType *t = (CountersIdType *)data;
1020  uint32_t hash = 0;
1021  int len = strlen(t->string);
1022 
1023  for (int i = 0; i < len; i++)
1024  hash += tolower((unsigned char)t->string[i]);
1025 
1026  hash = hash % ht->array_size;
1027  return hash;
1028 }
1029 
1030 static char CountersIdHashCompareFunc(void *data1, uint16_t datalen1,
1031  void *data2, uint16_t datalen2)
1032 {
1033  CountersIdType *t1 = (CountersIdType *)data1;
1034  CountersIdType *t2 = (CountersIdType *)data2;
1035  int len1 = 0;
1036  int len2 = 0;
1037 
1038  if (t1 == NULL || t2 == NULL)
1039  return 0;
1040 
1041  if (t1->string == NULL || t2->string == NULL)
1042  return 0;
1043 
1044  len1 = strlen(t1->string);
1045  len2 = strlen(t2->string);
1046 
1047  if (len1 == len2 && memcmp(t1->string, t2->string, len1) == 0) {
1048  return 1;
1049  }
1050 
1051  return 0;
1052 }
1053 
1054 static void CountersIdHashFreeFunc(void *data)
1055 {
1056  SCFree(data);
1057 }
1058 
1059 
1060 /** \internal
1061  * \brief Adds a TM to the clubbed TM table. Multiple instances of the same TM
1062  * are stacked together in a PCTMI container.
1063  *
1064  * \param tm_name Name of the tm to be added to the table
1065  * \param pctx StatsPublicThreadContext associated with the TM tm_name
1066  *
1067  * \retval 1 on success, 0 on failure
1068  */
1069 static int StatsThreadRegister(const char *thread_name, StatsPublicThreadContext *pctx)
1070 {
1071  if (stats_ctx == NULL) {
1072  SCLogDebug("Counter module has been disabled");
1073  return 0;
1074  }
1075 
1076  if (thread_name == NULL || pctx == NULL) {
1077  SCLogDebug("supplied argument(s) to StatsThreadRegister NULL");
1078  return 0;
1079  }
1080 
1081  SCMutexLock(&stats_ctx->sts_lock);
1082  if (stats_ctx->counters_id_hash == NULL) {
1083  stats_ctx->counters_id_hash = HashTableInit(256, CountersIdHashFunc,
1084  CountersIdHashCompareFunc,
1085  CountersIdHashFreeFunc);
1086  BUG_ON(stats_ctx->counters_id_hash == NULL);
1087  }
1088  StatsCounter *pc = pctx->head;
1089  while (pc != NULL) {
1090  CountersIdType t = { 0, pc->name }, *id = NULL;
1091  id = HashTableLookup(stats_ctx->counters_id_hash, &t, sizeof(t));
1092  if (id == NULL) {
1093  id = SCCalloc(1, sizeof(*id));
1094  BUG_ON(id == NULL);
1095  id->id = counters_global_id++;
1096  id->string = pc->name;
1097  BUG_ON(HashTableAdd(stats_ctx->counters_id_hash, id, sizeof(*id)) < 0);
1098  }
1099  pc->gid = id->id;
1100  pc = pc->next;
1101  }
1102 
1103 
1104  StatsThreadStore *temp = NULL;
1105  if ( (temp = SCMalloc(sizeof(StatsThreadStore))) == NULL) {
1106  SCMutexUnlock(&stats_ctx->sts_lock);
1107  return 0;
1108  }
1109  memset(temp, 0, sizeof(StatsThreadStore));
1110 
1111  temp->ctx = pctx;
1112  temp->name = thread_name;
1113 
1114  temp->next = stats_ctx->sts;
1115  stats_ctx->sts = temp;
1116  stats_ctx->sts_cnt++;
1117  SCLogDebug("stats_ctx->sts %p", stats_ctx->sts);
1118 
1119  SCMutexUnlock(&stats_ctx->sts_lock);
1120  return 1;
1121 }
1122 
1123 /** \internal
1124  * \brief Returns a counter array for counters in this id range(s_id - e_id)
1125  *
1126  * \param s_id Counter id of the first counter to be added to the array
1127  * \param e_id Counter id of the last counter to be added to the array
1128  * \param pctx Pointer to the tv's StatsPublicThreadContext
1129  *
1130  * \retval a counter-array in this(s_id-e_id) range for this TM instance
1131  */
1132 static int StatsGetCounterArrayRange(uint16_t s_id, uint16_t e_id,
1135 {
1136  StatsCounter *pc = NULL;
1137  uint32_t i = 0;
1138 
1139  if (pctx == NULL || pca == NULL) {
1140  SCLogDebug("pctx/pca is NULL");
1141  return -1;
1142  }
1143 
1144  if (s_id < 1 || e_id < 1 || s_id > e_id) {
1145  SCLogDebug("error with the counter ids");
1146  return -1;
1147  }
1148 
1149  if (e_id > pctx->curr_id) {
1150  SCLogDebug("end id is greater than the max id for this tv");
1151  return -1;
1152  }
1153 
1154  if ( (pca->head = SCMalloc(sizeof(StatsLocalCounter) * (e_id - s_id + 2))) == NULL) {
1155  return -1;
1156  }
1157  memset(pca->head, 0, sizeof(StatsLocalCounter) * (e_id - s_id + 2));
1158 
1159  pc = pctx->head;
1160  while (pc->id != s_id)
1161  pc = pc->next;
1162 
1163  i = 1;
1164  while ((pc != NULL) && (pc->id <= e_id)) {
1165  pca->head[i].pc = pc;
1166  pca->head[i].id = pc->id;
1167  pc = pc->next;
1168  i++;
1169  }
1170  pca->size = i - 1;
1171 
1172  pca->initialized = 1;
1173  return 0;
1174 }
1175 
1176 /** \internal
1177  * \brief Returns a counter array for all counters registered for this tm
1178  * instance
1179  *
1180  * \param pctx Pointer to the tv's StatsPublicThreadContext
1181  *
1182  * \retval pca Pointer to a counter-array for all counter of this tm instance
1183  * on success; NULL on failure
1184  */
1185 static int StatsGetAllCountersArray(StatsPublicThreadContext *pctx, StatsPrivateThreadContext *private)
1186 {
1187  if (pctx == NULL || private == NULL)
1188  return -1;
1189 
1190  return StatsGetCounterArrayRange(1, pctx->curr_id, pctx, private);
1191 }
1192 
1193 
1195 {
1196  StatsGetAllCountersArray(&(tv)->perf_public_ctx, &(tv)->perf_private_ctx);
1197 
1198  StatsThreadRegister(tv->printable_name ? tv->printable_name : tv->name,
1199  &(tv)->perf_public_ctx);
1200  return 0;
1201 }
1202 
1203 /**
1204  * \brief the private stats store with the public stats store
1205  *
1206  * \param pca Pointer to the StatsPrivateThreadContext
1207  * \param pctx Pointer the the tv's StatsPublicThreadContext
1208  *
1209  * \retval 1 on success
1210  * \retval -1 on error
1211  */
1213 {
1214 
1215  if (pca == NULL || pctx == NULL) {
1216  SCLogDebug("pca or pctx is NULL inside StatsUpdateCounterArray");
1217  return -1;
1218  }
1219 
1220  SCMutexLock(&pctx->m);
1221  StatsLocalCounter *pcae = pca->head;
1222  for (uint32_t i = 1; i <= pca->size; i++) {
1223  StatsCopyCounterValue(&pcae[i]);
1224  }
1225  SCMutexUnlock(&pctx->m);
1226 
1227  pctx->perf_flag = 0;
1228  return 1;
1229 }
1230 
1231 /**
1232  * \brief Get the value of the local copy of the counter that hold this id.
1233  *
1234  * \param tv threadvars
1235  * \param id The counter id.
1236  *
1237  * \retval 0 on success.
1238  * \retval -1 on error.
1239  */
1240 uint64_t StatsGetLocalCounterValue(ThreadVars *tv, uint16_t id)
1241 {
1243 #ifdef DEBUG
1244  BUG_ON ((id < 1) || (id > pca->size));
1245 #endif
1246  return pca->head[id].value;
1247 }
1248 
1249 /**
1250  * \brief Releases the resources alloted by the Stats API
1251  */
1253 {
1254  StatsLogSummary();
1255  StatsReleaseCtx();
1256 }
1257 
1258 /**
1259  * \brief Releases counters
1260  *
1261  * \param head Pointer to the head of the list of perf counters that have to
1262  * be freed
1263  */
1265 {
1266  StatsCounter *pc = NULL;
1267 
1268  while (head != NULL) {
1269  pc = head;
1270  head = head->next;
1271  StatsReleaseCounter(pc);
1272  }
1273 }
1274 
1275 /** \internal
1276  * \brief Releases the StatsPrivateThreadContext allocated by the user,
1277  * for storing and updating local counter values
1278  *
1279  * \param pca Pointer to the StatsPrivateThreadContext
1280  */
1281 static void StatsReleasePrivateThreadContext(StatsPrivateThreadContext *pca)
1282 {
1283  if (pca != NULL) {
1284  if (pca->head != NULL) {
1285  SCFree(pca->head);
1286  pca->head = NULL;
1287  pca->size = 0;
1288  }
1289  pca->initialized = 0;
1290  }
1291 }
1292 
1294 {
1295  StatsPublicThreadContextCleanup(&tv->perf_public_ctx);
1296  StatsReleasePrivateThreadContext(&tv->perf_private_ctx);
1297 }
1298 
1299 /*----------------------------------Unit_Tests--------------------------------*/
1300 
1301 #ifdef UNITTESTS
1302 /** \internal
1303  * \brief Registers a normal, unqualified counter
1304  *
1305  * \param name Name of the counter, to be registered
1306  * \param tm_name Name of the engine module under which the counter has to be
1307  * registered
1308  * \param type Datatype of this counter variable
1309  * \param pctx StatsPublicThreadContext corresponding to the tm_name key under which the
1310  * key has to be registered
1311  *
1312  * \retval id Counter id for the newly registered counter, or the already
1313  * present counter
1314  */
1315 static uint16_t RegisterCounter(const char *name, const char *tm_name,
1317 {
1318  uint16_t id = StatsRegisterQualifiedCounter(name, tm_name, pctx,
1319  STATS_TYPE_NORMAL, NULL);
1320  return id;
1321 }
1322 
1323 static int StatsTestCounterReg02(void)
1324 {
1326 
1327  memset(&pctx, 0, sizeof(StatsPublicThreadContext));
1328 
1329  return RegisterCounter(NULL, NULL, &pctx) == 0;
1330 }
1331 
1332 static int StatsTestCounterReg03(void)
1333 {
1335  int result;
1336 
1337  memset(&pctx, 0, sizeof(StatsPublicThreadContext));
1338 
1339  result = RegisterCounter("t1", "c1", &pctx);
1340 
1341  StatsReleaseCounters(pctx.head);
1342 
1343  return result;
1344 }
1345 
1346 static int StatsTestCounterReg04(void)
1347 {
1349  int result;
1350 
1351  memset(&pctx, 0, sizeof(StatsPublicThreadContext));
1352 
1353  RegisterCounter("t1", "c1", &pctx);
1354  RegisterCounter("t2", "c2", &pctx);
1355  RegisterCounter("t3", "c3", &pctx);
1356 
1357  result = RegisterCounter("t1", "c1", &pctx);
1358 
1359  StatsReleaseCounters(pctx.head);
1360 
1361  return result;
1362 }
1363 
1364 static int StatsTestGetCntArray05(void)
1365 {
1366  ThreadVars tv;
1367  int id;
1368 
1369  memset(&tv, 0, sizeof(ThreadVars));
1370 
1371  id = RegisterCounter("t1", "c1", &tv.perf_public_ctx);
1372  if (id != 1) {
1373  printf("id %d: ", id);
1374  return 0;
1375  }
1376 
1377  int r = StatsGetAllCountersArray(NULL, &tv.perf_private_ctx);
1378  return (r == -1) ? 1 : 0;
1379 }
1380 
1381 static int StatsTestGetCntArray06(void)
1382 {
1383  ThreadVars tv;
1384  int id;
1385  int result;
1386 
1387  memset(&tv, 0, sizeof(ThreadVars));
1388 
1389  id = RegisterCounter("t1", "c1", &tv.perf_public_ctx);
1390  if (id != 1)
1391  return 0;
1392 
1393  int r = StatsGetAllCountersArray(&tv.perf_public_ctx, &tv.perf_private_ctx);
1394 
1395  result = (r == 0) ? 1 : 0;
1396 
1398  StatsReleasePrivateThreadContext(&tv.perf_private_ctx);
1399 
1400  return result;
1401 }
1402 
1403 static int StatsTestCntArraySize07(void)
1404 {
1405  ThreadVars tv;
1406  StatsPrivateThreadContext *pca = NULL;
1407  int result;
1408 
1409  memset(&tv, 0, sizeof(ThreadVars));
1410 
1411  //pca = (StatsPrivateThreadContext *)&tv.perf_private_ctx;
1412 
1413  RegisterCounter("t1", "c1", &tv.perf_public_ctx);
1414  RegisterCounter("t2", "c2", &tv.perf_public_ctx);
1415 
1416  StatsGetAllCountersArray(&tv.perf_public_ctx, &tv.perf_private_ctx);
1417  pca = &tv.perf_private_ctx;
1418 
1419  StatsIncr(&tv, 1);
1420  StatsIncr(&tv, 2);
1421 
1422  result = pca->size;
1423 
1425  StatsReleasePrivateThreadContext(pca);
1426 
1427  PASS_IF(result == 2);
1428 }
1429 
1430 static int StatsTestUpdateCounter08(void)
1431 {
1432  ThreadVars tv;
1433  StatsPrivateThreadContext *pca = NULL;
1434  int id;
1435  int result;
1436 
1437  memset(&tv, 0, sizeof(ThreadVars));
1438 
1439  id = RegisterCounter("t1", "c1", &tv.perf_public_ctx);
1440 
1441  StatsGetAllCountersArray(&tv.perf_public_ctx, &tv.perf_private_ctx);
1442  pca = &tv.perf_private_ctx;
1443 
1444  StatsIncr(&tv, id);
1445  StatsAddUI64(&tv, id, 100);
1446 
1447  result = pca->head[id].value;
1448 
1450  StatsReleasePrivateThreadContext(pca);
1451 
1452  return result == 101;
1453 }
1454 
1455 static int StatsTestUpdateCounter09(void)
1456 {
1457  ThreadVars tv;
1458  StatsPrivateThreadContext *pca = NULL;
1459  uint16_t id1, id2;
1460  int result;
1461 
1462  memset(&tv, 0, sizeof(ThreadVars));
1463 
1464  id1 = RegisterCounter("t1", "c1", &tv.perf_public_ctx);
1465  RegisterCounter("t2", "c2", &tv.perf_public_ctx);
1466  RegisterCounter("t3", "c3", &tv.perf_public_ctx);
1467  RegisterCounter("t4", "c4", &tv.perf_public_ctx);
1468  id2 = RegisterCounter("t5", "c5", &tv.perf_public_ctx);
1469 
1470  StatsGetAllCountersArray(&tv.perf_public_ctx, &tv.perf_private_ctx);
1471  pca = &tv.perf_private_ctx;
1472 
1473  StatsIncr(&tv, id2);
1474  StatsAddUI64(&tv, id2, 100);
1475 
1476  result = (pca->head[id1].value == 0) && (pca->head[id2].value == 101);
1477 
1479  StatsReleasePrivateThreadContext(pca);
1480 
1481  return result;
1482 }
1483 
1484 static int StatsTestUpdateGlobalCounter10(void)
1485 {
1486  ThreadVars tv;
1487  StatsPrivateThreadContext *pca = NULL;
1488 
1489  int result = 1;
1490  uint16_t id1, id2, id3;
1491 
1492  memset(&tv, 0, sizeof(ThreadVars));
1493 
1494  id1 = RegisterCounter("t1", "c1", &tv.perf_public_ctx);
1495  id2 = RegisterCounter("t2", "c2", &tv.perf_public_ctx);
1496  id3 = RegisterCounter("t3", "c3", &tv.perf_public_ctx);
1497 
1498  StatsGetAllCountersArray(&tv.perf_public_ctx, &tv.perf_private_ctx);
1499  pca = &tv.perf_private_ctx;
1500 
1501  StatsIncr(&tv, id1);
1502  StatsAddUI64(&tv, id2, 100);
1503  StatsIncr(&tv, id3);
1504  StatsAddUI64(&tv, id3, 100);
1505 
1507 
1508  result = (1 == tv.perf_public_ctx.head->value);
1509  result &= (100 == tv.perf_public_ctx.head->next->value);
1510  result &= (101 == tv.perf_public_ctx.head->next->next->value);
1511 
1513  StatsReleasePrivateThreadContext(pca);
1514 
1515  return result;
1516 }
1517 
1518 static int StatsTestCounterValues11(void)
1519 {
1520  ThreadVars tv;
1521  StatsPrivateThreadContext *pca = NULL;
1522 
1523  int result = 1;
1524  uint16_t id1, id2, id3, id4;
1525 
1526  memset(&tv, 0, sizeof(ThreadVars));
1527 
1528  id1 = RegisterCounter("t1", "c1", &tv.perf_public_ctx);
1529  id2 = RegisterCounter("t2", "c2", &tv.perf_public_ctx);
1530  id3 = RegisterCounter("t3", "c3", &tv.perf_public_ctx);
1531  id4 = RegisterCounter("t4", "c4", &tv.perf_public_ctx);
1532 
1533  StatsGetAllCountersArray(&tv.perf_public_ctx, &tv.perf_private_ctx);
1534  pca = &tv.perf_private_ctx;
1535 
1536  StatsIncr(&tv, id1);
1537  StatsAddUI64(&tv, id2, 256);
1538  StatsAddUI64(&tv, id3, 257);
1539  StatsAddUI64(&tv, id4, 16843024);
1540 
1542 
1543  result &= (1 == tv.perf_public_ctx.head->value);
1544 
1545  result &= (256 == tv.perf_public_ctx.head->next->value);
1546 
1547  result &= (257 == tv.perf_public_ctx.head->next->next->value);
1548 
1549  result &= (16843024 == tv.perf_public_ctx.head->next->next->next->value);
1550 
1552  StatsReleasePrivateThreadContext(pca);
1553 
1554  return result;
1555 }
1556 
1557 #endif
1558 
1560 {
1561 #ifdef UNITTESTS
1562  UtRegisterTest("StatsTestCounterReg02", StatsTestCounterReg02);
1563  UtRegisterTest("StatsTestCounterReg03", StatsTestCounterReg03);
1564  UtRegisterTest("StatsTestCounterReg04", StatsTestCounterReg04);
1565  UtRegisterTest("StatsTestGetCntArray05", StatsTestGetCntArray05);
1566  UtRegisterTest("StatsTestGetCntArray06", StatsTestGetCntArray06);
1567  UtRegisterTest("StatsTestCntArraySize07", StatsTestCntArraySize07);
1568  UtRegisterTest("StatsTestUpdateCounter08", StatsTestUpdateCounter08);
1569  UtRegisterTest("StatsTestUpdateCounter09", StatsTestUpdateCounter09);
1570  UtRegisterTest("StatsTestUpdateGlobalCounter10",
1571  StatsTestUpdateGlobalCounter10);
1572  UtRegisterTest("StatsTestCounterValues11", StatsTestCounterValues11);
1573 #endif
1574 }
STATS_TYPE_FUNC
@ STATS_TYPE_FUNC
Definition: counters.c:60
util-byte.h
tm-threads.h
FROM_TIMEVAL
#define FROM_TIMEVAL(timev)
intialize a 'struct timespec' from a 'struct timeval'.
Definition: util-time.h:34
thread_name_counter_wakeup
const char * thread_name_counter_wakeup
Definition: runmodes.c:74
StatsTable_::ntstats
uint32_t ntstats
Definition: output-stats.h:40
len
uint8_t len
Definition: app-layer-dnp3.h:2
TmThreadSpawn
TmEcode TmThreadSpawn(ThreadVars *tv)
Spawns a thread associated with the ThreadVars instance tv.
Definition: tm-threads.c:1708
TmThreadSetupOptions
TmEcode TmThreadSetupOptions(ThreadVars *tv)
Set the thread options (cpu affinitythread). Priority should be already set by pthread_create.
Definition: tm-threads.c:876
StatsThreadStore_::size
uint32_t size
Definition: counters.c:75
StatsIncr
void StatsIncr(ThreadVars *tv, uint16_t id)
Increments the local counter.
Definition: counters.c:169
offset
uint64_t offset
Definition: util-streaming-buffer.h:0
ThreadVars_::name
char name[16]
Definition: threadvars.h:65
SC_ERR_INVALID_VALUE
@ SC_ERR_INVALID_VALUE
Definition: util-error.h:160
StatsThreadStore_
per thread store of counters
Definition: counters.c:68
StatsThreadStore_::head
StatsPublicThreadContext ** head
Definition: counters.c:74
ConfNode_::val
char * val
Definition: conf.h:34
StatsGlobalContext_
Holds the output interface context for the counter api.
Definition: counters.c:83
UtRegisterTest
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
Definition: util-unittest.c:103
StatsRecord
struct StatsRecord_ StatsRecord
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:298
TmThreadsSetFlag
void TmThreadsSetFlag(ThreadVars *tv, uint32_t flag)
Set a thread flag.
Definition: tm-threads.c:97
TVT_PPT
@ TVT_PPT
Definition: tm-threads-common.h:87
StatsSetupPostConfigPreOutput
void StatsSetupPostConfigPreOutput(void)
Definition: counters.c:873
TmThreadWaitForFlag
void TmThreadWaitForFlag(ThreadVars *tv, uint32_t flags)
Waits till the specified flag(s) is(are) set. We don't bother if the kill flag has been set or not on...
Definition: tm-threads.c:1807
StatsRegisterGlobalCounter
uint16_t StatsRegisterGlobalCounter(const char *name, uint64_t(*Func)(void))
Registers a counter, which represents a global value.
Definition: counters.c:997
STATS_MGMTT_TTS
#define STATS_MGMTT_TTS
Definition: counters.c:50
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
StatsCounter_::type
int type
Definition: counters.h:35
stats_stream_events
bool stats_stream_events
Definition: counters.c:106
PacketQueue_
simple fifo queue for packets with mutex and cond Calling the mutex or triggering the cond is respons...
Definition: packet-queue.h:47
TMM_STATSLOGGER
@ TMM_STATSLOGGER
Definition: tm-threads-common.h:61
THV_DEINIT
#define THV_DEINIT
Definition: threadvars.h:46
ConfGetNode
ConfNode * ConfGetNode(const char *name)
Get a ConfNode by name.
Definition: conf.c:175
CountersIdType
struct CountersIdType_ CountersIdType
StatsCounter_
Container to hold the counter variable.
Definition: counters.h:34
thread_name_counter_stats
const char * thread_name_counter_stats
Definition: runmodes.c:73
Tmq_::pq
PacketQueue * pq
Definition: tm-queues.h:35
SCSetThreadName
#define SCSetThreadName(n)
Definition: threads.h:303
StatsRecord_
Definition: output-stats.h:29
StatsCounter_::updates
uint64_t updates
Definition: counters.h:45
SC_WARN_NO_STATS_LOGGERS
@ SC_WARN_NO_STATS_LOGGERS
Definition: util-error.h:293
StatsSetUI64
void StatsSetUI64(ThreadVars *tv, uint16_t id, uint64_t x)
Sets a value of type double to the local counter.
Definition: counters.c:191
StatsCounter_::name
const char * name
Definition: counters.h:52
TAILQ_FOREACH
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:350
StatsSetupPrivate
int StatsSetupPrivate(ThreadVars *tv)
Definition: counters.c:1194
StatsRecord_::value
uint64_t value
Definition: output-stats.h:32
StatsCounter_::Func
uint64_t(* Func)(void)
Definition: counters.h:49
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
HashTable_
Definition: util-hash.h:35
tv_root
ThreadVars * tv_root[TVT_MAX]
Definition: tm-threads.c:78
StatsInit
void StatsInit(void)
Initializes the perf counter api. Things are hard coded currently. More work to be done when we imple...
Definition: counters.c:861
util-privs.h
STATS_TYPE_MAXIMUM
@ STATS_TYPE_MAXIMUM
Definition: counters.c:59
SCMUTEX_INITIALIZER
#define SCMUTEX_INITIALIZER
Definition: threads-debug.h:121
CountersIdType_::string
const char * string
Definition: counters.c:1014
SCDropCaps
#define SCDropCaps(...)
Definition: util-privs.h:37
m
SCMutex m
Definition: flow-hash.h:6
JSON_STATS_TOTALS
#define JSON_STATS_TOTALS
Definition: output-json-stats.h:29
TM_ECODE_FAILED
@ TM_ECODE_FAILED
Definition: tm-threads-common.h:81
util-unittest.h
THV_PAUSE
#define THV_PAUSE
Definition: threadvars.h:39
TVT_MGMT
@ TVT_MGMT
Definition: tm-threads-common.h:88
StatsLocalCounter_::updates
uint64_t updates
Definition: counters.h:90
TM_ECODE_OK
@ TM_ECODE_OK
Definition: tm-threads-common.h:80
HashTableFree
void HashTableFree(HashTable *ht)
Definition: util-hash.c:79
ThreadVars_::cap_flags
uint8_t cap_flags
Definition: threadvars.h:81
ThreadVars_::perf_private_ctx
StatsPrivateThreadContext perf_private_ctx
Definition: threadvars.h:120
HashTable_::array_size
uint32_t array_size
Definition: util-hash.h:37
TmModule_::ThreadDeinit
TmEcode(* ThreadDeinit)(ThreadVars *, void *)
Definition: tm-modules.h:49
SC_ERR_STATS_NOT_INIT
@ SC_ERR_STATS_NOT_INIT
Definition: util-error.h:83
StatsThreadStore_::next
struct StatsThreadStore_ * next
Definition: counters.c:77
stats_decoder_events_prefix
const char * stats_decoder_events_prefix
Definition: counters.c:104
THV_RUNNING_DONE
#define THV_RUNNING_DONE
Definition: threadvars.h:47
TmThreadsUnsetFlag
void TmThreadsUnsetFlag(ThreadVars *tv, uint32_t flag)
Unset a thread flag.
Definition: tm-threads.c:105
util-signal.h
SC_ERR_THREAD_INIT
@ SC_ERR_THREAD_INIT
Definition: util-error.h:79
ConfGet
int ConfGet(const char *name, const char **vptr)
Retrieve the value of a configuration node.
Definition: conf.c:330
counters.h
SC_ERR_STATS_LOG_GENERIC
@ SC_ERR_STATS_LOG_GENERIC
Definition: util-error.h:311
StatsRegisterMaxCounter
uint16_t StatsRegisterMaxCounter(const char *name, struct ThreadVars_ *tv)
Registers a counter, whose value holds the maximum of all the values assigned to it.
Definition: counters.c:979
util-debug.h
CountersIdType_
Definition: counters.c:1012
type
uint8_t type
Definition: decode-icmpv4.h:0
StatsCounter_::next
struct StatsCounter_ * next
Definition: counters.h:55
StatsSetupPostConfigPostOutput
void StatsSetupPostConfigPostOutput(void)
Definition: counters.c:878
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:119
ThreadVars_::perf_public_ctx
StatsPublicThreadContext perf_public_ctx
Definition: threadvars.h:126
StatsGlobalContext_::counters_id_hash
HashTable * counters_id_hash
Definition: counters.c:89
SCEnter
#define SCEnter(...)
Definition: util-debug.h:300
HashTableLookup
void * HashTableLookup(HashTable *ht, void *data, uint16_t datalen)
Definition: util-hash.c:193
StatsRecord_::name
const char * name
Definition: output-stats.h:30
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
TmThreadTestThreadUnPaused
void TmThreadTestThreadUnPaused(ThreadVars *tv)
Tests if the thread represented in the arg has been unpaused or not.
Definition: tm-threads.c:1789
StatsThreadStore_::name
const char * name
Definition: counters.c:70
THV_KILL
#define THV_KILL
Definition: threadvars.h:41
util-time.h
HashTableAdd
int HashTableAdd(HashTable *ht, void *data, uint16_t datalen)
Definition: util-hash.c:113
TRUE
#define TRUE
Definition: suricata-common.h:33
ThreadVars_::next
struct ThreadVars_ * next
Definition: threadvars.h:123
StatsPublicThreadContext_
Stats Context for a ThreadVars instance.
Definition: counters.h:61
StatsLocalCounter_::pc
StatsCounter * pc
Definition: counters.h:81
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:282
StatsTable_
Definition: output-stats.h:36
tv_root_lock
SCMutex tv_root_lock
Definition: tm-threads.c:81
StatsGetLocalCounterValue
uint64_t StatsGetLocalCounterValue(ThreadVars *tv, uint16_t id)
Get the value of the local copy of the counter that hold this id.
Definition: counters.c:1240
FALSE
#define FALSE
Definition: suricata-common.h:34
SCReturn
#define SCReturn
Definition: util-debug.h:302
SCCtrlMutexLock
#define SCCtrlMutexLock(mut)
Definition: threads-debug.h:376
StatsToJSON
json_t * StatsToJSON(const StatsTable *st, uint8_t flags)
turn StatsTable into a json object
Definition: output-json-stats.c:211
CountersIdType_::id
uint16_t id
Definition: counters.c:1013
tmm_modules
TmModule tmm_modules[TMM_SIZE]
Definition: tm-modules.c:33
StatsLocalCounter_::value
uint64_t value
Definition: counters.h:87
ThreadVars_::ctrl_cond
SCCtrlCondT * ctrl_cond
Definition: threadvars.h:131
conf.h
ThreadVars_::thread_group_name
char * thread_group_name
Definition: threadvars.h:67
StatsCounter_::id
uint16_t id
Definition: counters.h:38
PASS_IF
#define PASS_IF(expr)
Pass the test if expression evaluates to true.
Definition: util-unittest.h:117
ThreadVars_::thread_setup_flags
uint8_t thread_setup_flags
Definition: threadvars.h:69
TmEcode
TmEcode
Definition: tm-threads-common.h:79
StatsTable_::start_time
time_t start_time
Definition: output-stats.h:41
StatsLocalCounter_::id
uint16_t id
Definition: counters.h:84
StatsPrivateThreadContext_
used to hold the private version of the counters registered
Definition: counters.h:96
SCCtrlCondTimedwait
#define SCCtrlCondTimedwait
Definition: threads-debug.h:385
runmodes.h
PacketQueue_::cond_q
SCCondT cond_q
Definition: packet-queue.h:55
TmThreadCreateMgmtThread
ThreadVars * TmThreadCreateMgmtThread(const char *name, void *(fn_p)(void *), int mucond)
Creates and returns the TV instance for a Management thread(MGMT). This function supports only custom...
Definition: tm-threads.c:1095
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:217
SCMutexInit
#define SCMutexInit(mut, mutattrs)
Definition: threads-debug.h:116
STATS_WUT_TTS
#define STATS_WUT_TTS
Definition: counters.c:47
Flow_::next
struct Flow_ * next
Definition: flow.h:394
StatsGlobalContext_::global_counter_ctx
StatsPublicThreadContext global_counter_ctx
Definition: counters.c:91
StatsTable_::stats
StatsRecord * stats
Definition: output-stats.h:37
TmModule_
Definition: tm-modules.h:43
StatsGlobalContext_::sts_lock
SCMutex sts_lock
Definition: counters.c:86
THV_PAUSED
#define THV_PAUSED
Definition: threadvars.h:40
THV_INIT_DONE
#define THV_INIT_DONE
Definition: threadvars.h:38
StatsPublicThreadContext_::m
SCMutex m
Definition: counters.h:72
StatsLocalCounter_
Storage for local counters, with a link to the public counter used for syncs.
Definition: counters.h:79
SCCtrlMutexUnlock
#define SCCtrlMutexUnlock(mut)
Definition: threads-debug.h:378
StringParseUint32
int StringParseUint32(uint32_t *res, int base, uint16_t len, const char *str)
Definition: util-byte.c:313
SCCondSignal
#define SCCondSignal
Definition: threads-debug.h:139
ThreadVars_::inq
Tmq * inq
Definition: threadvars.h:90
StatsGlobalContext_::sts_cnt
int sts_cnt
Definition: counters.c:87
suricata-common.h
output-json-stats.h
StatsThreadStore_::ctx
StatsPublicThreadContext * ctx
Definition: counters.c:72
StatsEnabled
bool StatsEnabled(void)
Definition: counters.c:120
StatsSpawnThreads
void StatsSpawnThreads(void)
Spawns the wakeup, and the management thread used by the stats api.
Definition: counters.c:890
StatsRecord_::tm_name
const char * tm_name
Definition: output-stats.h:31
SCLogError
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:257
TmModule_::ThreadInit
TmEcode(* ThreadInit)(ThreadVars *, const void *, void **)
Definition: tm-modules.h:47
JSON_STATS_THREADS
#define JSON_STATS_THREADS
Definition: output-json-stats.h:30
FatalError
#define FatalError(x,...)
Definition: util-debug.h:532
ConfGetChildValueBool
int ConfGetChildValueBool(const ConfNode *base, const char *name, int *val)
Definition: conf.c:529
StatsTable_::tstats
StatsRecord * tstats
Definition: output-stats.h:38
ThreadVars_::printable_name
char * printable_name
Definition: threadvars.h:66
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:29
StatsPublicThreadContext_::perf_flag
uint32_t perf_flag
Definition: counters.h:63
threadvars.h
ConfUnixSocketIsEnable
int ConfUnixSocketIsEnable(void)
Definition: util-conf.c:143
StatsAddUI64
void StatsAddUI64(ThreadVars *tv, uint16_t id, uint64_t x)
Adds a value of type uint64_t to the local counter.
Definition: counters.c:148
SCMalloc
#define SCMalloc(sz)
Definition: util-mem.h:47
StatsCounter_::gid
uint16_t gid
Definition: counters.h:41
unix-manager.h
OutputStatsLoggersRegistered
int OutputStatsLoggersRegistered(void)
Definition: output-stats.c:206
head
Flow * head
Definition: flow-hash.h:1
SCLogWarning
#define SCLogWarning(err_code,...)
Macro used to log WARNING messages.
Definition: util-debug.h:244
StatsCounter_::value
uint64_t value
Definition: counters.h:44
SCFree
#define SCFree(p)
Definition: util-mem.h:61
ConfNode_
Definition: conf.h:32
SC_ERR_FATAL
@ SC_ERR_FATAL
Definition: util-error.h:203
StatsPrivateThreadContext_::initialized
int initialized
Definition: counters.h:103
StatsPrivateThreadContext_::size
uint32_t size
Definition: counters.h:101
StatsUpdateCounterArray
int StatsUpdateCounterArray(StatsPrivateThreadContext *pca, StatsPublicThreadContext *pctx)
the private stats store with the public stats store
Definition: counters.c:1212
ConfValIsFalse
int ConfValIsFalse(const char *val)
Check if a value is false.
Definition: conf.c:590
HashTableInit
HashTable * HashTableInit(uint32_t size, uint32_t(*Hash)(struct HashTable_ *, void *, uint16_t), char(*Compare)(void *, uint16_t, void *, uint16_t), void(*Free)(void *))
Definition: util-hash.c:34
StatsReleaseCounters
void StatsReleaseCounters(StatsCounter *head)
Releases counters.
Definition: counters.c:1264
SC_ERR_MEM_ALLOC
@ SC_ERR_MEM_ALLOC
Definition: util-error.h:31
suricata.h
StatsPublicThreadContext_::head
StatsCounter * head
Definition: counters.h:66
GetDocURL
const char * GetDocURL(void)
Definition: suricata.c:1022
StatsRecord_::pvalue
uint64_t pvalue
Definition: output-stats.h:33
StatsGlobalContext_::sts
StatsThreadStore * sts
Definition: counters.c:85
StatsGlobalContext
struct StatsGlobalContext_ StatsGlobalContext
Holds the output interface context for the counter api.
output-stats.h
StatsRegisterAvgCounter
uint16_t StatsRegisterAvgCounter(const char *name, struct ThreadVars_ *tv)
Registers a counter, whose value holds the average of all the values assigned to it.
Definition: counters.c:959
ThreadVars_::ctrl_mutex
SCCtrlMutex * ctrl_mutex
Definition: threadvars.h:130
StatsThreadStore
struct StatsThreadStore_ StatsThreadStore
per thread store of counters
SC_ERR_THREAD_DEINIT
@ SC_ERR_THREAD_DEINIT
Definition: util-error.h:297
stats_decoder_events
bool stats_decoder_events
Definition: counters.c:103
TmThreadsCheckFlag
int TmThreadsCheckFlag(ThreadVars *tv, uint32_t flag)
Check if a thread flag is set.
Definition: tm-threads.c:89
StatsRegisterCounter
uint16_t StatsRegisterCounter(const char *name, struct ThreadVars_ *tv)
Registers a normal, unqualified counter.
Definition: counters.c:939
StatsPublicThreadContext_::curr_id
uint16_t curr_id
Definition: counters.h:69
THV_CLOSED
#define THV_CLOSED
Definition: threadvars.h:43
STATS_TYPE_NORMAL
@ STATS_TYPE_NORMAL
Definition: counters.c:57
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
StatsReleaseResources
void StatsReleaseResources()
Releases the resources alloted by the Stats API.
Definition: counters.c:1252
SCMutexDestroy
#define SCMutexDestroy
Definition: threads-debug.h:120
StatsThreadCleanup
void StatsThreadCleanup(ThreadVars *tv)
Definition: counters.c:1293
StatsTable_::nstats
uint32_t nstats
Definition: output-stats.h:39
SCMutex
#define SCMutex
Definition: threads-debug.h:114
StatsPrivateThreadContext_::head
StatsLocalCounter * head
Definition: counters.h:98
OutputStatsLog
TmEcode OutputStatsLog(ThreadVars *tv, void *thread_data, StatsTable *st)
Definition: output-stats.c:87
STATS_TYPE_AVERAGE
@ STATS_TYPE_AVERAGE
Definition: counters.c:58
StatsRegisterTests
void StatsRegisterTests(void)
Definition: counters.c:1559
output.h
STATS_TYPE_MAX
@ STATS_TYPE_MAX
Definition: counters.c:62
ConfNodeLookupChildValue
const char * ConfNodeLookupChildValue(const ConfNode *node, const char *name)
Lookup the value of a child configuration node by name.
Definition: conf.c:842