treewide: replace memset to 0 with initializers
[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_latency.h"
33
34 #include <sys/types.h>
35 #include <netdb.h>
36 #include <poll.h>
37
38 /* AIX doesn't have MSG_DONTWAIT */
39 #ifndef MSG_DONTWAIT
40 #  define MSG_DONTWAIT MSG_NONBLOCK
41 #endif
42
43 #ifndef STATSD_DEFAULT_NODE
44 # define STATSD_DEFAULT_NODE NULL
45 #endif
46
47 #ifndef STATSD_DEFAULT_SERVICE
48 # define STATSD_DEFAULT_SERVICE "8125"
49 #endif
50
51 enum metric_type_e
52 {
53   STATSD_COUNTER,
54   STATSD_TIMER,
55   STATSD_GAUGE,
56   STATSD_SET
57 };
58 typedef enum metric_type_e metric_type_t;
59
60 struct statsd_metric_s
61 {
62   metric_type_t type;
63   double value;
64   derive_t counter;
65   latency_counter_t *latency;
66   c_avl_tree_t *set;
67   unsigned long updates_num;
68 };
69 typedef struct statsd_metric_s statsd_metric_t;
70
71 static c_avl_tree_t   *metrics_tree = NULL;
72 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
73
74 static pthread_t network_thread;
75 static _Bool     network_thread_running = 0;
76 static _Bool     network_thread_shutdown = 0;
77
78 static char *conf_node = NULL;
79 static char *conf_service = NULL;
80
81 static _Bool conf_delete_counters = 0;
82 static _Bool conf_delete_timers   = 0;
83 static _Bool conf_delete_gauges   = 0;
84 static _Bool conf_delete_sets     = 0;
85
86 static double *conf_timer_percentile = NULL;
87 static size_t  conf_timer_percentile_num = 0;
88
89 static _Bool conf_counter_sum     = 0;
90 static _Bool conf_timer_lower     = 0;
91 static _Bool conf_timer_upper     = 0;
92 static _Bool conf_timer_sum       = 0;
93 static _Bool conf_timer_count     = 0;
94
95 /* Must hold metrics_lock when calling this function. */
96 static statsd_metric_t *statsd_metric_lookup_unsafe (char const *name, /* {{{ */
97     metric_type_t type)
98 {
99   char key[DATA_MAX_NAME_LEN + 2];
100   char *key_copy;
101   statsd_metric_t *metric;
102   int status;
103
104   switch (type)
105   {
106     case STATSD_COUNTER: key[0] = 'c'; break;
107     case STATSD_TIMER:   key[0] = 't'; break;
108     case STATSD_GAUGE:   key[0] = 'g'; break;
109     case STATSD_SET:     key[0] = 's'; break;
110     default: return (NULL);
111   }
112
113   key[1] = ':';
114   sstrncpy (&key[2], name, sizeof (key) - 2);
115
116   status = c_avl_get (metrics_tree, key, (void *) &metric);
117   if (status == 0)
118     return (metric);
119
120   key_copy = strdup (key);
121   if (key_copy == NULL)
122   {
123     ERROR ("statsd plugin: strdup failed.");
124     return (NULL);
125   }
126
127   metric = calloc (1, sizeof (*metric));
128   if (metric == NULL)
129   {
130     ERROR ("statsd plugin: calloc failed.");
131     sfree (key_copy);
132     return (NULL);
133   }
134
135   metric->type = type;
136   metric->latency = NULL;
137   metric->set = NULL;
138
139   status = c_avl_insert (metrics_tree, key_copy, metric);
140   if (status != 0)
141   {
142     ERROR ("statsd plugin: c_avl_insert failed.");
143     sfree (key_copy);
144     sfree (metric);
145     return (NULL);
146   }
147
148   return (metric);
149 } /* }}} statsd_metric_lookup_unsafe */
150
151 static int statsd_metric_set (char const *name, double value, /* {{{ */
152     metric_type_t type)
153 {
154   statsd_metric_t *metric;
155
156   pthread_mutex_lock (&metrics_lock);
157
158   metric = statsd_metric_lookup_unsafe (name, type);
159   if (metric == NULL)
160   {
161     pthread_mutex_unlock (&metrics_lock);
162     return (-1);
163   }
164
165   metric->value = value;
166   metric->updates_num++;
167
168   pthread_mutex_unlock (&metrics_lock);
169
170   return (0);
171 } /* }}} int statsd_metric_set */
172
173 static int statsd_metric_add (char const *name, double delta, /* {{{ */
174     metric_type_t type)
175 {
176   statsd_metric_t *metric;
177
178   pthread_mutex_lock (&metrics_lock);
179
180   metric = statsd_metric_lookup_unsafe (name, type);
181   if (metric == NULL)
182   {
183     pthread_mutex_unlock (&metrics_lock);
184     return (-1);
185   }
186
187   metric->value += delta;
188   metric->updates_num++;
189
190   pthread_mutex_unlock (&metrics_lock);
191
192   return (0);
193 } /* }}} int statsd_metric_add */
194
195 static void statsd_metric_free (statsd_metric_t *metric) /* {{{ */
196 {
197   if (metric == NULL)
198     return;
199
200   if (metric->latency != NULL)
201   {
202     latency_counter_destroy (metric->latency);
203     metric->latency = NULL;
204   }
205
206   if (metric->set != NULL)
207   {
208     void *key;
209     void *value;
210
211     while (c_avl_pick (metric->set, &key, &value) == 0)
212     {
213       sfree (key);
214       assert (value == NULL);
215     }
216
217     c_avl_destroy (metric->set);
218     metric->set = NULL;
219   }
220
221   sfree (metric);
222 } /* }}} void statsd_metric_free */
223
224 static int statsd_parse_value (char const *str, value_t *ret_value) /* {{{ */
225 {
226   char *endptr = NULL;
227
228   ret_value->gauge = (gauge_t) strtod (str, &endptr);
229   if ((str == endptr) || ((endptr != NULL) && (*endptr != 0)))
230     return (-1);
231
232   return (0);
233 } /* }}} int statsd_parse_value */
234
235 static int statsd_handle_counter (char const *name, /* {{{ */
236     char const *value_str,
237     char const *extra)
238 {
239   value_t value;
240   value_t scale;
241   int status;
242
243   if ((extra != NULL) && (extra[0] != '@'))
244     return (-1);
245
246   scale.gauge = 1.0;
247   if (extra != NULL)
248   {
249     status = statsd_parse_value (extra + 1, &scale);
250     if (status != 0)
251       return (status);
252
253     if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
254       return (-1);
255   }
256
257   value.gauge = 1.0;
258   status = statsd_parse_value (value_str, &value);
259   if (status != 0)
260     return (status);
261
262   /* Changes to the counter are added to (statsd_metric_t*)->value. ->counter is
263    * only updated in statsd_metric_submit_unsafe(). */
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 ((int (*) (const void *, const 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 = { 0 };
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   ai_hints.ai_flags = AI_PASSIVE;
513 #ifdef AI_ADDRCONFIG
514   ai_hints.ai_flags |= AI_ADDRCONFIG;
515 #endif
516   ai_hints.ai_family = AF_UNSPEC;
517   ai_hints.ai_socktype = SOCK_DGRAM;
518
519   status = getaddrinfo (node, service, &ai_hints, &ai_list);
520   if (status != 0)
521   {
522     ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
523         node, service, gai_strerror (status));
524     return (status);
525   }
526
527   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
528   {
529     int fd;
530     struct pollfd *tmp;
531
532     char dbg_node[NI_MAXHOST];
533     char dbg_service[NI_MAXSERV];
534
535     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
536     if (fd < 0)
537     {
538       char errbuf[1024];
539       ERROR ("statsd plugin: socket(2) failed: %s",
540           sstrerror (errno, errbuf, sizeof (errbuf)));
541       continue;
542     }
543
544     getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
545         dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
546         NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
547     DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
548
549     status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
550     if (status != 0)
551     {
552       char errbuf[1024];
553       ERROR ("statsd plugin: bind(2) failed: %s",
554           sstrerror (errno, errbuf, sizeof (errbuf)));
555       close (fd);
556       continue;
557     }
558
559     tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
560     if (tmp == NULL)
561     {
562       ERROR ("statsd plugin: realloc failed.");
563       close (fd);
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 ("CounterSum", child->key) == 0)
688       cf_util_get_boolean (child, &conf_counter_sum);
689     else if (strcasecmp ("TimerLower", child->key) == 0)
690       cf_util_get_boolean (child, &conf_timer_lower);
691     else if (strcasecmp ("TimerUpper", child->key) == 0)
692       cf_util_get_boolean (child, &conf_timer_upper);
693     else if (strcasecmp ("TimerSum", child->key) == 0)
694       cf_util_get_boolean (child, &conf_timer_sum);
695     else if (strcasecmp ("TimerCount", child->key) == 0)
696       cf_util_get_boolean (child, &conf_timer_count);
697     else if (strcasecmp ("TimerPercentile", child->key) == 0)
698       statsd_config_timer_percentile (child);
699     else
700       ERROR ("statsd plugin: The \"%s\" config option is not valid.",
701           child->key);
702   }
703
704   return (0);
705 } /* }}} int statsd_config */
706
707 static int statsd_init (void) /* {{{ */
708 {
709   pthread_mutex_lock (&metrics_lock);
710   if (metrics_tree == NULL)
711     metrics_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
712
713   if (!network_thread_running)
714   {
715     int status;
716
717     status = pthread_create (&network_thread,
718         /* attr = */ NULL,
719         statsd_network_thread,
720         /* args = */ NULL);
721     if (status != 0)
722     {
723       char errbuf[1024];
724       pthread_mutex_unlock (&metrics_lock);
725       ERROR ("statsd plugin: pthread_create failed: %s",
726           sstrerror (errno, errbuf, sizeof (errbuf)));
727       return (status);
728     }
729   }
730   network_thread_running = 1;
731
732   pthread_mutex_unlock (&metrics_lock);
733
734   return (0);
735 } /* }}} int statsd_init */
736
737 /* Must hold metrics_lock when calling this function. */
738 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
739 {
740   void *key;
741   void *value;
742
743   if ((metric == NULL) || (metric->type != STATSD_SET))
744     return (EINVAL);
745
746   if (metric->set == NULL)
747     return (0);
748
749   while (c_avl_pick (metric->set, &key, &value) == 0)
750   {
751     sfree (key);
752     sfree (value);
753   }
754
755   return (0);
756 } /* }}} int statsd_metric_clear_set_unsafe */
757
758 /* Must hold metrics_lock when calling this function. */
759 static int statsd_metric_submit_unsafe (char const *name, statsd_metric_t *metric) /* {{{ */
760 {
761   value_t values[1];
762   value_list_t vl = VALUE_LIST_INIT;
763
764   vl.values = values;
765   vl.values_len = 1;
766   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
767   sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
768
769   if (metric->type == STATSD_GAUGE)
770     sstrncpy (vl.type, "gauge", sizeof (vl.type));
771   else if (metric->type == STATSD_TIMER)
772     sstrncpy (vl.type, "latency", sizeof (vl.type));
773   else if (metric->type == STATSD_SET)
774     sstrncpy (vl.type, "objects", sizeof (vl.type));
775   else /* if (metric->type == STATSD_COUNTER) */
776     sstrncpy (vl.type, "derive", sizeof (vl.type));
777
778   sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
779
780   if (metric->type == STATSD_GAUGE)
781     values[0].gauge = (gauge_t) metric->value;
782   else if (metric->type == STATSD_TIMER)
783   {
784     size_t i;
785     _Bool have_events = (metric->updates_num > 0);
786
787     /* Make sure all timer metrics share the *same* timestamp. */
788     vl.time = cdtime ();
789
790     ssnprintf (vl.type_instance, sizeof (vl.type_instance),
791         "%s-average", name);
792     values[0].gauge = have_events
793       ? CDTIME_T_TO_DOUBLE (latency_counter_get_average (metric->latency))
794       : NAN;
795     plugin_dispatch_values (&vl);
796
797     if (conf_timer_lower) {
798       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
799           "%s-lower", name);
800       values[0].gauge = have_events
801         ? CDTIME_T_TO_DOUBLE (latency_counter_get_min (metric->latency))
802         : NAN;
803       plugin_dispatch_values (&vl);
804     }
805
806     if (conf_timer_upper) {
807       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
808           "%s-upper", name);
809       values[0].gauge = have_events
810         ? CDTIME_T_TO_DOUBLE (latency_counter_get_max (metric->latency))
811         : NAN;
812       plugin_dispatch_values (&vl);
813     }
814
815     if (conf_timer_sum) {
816       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
817           "%s-sum", name);
818       values[0].gauge = have_events
819         ? CDTIME_T_TO_DOUBLE (latency_counter_get_sum (metric->latency))
820         : NAN;
821       plugin_dispatch_values (&vl);
822     }
823
824     for (i = 0; i < conf_timer_percentile_num; i++)
825     {
826       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
827           "%s-percentile-%.0f", name, conf_timer_percentile[i]);
828       values[0].gauge = have_events
829         ? CDTIME_T_TO_DOUBLE (latency_counter_get_percentile (metric->latency, conf_timer_percentile[i]))
830         : NAN;
831       plugin_dispatch_values (&vl);
832     }
833
834     /* Keep this at the end, since vl.type is set to "gauge" here. The
835      * vl.type's above are implicitly set to "latency". */
836     if (conf_timer_count) {
837       sstrncpy (vl.type, "gauge", sizeof (vl.type));
838       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
839           "%s-count", name);
840       values[0].gauge = latency_counter_get_num (metric->latency);
841       plugin_dispatch_values (&vl);
842     }
843
844     latency_counter_reset (metric->latency);
845     return (0);
846   }
847   else if (metric->type == STATSD_SET)
848   {
849     if (metric->set == NULL)
850       values[0].gauge = 0.0;
851     else
852       values[0].gauge = (gauge_t) c_avl_size (metric->set);
853   }
854   else { /* STATSD_COUNTER */
855     gauge_t delta = nearbyint (metric->value);
856
857     /* Etsy's statsd writes counters as two metrics: a rate and the change since
858      * the last write. Since collectd does not reset its DERIVE metrics to zero,
859      * this makes little sense, but we're dispatching a "count" metric here
860      * anyway - if requested by the user - for compatibility reasons. */
861     if (conf_counter_sum)
862     {
863       sstrncpy (vl.type, "count", sizeof (vl.type));
864       values[0].gauge = delta;
865       plugin_dispatch_values (&vl);
866
867       /* restore vl.type */
868       sstrncpy (vl.type, "derive", sizeof (vl.type));
869     }
870
871     /* Rather than resetting value to zero, subtract delta so we correctly keep
872      * track of residuals. */
873     metric->value   -= delta;
874     metric->counter += (derive_t) delta;
875
876     values[0].derive = metric->counter;
877   }
878
879   return (plugin_dispatch_values (&vl));
880 } /* }}} int statsd_metric_submit_unsafe */
881
882 static int statsd_read (void) /* {{{ */
883 {
884   c_avl_iterator_t *iter;
885   char *name;
886   statsd_metric_t *metric;
887
888   char **to_be_deleted = NULL;
889   size_t to_be_deleted_num = 0;
890   size_t i;
891
892   pthread_mutex_lock (&metrics_lock);
893
894   if (metrics_tree == NULL)
895   {
896     pthread_mutex_unlock (&metrics_lock);
897     return (0);
898   }
899
900   iter = c_avl_get_iterator (metrics_tree);
901   while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
902   {
903     if ((metric->updates_num == 0)
904         && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
905           || (conf_delete_timers && (metric->type == STATSD_TIMER))
906           || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
907           || (conf_delete_sets && (metric->type == STATSD_SET))))
908     {
909       DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
910       strarray_add (&to_be_deleted, &to_be_deleted_num, name);
911       continue;
912     }
913
914     /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
915      * Remove this here. */
916     statsd_metric_submit_unsafe (name + 2, metric);
917
918     /* Reset the metric. */
919     metric->updates_num = 0;
920     if (metric->type == STATSD_SET)
921       statsd_metric_clear_set_unsafe (metric);
922   }
923   c_avl_iterator_destroy (iter);
924
925   for (i = 0; i < to_be_deleted_num; i++)
926   {
927     int status;
928
929     status = c_avl_remove (metrics_tree, to_be_deleted[i],
930         (void *) &name, (void *) &metric);
931     if (status != 0)
932     {
933       ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
934           to_be_deleted[i], status);
935       continue;
936     }
937
938     sfree (name);
939     statsd_metric_free (metric);
940   }
941
942   pthread_mutex_unlock (&metrics_lock);
943
944   strarray_free (to_be_deleted, to_be_deleted_num);
945
946   return (0);
947 } /* }}} int statsd_read */
948
949 static int statsd_shutdown (void) /* {{{ */
950 {
951   void *key;
952   void *value;
953
954   if (network_thread_running)
955   {
956     network_thread_shutdown = 1;
957     pthread_kill (network_thread, SIGTERM);
958     pthread_join (network_thread, /* retval = */ NULL);
959   }
960   network_thread_running = 0;
961
962   pthread_mutex_lock (&metrics_lock);
963
964   while (c_avl_pick (metrics_tree, &key, &value) == 0)
965   {
966     sfree (key);
967     statsd_metric_free (value);
968   }
969   c_avl_destroy (metrics_tree);
970   metrics_tree = NULL;
971
972   sfree (conf_node);
973   sfree (conf_service);
974
975   pthread_mutex_unlock (&metrics_lock);
976
977   return (0);
978 } /* }}} int statsd_shutdown */
979
980 void module_register (void)
981 {
982   plugin_register_complex_config ("statsd", statsd_config);
983   plugin_register_init ("statsd", statsd_init);
984   plugin_register_read ("statsd", statsd_read);
985   plugin_register_shutdown ("statsd", statsd_shutdown);
986 }
987
988 /* vim: set sw=2 sts=2 et fdm=marker : */