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"
31 #include <sys/types.h>
32 #include <sys/socket.h>
36 #ifndef STATSD_DEFAULT_NODE
37 # define STATSD_DEFAULT_NODE NULL
40 #ifndef STATSD_DEFAULT_SERVICE
41 # define STATSD_DEFAULT_SERVICE "8125"
51 typedef enum metric_type_e metric_type_t;
53 struct statsd_metric_s
58 unsigned long updates_num;
60 typedef struct statsd_metric_s statsd_metric_t;
62 static c_avl_tree_t *metrics_tree = NULL;
63 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
65 static pthread_t network_thread;
66 static _Bool network_thread_running = 0;
67 static _Bool network_thread_shutdown = 0;
69 static char *conf_node = NULL;
70 static char *conf_service = NULL;
72 static _Bool conf_delete_counters = 0;
73 static _Bool conf_delete_timers = 0;
74 static _Bool conf_delete_gauges = 0;
75 static _Bool conf_delete_sets = 0;
77 /* Must hold metrics_lock when calling this function. */
78 static int statsd_metric_set_unsafe (char const *name, int64_t value, /* {{{ */
81 statsd_metric_t *metric;
85 status = c_avl_get (metrics_tree, name, (void *) &metric);
88 metric->value = value;
89 metric->updates_num++;
94 DEBUG ("stats plugin: Adding new metric \"%s\".", name);
96 metric = calloc (1, sizeof (*metric));
97 if ((key == NULL) || (metric == NULL))
105 metric->value = value;
106 metric->updates_num = 1;
108 status = c_avl_insert (metrics_tree, key, metric);
118 } /* }}} int statsd_metric_set_unsafe */
120 static int statsd_metric_set (char const *name, int64_t value, /* {{{ */
125 pthread_mutex_lock (&metrics_lock);
126 status = statsd_metric_set_unsafe (name, value, type);
127 pthread_mutex_unlock (&metrics_lock);
130 } /* }}} int statsd_metric_set */
132 static int statsd_metric_add (char const *name, int64_t delta, /* {{{ */
135 statsd_metric_t *metric;
138 pthread_mutex_lock (&metrics_lock);
140 status = c_avl_get (metrics_tree, name, (void *) &metric);
143 metric->value += delta;
144 metric->updates_num++;
146 pthread_mutex_unlock (&metrics_lock);
149 else /* no such value yet */
151 status = statsd_metric_set_unsafe (name, delta, type);
153 pthread_mutex_unlock (&metrics_lock);
156 } /* }}} int statsd_metric_add */
158 static int statsd_handle_counter (char const *name, /* {{{ */
159 char const *value_str,
162 char key[DATA_MAX_NAME_LEN + 2];
167 if ((extra != NULL) && (extra[0] != '@'))
173 status = parse_value (extra + 1, &scale, DS_TYPE_GAUGE);
177 if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
182 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
186 if (value.derive < 1)
189 ssnprintf (key, sizeof (key), "c:%s", name);
191 return (statsd_metric_add (key,
192 (int64_t) (((gauge_t) value.derive) / scale.gauge),
194 } /* }}} int statsd_handle_counter */
196 static int statsd_handle_gauge (char const *name, /* {{{ */
197 char const *value_str)
199 char key[DATA_MAX_NAME_LEN + 2];
204 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
208 ssnprintf (key, sizeof (key), "g:%s", name);
210 if ((value_str[0] == '+') || (value_str[0] == '-'))
211 return (statsd_metric_add (key, (int64_t) value.derive, STATSD_GAUGE));
213 return (statsd_metric_set (key, (int64_t) value.derive, STATSD_GAUGE));
214 } /* }}} int statsd_handle_gauge */
216 static int statsd_handle_timer (char const *name, /* {{{ */
217 char const *value_str)
219 char key[DATA_MAX_NAME_LEN + 2];
224 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
228 ssnprintf (key, sizeof (key), "t:%s", name);
230 return (statsd_metric_add (key, (int64_t) value.derive, STATSD_TIMER));
231 } /* }}} int statsd_handle_timer */
233 static int statsd_handle_set (char const *key_orig, /* {{{ */
234 char const *name_orig)
236 char key[DATA_MAX_NAME_LEN + 2];
238 statsd_metric_t *metric = NULL;
241 ssnprintf (key, sizeof (key), "s:%s", key_orig);
243 pthread_mutex_lock (&metrics_lock);
245 status = c_avl_get (metrics_tree, key, (void *) &metric);
246 if (status != 0) /* Create a new metric */
250 DEBUG ("stats plugin: Adding new metric \"%s\".", key);
251 key_copy = strdup (key);
252 if (key_copy == NULL)
254 pthread_mutex_unlock (&metrics_lock);
255 ERROR ("statsd plugin: strdup failed.");
259 metric = calloc (1, sizeof (*metric));
262 pthread_mutex_unlock (&metrics_lock);
263 ERROR ("statsd plugin: calloc failed.");
267 metric->type = STATSD_SET;
270 status = c_avl_insert (metrics_tree, key_copy, metric);
273 pthread_mutex_unlock (&metrics_lock);
274 ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
281 assert (metric != NULL);
283 /* Make sure metric->set exists. */
284 if (metric->set == NULL)
285 metric->set = c_avl_create ((void *) strcmp);
287 if (metric->set == NULL)
289 pthread_mutex_unlock (&metrics_lock);
290 ERROR ("statsd plugin: c_avl_create failed.");
294 name = strdup (name_orig);
297 pthread_mutex_unlock (&metrics_lock);
298 ERROR ("statsd plugin: strdup failed.");
302 status = c_avl_insert (metric->set, name, /* value = */ NULL);
305 pthread_mutex_unlock (&metrics_lock);
307 ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
312 else if (status > 0) /* key already exists */
317 metric->updates_num++;
319 pthread_mutex_unlock (&metrics_lock);
321 } /* }}} int statsd_handle_set */
323 static int statsd_parse_line (char *buffer) /* {{{ */
330 type = strchr (name, '|');
336 value = strrchr (name, ':');
342 extra = strchr (type, '|');
349 if (strcmp ("c", type) == 0)
350 return (statsd_handle_counter (name, value, extra));
352 /* extra is only valid for counters */
356 if (strcmp ("g", type) == 0)
357 return (statsd_handle_gauge (name, value));
358 else if (strcmp ("ms", type) == 0)
359 return (statsd_handle_timer (name, value));
360 else if (strcmp ("s", type) == 0)
361 return (statsd_handle_set (name, value));
364 } /* }}} void statsd_parse_line */
366 static void statsd_parse_buffer (char *buffer) /* {{{ */
369 char *saveptr = NULL;
373 (ptr = strtok_r (dummy, "\r\n", &saveptr)) != NULL;
376 char *line_orig = sstrdup (ptr);
379 status = statsd_parse_line (ptr);
381 ERROR ("statsd plugin: Unable to parse line: \"%s\"", line_orig);
385 } /* }}} void statsd_parse_buffer */
387 static void statsd_network_read (int fd) /* {{{ */
393 status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
398 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
401 ERROR ("statsd plugin: recv(2) failed: %s",
402 sstrerror (errno, errbuf, sizeof (errbuf)));
406 buffer_size = (size_t) status;
407 if (buffer_size >= sizeof (buffer))
408 buffer_size = sizeof (buffer) - 1;
409 buffer[buffer_size] = 0;
411 statsd_parse_buffer (buffer);
412 } /* }}} void statsd_network_read */
414 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
417 struct pollfd *fds = NULL;
420 struct addrinfo ai_hints;
421 struct addrinfo *ai_list = NULL;
422 struct addrinfo *ai_ptr;
425 char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
426 char const *service = (conf_service != NULL)
427 ? conf_service : STATSD_DEFAULT_SERVICE;
429 memset (&ai_hints, 0, sizeof (ai_hints));
430 ai_hints.ai_flags = AI_PASSIVE;
432 ai_hints.ai_flags |= AI_ADDRCONFIG;
434 ai_hints.ai_family = AF_UNSPEC;
435 ai_hints.ai_socktype = SOCK_DGRAM;
437 status = getaddrinfo (node, service, &ai_hints, &ai_list);
440 ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
441 node, service, gai_strerror (status));
445 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
450 char dbg_node[NI_MAXHOST];
451 char dbg_service[NI_MAXSERV];
453 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
457 ERROR ("statsd plugin: socket(2) failed: %s",
458 sstrerror (errno, errbuf, sizeof (errbuf)));
462 getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
463 dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
464 NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
465 DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
467 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
471 ERROR ("statsd plugin: bind(2) failed: %s",
472 sstrerror (errno, errbuf, sizeof (errbuf)));
477 tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
480 ERROR ("statsd plugin: realloc failed.");
487 memset (tmp, 0, sizeof (*tmp));
489 tmp->events = POLLIN | POLLPRI;
492 freeaddrinfo (ai_list);
496 ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
497 (node != NULL) ? node : "::", service);
502 *ret_fds_num = fds_num;
504 } /* }}} int statsd_network_init */
506 static void *statsd_network_thread (void *args) /* {{{ */
508 struct pollfd *fds = NULL;
513 status = statsd_network_init (&fds, &fds_num);
516 ERROR ("statsd plugin: Unable to open listening sockets.");
517 pthread_exit ((void *) 0);
520 while (!network_thread_shutdown)
522 status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
527 if ((errno == EINTR) || (errno == EAGAIN))
530 ERROR ("statsd plugin: poll(2) failed: %s",
531 sstrerror (errno, errbuf, sizeof (errbuf)));
535 for (i = 0; i < fds_num; i++)
537 if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
540 statsd_network_read (fds[i].fd);
543 } /* while (!network_thread_shutdown) */
546 for (i = 0; i < fds_num; i++)
551 } /* }}} void *statsd_network_thread */
553 static int statsd_config (oconfig_item_t *ci) /* {{{ */
557 for (i = 0; i < ci->children_num; i++)
559 oconfig_item_t *child = ci->children + i;
561 if (strcasecmp ("Host", child->key) == 0)
562 cf_util_get_string (child, &conf_node);
563 else if (strcasecmp ("Port", child->key) == 0)
564 cf_util_get_service (child, &conf_service);
565 else if (strcasecmp ("DeleteCounters", child->key) == 0)
566 cf_util_get_boolean (child, &conf_delete_counters);
567 else if (strcasecmp ("DeleteTimers", child->key) == 0)
568 cf_util_get_boolean (child, &conf_delete_timers);
569 else if (strcasecmp ("DeleteGauges", child->key) == 0)
570 cf_util_get_boolean (child, &conf_delete_gauges);
571 else if (strcasecmp ("DeleteSets", child->key) == 0)
572 cf_util_get_boolean (child, &conf_delete_sets);
574 ERROR ("statsd plugin: The \"%s\" config option is not valid.",
579 } /* }}} int statsd_config */
581 static int statsd_init (void) /* {{{ */
583 pthread_mutex_lock (&metrics_lock);
584 if (metrics_tree == NULL)
585 metrics_tree = c_avl_create ((void *) strcasecmp);
587 if (!network_thread_running)
591 status = pthread_create (&network_thread,
593 statsd_network_thread,
598 pthread_mutex_unlock (&metrics_lock);
599 ERROR ("statsd plugin: pthread_create failed: %s",
600 sstrerror (errno, errbuf, sizeof (errbuf)));
604 network_thread_running = 1;
606 pthread_mutex_unlock (&metrics_lock);
609 } /* }}} int statsd_init */
611 /* Must hold metrics_lock when calling this function. */
612 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
617 if ((metric == NULL) || (metric->type != STATSD_SET))
620 if (metric->set == NULL)
623 while (c_avl_pick (metric->set, &key, &value) == 0)
630 } /* }}} int statsd_metric_clear_set_unsafe */
632 /* Must hold metrics_lock when calling this function. */
633 static int statsd_metric_submit_unsafe (char const *name, /* {{{ */
634 statsd_metric_t const *metric)
637 value_list_t vl = VALUE_LIST_INIT;
639 if (metric->type == STATSD_GAUGE)
640 values[0].gauge = (gauge_t) metric->value;
641 else if (metric->type == STATSD_TIMER)
643 if (metric->updates_num == 0)
644 values[0].gauge = NAN;
647 ((gauge_t) metric->value) / ((gauge_t) metric->updates_num);
649 else if (metric->type == STATSD_SET)
651 if (metric->set == NULL)
652 values[0].gauge = 0.0;
654 values[0].gauge = (gauge_t) c_avl_size (metric->set);
657 values[0].derive = (derive_t) metric->value;
661 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
662 sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
664 if (metric->type == STATSD_GAUGE)
665 sstrncpy (vl.type, "gauge", sizeof (vl.type));
666 else if (metric->type == STATSD_TIMER)
667 sstrncpy (vl.type, "latency", sizeof (vl.type));
668 else if (metric->type == STATSD_SET)
669 sstrncpy (vl.type, "objects", sizeof (vl.type));
670 else /* if (metric->type == STATSD_COUNTER) */
671 sstrncpy (vl.type, "derive", sizeof (vl.type));
673 sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
675 return (plugin_dispatch_values (&vl));
676 } /* }}} int statsd_metric_submit_unsafe */
678 static int statsd_read (void) /* {{{ */
680 c_avl_iterator_t *iter;
682 statsd_metric_t *metric;
684 char **to_be_deleted = NULL;
685 size_t to_be_deleted_num = 0;
688 pthread_mutex_lock (&metrics_lock);
690 if (metrics_tree == NULL)
692 pthread_mutex_unlock (&metrics_lock);
696 iter = c_avl_get_iterator (metrics_tree);
697 while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
699 if ((metric->updates_num == 0)
700 && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
701 || (conf_delete_timers && (metric->type == STATSD_TIMER))
702 || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
703 || (conf_delete_sets && (metric->type == STATSD_SET))))
705 DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
706 strarray_add (&to_be_deleted, &to_be_deleted_num, name);
710 /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
711 * Remove this here. */
712 statsd_metric_submit_unsafe (name + 2, metric);
714 /* Reset the metric. */
715 metric->updates_num = 0;
716 if (metric->type == STATSD_SET)
717 statsd_metric_clear_set_unsafe (metric);
719 c_avl_iterator_destroy (iter);
721 for (i = 0; i < to_be_deleted_num; i++)
725 status = c_avl_remove (metrics_tree, to_be_deleted[i],
726 (void *) &name, (void *) &metric);
729 ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
730 to_be_deleted[i], status);
738 pthread_mutex_unlock (&metrics_lock);
740 strarray_free (to_be_deleted, to_be_deleted_num);
743 } /* }}} int statsd_read */
745 static int statsd_shutdown (void) /* {{{ */
750 pthread_mutex_lock (&metrics_lock);
752 if (network_thread_running)
754 network_thread_shutdown = 1;
755 pthread_kill (network_thread, SIGTERM);
756 pthread_join (network_thread, /* retval = */ NULL);
758 network_thread_running = 0;
760 while (c_avl_pick (metrics_tree, &key, &value) == 0)
765 c_avl_destroy (metrics_tree);
769 sfree (conf_service);
771 pthread_mutex_unlock (&metrics_lock);
774 } /* }}} int statsd_shutdown */
776 void module_register (void)
778 plugin_register_complex_config ("statsd", statsd_config);
779 plugin_register_init ("statsd", statsd_init);
780 plugin_register_read ("statsd", statsd_read);
781 plugin_register_shutdown ("statsd", statsd_shutdown);
784 /* vim: set sw=2 sts=2 et fdm=marker : */