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 static _Bool conf_timer_lower = 0;
83 static _Bool conf_timer_upper = 0;
85 /* Must hold metrics_lock when calling this function. */
86 static statsd_metric_t *statsd_metric_lookup_unsafe (char const *name, /* {{{ */
89 char key[DATA_MAX_NAME_LEN + 2];
91 statsd_metric_t *metric;
96 case STATSD_COUNTER: key[0] = 'c'; break;
97 case STATSD_TIMER: key[0] = 't'; break;
98 case STATSD_GAUGE: key[0] = 'g'; break;
99 case STATSD_SET: key[0] = 's'; break;
100 default: return (NULL);
104 sstrncpy (&key[2], name, sizeof (key) - 2);
106 status = c_avl_get (metrics_tree, key, (void *) &metric);
110 key_copy = strdup (key);
111 if (key_copy == NULL)
113 ERROR ("statsd plugin: strdup failed.");
117 metric = malloc (sizeof (*metric));
120 ERROR ("statsd plugin: malloc failed.");
124 memset (metric, 0, sizeof (*metric));
127 metric->latency = NULL;
130 status = c_avl_insert (metrics_tree, key_copy, metric);
133 ERROR ("statsd plugin: c_avl_insert failed.");
140 } /* }}} statsd_metric_lookup_unsafe */
142 static int statsd_metric_set (char const *name, double value, /* {{{ */
145 statsd_metric_t *metric;
147 pthread_mutex_lock (&metrics_lock);
149 metric = statsd_metric_lookup_unsafe (name, type);
152 pthread_mutex_unlock (&metrics_lock);
156 metric->value = value;
157 metric->updates_num++;
159 pthread_mutex_unlock (&metrics_lock);
162 } /* }}} int statsd_metric_set */
164 static int statsd_metric_add (char const *name, double delta, /* {{{ */
167 statsd_metric_t *metric;
169 pthread_mutex_lock (&metrics_lock);
171 metric = statsd_metric_lookup_unsafe (name, type);
174 pthread_mutex_unlock (&metrics_lock);
178 metric->value += delta;
179 metric->updates_num++;
181 pthread_mutex_unlock (&metrics_lock);
184 } /* }}} int statsd_metric_add */
186 static int statsd_parse_value (char const *str, value_t *ret_value) /* {{{ */
190 ret_value->gauge = (gauge_t) strtod (str, &endptr);
191 if ((str == endptr) || ((endptr != NULL) && (*endptr != 0)))
195 } /* }}} int statsd_parse_value */
197 static int statsd_handle_counter (char const *name, /* {{{ */
198 char const *value_str,
205 if ((extra != NULL) && (extra[0] != '@'))
211 status = statsd_parse_value (extra + 1, &scale);
215 if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
220 status = statsd_parse_value (value_str, &value);
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 ("TimerLower", child->key) == 0)
632 cf_util_get_boolean (child, &conf_timer_lower);
633 else if (strcasecmp ("TimerUpper", child->key) == 0)
634 cf_util_get_boolean (child, &conf_timer_upper);
635 else if (strcasecmp ("TimerPercentile", child->key) == 0)
636 statsd_config_timer_percentile (child);
638 ERROR ("statsd plugin: The \"%s\" config option is not valid.",
643 } /* }}} int statsd_config */
645 static int statsd_init (void) /* {{{ */
647 pthread_mutex_lock (&metrics_lock);
648 if (metrics_tree == NULL)
649 metrics_tree = c_avl_create ((void *) strcmp);
651 if (!network_thread_running)
655 status = pthread_create (&network_thread,
657 statsd_network_thread,
662 pthread_mutex_unlock (&metrics_lock);
663 ERROR ("statsd plugin: pthread_create failed: %s",
664 sstrerror (errno, errbuf, sizeof (errbuf)));
668 network_thread_running = 1;
670 pthread_mutex_unlock (&metrics_lock);
673 } /* }}} int statsd_init */
675 /* Must hold metrics_lock when calling this function. */
676 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
681 if ((metric == NULL) || (metric->type != STATSD_SET))
684 if (metric->set == NULL)
687 while (c_avl_pick (metric->set, &key, &value) == 0)
694 } /* }}} int statsd_metric_clear_set_unsafe */
696 /* Must hold metrics_lock when calling this function. */
697 static int statsd_metric_submit_unsafe (char const *name, /* {{{ */
698 statsd_metric_t const *metric)
701 value_list_t vl = VALUE_LIST_INIT;
705 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
706 sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
708 if (metric->type == STATSD_GAUGE)
709 sstrncpy (vl.type, "gauge", sizeof (vl.type));
710 else if (metric->type == STATSD_TIMER)
711 sstrncpy (vl.type, "latency", sizeof (vl.type));
712 else if (metric->type == STATSD_SET)
713 sstrncpy (vl.type, "objects", sizeof (vl.type));
714 else /* if (metric->type == STATSD_COUNTER) */
715 sstrncpy (vl.type, "derive", sizeof (vl.type));
717 sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
719 if (metric->type == STATSD_GAUGE)
720 values[0].gauge = (gauge_t) metric->value;
721 else if (metric->type == STATSD_TIMER)
725 if (metric->updates_num == 0)
730 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
732 values[0].gauge = CDTIME_T_TO_DOUBLE (
733 latency_counter_get_average (metric->latency));
734 plugin_dispatch_values (&vl);
736 if (conf_timer_lower) {
737 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
739 values[0].gauge = CDTIME_T_TO_DOUBLE (
740 latency_counter_get_min (metric->latency));
741 plugin_dispatch_values (&vl);
744 if (conf_timer_upper) {
745 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
747 values[0].gauge = CDTIME_T_TO_DOUBLE (
748 latency_counter_get_max (metric->latency));
749 plugin_dispatch_values (&vl);
752 for (i = 0; i < conf_timer_percentile_num; i++)
754 ssnprintf (vl.type_instance, sizeof (vl.type_instance),
755 "%s-percentile-%.0f", name, conf_timer_percentile[i]);
756 values[0].gauge = CDTIME_T_TO_DOUBLE (
757 latency_counter_get_percentile (
758 metric->latency, conf_timer_percentile[i]));
759 plugin_dispatch_values (&vl);
762 latency_counter_reset (metric->latency);
765 else if (metric->type == STATSD_SET)
767 if (metric->set == NULL)
768 values[0].gauge = 0.0;
770 values[0].gauge = (gauge_t) c_avl_size (metric->set);
773 values[0].derive = (derive_t) metric->value;
775 return (plugin_dispatch_values (&vl));
776 } /* }}} int statsd_metric_submit_unsafe */
778 static int statsd_read (void) /* {{{ */
780 c_avl_iterator_t *iter;
782 statsd_metric_t *metric;
784 char **to_be_deleted = NULL;
785 size_t to_be_deleted_num = 0;
788 pthread_mutex_lock (&metrics_lock);
790 if (metrics_tree == NULL)
792 pthread_mutex_unlock (&metrics_lock);
796 iter = c_avl_get_iterator (metrics_tree);
797 while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
799 if ((metric->updates_num == 0)
800 && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
801 || (conf_delete_timers && (metric->type == STATSD_TIMER))
802 || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
803 || (conf_delete_sets && (metric->type == STATSD_SET))))
805 DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
806 strarray_add (&to_be_deleted, &to_be_deleted_num, name);
810 /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
811 * Remove this here. */
812 statsd_metric_submit_unsafe (name + 2, metric);
814 /* Reset the metric. */
815 metric->updates_num = 0;
816 if (metric->type == STATSD_SET)
817 statsd_metric_clear_set_unsafe (metric);
819 c_avl_iterator_destroy (iter);
821 for (i = 0; i < to_be_deleted_num; i++)
825 status = c_avl_remove (metrics_tree, to_be_deleted[i],
826 (void *) &name, (void *) &metric);
829 ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
830 to_be_deleted[i], status);
838 pthread_mutex_unlock (&metrics_lock);
840 strarray_free (to_be_deleted, to_be_deleted_num);
843 } /* }}} int statsd_read */
845 static int statsd_shutdown (void) /* {{{ */
850 pthread_mutex_lock (&metrics_lock);
852 if (network_thread_running)
854 network_thread_shutdown = 1;
855 pthread_kill (network_thread, SIGTERM);
856 pthread_join (network_thread, /* retval = */ NULL);
858 network_thread_running = 0;
860 while (c_avl_pick (metrics_tree, &key, &value) == 0)
865 c_avl_destroy (metrics_tree);
869 sfree (conf_service);
871 pthread_mutex_unlock (&metrics_lock);
874 } /* }}} int statsd_shutdown */
876 void module_register (void)
878 plugin_register_complex_config ("statsd", statsd_config);
879 plugin_register_init ("statsd", statsd_init);
880 plugin_register_read ("statsd", statsd_read);
881 plugin_register_shutdown ("statsd", statsd_shutdown);
884 /* vim: set sw=2 sts=2 et fdm=marker : */