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"
50 typedef enum metric_type_e metric_type_t;
52 struct statsd_metric_s
56 unsigned long updates_num;
58 typedef struct statsd_metric_s statsd_metric_t;
60 static c_avl_tree_t *metrics_tree = NULL;
61 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
63 static pthread_t network_thread;
64 static _Bool network_thread_running = 0;
65 static _Bool network_thread_shutdown = 0;
67 static char *conf_node = NULL;
68 static char *conf_service = NULL;
70 static _Bool conf_delete_counters = 0;
71 static _Bool conf_delete_timers = 0;
72 static _Bool conf_delete_gauges = 0;
74 /* Must hold metrics_lock when calling this function. */
75 static int statsd_metric_set_unsafe (char const *name, int64_t value, /* {{{ */
78 statsd_metric_t *metric;
82 status = c_avl_get (metrics_tree, name, (void *) &metric);
85 metric->value = value;
86 metric->updates_num++;
91 DEBUG ("stats plugin: Adding new metric \"%s\".", name);
92 /* FIXME: The keys should have a prefix so counter, gauge and timer with the
93 * same name can exist. */
95 metric = calloc (1, sizeof (*metric));
96 if ((key == NULL) || (metric == NULL))
104 metric->value = value;
105 metric->updates_num = 1;
107 status = c_avl_insert (metrics_tree, key, metric);
117 } /* }}} int statsd_metric_set_unsafe */
119 static int statsd_metric_set (char const *name, int64_t value, /* {{{ */
124 pthread_mutex_lock (&metrics_lock);
125 status = statsd_metric_set_unsafe (name, value, type);
126 pthread_mutex_unlock (&metrics_lock);
129 } /* }}} int statsd_metric_set */
131 static int statsd_metric_add (char const *name, int64_t delta, /* {{{ */
134 statsd_metric_t *metric;
137 pthread_mutex_lock (&metrics_lock);
139 status = c_avl_get (metrics_tree, name, (void *) &metric);
142 metric->value += delta;
143 metric->updates_num++;
145 pthread_mutex_unlock (&metrics_lock);
148 else /* no such value yet */
150 status = statsd_metric_set_unsafe (name, delta, type);
152 pthread_mutex_unlock (&metrics_lock);
155 } /* }}} int statsd_metric_add */
157 static int statsd_handle_counter (char const *name, /* {{{ */
158 char const *value_str,
165 if ((extra != NULL) && (extra[0] != '@'))
171 status = parse_value (extra + 1, &scale, DS_TYPE_GAUGE);
175 if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
180 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
184 if (value.derive < 1)
187 return (statsd_metric_add (name,
188 (int64_t) (((gauge_t) value.derive) / scale.gauge),
190 } /* }}} int statsd_handle_counter */
192 static int statsd_handle_gauge (char const *name, /* {{{ */
193 char const *value_str)
199 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
203 if ((value_str[0] == '+') || (value_str[0] == '-'))
204 return (statsd_metric_add (name, (int64_t) value.derive, STATSD_GAUGE));
206 return (statsd_metric_set (name, (int64_t) value.derive, STATSD_GAUGE));
207 } /* }}} int statsd_handle_gauge */
209 static int statsd_handle_timer (char const *name, /* {{{ */
210 char const *value_str)
216 status = parse_value (value_str, &value, DS_TYPE_DERIVE);
220 return (statsd_metric_add (name, (int64_t) value.derive, STATSD_TIMER));
221 } /* }}} int statsd_handle_timer */
223 static int statsd_handle_set (char const *name __attribute__((unused)), /* {{{ */
224 char const *value_str __attribute__((unused)))
226 static c_complain_t c = C_COMPLAIN_INIT_STATIC;
228 c_complain (LOG_WARNING, &c,
229 "statsd plugin: Support for sets is not yet implemented.");
232 } /* }}} int statsd_handle_set */
234 static int statsd_parse_line (char *buffer) /* {{{ */
241 type = strchr (name, '|');
247 value = strrchr (name, ':');
253 extra = strchr (type, '|');
260 if (strcmp ("c", type) == 0)
261 return (statsd_handle_counter (name, value, extra));
263 /* extra is only valid for counters */
267 if (strcmp ("g", type) == 0)
268 return (statsd_handle_gauge (name, value));
269 else if (strcmp ("ms", type) == 0)
270 return (statsd_handle_timer (name, value));
271 else if (strcmp ("s", type) == 0)
272 return (statsd_handle_set (name, value));
275 } /* }}} void statsd_parse_line */
277 static void statsd_parse_buffer (char *buffer) /* {{{ */
280 char *saveptr = NULL;
284 (ptr = strtok_r (dummy, "\r\n", &saveptr)) != NULL;
287 char *line_orig = sstrdup (ptr);
290 status = statsd_parse_line (ptr);
292 ERROR ("statsd plugin: Unable to parse line: \"%s\"", line_orig);
296 } /* }}} void statsd_parse_buffer */
298 static void statsd_network_read (int fd) /* {{{ */
304 status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
309 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
312 ERROR ("statsd plugin: recv(2) failed: %s",
313 sstrerror (errno, errbuf, sizeof (errbuf)));
317 buffer_size = (size_t) status;
318 if (buffer_size >= sizeof (buffer))
319 buffer_size = sizeof (buffer) - 1;
320 buffer[buffer_size] = 0;
322 statsd_parse_buffer (buffer);
323 } /* }}} void statsd_network_read */
325 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
328 struct pollfd *fds = NULL;
331 struct addrinfo ai_hints;
332 struct addrinfo *ai_list = NULL;
333 struct addrinfo *ai_ptr;
336 char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
337 char const *service = (conf_service != NULL)
338 ? conf_service : STATSD_DEFAULT_SERVICE;
340 memset (&ai_hints, 0, sizeof (ai_hints));
341 ai_hints.ai_flags = AI_PASSIVE;
343 ai_hints.ai_flags |= AI_ADDRCONFIG;
345 ai_hints.ai_family = AF_UNSPEC;
346 ai_hints.ai_socktype = SOCK_DGRAM;
348 status = getaddrinfo (node, service, &ai_hints, &ai_list);
351 ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
352 node, service, gai_strerror (status));
356 for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
361 char dbg_node[NI_MAXHOST];
362 char dbg_service[NI_MAXSERV];
364 fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
368 ERROR ("statsd plugin: socket(2) failed: %s",
369 sstrerror (errno, errbuf, sizeof (errbuf)));
373 getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
374 dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
375 NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
376 DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
378 status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
382 ERROR ("statsd plugin: bind(2) failed: %s",
383 sstrerror (errno, errbuf, sizeof (errbuf)));
388 tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
391 ERROR ("statsd plugin: realloc failed.");
398 memset (tmp, 0, sizeof (*tmp));
400 tmp->events = POLLIN | POLLPRI;
403 freeaddrinfo (ai_list);
407 ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
408 (node != NULL) ? node : "::", service);
413 *ret_fds_num = fds_num;
415 } /* }}} int statsd_network_init */
417 static void *statsd_network_thread (void *args) /* {{{ */
419 struct pollfd *fds = NULL;
424 status = statsd_network_init (&fds, &fds_num);
427 ERROR ("statsd plugin: Unable to open listening sockets.");
428 pthread_exit ((void *) 0);
431 while (!network_thread_shutdown)
433 status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
438 if ((errno == EINTR) || (errno == EAGAIN))
441 ERROR ("statsd plugin: poll(2) failed: %s",
442 sstrerror (errno, errbuf, sizeof (errbuf)));
446 for (i = 0; i < fds_num; i++)
448 if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
451 statsd_network_read (fds[i].fd);
454 } /* while (!network_thread_shutdown) */
457 for (i = 0; i < fds_num; i++)
462 } /* }}} void *statsd_network_thread */
464 static int statsd_config (oconfig_item_t *ci) /* {{{ */
468 for (i = 0; i < ci->children_num; i++)
470 oconfig_item_t *child = ci->children + i;
472 if (strcasecmp ("Host", child->key) == 0)
473 cf_util_get_string (child, &conf_node);
474 else if (strcasecmp ("Port", child->key) == 0)
475 cf_util_get_service (child, &conf_service);
476 else if (strcasecmp ("DeleteCounters", child->key) == 0)
477 cf_util_get_boolean (child, &conf_delete_counters);
478 else if (strcasecmp ("DeleteTimers", child->key) == 0)
479 cf_util_get_boolean (child, &conf_delete_timers);
480 else if (strcasecmp ("DeleteGauges", child->key) == 0)
481 cf_util_get_boolean (child, &conf_delete_gauges);
483 ERROR ("statsd plugin: The \"%s\" config option is not valid.",
488 } /* }}} int statsd_config */
490 static int statsd_init (void) /* {{{ */
492 pthread_mutex_lock (&metrics_lock);
493 if (metrics_tree == NULL)
494 metrics_tree = c_avl_create ((void *) strcasecmp);
496 if (!network_thread_running)
500 status = pthread_create (&network_thread,
502 statsd_network_thread,
507 pthread_mutex_unlock (&metrics_lock);
508 ERROR ("statsd plugin: pthread_create failed: %s",
509 sstrerror (errno, errbuf, sizeof (errbuf)));
513 network_thread_running = 1;
515 pthread_mutex_unlock (&metrics_lock);
518 } /* }}} int statsd_init */
520 static int statsd_metric_submit (char const *name, /* {{{ */
521 statsd_metric_t const *metric)
524 value_list_t vl = VALUE_LIST_INIT;
526 if (metric->type == STATSD_GAUGE)
527 values[0].gauge = (gauge_t) metric->value;
528 else if (metric->type == STATSD_TIMER)
530 if (metric->updates_num == 0)
531 values[0].gauge = NAN;
534 ((gauge_t) metric->value) / ((gauge_t) metric->updates_num);
537 values[0].derive = (derive_t) metric->value;
541 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
542 sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
544 if (metric->type == STATSD_GAUGE)
545 sstrncpy (vl.type, "gauge", sizeof (vl.type));
546 else if (metric->type == STATSD_TIMER)
547 sstrncpy (vl.type, "latency", sizeof (vl.type));
548 else /* if (metric->type == STATSD_COUNTER) */
549 sstrncpy (vl.type, "derive", sizeof (vl.type));
551 sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
553 return (plugin_dispatch_values (&vl));
554 } /* }}} int statsd_metric_submit */
556 static int statsd_read (void) /* {{{ */
558 c_avl_iterator_t *iter;
560 statsd_metric_t *metric;
562 char **to_be_deleted = NULL;
563 size_t to_be_deleted_num = 0;
566 pthread_mutex_lock (&metrics_lock);
568 if (metrics_tree == NULL)
570 pthread_mutex_unlock (&metrics_lock);
574 iter = c_avl_get_iterator (metrics_tree);
575 while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
577 if ((metric->updates_num == 0)
578 && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
579 || (conf_delete_timers && (metric->type == STATSD_TIMER))
580 || (conf_delete_gauges && (metric->type == STATSD_GAUGE))))
582 DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
583 strarray_add (&to_be_deleted, &to_be_deleted_num, name);
587 statsd_metric_submit (name, metric);
588 metric->updates_num = 0;
590 c_avl_iterator_destroy (iter);
592 for (i = 0; i < to_be_deleted_num; i++)
596 status = c_avl_remove (metrics_tree, to_be_deleted[i],
597 (void *) &name, (void *) &metric);
600 ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
601 to_be_deleted[i], status);
609 pthread_mutex_unlock (&metrics_lock);
611 strarray_free (to_be_deleted, to_be_deleted_num);
614 } /* }}} int statsd_read */
616 static int statsd_shutdown (void) /* {{{ */
621 pthread_mutex_lock (&metrics_lock);
623 if (network_thread_running)
625 network_thread_shutdown = 1;
626 pthread_kill (network_thread, SIGTERM);
627 pthread_join (network_thread, /* retval = */ NULL);
629 network_thread_running = 0;
631 while (c_avl_pick (metrics_tree, &key, &value) == 0)
636 c_avl_destroy (metrics_tree);
640 sfree (conf_service);
642 pthread_mutex_unlock (&metrics_lock);
645 } /* }}} int statsd_shutdown */
647 void module_register (void)
649 plugin_register_complex_config ("statsd", statsd_config);
650 plugin_register_init ("statsd", statsd_init);
651 plugin_register_read ("statsd", statsd_read);
652 plugin_register_shutdown ("statsd", statsd_shutdown);
655 /* vim: set sw=2 sts=2 et fdm=marker : */