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