2 * collectd - src/statsd.c
4 * Copyright (C) 2013 Florian octo Forster
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
15 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
16 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 * Florian octo Forster <octo at collectd.org>
25 #include "configfile.h"
26 #include "utils_avltree.h"
27 #include "utils_complain.h"
28 #include "utils_latency.h"
32 #include <sys/types.h>
33 #include <sys/socket.h>
37 #ifndef STATSD_DEFAULT_NODE
38 # define STATSD_DEFAULT_NODE NULL
41 #ifndef STATSD_DEFAULT_SERVICE
42 # define STATSD_DEFAULT_SERVICE "8125"
52 typedef enum metric_type_e metric_type_t;
54 struct statsd_metric_s
58 latency_counter_t *latency;
60 unsigned long updates_num;
62 typedef struct statsd_metric_s statsd_metric_t;
64 static c_avl_tree_t *metrics_tree = NULL;
65 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
67 static pthread_t network_thread;
68 static _Bool network_thread_running = 0;
69 static _Bool network_thread_shutdown = 0;
71 static char *conf_node = NULL;
72 static char *conf_service = NULL;
74 static _Bool conf_delete_counters = 0;
75 static _Bool conf_delete_timers = 0;
76 static _Bool conf_delete_gauges = 0;
77 static _Bool conf_delete_sets = 0;
79 static double *conf_timer_percentile = NULL;
80 static size_t conf_timer_percentile_num = 0;
82 /* Must hold metrics_lock when calling this function. */
83 static statsd_metric_t *statsd_metric_lookup_unsafe (char const *name, /* {{{ */
86 char key[DATA_MAX_NAME_LEN + 2];
88 statsd_metric_t *metric;
93 case STATSD_COUNTER: key[0] = 'c'; break;
94 case STATSD_TIMER: key[0] = 't'; break;
95 case STATSD_GAUGE: key[0] = 'g'; break;
96 case STATSD_SET: key[0] = 's'; break;
97 default: return (NULL);
101 sstrncpy (&key[2], name, sizeof (key) - 2);
103 status = c_avl_get (metrics_tree, key, (void *) &metric);
107 key_copy = strdup (key);
108 if (key_copy == NULL)
110 ERROR ("statsd plugin: strdup failed.");
114 metric = malloc (sizeof (*metric));
117 ERROR ("statsd plugin: malloc failed.");
121 memset (metric, 0, sizeof (*metric));
124 metric->latency = NULL;
127 status = c_avl_insert (metrics_tree, key_copy, metric);
130 ERROR ("statsd plugin: c_avl_insert failed.");
137 } /* }}} statsd_metric_lookup_unsafe */
139 static int statsd_metric_set (char const *name, int64_t value, /* {{{ */
142 statsd_metric_t *metric;
144 pthread_mutex_lock (&metrics_lock);
146 metric = statsd_metric_lookup_unsafe (name, type);
149 pthread_mutex_unlock (&metrics_lock);
153 metric->value = value;
154 metric->updates_num++;
156 pthread_mutex_unlock (&metrics_lock);
159 } /* }}} int statsd_metric_set */
161 static int statsd_metric_add (char const *name, int64_t delta, /* {{{ */
164 statsd_metric_t *metric;
166 pthread_mutex_lock (&metrics_lock);
168 metric = statsd_metric_lookup_unsafe (name, type);
171 pthread_mutex_unlock (&metrics_lock);
175 metric->value += delta;
176 metric->updates_num++;
178 pthread_mutex_unlock (&metrics_lock);
181 } /* }}} int statsd_metric_add */
183 static int statsd_parse_value (char const *str, value_t *ret_value) /* {{{ */
187 ret_value->derive = (derive_t) strtoll (str, &endptr, /* base = */ 0);
188 if ((str == endptr) || ((endptr != NULL) && (*endptr != 0)))
192 } /* }}} int statsd_parse_value */
194 static int statsd_handle_counter (char const *name, /* {{{ */
195 char const *value_str,
202 if ((extra != NULL) && (extra[0] != '@'))
208 status = parse_value (extra + 1, &scale, DS_TYPE_GAUGE);
212 if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
217 status = statsd_parse_value (value_str, &value);
221 if (value.derive < 1)
224 return (statsd_metric_add (name,
225 (int64_t) (((gauge_t) value.derive) / scale.gauge),
227 } /* }}} int statsd_handle_counter */
229 static int statsd_handle_gauge (char const *name, /* {{{ */
230 char const *value_str)
236 status = statsd_parse_value (value_str, &value);
240 if ((value_str[0] == '+') || (value_str[0] == '-'))
241 return (statsd_metric_add (name, (int64_t) value.derive, STATSD_GAUGE));
243 return (statsd_metric_set (name, (int64_t) value.derive, STATSD_GAUGE));
244 } /* }}} int statsd_handle_gauge */
246 static int statsd_handle_timer (char const *name, /* {{{ */
247 char const *value_str)
249 statsd_metric_t *metric;
255 status = statsd_parse_value (value_str, &value_ms);
259 value = MS_TO_CDTIME_T (value_ms.derive);
261 pthread_mutex_lock (&metrics_lock);
263 metric = statsd_metric_lookup_unsafe (name, STATSD_TIMER);
266 pthread_mutex_unlock (&metrics_lock);
270 if (metric->latency == NULL)
271 metric->latency = latency_counter_create ();
272 if (metric->latency == NULL)
274 pthread_mutex_unlock (&metrics_lock);
278 latency_counter_add (metric->latency, value);
279 metric->updates_num++;
281 pthread_mutex_unlock (&metrics_lock);
283 } /* }}} int statsd_handle_timer */
285 static int statsd_handle_set (char const *name, /* {{{ */
286 char const *set_key_orig)
288 statsd_metric_t *metric = NULL;
292 pthread_mutex_lock (&metrics_lock);
294 metric = statsd_metric_lookup_unsafe (name, STATSD_SET);
297 pthread_mutex_unlock (&metrics_lock);
301 /* Make sure metric->set exists. */
302 if (metric->set == NULL)
303 metric->set = c_avl_create ((void *) strcmp);
305 if (metric->set == NULL)
307 pthread_mutex_unlock (&metrics_lock);
308 ERROR ("statsd plugin: c_avl_create failed.");
312 set_key = strdup (set_key_orig);
315 pthread_mutex_unlock (&metrics_lock);
316 ERROR ("statsd plugin: strdup failed.");
320 status = c_avl_insert (metric->set, set_key, /* value = */ NULL);
323 pthread_mutex_unlock (&metrics_lock);
325 ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
330 else if (status > 0) /* key already exists */
335 metric->updates_num++;
337 pthread_mutex_unlock (&metrics_lock);
339 } /* }}} int statsd_handle_set */
341 static int statsd_parse_line (char *buffer) /* {{{ */
348 type = strchr (name, '|');
354 value = strrchr (name, ':');
360 extra = strchr (type, '|');
367 if (strcmp ("c", type) == 0)
368 return (statsd_handle_counter (name, value, extra));
370 /* extra is only valid for counters */
374 if (strcmp ("g", type) == 0)
375 return (statsd_handle_gauge (name, value));
376 else if (strcmp ("ms", type) == 0)
377 return (statsd_handle_timer (name, value));
378 else if (strcmp ("s", type) == 0)
379 return (statsd_handle_set (name, value));
382 } /* }}} void statsd_parse_line */
384 static void statsd_parse_buffer (char *buffer) /* {{{ */
386 while (buffer != NULL)
392 next = strchr (buffer, '\n');
405 sstrncpy (orig, buffer, sizeof (orig));
407 status = statsd_parse_line (buffer);
409 ERROR ("statsd plugin: Unable to parse line: \"%s\"", orig);
413 } /* }}} void statsd_parse_buffer */
415 static void statsd_network_read (int fd) /* {{{ */
421 status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
426 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
429 ERROR ("statsd plugin: recv(2) failed: %s",
430 sstrerror (errno, errbuf, sizeof (errbuf)));
434 buffer_size = (size_t) status;
435 if (buffer_size >= sizeof (buffer))
436 buffer_size = sizeof (buffer) - 1;
437 buffer[buffer_size] = 0;
439 statsd_parse_buffer (buffer);
440 } /* }}} void statsd_network_read */
442 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
445 struct pollfd *fds = NULL;
448 struct addrinfo ai_hints;
449 struct addrinfo *ai_list = NULL;
450 struct addrinfo *ai_ptr;
453 char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
454 char const *service = (conf_service != NULL)
455 ? conf_service : STATSD_DEFAULT_SERVICE;
457 memset (&ai_hints, 0, sizeof (ai_hints));
458 ai_hints.ai_flags = AI_PASSIVE;
460 ai_hints.ai_flags |= AI_ADDRCONFIG;
462 ai_hints.ai_family = AF_UNSPEC;
463 ai_hints.ai_socktype = SOCK_DGRAM;
465 status = getaddrinfo (node, service, &ai_hints, &ai_list);
468 ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
469 node, service, gai_strerror (status));
473 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
478 char dbg_node[NI_MAXHOST];
479 char dbg_service[NI_MAXSERV];
481 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
485 ERROR ("statsd plugin: socket(2) failed: %s",
486 sstrerror (errno, errbuf, sizeof (errbuf)));
490 getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
491 dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
492 NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
493 DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
495 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
499 ERROR ("statsd plugin: bind(2) failed: %s",
500 sstrerror (errno, errbuf, sizeof (errbuf)));
505 tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
508 ERROR ("statsd plugin: realloc failed.");
515 memset (tmp, 0, sizeof (*tmp));
517 tmp->events = POLLIN | POLLPRI;
520 freeaddrinfo (ai_list);
524 ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
525 (node != NULL) ? node : "::", service);
530 *ret_fds_num = fds_num;
532 } /* }}} int statsd_network_init */
534 static void *statsd_network_thread (void *args) /* {{{ */
536 struct pollfd *fds = NULL;
541 status = statsd_network_init (&fds, &fds_num);
544 ERROR ("statsd plugin: Unable to open listening sockets.");
545 pthread_exit ((void *) 0);
548 while (!network_thread_shutdown)
550 status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
555 if ((errno == EINTR) || (errno == EAGAIN))
558 ERROR ("statsd plugin: poll(2) failed: %s",
559 sstrerror (errno, errbuf, sizeof (errbuf)));
563 for (i = 0; i < fds_num; i++)
565 if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
568 statsd_network_read (fds[i].fd);
571 } /* while (!network_thread_shutdown) */
574 for (i = 0; i < fds_num; i++)
579 } /* }}} void *statsd_network_thread */
581 static int statsd_config_timer_percentile (oconfig_item_t *ci) /* {{{ */
583 double percent = NAN;
587 status = cf_util_get_double (ci, &percent);
591 if ((percent <= 0.0) || (percent >= 100))
593 ERROR ("statsd plugin: The value for \"%s\" must be between 0 and 100, "
594 "exclusively.", ci->key);
598 tmp = realloc (conf_timer_percentile,
599 sizeof (*conf_timer_percentile) * (conf_timer_percentile_num + 1));
602 ERROR ("statsd plugin: realloc failed.");
605 conf_timer_percentile = tmp;
606 conf_timer_percentile[conf_timer_percentile_num] = percent;
607 conf_timer_percentile_num++;
610 } /* }}} int statsd_config_timer_percentile */
612 static int statsd_config (oconfig_item_t *ci) /* {{{ */
616 for (i = 0; i < ci->children_num; i++)
618 oconfig_item_t *child = ci->children + i;
620 if (strcasecmp ("Host", child->key) == 0)
621 cf_util_get_string (child, &conf_node);
622 else if (strcasecmp ("Port", child->key) == 0)
623 cf_util_get_service (child, &conf_service);
624 else if (strcasecmp ("DeleteCounters", child->key) == 0)
625 cf_util_get_boolean (child, &conf_delete_counters);
626 else if (strcasecmp ("DeleteTimers", child->key) == 0)
627 cf_util_get_boolean (child, &conf_delete_timers);
628 else if (strcasecmp ("DeleteGauges", child->key) == 0)
629 cf_util_get_boolean (child, &conf_delete_gauges);
630 else if (strcasecmp ("DeleteSets", child->key) == 0)
631 cf_util_get_boolean (child, &conf_delete_sets);
632 else if (strcasecmp ("TimerPercentile", child->key) == 0)
633 statsd_config_timer_percentile (child);
635 ERROR ("statsd plugin: The \"%s\" config option is not valid.",
640 } /* }}} int statsd_config */
642 static int statsd_init (void) /* {{{ */
644 pthread_mutex_lock (&metrics_lock);
645 if (metrics_tree == NULL)
646 metrics_tree = c_avl_create ((void *) strcasecmp);
648 if (!network_thread_running)
652 status = pthread_create (&network_thread,
654 statsd_network_thread,
659 pthread_mutex_unlock (&metrics_lock);
660 ERROR ("statsd plugin: pthread_create failed: %s",
661 sstrerror (errno, errbuf, sizeof (errbuf)));
665 network_thread_running = 1;
667 pthread_mutex_unlock (&metrics_lock);
670 } /* }}} int statsd_init */
672 /* Must hold metrics_lock when calling this function. */
673 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
678 if ((metric == NULL) || (metric->type != STATSD_SET))
681 if (metric->set == NULL)
684 while (c_avl_pick (metric->set, &key, &value) == 0)
691 } /* }}} int statsd_metric_clear_set_unsafe */
693 /* Must hold metrics_lock when calling this function. */
694 static int statsd_metric_submit_unsafe (char const *name, /* {{{ */
695 statsd_metric_t const *metric)
698 value_list_t vl = VALUE_LIST_INIT;
702 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
703 sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
705 if (metric->type == STATSD_GAUGE)
706 sstrncpy (vl.type, "gauge", sizeof (vl.type));
707 else if (metric->type == STATSD_TIMER)
708 sstrncpy (vl.type, "latency", sizeof (vl.type));
709 else if (metric->type == STATSD_SET)
710 sstrncpy (vl.type, "objects", sizeof (vl.type));
711 else /* if (metric->type == STATSD_COUNTER) */
712 sstrncpy (vl.type, "derive", sizeof (vl.type));
714 sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
716 if (metric->type == STATSD_GAUGE)
717 values[0].gauge = (gauge_t) metric->value;
718 else if (metric->type == STATSD_TIMER)
722 if (metric->updates_num == 0)
727 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
729 values[0].gauge = CDTIME_T_TO_DOUBLE (
730 latency_counter_get_average (metric->latency));
731 plugin_dispatch_values (&vl);
733 for (i = 0; i < conf_timer_percentile_num; i++)
735 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
736 "%s-percentile-%.0f", name, conf_timer_percentile[i]);
737 values[0].gauge = CDTIME_T_TO_DOUBLE (
738 latency_counter_get_percentile (
739 metric->latency, conf_timer_percentile[i]));
740 plugin_dispatch_values (&vl);
743 latency_counter_reset (metric->latency);
746 else if (metric->type == STATSD_SET)
748 if (metric->set == NULL)
749 values[0].gauge = 0.0;
751 values[0].gauge = (gauge_t) c_avl_size (metric->set);
754 values[0].derive = (derive_t) metric->value;
756 return (plugin_dispatch_values (&vl));
757 } /* }}} int statsd_metric_submit_unsafe */
759 static int statsd_read (void) /* {{{ */
761 c_avl_iterator_t *iter;
763 statsd_metric_t *metric;
765 char **to_be_deleted = NULL;
766 size_t to_be_deleted_num = 0;
769 pthread_mutex_lock (&metrics_lock);
771 if (metrics_tree == NULL)
773 pthread_mutex_unlock (&metrics_lock);
777 iter = c_avl_get_iterator (metrics_tree);
778 while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
780 if ((metric->updates_num == 0)
781 && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
782 || (conf_delete_timers && (metric->type == STATSD_TIMER))
783 || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
784 || (conf_delete_sets && (metric->type == STATSD_SET))))
786 DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
787 strarray_add (&to_be_deleted, &to_be_deleted_num, name);
791 /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
792 * Remove this here. */
793 statsd_metric_submit_unsafe (name + 2, metric);
795 /* Reset the metric. */
796 metric->updates_num = 0;
797 if (metric->type == STATSD_SET)
798 statsd_metric_clear_set_unsafe (metric);
800 c_avl_iterator_destroy (iter);
802 for (i = 0; i < to_be_deleted_num; i++)
806 status = c_avl_remove (metrics_tree, to_be_deleted[i],
807 (void *) &name, (void *) &metric);
810 ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
811 to_be_deleted[i], status);
819 pthread_mutex_unlock (&metrics_lock);
821 strarray_free (to_be_deleted, to_be_deleted_num);
824 } /* }}} int statsd_read */
826 static int statsd_shutdown (void) /* {{{ */
831 pthread_mutex_lock (&metrics_lock);
833 if (network_thread_running)
835 network_thread_shutdown = 1;
836 pthread_kill (network_thread, SIGTERM);
837 pthread_join (network_thread, /* retval = */ NULL);
839 network_thread_running = 0;
841 while (c_avl_pick (metrics_tree, &key, &value) == 0)
846 c_avl_destroy (metrics_tree);
850 sfree (conf_service);
852 pthread_mutex_unlock (&metrics_lock);
855 } /* }}} int statsd_shutdown */
857 void module_register (void)
859 plugin_register_complex_config ("statsd", statsd_config);
860 plugin_register_init ("statsd", statsd_init);
861 plugin_register_read ("statsd", statsd_read);
862 plugin_register_shutdown ("statsd", statsd_shutdown);
865 /* vim: set sw=2 sts=2 et fdm=marker : */