1 /* Copyright (c) 2020, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
5 * @file metrics_store_entry.c
6 * @brief Metrics store entry which contains the gathered data.
9 #define METRICS_STORE_ENTRY_PRIVATE
15 #include "lib/container/smartlist.h"
16 #include "lib/log/util_bug.h"
17 #include "lib/malloc/malloc.h"
19 #include "lib/metrics/metrics_store_entry.h"
25 /** Return newly allocated store entry of type COUNTER. */
26 metrics_store_entry_t
*
27 metrics_store_entry_new(const metrics_type_t type
, const char *name
,
30 metrics_store_entry_t
*entry
= tor_malloc_zero(sizeof(*entry
));
35 entry
->name
= tor_strdup(name
);
36 entry
->labels
= smartlist_new();
38 entry
->help
= tor_strdup(help
);
44 /** Free a store entry. */
46 metrics_store_entry_free_(metrics_store_entry_t
*entry
)
51 SMARTLIST_FOREACH(entry
->labels
, char *, l
, tor_free(l
));
52 smartlist_free(entry
->labels
);
53 tor_free(entry
->name
);
54 tor_free(entry
->help
);
58 /** Update a store entry with value. */
60 metrics_store_entry_update(metrics_store_entry_t
*entry
, const int64_t value
)
64 switch (entry
->type
) {
65 case METRICS_TYPE_COUNTER
:
66 /* Counter can ONLY be positive. */
70 entry
->u
.counter
.value
+= value
;
72 case METRICS_TYPE_GAUGE
:
73 /* Gauge can increment or decrement. And can be positive or negative. */
74 entry
->u
.gauge
.value
+= value
;
79 /** Reset a store entry that is set its metric data to 0. */
81 metrics_store_entry_reset(metrics_store_entry_t
*entry
)
84 /* Everything back to 0. */
85 memset(&entry
->u
, 0, sizeof(entry
->u
));
88 /** Return store entry value. */
90 metrics_store_entry_get_value(const metrics_store_entry_t
*entry
)
94 switch (entry
->type
) {
95 case METRICS_TYPE_COUNTER
:
96 if (entry
->u
.counter
.value
> INT64_MAX
) {
99 return entry
->u
.counter
.value
;
100 case METRICS_TYPE_GAUGE
:
101 return entry
->u
.gauge
.value
;
105 tor_assert_unreached();
109 /** Add a label into the given entry.*/
111 metrics_store_entry_add_label(metrics_store_entry_t
*entry
,
117 smartlist_add(entry
->labels
, tor_strdup(label
));
120 /** Return true iff the given entry has the given label. */
122 metrics_store_entry_has_label(const metrics_store_entry_t
*entry
,
128 return smartlist_contains_string(entry
->labels
, label
);