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,
87 char key[DATA_MAX_NAME_LEN + 2];
89 statsd_metric_t *metric;
94 case STATSD_COUNTER: prefix = "c"; break;
95 case STATSD_TIMER: prefix = "t"; break;
96 case STATSD_GAUGE: prefix = "g"; break;
97 case STATSD_SET: prefix = "s"; break;
98 default: return (NULL);
101 ssnprintf (key, sizeof (key), "%s:%s", prefix, name);
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_handle_counter (char const *name, /* {{{ */
184 char const *value_str,
187 char key[DATA_MAX_NAME_LEN + 2];
192 if ((extra != NULL) && (extra[0] != '@'))
198 status = parse_value (extra + 1, &scale, DS_TYPE_GAUGE);
202 if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
207 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
211 if (value.derive < 1)
214 ssnprintf (key, sizeof (key), "c:%s", name);
216 return (statsd_metric_add (key,
217 (int64_t) (((gauge_t) value.derive) / scale.gauge),
219 } /* }}} int statsd_handle_counter */
221 static int statsd_handle_gauge (char const *name, /* {{{ */
222 char const *value_str)
224 char key[DATA_MAX_NAME_LEN + 2];
229 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
233 ssnprintf (key, sizeof (key), "g:%s", name);
235 if ((value_str[0] == '+') || (value_str[0] == '-'))
236 return (statsd_metric_add (key, (int64_t) value.derive, STATSD_GAUGE));
238 return (statsd_metric_set (key, (int64_t) value.derive, STATSD_GAUGE));
239 } /* }}} int statsd_handle_gauge */
241 static int statsd_handle_timer (char const *name, /* {{{ */
242 char const *value_str)
244 statsd_metric_t *metric;
250 status = parse_value (value_str, &value_ms, DS_TYPE_DERIVE);
254 value = MS_TO_CDTIME_T (value_ms.derive);
256 pthread_mutex_lock (&metrics_lock);
258 metric = statsd_metric_lookup_unsafe (name, STATSD_TIMER);
261 pthread_mutex_unlock (&metrics_lock);
265 if (metric->latency == NULL)
266 metric->latency = latency_counter_create ();
267 if (metric->latency == NULL)
269 pthread_mutex_unlock (&metrics_lock);
273 latency_counter_add (metric->latency, value);
274 metric->updates_num++;
276 pthread_mutex_unlock (&metrics_lock);
278 } /* }}} int statsd_handle_timer */
280 static int statsd_handle_set (char const *name, /* {{{ */
281 char const *set_key_orig)
283 statsd_metric_t *metric = NULL;
287 pthread_mutex_lock (&metrics_lock);
289 metric = statsd_metric_lookup_unsafe (name, STATSD_SET);
292 pthread_mutex_unlock (&metrics_lock);
296 /* Make sure metric->set exists. */
297 if (metric->set == NULL)
298 metric->set = c_avl_create ((void *) strcmp);
300 if (metric->set == NULL)
302 pthread_mutex_unlock (&metrics_lock);
303 ERROR ("statsd plugin: c_avl_create failed.");
307 set_key = strdup (set_key_orig);
310 pthread_mutex_unlock (&metrics_lock);
311 ERROR ("statsd plugin: strdup failed.");
315 status = c_avl_insert (metric->set, set_key, /* value = */ NULL);
318 pthread_mutex_unlock (&metrics_lock);
320 ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
325 else if (status > 0) /* key already exists */
330 metric->updates_num++;
332 pthread_mutex_unlock (&metrics_lock);
334 } /* }}} int statsd_handle_set */
336 static int statsd_parse_line (char *buffer) /* {{{ */
343 type = strchr (name, '|');
349 value = strrchr (name, ':');
355 extra = strchr (type, '|');
362 if (strcmp ("c", type) == 0)
363 return (statsd_handle_counter (name, value, extra));
365 /* extra is only valid for counters */
369 if (strcmp ("g", type) == 0)
370 return (statsd_handle_gauge (name, value));
371 else if (strcmp ("ms", type) == 0)
372 return (statsd_handle_timer (name, value));
373 else if (strcmp ("s", type) == 0)
374 return (statsd_handle_set (name, value));
377 } /* }}} void statsd_parse_line */
379 static void statsd_parse_buffer (char *buffer) /* {{{ */
382 char *saveptr = NULL;
386 (ptr = strtok_r (dummy, "\r\n", &saveptr)) != NULL;
389 char *line_orig = sstrdup (ptr);
392 status = statsd_parse_line (ptr);
394 ERROR ("statsd plugin: Unable to parse line: \"%s\"", line_orig);
398 } /* }}} void statsd_parse_buffer */
400 static void statsd_network_read (int fd) /* {{{ */
406 status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
411 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
414 ERROR ("statsd plugin: recv(2) failed: %s",
415 sstrerror (errno, errbuf, sizeof (errbuf)));
419 buffer_size = (size_t) status;
420 if (buffer_size >= sizeof (buffer))
421 buffer_size = sizeof (buffer) - 1;
422 buffer[buffer_size] = 0;
424 statsd_parse_buffer (buffer);
425 } /* }}} void statsd_network_read */
427 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
430 struct pollfd *fds = NULL;
433 struct addrinfo ai_hints;
434 struct addrinfo *ai_list = NULL;
435 struct addrinfo *ai_ptr;
438 char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
439 char const *service = (conf_service != NULL)
440 ? conf_service : STATSD_DEFAULT_SERVICE;
442 memset (&ai_hints, 0, sizeof (ai_hints));
443 ai_hints.ai_flags = AI_PASSIVE;
445 ai_hints.ai_flags |= AI_ADDRCONFIG;
447 ai_hints.ai_family = AF_UNSPEC;
448 ai_hints.ai_socktype = SOCK_DGRAM;
450 status = getaddrinfo (node, service, &ai_hints, &ai_list);
453 ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
454 node, service, gai_strerror (status));
458 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
463 char dbg_node[NI_MAXHOST];
464 char dbg_service[NI_MAXSERV];
466 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
470 ERROR ("statsd plugin: socket(2) failed: %s",
471 sstrerror (errno, errbuf, sizeof (errbuf)));
475 getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
476 dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
477 NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
478 DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
480 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
484 ERROR ("statsd plugin: bind(2) failed: %s",
485 sstrerror (errno, errbuf, sizeof (errbuf)));
490 tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
493 ERROR ("statsd plugin: realloc failed.");
500 memset (tmp, 0, sizeof (*tmp));
502 tmp->events = POLLIN | POLLPRI;
505 freeaddrinfo (ai_list);
509 ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
510 (node != NULL) ? node : "::", service);
515 *ret_fds_num = fds_num;
517 } /* }}} int statsd_network_init */
519 static void *statsd_network_thread (void *args) /* {{{ */
521 struct pollfd *fds = NULL;
526 status = statsd_network_init (&fds, &fds_num);
529 ERROR ("statsd plugin: Unable to open listening sockets.");
530 pthread_exit ((void *) 0);
533 while (!network_thread_shutdown)
535 status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
540 if ((errno == EINTR) || (errno == EAGAIN))
543 ERROR ("statsd plugin: poll(2) failed: %s",
544 sstrerror (errno, errbuf, sizeof (errbuf)));
548 for (i = 0; i < fds_num; i++)
550 if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
553 statsd_network_read (fds[i].fd);
556 } /* while (!network_thread_shutdown) */
559 for (i = 0; i < fds_num; i++)
564 } /* }}} void *statsd_network_thread */
566 static int statsd_config_timer_percentile (oconfig_item_t *ci) /* {{{ */
568 double percent = NAN;
572 status = cf_util_get_double (ci, &percent);
576 if ((percent <= 0.0) || (percent >= 100))
578 ERROR ("statsd plugin: The value for \"%s\" must be between 0 and 100, "
579 "exclusively.", ci->key);
583 tmp = realloc (conf_timer_percentile,
584 sizeof (*conf_timer_percentile) * (conf_timer_percentile_num + 1));
587 ERROR ("statsd plugin: realloc failed.");
590 conf_timer_percentile = tmp;
591 conf_timer_percentile[conf_timer_percentile_num] = percent;
592 conf_timer_percentile_num++;
595 } /* }}} int statsd_config_timer_percentile */
597 static int statsd_config (oconfig_item_t *ci) /* {{{ */
601 for (i = 0; i < ci->children_num; i++)
603 oconfig_item_t *child = ci->children + i;
605 if (strcasecmp ("Host", child->key) == 0)
606 cf_util_get_string (child, &conf_node);
607 else if (strcasecmp ("Port", child->key) == 0)
608 cf_util_get_service (child, &conf_service);
609 else if (strcasecmp ("DeleteCounters", child->key) == 0)
610 cf_util_get_boolean (child, &conf_delete_counters);
611 else if (strcasecmp ("DeleteTimers", child->key) == 0)
612 cf_util_get_boolean (child, &conf_delete_timers);
613 else if (strcasecmp ("DeleteGauges", child->key) == 0)
614 cf_util_get_boolean (child, &conf_delete_gauges);
615 else if (strcasecmp ("DeleteSets", child->key) == 0)
616 cf_util_get_boolean (child, &conf_delete_sets);
617 else if (strcasecmp ("TimerPercentile", child->key) == 0)
618 statsd_config_timer_percentile (child);
620 ERROR ("statsd plugin: The \"%s\" config option is not valid.",
625 } /* }}} int statsd_config */
627 static int statsd_init (void) /* {{{ */
629 pthread_mutex_lock (&metrics_lock);
630 if (metrics_tree == NULL)
631 metrics_tree = c_avl_create ((void *) strcasecmp);
633 if (!network_thread_running)
637 status = pthread_create (&network_thread,
639 statsd_network_thread,
644 pthread_mutex_unlock (&metrics_lock);
645 ERROR ("statsd plugin: pthread_create failed: %s",
646 sstrerror (errno, errbuf, sizeof (errbuf)));
650 network_thread_running = 1;
652 pthread_mutex_unlock (&metrics_lock);
655 } /* }}} int statsd_init */
657 /* Must hold metrics_lock when calling this function. */
658 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
663 if ((metric == NULL) || (metric->type != STATSD_SET))
666 if (metric->set == NULL)
669 while (c_avl_pick (metric->set, &key, &value) == 0)
676 } /* }}} int statsd_metric_clear_set_unsafe */
678 /* Must hold metrics_lock when calling this function. */
679 static int statsd_metric_submit_unsafe (char const *name, /* {{{ */
680 statsd_metric_t const *metric)
683 value_list_t vl = VALUE_LIST_INIT;
687 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
688 sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
690 if (metric->type == STATSD_GAUGE)
691 sstrncpy (vl.type, "gauge", sizeof (vl.type));
692 else if (metric->type == STATSD_TIMER)
693 sstrncpy (vl.type, "latency", sizeof (vl.type));
694 else if (metric->type == STATSD_SET)
695 sstrncpy (vl.type, "objects", sizeof (vl.type));
696 else /* if (metric->type == STATSD_COUNTER) */
697 sstrncpy (vl.type, "derive", sizeof (vl.type));
699 sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
701 if (metric->type == STATSD_GAUGE)
702 values[0].gauge = (gauge_t) metric->value;
703 else if (metric->type == STATSD_TIMER)
707 if (metric->updates_num == 0)
712 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
714 values[0].gauge = CDTIME_T_TO_DOUBLE (
715 latency_counter_get_average (metric->latency));
716 plugin_dispatch_values (&vl);
718 for (i = 0; i < conf_timer_percentile_num; i++)
720 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
721 "%s-percentile-%.0f", name, conf_timer_percentile[i]);
722 values[0].gauge = CDTIME_T_TO_DOUBLE (
723 latency_counter_get_percentile (
724 metric->latency, conf_timer_percentile[i]));
725 plugin_dispatch_values (&vl);
728 latency_counter_reset (metric->latency);
731 else if (metric->type == STATSD_SET)
733 if (metric->set == NULL)
734 values[0].gauge = 0.0;
736 values[0].gauge = (gauge_t) c_avl_size (metric->set);
739 values[0].derive = (derive_t) metric->value;
741 return (plugin_dispatch_values (&vl));
742 } /* }}} int statsd_metric_submit_unsafe */
744 static int statsd_read (void) /* {{{ */
746 c_avl_iterator_t *iter;
748 statsd_metric_t *metric;
750 char **to_be_deleted = NULL;
751 size_t to_be_deleted_num = 0;
754 pthread_mutex_lock (&metrics_lock);
756 if (metrics_tree == NULL)
758 pthread_mutex_unlock (&metrics_lock);
762 iter = c_avl_get_iterator (metrics_tree);
763 while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
765 if ((metric->updates_num == 0)
766 && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
767 || (conf_delete_timers && (metric->type == STATSD_TIMER))
768 || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
769 || (conf_delete_sets && (metric->type == STATSD_SET))))
771 DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
772 strarray_add (&to_be_deleted, &to_be_deleted_num, name);
776 /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
777 * Remove this here. */
778 statsd_metric_submit_unsafe (name + 2, metric);
780 /* Reset the metric. */
781 metric->updates_num = 0;
782 if (metric->type == STATSD_SET)
783 statsd_metric_clear_set_unsafe (metric);
785 c_avl_iterator_destroy (iter);
787 for (i = 0; i < to_be_deleted_num; i++)
791 status = c_avl_remove (metrics_tree, to_be_deleted[i],
792 (void *) &name, (void *) &metric);
795 ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
796 to_be_deleted[i], status);
804 pthread_mutex_unlock (&metrics_lock);
806 strarray_free (to_be_deleted, to_be_deleted_num);
809 } /* }}} int statsd_read */
811 static int statsd_shutdown (void) /* {{{ */
816 pthread_mutex_lock (&metrics_lock);
818 if (network_thread_running)
820 network_thread_shutdown = 1;
821 pthread_kill (network_thread, SIGTERM);
822 pthread_join (network_thread, /* retval = */ NULL);
824 network_thread_running = 0;
826 while (c_avl_pick (metrics_tree, &key, &value) == 0)
831 c_avl_destroy (metrics_tree);
835 sfree (conf_service);
837 pthread_mutex_unlock (&metrics_lock);
840 } /* }}} int statsd_shutdown */
842 void module_register (void)
844 plugin_register_complex_config ("statsd", statsd_config);
845 plugin_register_init ("statsd", statsd_init);
846 plugin_register_read ("statsd", statsd_read);
847 plugin_register_shutdown ("statsd", statsd_shutdown);
850 /* vim: set sw=2 sts=2 et fdm=marker : */