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, double 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, double 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->gauge = (gauge_t) strtod (str, &endptr);
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 = statsd_parse_value (extra + 1, &scale);
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, (double) (value.gauge / scale.gauge),
226 } /* }}} int statsd_handle_counter */
228 static int statsd_handle_gauge (char const *name, /* {{{ */
229 char const *value_str)
235 status = statsd_parse_value (value_str, &value);
239 if ((value_str[0] == '+') || (value_str[0] == '-'))
240 return (statsd_metric_add (name, (double) value.gauge, STATSD_GAUGE));
242 return (statsd_metric_set (name, (double) value.gauge, STATSD_GAUGE));
243 } /* }}} int statsd_handle_gauge */
245 static int statsd_handle_timer (char const *name, /* {{{ */
246 char const *value_str)
248 statsd_metric_t *metric;
254 status = statsd_parse_value (value_str, &value_ms);
258 value = MS_TO_CDTIME_T (value_ms.gauge);
260 pthread_mutex_lock (&metrics_lock);
262 metric = statsd_metric_lookup_unsafe (name, STATSD_TIMER);
265 pthread_mutex_unlock (&metrics_lock);
269 if (metric->latency == NULL)
270 metric->latency = latency_counter_create ();
271 if (metric->latency == NULL)
273 pthread_mutex_unlock (&metrics_lock);
277 latency_counter_add (metric->latency, value);
278 metric->updates_num++;
280 pthread_mutex_unlock (&metrics_lock);
282 } /* }}} int statsd_handle_timer */
284 static int statsd_handle_set (char const *name, /* {{{ */
285 char const *set_key_orig)
287 statsd_metric_t *metric = NULL;
291 pthread_mutex_lock (&metrics_lock);
293 metric = statsd_metric_lookup_unsafe (name, STATSD_SET);
296 pthread_mutex_unlock (&metrics_lock);
300 /* Make sure metric->set exists. */
301 if (metric->set == NULL)
302 metric->set = c_avl_create ((void *) strcmp);
304 if (metric->set == NULL)
306 pthread_mutex_unlock (&metrics_lock);
307 ERROR ("statsd plugin: c_avl_create failed.");
311 set_key = strdup (set_key_orig);
314 pthread_mutex_unlock (&metrics_lock);
315 ERROR ("statsd plugin: strdup failed.");
319 status = c_avl_insert (metric->set, set_key, /* value = */ NULL);
322 pthread_mutex_unlock (&metrics_lock);
324 ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
329 else if (status > 0) /* key already exists */
334 metric->updates_num++;
336 pthread_mutex_unlock (&metrics_lock);
338 } /* }}} int statsd_handle_set */
340 static int statsd_parse_line (char *buffer) /* {{{ */
347 type = strchr (name, '|');
353 value = strrchr (name, ':');
359 extra = strchr (type, '|');
366 if (strcmp ("c", type) == 0)
367 return (statsd_handle_counter (name, value, extra));
369 /* extra is only valid for counters */
373 if (strcmp ("g", type) == 0)
374 return (statsd_handle_gauge (name, value));
375 else if (strcmp ("ms", type) == 0)
376 return (statsd_handle_timer (name, value));
377 else if (strcmp ("s", type) == 0)
378 return (statsd_handle_set (name, value));
381 } /* }}} void statsd_parse_line */
383 static void statsd_parse_buffer (char *buffer) /* {{{ */
385 while (buffer != NULL)
391 next = strchr (buffer, '\n');
404 sstrncpy (orig, buffer, sizeof (orig));
406 status = statsd_parse_line (buffer);
408 ERROR ("statsd plugin: Unable to parse line: \"%s\"", orig);
412 } /* }}} void statsd_parse_buffer */
414 static void statsd_network_read (int fd) /* {{{ */
420 status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
425 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
428 ERROR ("statsd plugin: recv(2) failed: %s",
429 sstrerror (errno, errbuf, sizeof (errbuf)));
433 buffer_size = (size_t) status;
434 if (buffer_size >= sizeof (buffer))
435 buffer_size = sizeof (buffer) - 1;
436 buffer[buffer_size] = 0;
438 statsd_parse_buffer (buffer);
439 } /* }}} void statsd_network_read */
441 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
444 struct pollfd *fds = NULL;
447 struct addrinfo ai_hints;
448 struct addrinfo *ai_list = NULL;
449 struct addrinfo *ai_ptr;
452 char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
453 char const *service = (conf_service != NULL)
454 ? conf_service : STATSD_DEFAULT_SERVICE;
456 memset (&ai_hints, 0, sizeof (ai_hints));
457 ai_hints.ai_flags = AI_PASSIVE;
459 ai_hints.ai_flags |= AI_ADDRCONFIG;
461 ai_hints.ai_family = AF_UNSPEC;
462 ai_hints.ai_socktype = SOCK_DGRAM;
464 status = getaddrinfo (node, service, &ai_hints, &ai_list);
467 ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
468 node, service, gai_strerror (status));
472 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
477 char dbg_node[NI_MAXHOST];
478 char dbg_service[NI_MAXSERV];
480 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
484 ERROR ("statsd plugin: socket(2) failed: %s",
485 sstrerror (errno, errbuf, sizeof (errbuf)));
489 getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
490 dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
491 NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
492 DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
494 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
498 ERROR ("statsd plugin: bind(2) failed: %s",
499 sstrerror (errno, errbuf, sizeof (errbuf)));
504 tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
507 ERROR ("statsd plugin: realloc failed.");
514 memset (tmp, 0, sizeof (*tmp));
516 tmp->events = POLLIN | POLLPRI;
519 freeaddrinfo (ai_list);
523 ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
524 (node != NULL) ? node : "::", service);
529 *ret_fds_num = fds_num;
531 } /* }}} int statsd_network_init */
533 static void *statsd_network_thread (void *args) /* {{{ */
535 struct pollfd *fds = NULL;
540 status = statsd_network_init (&fds, &fds_num);
543 ERROR ("statsd plugin: Unable to open listening sockets.");
544 pthread_exit ((void *) 0);
547 while (!network_thread_shutdown)
549 status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
554 if ((errno == EINTR) || (errno == EAGAIN))
557 ERROR ("statsd plugin: poll(2) failed: %s",
558 sstrerror (errno, errbuf, sizeof (errbuf)));
562 for (i = 0; i < fds_num; i++)
564 if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
567 statsd_network_read (fds[i].fd);
570 } /* while (!network_thread_shutdown) */
573 for (i = 0; i < fds_num; i++)
578 } /* }}} void *statsd_network_thread */
580 static int statsd_config_timer_percentile (oconfig_item_t *ci) /* {{{ */
582 double percent = NAN;
586 status = cf_util_get_double (ci, &percent);
590 if ((percent <= 0.0) || (percent >= 100))
592 ERROR ("statsd plugin: The value for \"%s\" must be between 0 and 100, "
593 "exclusively.", ci->key);
597 tmp = realloc (conf_timer_percentile,
598 sizeof (*conf_timer_percentile) * (conf_timer_percentile_num + 1));
601 ERROR ("statsd plugin: realloc failed.");
604 conf_timer_percentile = tmp;
605 conf_timer_percentile[conf_timer_percentile_num] = percent;
606 conf_timer_percentile_num++;
609 } /* }}} int statsd_config_timer_percentile */
611 static int statsd_config (oconfig_item_t *ci) /* {{{ */
615 for (i = 0; i < ci->children_num; i++)
617 oconfig_item_t *child = ci->children + i;
619 if (strcasecmp ("Host", child->key) == 0)
620 cf_util_get_string (child, &conf_node);
621 else if (strcasecmp ("Port", child->key) == 0)
622 cf_util_get_service (child, &conf_service);
623 else if (strcasecmp ("DeleteCounters", child->key) == 0)
624 cf_util_get_boolean (child, &conf_delete_counters);
625 else if (strcasecmp ("DeleteTimers", child->key) == 0)
626 cf_util_get_boolean (child, &conf_delete_timers);
627 else if (strcasecmp ("DeleteGauges", child->key) == 0)
628 cf_util_get_boolean (child, &conf_delete_gauges);
629 else if (strcasecmp ("DeleteSets", child->key) == 0)
630 cf_util_get_boolean (child, &conf_delete_sets);
631 else if (strcasecmp ("TimerPercentile", child->key) == 0)
632 statsd_config_timer_percentile (child);
634 ERROR ("statsd plugin: The \"%s\" config option is not valid.",
639 } /* }}} int statsd_config */
641 static int statsd_init (void) /* {{{ */
643 pthread_mutex_lock (&metrics_lock);
644 if (metrics_tree == NULL)
645 metrics_tree = c_avl_create ((void *) strcmp);
647 if (!network_thread_running)
651 status = pthread_create (&network_thread,
653 statsd_network_thread,
658 pthread_mutex_unlock (&metrics_lock);
659 ERROR ("statsd plugin: pthread_create failed: %s",
660 sstrerror (errno, errbuf, sizeof (errbuf)));
664 network_thread_running = 1;
666 pthread_mutex_unlock (&metrics_lock);
669 } /* }}} int statsd_init */
671 /* Must hold metrics_lock when calling this function. */
672 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
677 if ((metric == NULL) || (metric->type != STATSD_SET))
680 if (metric->set == NULL)
683 while (c_avl_pick (metric->set, &key, &value) == 0)
690 } /* }}} int statsd_metric_clear_set_unsafe */
692 /* Must hold metrics_lock when calling this function. */
693 static int statsd_metric_submit_unsafe (char const *name, /* {{{ */
694 statsd_metric_t const *metric)
697 value_list_t vl = VALUE_LIST_INIT;
701 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
702 sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
704 if (metric->type == STATSD_GAUGE)
705 sstrncpy (vl.type, "gauge", sizeof (vl.type));
706 else if (metric->type == STATSD_TIMER)
707 sstrncpy (vl.type, "latency", sizeof (vl.type));
708 else if (metric->type == STATSD_SET)
709 sstrncpy (vl.type, "objects", sizeof (vl.type));
710 else /* if (metric->type == STATSD_COUNTER) */
711 sstrncpy (vl.type, "derive", sizeof (vl.type));
713 sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
715 if (metric->type == STATSD_GAUGE)
716 values[0].gauge = (gauge_t) metric->value;
717 else if (metric->type == STATSD_TIMER)
721 if (metric->updates_num == 0)
726 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
728 values[0].gauge = CDTIME_T_TO_DOUBLE (
729 latency_counter_get_average (metric->latency));
730 plugin_dispatch_values (&vl);
732 for (i = 0; i < conf_timer_percentile_num; i++)
734 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
735 "%s-percentile-%.0f", name, conf_timer_percentile[i]);
736 values[0].gauge = CDTIME_T_TO_DOUBLE (
737 latency_counter_get_percentile (
738 metric->latency, conf_timer_percentile[i]));
739 plugin_dispatch_values (&vl);
742 latency_counter_reset (metric->latency);
745 else if (metric->type == STATSD_SET)
747 if (metric->set == NULL)
748 values[0].gauge = 0.0;
750 values[0].gauge = (gauge_t) c_avl_size (metric->set);
753 values[0].derive = (derive_t) metric->value;
755 return (plugin_dispatch_values (&vl));
756 } /* }}} int statsd_metric_submit_unsafe */
758 static int statsd_read (void) /* {{{ */
760 c_avl_iterator_t *iter;
762 statsd_metric_t *metric;
764 char **to_be_deleted = NULL;
765 size_t to_be_deleted_num = 0;
768 pthread_mutex_lock (&metrics_lock);
770 if (metrics_tree == NULL)
772 pthread_mutex_unlock (&metrics_lock);
776 iter = c_avl_get_iterator (metrics_tree);
777 while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
779 if ((metric->updates_num == 0)
780 && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
781 || (conf_delete_timers && (metric->type == STATSD_TIMER))
782 || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
783 || (conf_delete_sets && (metric->type == STATSD_SET))))
785 DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
786 strarray_add (&to_be_deleted, &to_be_deleted_num, name);
790 /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
791 * Remove this here. */
792 statsd_metric_submit_unsafe (name + 2, metric);
794 /* Reset the metric. */
795 metric->updates_num = 0;
796 if (metric->type == STATSD_SET)
797 statsd_metric_clear_set_unsafe (metric);
799 c_avl_iterator_destroy (iter);
801 for (i = 0; i < to_be_deleted_num; i++)
805 status = c_avl_remove (metrics_tree, to_be_deleted[i],
806 (void *) &name, (void *) &metric);
809 ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
810 to_be_deleted[i], status);
818 pthread_mutex_unlock (&metrics_lock);
820 strarray_free (to_be_deleted, to_be_deleted_num);
823 } /* }}} int statsd_read */
825 static int statsd_shutdown (void) /* {{{ */
830 pthread_mutex_lock (&metrics_lock);
832 if (network_thread_running)
834 network_thread_shutdown = 1;
835 pthread_kill (network_thread, SIGTERM);
836 pthread_join (network_thread, /* retval = */ NULL);
838 network_thread_running = 0;
840 while (c_avl_pick (metrics_tree, &key, &value) == 0)
845 c_avl_destroy (metrics_tree);
849 sfree (conf_service);
851 pthread_mutex_unlock (&metrics_lock);
854 } /* }}} int statsd_shutdown */
856 void module_register (void)
858 plugin_register_complex_config ("statsd", statsd_config);
859 plugin_register_init ("statsd", statsd_init);
860 plugin_register_read ("statsd", statsd_read);
861 plugin_register_shutdown ("statsd", statsd_shutdown);
864 /* vim: set sw=2 sts=2 et fdm=marker : */