Merge branch 'udev-disk'
[collectd.git] / src / statsd.c
1 /**
2  * collectd - src/statsd.c
3  *
4  * Copyright (C) 2013       Florian octo Forster
5  *
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.
9  *
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.
17  *
18  * Authors:
19  *   Florian octo Forster <octo at collectd.org>
20  */
21
22 #include "collectd.h"
23 #include "plugin.h"
24 #include "common.h"
25 #include "configfile.h"
26 #include "utils_avltree.h"
27 #include "utils_complain.h"
28 #include "utils_latency.h"
29
30 #include <pthread.h>
31
32 #include <sys/types.h>
33 #include <sys/socket.h>
34 #include <netdb.h>
35 #include <poll.h>
36
37 /* AIX doesn't have MSG_DONTWAIT */
38 #ifndef MSG_DONTWAIT
39 #  define MSG_DONTWAIT MSG_NONBLOCK
40 #endif
41
42 #ifndef STATSD_DEFAULT_NODE
43 # define STATSD_DEFAULT_NODE NULL
44 #endif
45
46 #ifndef STATSD_DEFAULT_SERVICE
47 # define STATSD_DEFAULT_SERVICE "8125"
48 #endif
49
50 enum metric_type_e
51 {
52   STATSD_COUNTER,
53   STATSD_TIMER,
54   STATSD_GAUGE,
55   STATSD_SET
56 };
57 typedef enum metric_type_e metric_type_t;
58
59 struct statsd_metric_s
60 {
61   metric_type_t type;
62   double value;
63   latency_counter_t *latency;
64   c_avl_tree_t *set;
65   unsigned long updates_num;
66 };
67 typedef struct statsd_metric_s statsd_metric_t;
68
69 static c_avl_tree_t   *metrics_tree = NULL;
70 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
71
72 static pthread_t network_thread;
73 static _Bool     network_thread_running = 0;
74 static _Bool     network_thread_shutdown = 0;
75
76 static char *conf_node = NULL;
77 static char *conf_service = NULL;
78
79 static _Bool conf_delete_counters = 0;
80 static _Bool conf_delete_timers   = 0;
81 static _Bool conf_delete_gauges   = 0;
82 static _Bool conf_delete_sets     = 0;
83
84 static double *conf_timer_percentile = NULL;
85 static size_t  conf_timer_percentile_num = 0;
86
87 static _Bool conf_timer_lower     = 0;
88 static _Bool conf_timer_upper     = 0;
89 static _Bool conf_timer_sum       = 0;
90 static _Bool conf_timer_count     = 0;
91
92 /* Must hold metrics_lock when calling this function. */
93 static statsd_metric_t *statsd_metric_lookup_unsafe (char const *name, /* {{{ */
94     metric_type_t type)
95 {
96   char key[DATA_MAX_NAME_LEN + 2];
97   char *key_copy;
98   statsd_metric_t *metric;
99   int status;
100
101   switch (type)
102   {
103     case STATSD_COUNTER: key[0] = 'c'; break;
104     case STATSD_TIMER:   key[0] = 't'; break;
105     case STATSD_GAUGE:   key[0] = 'g'; break;
106     case STATSD_SET:     key[0] = 's'; break;
107     default: return (NULL);
108   }
109
110   key[1] = ':';
111   sstrncpy (&key[2], name, sizeof (key) - 2);
112
113   status = c_avl_get (metrics_tree, key, (void *) &metric);
114   if (status == 0)
115     return (metric);
116
117   key_copy = strdup (key);
118   if (key_copy == NULL)
119   {
120     ERROR ("statsd plugin: strdup failed.");
121     return (NULL);
122   }
123
124   metric = malloc (sizeof (*metric));
125   if (metric == NULL)
126   {
127     ERROR ("statsd plugin: malloc failed.");
128     sfree (key_copy);
129     return (NULL);
130   }
131   memset (metric, 0, sizeof (*metric));
132
133   metric->type = type;
134   metric->latency = NULL;
135   metric->set = NULL;
136
137   status = c_avl_insert (metrics_tree, key_copy, metric);
138   if (status != 0)
139   {
140     ERROR ("statsd plugin: c_avl_insert failed.");
141     sfree (key_copy);
142     sfree (metric);
143     return (NULL);
144   }
145
146   return (metric);
147 } /* }}} statsd_metric_lookup_unsafe */
148
149 static int statsd_metric_set (char const *name, double value, /* {{{ */
150     metric_type_t type)
151 {
152   statsd_metric_t *metric;
153
154   pthread_mutex_lock (&metrics_lock);
155
156   metric = statsd_metric_lookup_unsafe (name, type);
157   if (metric == NULL)
158   {
159     pthread_mutex_unlock (&metrics_lock);
160     return (-1);
161   }
162
163   metric->value = value;
164   metric->updates_num++;
165
166   pthread_mutex_unlock (&metrics_lock);
167
168   return (0);
169 } /* }}} int statsd_metric_set */
170
171 static int statsd_metric_add (char const *name, double delta, /* {{{ */
172     metric_type_t type)
173 {
174   statsd_metric_t *metric;
175
176   pthread_mutex_lock (&metrics_lock);
177
178   metric = statsd_metric_lookup_unsafe (name, type);
179   if (metric == NULL)
180   {
181     pthread_mutex_unlock (&metrics_lock);
182     return (-1);
183   }
184
185   metric->value += delta;
186   metric->updates_num++;
187
188   pthread_mutex_unlock (&metrics_lock);
189
190   return (0);
191 } /* }}} int statsd_metric_add */
192
193 static int statsd_parse_value (char const *str, value_t *ret_value) /* {{{ */
194 {
195   char *endptr = NULL;
196
197   ret_value->gauge = (gauge_t) strtod (str, &endptr);
198   if ((str == endptr) || ((endptr != NULL) && (*endptr != 0)))
199     return (-1);
200
201   return (0);
202 } /* }}} int statsd_parse_value */
203
204 static int statsd_handle_counter (char const *name, /* {{{ */
205     char const *value_str,
206     char const *extra)
207 {
208   value_t value;
209   value_t scale;
210   int status;
211
212   if ((extra != NULL) && (extra[0] != '@'))
213     return (-1);
214
215   scale.gauge = 1.0;
216   if (extra != NULL)
217   {
218     status = statsd_parse_value (extra + 1, &scale);
219     if (status != 0)
220       return (status);
221
222     if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
223       return (-1);
224   }
225
226   value.gauge = 1.0;
227   status = statsd_parse_value (value_str, &value);
228   if (status != 0)
229     return (status);
230
231   return (statsd_metric_add (name, (double) (value.gauge / scale.gauge),
232         STATSD_COUNTER));
233 } /* }}} int statsd_handle_counter */
234
235 static int statsd_handle_gauge (char const *name, /* {{{ */
236     char const *value_str)
237 {
238   value_t value;
239   int status;
240
241   value.gauge = 0;
242   status = statsd_parse_value (value_str, &value);
243   if (status != 0)
244     return (status);
245
246   if ((value_str[0] == '+') || (value_str[0] == '-'))
247     return (statsd_metric_add (name, (double) value.gauge, STATSD_GAUGE));
248   else
249     return (statsd_metric_set (name, (double) value.gauge, STATSD_GAUGE));
250 } /* }}} int statsd_handle_gauge */
251
252 static int statsd_handle_timer (char const *name, /* {{{ */
253     char const *value_str)
254 {
255   statsd_metric_t *metric;
256   value_t value_ms;
257   cdtime_t value;
258   int status;
259
260   value_ms.derive = 0;
261   status = statsd_parse_value (value_str, &value_ms);
262   if (status != 0)
263     return (status);
264
265   value = MS_TO_CDTIME_T (value_ms.gauge);
266
267   pthread_mutex_lock (&metrics_lock);
268
269   metric = statsd_metric_lookup_unsafe (name, STATSD_TIMER);
270   if (metric == NULL)
271   {
272     pthread_mutex_unlock (&metrics_lock);
273     return (-1);
274   }
275
276   if (metric->latency == NULL)
277     metric->latency = latency_counter_create ();
278   if (metric->latency == NULL)
279   {
280     pthread_mutex_unlock (&metrics_lock);
281     return (-1);
282   }
283
284   latency_counter_add (metric->latency, value);
285   metric->updates_num++;
286
287   pthread_mutex_unlock (&metrics_lock);
288   return (0);
289 } /* }}} int statsd_handle_timer */
290
291 static int statsd_handle_set (char const *name, /* {{{ */
292     char const *set_key_orig)
293 {
294   statsd_metric_t *metric = NULL;
295   char *set_key;
296   int status;
297
298   pthread_mutex_lock (&metrics_lock);
299
300   metric = statsd_metric_lookup_unsafe (name, STATSD_SET);
301   if (metric == NULL)
302   {
303     pthread_mutex_unlock (&metrics_lock);
304     return (-1);
305   }
306
307   /* Make sure metric->set exists. */
308   if (metric->set == NULL)
309     metric->set = c_avl_create ((void *) strcmp);
310
311   if (metric->set == NULL)
312   {
313     pthread_mutex_unlock (&metrics_lock);
314     ERROR ("statsd plugin: c_avl_create failed.");
315     return (-1);
316   }
317
318   set_key = strdup (set_key_orig);
319   if (set_key == NULL)
320   {
321     pthread_mutex_unlock (&metrics_lock);
322     ERROR ("statsd plugin: strdup failed.");
323     return (-1);
324   }
325
326   status = c_avl_insert (metric->set, set_key, /* value = */ NULL);
327   if (status < 0)
328   {
329     pthread_mutex_unlock (&metrics_lock);
330     if (status < 0)
331       ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
332           set_key, status);
333     sfree (set_key);
334     return (-1);
335   }
336   else if (status > 0) /* key already exists */
337   {
338     sfree (set_key);
339   }
340
341   metric->updates_num++;
342
343   pthread_mutex_unlock (&metrics_lock);
344   return (0);
345 } /* }}} int statsd_handle_set */
346
347 static int statsd_parse_line (char *buffer) /* {{{ */
348 {
349   char *name = buffer;
350   char *value;
351   char *type;
352   char *extra;
353
354   type = strchr (name, '|');
355   if (type == NULL)
356     return (-1);
357   *type = 0;
358   type++;
359
360   value = strrchr (name, ':');
361   if (value == NULL)
362     return (-1);
363   *value = 0;
364   value++;
365
366   extra = strchr (type, '|');
367   if (extra != NULL)
368   {
369     *extra = 0;
370     extra++;
371   }
372
373   if (strcmp ("c", type) == 0)
374     return (statsd_handle_counter (name, value, extra));
375
376   /* extra is only valid for counters */
377   if (extra != NULL)
378     return (-1);
379
380   if (strcmp ("g", type) == 0)
381     return (statsd_handle_gauge (name, value));
382   else if (strcmp ("ms", type) == 0)
383     return (statsd_handle_timer (name, value));
384   else if (strcmp ("s", type) == 0)
385     return (statsd_handle_set (name, value));
386   else
387     return (-1);
388 } /* }}} void statsd_parse_line */
389
390 static void statsd_parse_buffer (char *buffer) /* {{{ */
391 {
392   while (buffer != NULL)
393   {
394     char orig[64];
395     char *next;
396     int status;
397
398     next = strchr (buffer, '\n');
399     if (next != NULL)
400     {
401       *next = 0;
402       next++;
403     }
404
405     if (*buffer == 0)
406     {
407       buffer = next;
408       continue;
409     }
410
411     sstrncpy (orig, buffer, sizeof (orig));
412
413     status = statsd_parse_line (buffer);
414     if (status != 0)
415       ERROR ("statsd plugin: Unable to parse line: \"%s\"", orig);
416
417     buffer = next;
418   }
419 } /* }}} void statsd_parse_buffer */
420
421 static void statsd_network_read (int fd) /* {{{ */
422 {
423   char buffer[4096];
424   size_t buffer_size;
425   ssize_t status;
426
427   status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
428   if (status < 0)
429   {
430     char errbuf[1024];
431
432     if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
433       return;
434
435     ERROR ("statsd plugin: recv(2) failed: %s",
436         sstrerror (errno, errbuf, sizeof (errbuf)));
437     return;
438   }
439
440   buffer_size = (size_t) status;
441   if (buffer_size >= sizeof (buffer))
442     buffer_size = sizeof (buffer) - 1;
443   buffer[buffer_size] = 0;
444
445   statsd_parse_buffer (buffer);
446 } /* }}} void statsd_network_read */
447
448 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
449     size_t *ret_fds_num)
450 {
451   struct pollfd *fds = NULL;
452   size_t fds_num = 0;
453
454   struct addrinfo ai_hints;
455   struct addrinfo *ai_list = NULL;
456   struct addrinfo *ai_ptr;
457   int status;
458
459   char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
460   char const *service = (conf_service != NULL)
461     ? conf_service : STATSD_DEFAULT_SERVICE;
462
463   memset (&ai_hints, 0, sizeof (ai_hints));
464   ai_hints.ai_flags = AI_PASSIVE;
465 #ifdef AI_ADDRCONFIG
466   ai_hints.ai_flags |= AI_ADDRCONFIG;
467 #endif
468   ai_hints.ai_family = AF_UNSPEC;
469   ai_hints.ai_socktype = SOCK_DGRAM;
470
471   status = getaddrinfo (node, service, &ai_hints, &ai_list);
472   if (status != 0)
473   {
474     ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
475         node, service, gai_strerror (status));
476     return (status);
477   }
478
479   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
480   {
481     int fd;
482     struct pollfd *tmp;
483
484     char dbg_node[NI_MAXHOST];
485     char dbg_service[NI_MAXSERV];
486
487     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
488     if (fd < 0)
489     {
490       char errbuf[1024];
491       ERROR ("statsd plugin: socket(2) failed: %s",
492           sstrerror (errno, errbuf, sizeof (errbuf)));
493       continue;
494     }
495
496     getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
497         dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
498         NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
499     DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
500
501     status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
502     if (status != 0)
503     {
504       char errbuf[1024];
505       ERROR ("statsd plugin: bind(2) failed: %s",
506           sstrerror (errno, errbuf, sizeof (errbuf)));
507       close (fd);
508       continue;
509     }
510
511     tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
512     if (tmp == NULL)
513     {
514       ERROR ("statsd plugin: realloc failed.");
515       continue;
516     }
517     fds = tmp;
518     tmp = fds + fds_num;
519     fds_num++;
520
521     memset (tmp, 0, sizeof (*tmp));
522     tmp->fd = fd;
523     tmp->events = POLLIN | POLLPRI;
524   }
525
526   freeaddrinfo (ai_list);
527
528   if (fds_num == 0)
529   {
530     ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
531         (node != NULL) ? node : "::", service);
532     return (ENOENT);
533   }
534
535   *ret_fds = fds;
536   *ret_fds_num = fds_num;
537   return (0);
538 } /* }}} int statsd_network_init */
539
540 static void *statsd_network_thread (void *args) /* {{{ */
541 {
542   struct pollfd *fds = NULL;
543   size_t fds_num = 0;
544   int status;
545   size_t i;
546
547   status = statsd_network_init (&fds, &fds_num);
548   if (status != 0)
549   {
550     ERROR ("statsd plugin: Unable to open listening sockets.");
551     pthread_exit ((void *) 0);
552   }
553
554   while (!network_thread_shutdown)
555   {
556     status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
557     if (status < 0)
558     {
559       char errbuf[1024];
560
561       if ((errno == EINTR) || (errno == EAGAIN))
562         continue;
563
564       ERROR ("statsd plugin: poll(2) failed: %s",
565           sstrerror (errno, errbuf, sizeof (errbuf)));
566       break;
567     }
568
569     for (i = 0; i < fds_num; i++)
570     {
571       if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
572         continue;
573
574       statsd_network_read (fds[i].fd);
575       fds[i].revents = 0;
576     }
577   } /* while (!network_thread_shutdown) */
578
579   /* Clean up */
580   for (i = 0; i < fds_num; i++)
581     close (fds[i].fd);
582   sfree (fds);
583
584   return ((void *) 0);
585 } /* }}} void *statsd_network_thread */
586
587 static int statsd_config_timer_percentile (oconfig_item_t *ci) /* {{{ */
588 {
589   double percent = NAN;
590   double *tmp;
591   int status;
592
593   status = cf_util_get_double (ci, &percent);
594   if (status != 0)
595     return (status);
596
597   if ((percent <= 0.0) || (percent >= 100))
598   {
599     ERROR ("statsd plugin: The value for \"%s\" must be between 0 and 100, "
600         "exclusively.", ci->key);
601     return (ERANGE);
602   }
603
604   tmp = realloc (conf_timer_percentile,
605       sizeof (*conf_timer_percentile) * (conf_timer_percentile_num + 1));
606   if (tmp == NULL)
607   {
608     ERROR ("statsd plugin: realloc failed.");
609     return (ENOMEM);
610   }
611   conf_timer_percentile = tmp;
612   conf_timer_percentile[conf_timer_percentile_num] = percent;
613   conf_timer_percentile_num++;
614
615   return (0);
616 } /* }}} int statsd_config_timer_percentile */
617
618 static int statsd_config (oconfig_item_t *ci) /* {{{ */
619 {
620   int i;
621
622   for (i = 0; i < ci->children_num; i++)
623   {
624     oconfig_item_t *child = ci->children + i;
625
626     if (strcasecmp ("Host", child->key) == 0)
627       cf_util_get_string (child, &conf_node);
628     else if (strcasecmp ("Port", child->key) == 0)
629       cf_util_get_service (child, &conf_service);
630     else if (strcasecmp ("DeleteCounters", child->key) == 0)
631       cf_util_get_boolean (child, &conf_delete_counters);
632     else if (strcasecmp ("DeleteTimers", child->key) == 0)
633       cf_util_get_boolean (child, &conf_delete_timers);
634     else if (strcasecmp ("DeleteGauges", child->key) == 0)
635       cf_util_get_boolean (child, &conf_delete_gauges);
636     else if (strcasecmp ("DeleteSets", child->key) == 0)
637       cf_util_get_boolean (child, &conf_delete_sets);
638     else if (strcasecmp ("TimerLower", child->key) == 0)
639       cf_util_get_boolean (child, &conf_timer_lower);
640     else if (strcasecmp ("TimerUpper", child->key) == 0)
641       cf_util_get_boolean (child, &conf_timer_upper);
642     else if (strcasecmp ("TimerSum", child->key) == 0)
643       cf_util_get_boolean (child, &conf_timer_sum);
644     else if (strcasecmp ("TimerCount", child->key) == 0)
645       cf_util_get_boolean (child, &conf_timer_count);
646     else if (strcasecmp ("TimerPercentile", child->key) == 0)
647       statsd_config_timer_percentile (child);
648     else
649       ERROR ("statsd plugin: The \"%s\" config option is not valid.",
650           child->key);
651   }
652
653   return (0);
654 } /* }}} int statsd_config */
655
656 static int statsd_init (void) /* {{{ */
657 {
658   pthread_mutex_lock (&metrics_lock);
659   if (metrics_tree == NULL)
660     metrics_tree = c_avl_create ((void *) strcmp);
661
662   if (!network_thread_running)
663   {
664     int status;
665
666     status = pthread_create (&network_thread,
667         /* attr = */ NULL,
668         statsd_network_thread,
669         /* args = */ NULL);
670     if (status != 0)
671     {
672       char errbuf[1024];
673       pthread_mutex_unlock (&metrics_lock);
674       ERROR ("statsd plugin: pthread_create failed: %s",
675           sstrerror (errno, errbuf, sizeof (errbuf)));
676       return (status);
677     }
678   }
679   network_thread_running = 1;
680
681   pthread_mutex_unlock (&metrics_lock);
682
683   return (0);
684 } /* }}} int statsd_init */
685
686 /* Must hold metrics_lock when calling this function. */
687 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
688 {
689   void *key;
690   void *value;
691
692   if ((metric == NULL) || (metric->type != STATSD_SET))
693     return (EINVAL);
694
695   if (metric->set == NULL)
696     return (0);
697
698   while (c_avl_pick (metric->set, &key, &value) == 0)
699   {
700     sfree (key);
701     sfree (value);
702   }
703
704   return (0);
705 } /* }}} int statsd_metric_clear_set_unsafe */
706
707 /* Must hold metrics_lock when calling this function. */
708 static int statsd_metric_submit_unsafe (char const *name, /* {{{ */
709     statsd_metric_t const *metric)
710 {
711   value_t values[1];
712   value_list_t vl = VALUE_LIST_INIT;
713
714   vl.values = values;
715   vl.values_len = 1;
716   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
717   sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
718
719   if (metric->type == STATSD_GAUGE)
720     sstrncpy (vl.type, "gauge", sizeof (vl.type));
721   else if (metric->type == STATSD_TIMER)
722     sstrncpy (vl.type, "latency", sizeof (vl.type));
723   else if (metric->type == STATSD_SET)
724     sstrncpy (vl.type, "objects", sizeof (vl.type));
725   else /* if (metric->type == STATSD_COUNTER) */
726     sstrncpy (vl.type, "derive", sizeof (vl.type));
727
728   sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
729
730   if (metric->type == STATSD_GAUGE)
731     values[0].gauge = (gauge_t) metric->value;
732   else if (metric->type == STATSD_TIMER)
733   {
734     size_t i;
735
736     if (metric->updates_num == 0)
737       return (0);
738
739     vl.time = cdtime ();
740
741     ssnprintf (vl.type_instance, sizeof (vl.type_instance),
742         "%s-average", name);
743     values[0].gauge = CDTIME_T_TO_DOUBLE (
744         latency_counter_get_average (metric->latency));
745     plugin_dispatch_values (&vl);
746
747     if (conf_timer_lower) {
748       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
749           "%s-lower", name);
750       values[0].gauge = CDTIME_T_TO_DOUBLE (
751           latency_counter_get_min (metric->latency));
752       plugin_dispatch_values (&vl);
753     }
754
755     if (conf_timer_upper) {
756       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
757           "%s-upper", name);
758       values[0].gauge = CDTIME_T_TO_DOUBLE (
759           latency_counter_get_max (metric->latency));
760       plugin_dispatch_values (&vl);
761     }
762
763     if (conf_timer_sum) {
764       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
765           "%s-sum", name);
766       values[0].gauge = CDTIME_T_TO_DOUBLE (
767           latency_counter_get_sum (metric->latency));
768       plugin_dispatch_values (&vl);
769     }
770
771     for (i = 0; i < conf_timer_percentile_num; i++)
772     {
773       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
774           "%s-percentile-%.0f", name, conf_timer_percentile[i]);
775       values[0].gauge = CDTIME_T_TO_DOUBLE (
776           latency_counter_get_percentile (
777             metric->latency, conf_timer_percentile[i]));
778       plugin_dispatch_values (&vl);
779     }
780
781     /* Keep this at the end, since vl.type is set to "gauge" here. The
782      * vl.type's above are implicitly set to "latency". */
783     if (conf_timer_count) {
784       sstrncpy (vl.type, "gauge", sizeof (vl.type));
785       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
786           "%s-count", name);
787       values[0].gauge = latency_counter_get_num (metric->latency);
788       plugin_dispatch_values (&vl);
789     }
790
791     latency_counter_reset (metric->latency);
792     return (0);
793   }
794   else if (metric->type == STATSD_SET)
795   {
796     if (metric->set == NULL)
797       values[0].gauge = 0.0;
798     else
799       values[0].gauge = (gauge_t) c_avl_size (metric->set);
800   }
801   else
802     values[0].derive = (derive_t) metric->value;
803
804   return (plugin_dispatch_values (&vl));
805 } /* }}} int statsd_metric_submit_unsafe */
806
807 static int statsd_read (void) /* {{{ */
808 {
809   c_avl_iterator_t *iter;
810   char *name;
811   statsd_metric_t *metric;
812
813   char **to_be_deleted = NULL;
814   size_t to_be_deleted_num = 0;
815   size_t i;
816
817   pthread_mutex_lock (&metrics_lock);
818
819   if (metrics_tree == NULL)
820   {
821     pthread_mutex_unlock (&metrics_lock);
822     return (0);
823   }
824
825   iter = c_avl_get_iterator (metrics_tree);
826   while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
827   {
828     if ((metric->updates_num == 0)
829         && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
830           || (conf_delete_timers && (metric->type == STATSD_TIMER))
831           || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
832           || (conf_delete_sets && (metric->type == STATSD_SET))))
833     {
834       DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
835       strarray_add (&to_be_deleted, &to_be_deleted_num, name);
836       continue;
837     }
838
839     /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
840      * Remove this here. */
841     statsd_metric_submit_unsafe (name + 2, metric);
842
843     /* Reset the metric. */
844     metric->updates_num = 0;
845     if (metric->type == STATSD_SET)
846       statsd_metric_clear_set_unsafe (metric);
847   }
848   c_avl_iterator_destroy (iter);
849
850   for (i = 0; i < to_be_deleted_num; i++)
851   {
852     int status;
853
854     status = c_avl_remove (metrics_tree, to_be_deleted[i],
855         (void *) &name, (void *) &metric);
856     if (status != 0)
857     {
858       ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
859           to_be_deleted[i], status);
860       continue;
861     }
862
863     sfree (name);
864     sfree (metric);
865   }
866
867   pthread_mutex_unlock (&metrics_lock);
868
869   strarray_free (to_be_deleted, to_be_deleted_num);
870
871   return (0);
872 } /* }}} int statsd_read */
873
874 static int statsd_shutdown (void) /* {{{ */
875 {
876   void *key;
877   void *value;
878
879   pthread_mutex_lock (&metrics_lock);
880
881   if (network_thread_running)
882   {
883     network_thread_shutdown = 1;
884     pthread_kill (network_thread, SIGTERM);
885     pthread_join (network_thread, /* retval = */ NULL);
886   }
887   network_thread_running = 0;
888
889   while (c_avl_pick (metrics_tree, &key, &value) == 0)
890   {
891     sfree (key);
892     sfree (value);
893   }
894   c_avl_destroy (metrics_tree);
895   metrics_tree = NULL;
896
897   sfree (conf_node);
898   sfree (conf_service);
899
900   pthread_mutex_unlock (&metrics_lock);
901
902   return (0);
903 } /* }}} int statsd_shutdown */
904
905 void module_register (void)
906 {
907   plugin_register_complex_config ("statsd", statsd_config);
908   plugin_register_init ("statsd", statsd_init);
909   plugin_register_read ("statsd", statsd_read);
910   plugin_register_shutdown ("statsd", statsd_shutdown);
911 }
912
913 /* vim: set sw=2 sts=2 et fdm=marker : */