sigrok: use pkg-config to find library
[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
29 #include "plugin.h"
30 #include "common.h"
31 #include "configfile.h"
32 #include "utils_avltree.h"
33 #include "utils_latency.h"
34
35 #include <sys/types.h>
36 #include <netdb.h>
37 #include <poll.h>
38
39 /* AIX doesn't have MSG_DONTWAIT */
40 #ifndef MSG_DONTWAIT
41 #  define MSG_DONTWAIT MSG_NONBLOCK
42 #endif
43
44 #ifndef STATSD_DEFAULT_NODE
45 # define STATSD_DEFAULT_NODE NULL
46 #endif
47
48 #ifndef STATSD_DEFAULT_SERVICE
49 # define STATSD_DEFAULT_SERVICE "8125"
50 #endif
51
52 enum metric_type_e
53 {
54   STATSD_COUNTER,
55   STATSD_TIMER,
56   STATSD_GAUGE,
57   STATSD_SET
58 };
59 typedef enum metric_type_e metric_type_t;
60
61 struct statsd_metric_s
62 {
63   metric_type_t type;
64   double value;
65   derive_t counter;
66   latency_counter_t *latency;
67   c_avl_tree_t *set;
68   unsigned long updates_num;
69 };
70 typedef struct statsd_metric_s statsd_metric_t;
71
72 static c_avl_tree_t   *metrics_tree = NULL;
73 static pthread_mutex_t metrics_lock = PTHREAD_MUTEX_INITIALIZER;
74
75 static pthread_t network_thread;
76 static _Bool     network_thread_running = 0;
77 static _Bool     network_thread_shutdown = 0;
78
79 static char *conf_node = NULL;
80 static char *conf_service = NULL;
81
82 static _Bool conf_delete_counters = 0;
83 static _Bool conf_delete_timers   = 0;
84 static _Bool conf_delete_gauges   = 0;
85 static _Bool conf_delete_sets     = 0;
86
87 static double *conf_timer_percentile = NULL;
88 static size_t  conf_timer_percentile_num = 0;
89
90 static _Bool conf_counter_sum     = 0;
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 = calloc (1, sizeof (*metric));
129   if (metric == NULL)
130   {
131     ERROR ("statsd plugin: calloc failed.");
132     sfree (key_copy);
133     return (NULL);
134   }
135
136   metric->type = type;
137   metric->latency = NULL;
138   metric->set = NULL;
139
140   status = c_avl_insert (metrics_tree, key_copy, metric);
141   if (status != 0)
142   {
143     ERROR ("statsd plugin: c_avl_insert failed.");
144     sfree (key_copy);
145     sfree (metric);
146     return (NULL);
147   }
148
149   return (metric);
150 } /* }}} statsd_metric_lookup_unsafe */
151
152 static int statsd_metric_set (char const *name, double value, /* {{{ */
153     metric_type_t type)
154 {
155   statsd_metric_t *metric;
156
157   pthread_mutex_lock (&metrics_lock);
158
159   metric = statsd_metric_lookup_unsafe (name, type);
160   if (metric == NULL)
161   {
162     pthread_mutex_unlock (&metrics_lock);
163     return (-1);
164   }
165
166   metric->value = value;
167   metric->updates_num++;
168
169   pthread_mutex_unlock (&metrics_lock);
170
171   return (0);
172 } /* }}} int statsd_metric_set */
173
174 static int statsd_metric_add (char const *name, double delta, /* {{{ */
175     metric_type_t type)
176 {
177   statsd_metric_t *metric;
178
179   pthread_mutex_lock (&metrics_lock);
180
181   metric = statsd_metric_lookup_unsafe (name, type);
182   if (metric == NULL)
183   {
184     pthread_mutex_unlock (&metrics_lock);
185     return (-1);
186   }
187
188   metric->value += delta;
189   metric->updates_num++;
190
191   pthread_mutex_unlock (&metrics_lock);
192
193   return (0);
194 } /* }}} int statsd_metric_add */
195
196 static void statsd_metric_free (statsd_metric_t *metric) /* {{{ */
197 {
198   if (metric == NULL)
199     return;
200
201   if (metric->latency != NULL)
202   {
203     latency_counter_destroy (metric->latency);
204     metric->latency = NULL;
205   }
206
207   if (metric->set != NULL)
208   {
209     void *key;
210     void *value;
211
212     while (c_avl_pick (metric->set, &key, &value) == 0)
213     {
214       sfree (key);
215       assert (value == NULL);
216     }
217
218     c_avl_destroy (metric->set);
219     metric->set = NULL;
220   }
221
222   sfree (metric);
223 } /* }}} void statsd_metric_free */
224
225 static int statsd_parse_value (char const *str, value_t *ret_value) /* {{{ */
226 {
227   char *endptr = NULL;
228
229   ret_value->gauge = (gauge_t) strtod (str, &endptr);
230   if ((str == endptr) || ((endptr != NULL) && (*endptr != 0)))
231     return (-1);
232
233   return (0);
234 } /* }}} int statsd_parse_value */
235
236 static int statsd_handle_counter (char const *name, /* {{{ */
237     char const *value_str,
238     char const *extra)
239 {
240   value_t value;
241   value_t scale;
242   int status;
243
244   if ((extra != NULL) && (extra[0] != '@'))
245     return (-1);
246
247   scale.gauge = 1.0;
248   if (extra != NULL)
249   {
250     status = statsd_parse_value (extra + 1, &scale);
251     if (status != 0)
252       return (status);
253
254     if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
255       return (-1);
256   }
257
258   value.gauge = 1.0;
259   status = statsd_parse_value (value_str, &value);
260   if (status != 0)
261     return (status);
262
263   /* Changes to the counter are added to (statsd_metric_t*)->value. ->counter is
264    * only updated in statsd_metric_submit_unsafe(). */
265   return (statsd_metric_add (name, (double) (value.gauge / scale.gauge),
266         STATSD_COUNTER));
267 } /* }}} int statsd_handle_counter */
268
269 static int statsd_handle_gauge (char const *name, /* {{{ */
270     char const *value_str)
271 {
272   value_t value;
273   int status;
274
275   value.gauge = 0;
276   status = statsd_parse_value (value_str, &value);
277   if (status != 0)
278     return (status);
279
280   if ((value_str[0] == '+') || (value_str[0] == '-'))
281     return (statsd_metric_add (name, (double) value.gauge, STATSD_GAUGE));
282   else
283     return (statsd_metric_set (name, (double) value.gauge, STATSD_GAUGE));
284 } /* }}} int statsd_handle_gauge */
285
286 static int statsd_handle_timer (char const *name, /* {{{ */
287     char const *value_str,
288     char const *extra)
289 {
290   statsd_metric_t *metric;
291   value_t value_ms;
292   value_t scale;
293   cdtime_t value;
294   int status;
295
296   if ((extra != NULL) && (extra[0] != '@'))
297     return (-1);
298
299   scale.gauge = 1.0;
300   if (extra != NULL)
301   {
302     status = statsd_parse_value (extra + 1, &scale);
303     if (status != 0)
304       return (status);
305
306     if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
307       return (-1);
308   }
309
310   value_ms.derive = 0;
311   status = statsd_parse_value (value_str, &value_ms);
312   if (status != 0)
313     return (status);
314
315   value = MS_TO_CDTIME_T (value_ms.gauge / scale.gauge);
316
317   pthread_mutex_lock (&metrics_lock);
318
319   metric = statsd_metric_lookup_unsafe (name, STATSD_TIMER);
320   if (metric == NULL)
321   {
322     pthread_mutex_unlock (&metrics_lock);
323     return (-1);
324   }
325
326   if (metric->latency == NULL)
327     metric->latency = latency_counter_create ();
328   if (metric->latency == NULL)
329   {
330     pthread_mutex_unlock (&metrics_lock);
331     return (-1);
332   }
333
334   latency_counter_add (metric->latency, value);
335   metric->updates_num++;
336
337   pthread_mutex_unlock (&metrics_lock);
338   return (0);
339 } /* }}} int statsd_handle_timer */
340
341 static int statsd_handle_set (char const *name, /* {{{ */
342     char const *set_key_orig)
343 {
344   statsd_metric_t *metric = NULL;
345   char *set_key;
346   int status;
347
348   pthread_mutex_lock (&metrics_lock);
349
350   metric = statsd_metric_lookup_unsafe (name, STATSD_SET);
351   if (metric == NULL)
352   {
353     pthread_mutex_unlock (&metrics_lock);
354     return (-1);
355   }
356
357   /* Make sure metric->set exists. */
358   if (metric->set == NULL)
359     metric->set = c_avl_create ((int (*) (const void *, const void *)) strcmp);
360
361   if (metric->set == NULL)
362   {
363     pthread_mutex_unlock (&metrics_lock);
364     ERROR ("statsd plugin: c_avl_create failed.");
365     return (-1);
366   }
367
368   set_key = strdup (set_key_orig);
369   if (set_key == NULL)
370   {
371     pthread_mutex_unlock (&metrics_lock);
372     ERROR ("statsd plugin: strdup failed.");
373     return (-1);
374   }
375
376   status = c_avl_insert (metric->set, set_key, /* value = */ NULL);
377   if (status < 0)
378   {
379     pthread_mutex_unlock (&metrics_lock);
380     if (status < 0)
381       ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
382           set_key, status);
383     sfree (set_key);
384     return (-1);
385   }
386   else if (status > 0) /* key already exists */
387   {
388     sfree (set_key);
389   }
390
391   metric->updates_num++;
392
393   pthread_mutex_unlock (&metrics_lock);
394   return (0);
395 } /* }}} int statsd_handle_set */
396
397 static int statsd_parse_line (char *buffer) /* {{{ */
398 {
399   char *name = buffer;
400   char *value;
401   char *type;
402   char *extra;
403
404   type = strchr (name, '|');
405   if (type == NULL)
406     return (-1);
407   *type = 0;
408   type++;
409
410   value = strrchr (name, ':');
411   if (value == NULL)
412     return (-1);
413   *value = 0;
414   value++;
415
416   extra = strchr (type, '|');
417   if (extra != NULL)
418   {
419     *extra = 0;
420     extra++;
421   }
422
423   if (strcmp ("c", type) == 0)
424     return (statsd_handle_counter (name, value, extra));
425   else if (strcmp ("ms", type) == 0)
426     return (statsd_handle_timer (name, value, extra));
427
428   /* extra is only valid for counters and timers */
429   if (extra != NULL)
430     return (-1);
431
432   if (strcmp ("g", type) == 0)
433     return (statsd_handle_gauge (name, value));
434   else if (strcmp ("s", type) == 0)
435     return (statsd_handle_set (name, value));
436   else
437     return (-1);
438 } /* }}} void statsd_parse_line */
439
440 static void statsd_parse_buffer (char *buffer) /* {{{ */
441 {
442   while (buffer != NULL)
443   {
444     char orig[64];
445     char *next;
446     int status;
447
448     next = strchr (buffer, '\n');
449     if (next != NULL)
450     {
451       *next = 0;
452       next++;
453     }
454
455     if (*buffer == 0)
456     {
457       buffer = next;
458       continue;
459     }
460
461     sstrncpy (orig, buffer, sizeof (orig));
462
463     status = statsd_parse_line (buffer);
464     if (status != 0)
465       ERROR ("statsd plugin: Unable to parse line: \"%s\"", orig);
466
467     buffer = next;
468   }
469 } /* }}} void statsd_parse_buffer */
470
471 static void statsd_network_read (int fd) /* {{{ */
472 {
473   char buffer[4096];
474   size_t buffer_size;
475   ssize_t status;
476
477   status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
478   if (status < 0)
479   {
480     char errbuf[1024];
481
482     if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
483       return;
484
485     ERROR ("statsd plugin: recv(2) failed: %s",
486         sstrerror (errno, errbuf, sizeof (errbuf)));
487     return;
488   }
489
490   buffer_size = (size_t) status;
491   if (buffer_size >= sizeof (buffer))
492     buffer_size = sizeof (buffer) - 1;
493   buffer[buffer_size] = 0;
494
495   statsd_parse_buffer (buffer);
496 } /* }}} void statsd_network_read */
497
498 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
499     size_t *ret_fds_num)
500 {
501   struct pollfd *fds = NULL;
502   size_t fds_num = 0;
503
504   struct addrinfo *ai_list;
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   struct addrinfo ai_hints = {
513     .ai_family = AF_UNSPEC,
514     .ai_flags = AI_PASSIVE | AI_ADDRCONFIG,
515     .ai_socktype = SOCK_DGRAM
516   };
517
518   status = getaddrinfo (node, service, &ai_hints, &ai_list);
519   if (status != 0)
520   {
521     ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
522         node, service, gai_strerror (status));
523     return (status);
524   }
525
526   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
527   {
528     int fd;
529     struct pollfd *tmp;
530
531     char dbg_node[NI_MAXHOST];
532     char dbg_service[NI_MAXSERV];
533
534     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
535     if (fd < 0)
536     {
537       char errbuf[1024];
538       ERROR ("statsd plugin: socket(2) failed: %s",
539           sstrerror (errno, errbuf, sizeof (errbuf)));
540       continue;
541     }
542
543     getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
544         dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
545         NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
546     DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
547
548     status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
549     if (status != 0)
550     {
551       char errbuf[1024];
552       ERROR ("statsd plugin: bind(2) failed: %s",
553           sstrerror (errno, errbuf, sizeof (errbuf)));
554       close (fd);
555       continue;
556     }
557
558     tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
559     if (tmp == NULL)
560     {
561       ERROR ("statsd plugin: realloc failed.");
562       close (fd);
563       continue;
564     }
565     fds = tmp;
566     tmp = fds + fds_num;
567     fds_num++;
568
569     memset (tmp, 0, sizeof (*tmp));
570     tmp->fd = fd;
571     tmp->events = POLLIN | POLLPRI;
572   }
573
574   freeaddrinfo (ai_list);
575
576   if (fds_num == 0)
577   {
578     ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
579         (node != NULL) ? node : "::", service);
580     return (ENOENT);
581   }
582
583   *ret_fds = fds;
584   *ret_fds_num = fds_num;
585   return (0);
586 } /* }}} int statsd_network_init */
587
588 static void *statsd_network_thread (void *args) /* {{{ */
589 {
590   struct pollfd *fds = NULL;
591   size_t fds_num = 0;
592   int status;
593   size_t i;
594
595   status = statsd_network_init (&fds, &fds_num);
596   if (status != 0)
597   {
598     ERROR ("statsd plugin: Unable to open listening sockets.");
599     pthread_exit ((void *) 0);
600   }
601
602   while (!network_thread_shutdown)
603   {
604     status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
605     if (status < 0)
606     {
607       char errbuf[1024];
608
609       if ((errno == EINTR) || (errno == EAGAIN))
610         continue;
611
612       ERROR ("statsd plugin: poll(2) failed: %s",
613           sstrerror (errno, errbuf, sizeof (errbuf)));
614       break;
615     }
616
617     for (i = 0; i < fds_num; i++)
618     {
619       if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
620         continue;
621
622       statsd_network_read (fds[i].fd);
623       fds[i].revents = 0;
624     }
625   } /* while (!network_thread_shutdown) */
626
627   /* Clean up */
628   for (i = 0; i < fds_num; i++)
629     close (fds[i].fd);
630   sfree (fds);
631
632   return ((void *) 0);
633 } /* }}} void *statsd_network_thread */
634
635 static int statsd_config_timer_percentile (oconfig_item_t *ci) /* {{{ */
636 {
637   double percent = NAN;
638   double *tmp;
639   int status;
640
641   status = cf_util_get_double (ci, &percent);
642   if (status != 0)
643     return (status);
644
645   if ((percent <= 0.0) || (percent >= 100))
646   {
647     ERROR ("statsd plugin: The value for \"%s\" must be between 0 and 100, "
648         "exclusively.", ci->key);
649     return (ERANGE);
650   }
651
652   tmp = realloc (conf_timer_percentile,
653       sizeof (*conf_timer_percentile) * (conf_timer_percentile_num + 1));
654   if (tmp == NULL)
655   {
656     ERROR ("statsd plugin: realloc failed.");
657     return (ENOMEM);
658   }
659   conf_timer_percentile = tmp;
660   conf_timer_percentile[conf_timer_percentile_num] = percent;
661   conf_timer_percentile_num++;
662
663   return (0);
664 } /* }}} int statsd_config_timer_percentile */
665
666 static int statsd_config (oconfig_item_t *ci) /* {{{ */
667 {
668   int i;
669
670   for (i = 0; i < ci->children_num; i++)
671   {
672     oconfig_item_t *child = ci->children + i;
673
674     if (strcasecmp ("Host", child->key) == 0)
675       cf_util_get_string (child, &conf_node);
676     else if (strcasecmp ("Port", child->key) == 0)
677       cf_util_get_service (child, &conf_service);
678     else if (strcasecmp ("DeleteCounters", child->key) == 0)
679       cf_util_get_boolean (child, &conf_delete_counters);
680     else if (strcasecmp ("DeleteTimers", child->key) == 0)
681       cf_util_get_boolean (child, &conf_delete_timers);
682     else if (strcasecmp ("DeleteGauges", child->key) == 0)
683       cf_util_get_boolean (child, &conf_delete_gauges);
684     else if (strcasecmp ("DeleteSets", child->key) == 0)
685       cf_util_get_boolean (child, &conf_delete_sets);
686     else if (strcasecmp ("CounterSum", child->key) == 0)
687       cf_util_get_boolean (child, &conf_counter_sum);
688     else if (strcasecmp ("TimerLower", child->key) == 0)
689       cf_util_get_boolean (child, &conf_timer_lower);
690     else if (strcasecmp ("TimerUpper", child->key) == 0)
691       cf_util_get_boolean (child, &conf_timer_upper);
692     else if (strcasecmp ("TimerSum", child->key) == 0)
693       cf_util_get_boolean (child, &conf_timer_sum);
694     else if (strcasecmp ("TimerCount", child->key) == 0)
695       cf_util_get_boolean (child, &conf_timer_count);
696     else if (strcasecmp ("TimerPercentile", child->key) == 0)
697       statsd_config_timer_percentile (child);
698     else
699       ERROR ("statsd plugin: The \"%s\" config option is not valid.",
700           child->key);
701   }
702
703   return (0);
704 } /* }}} int statsd_config */
705
706 static int statsd_init (void) /* {{{ */
707 {
708   pthread_mutex_lock (&metrics_lock);
709   if (metrics_tree == NULL)
710     metrics_tree = c_avl_create ((int (*) (const void *, const void *)) strcmp);
711
712   if (!network_thread_running)
713   {
714     int status;
715
716     status = pthread_create (&network_thread,
717         /* attr = */ NULL,
718         statsd_network_thread,
719         /* args = */ NULL);
720     if (status != 0)
721     {
722       char errbuf[1024];
723       pthread_mutex_unlock (&metrics_lock);
724       ERROR ("statsd plugin: pthread_create failed: %s",
725           sstrerror (errno, errbuf, sizeof (errbuf)));
726       return (status);
727     }
728   }
729   network_thread_running = 1;
730
731   pthread_mutex_unlock (&metrics_lock);
732
733   return (0);
734 } /* }}} int statsd_init */
735
736 /* Must hold metrics_lock when calling this function. */
737 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
738 {
739   void *key;
740   void *value;
741
742   if ((metric == NULL) || (metric->type != STATSD_SET))
743     return (EINVAL);
744
745   if (metric->set == NULL)
746     return (0);
747
748   while (c_avl_pick (metric->set, &key, &value) == 0)
749   {
750     sfree (key);
751     sfree (value);
752   }
753
754   return (0);
755 } /* }}} int statsd_metric_clear_set_unsafe */
756
757 /* Must hold metrics_lock when calling this function. */
758 static int statsd_metric_submit_unsafe (char const *name, statsd_metric_t *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     gauge_t delta = nearbyint (metric->value);
855
856     /* Etsy's statsd writes counters as two metrics: a rate and the change since
857      * the last write. Since collectd does not reset its DERIVE metrics to zero,
858      * this makes little sense, but we're dispatching a "count" metric here
859      * anyway - if requested by the user - for compatibility reasons. */
860     if (conf_counter_sum)
861     {
862       sstrncpy (vl.type, "count", sizeof (vl.type));
863       values[0].gauge = delta;
864       plugin_dispatch_values (&vl);
865
866       /* restore vl.type */
867       sstrncpy (vl.type, "derive", sizeof (vl.type));
868     }
869
870     /* Rather than resetting value to zero, subtract delta so we correctly keep
871      * track of residuals. */
872     metric->value   -= delta;
873     metric->counter += (derive_t) delta;
874
875     values[0].derive = metric->counter;
876   }
877
878   return (plugin_dispatch_values (&vl));
879 } /* }}} int statsd_metric_submit_unsafe */
880
881 static int statsd_read (void) /* {{{ */
882 {
883   c_avl_iterator_t *iter;
884   char *name;
885   statsd_metric_t *metric;
886
887   char **to_be_deleted = NULL;
888   size_t to_be_deleted_num = 0;
889   size_t i;
890
891   pthread_mutex_lock (&metrics_lock);
892
893   if (metrics_tree == NULL)
894   {
895     pthread_mutex_unlock (&metrics_lock);
896     return (0);
897   }
898
899   iter = c_avl_get_iterator (metrics_tree);
900   while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
901   {
902     if ((metric->updates_num == 0)
903         && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
904           || (conf_delete_timers && (metric->type == STATSD_TIMER))
905           || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
906           || (conf_delete_sets && (metric->type == STATSD_SET))))
907     {
908       DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
909       strarray_add (&to_be_deleted, &to_be_deleted_num, name);
910       continue;
911     }
912
913     /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
914      * Remove this here. */
915     statsd_metric_submit_unsafe (name + 2, metric);
916
917     /* Reset the metric. */
918     metric->updates_num = 0;
919     if (metric->type == STATSD_SET)
920       statsd_metric_clear_set_unsafe (metric);
921   }
922   c_avl_iterator_destroy (iter);
923
924   for (i = 0; i < to_be_deleted_num; i++)
925   {
926     int status;
927
928     status = c_avl_remove (metrics_tree, to_be_deleted[i],
929         (void *) &name, (void *) &metric);
930     if (status != 0)
931     {
932       ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
933           to_be_deleted[i], status);
934       continue;
935     }
936
937     sfree (name);
938     statsd_metric_free (metric);
939   }
940
941   pthread_mutex_unlock (&metrics_lock);
942
943   strarray_free (to_be_deleted, to_be_deleted_num);
944
945   return (0);
946 } /* }}} int statsd_read */
947
948 static int statsd_shutdown (void) /* {{{ */
949 {
950   void *key;
951   void *value;
952
953   if (network_thread_running)
954   {
955     network_thread_shutdown = 1;
956     pthread_kill (network_thread, SIGTERM);
957     pthread_join (network_thread, /* retval = */ NULL);
958   }
959   network_thread_running = 0;
960
961   pthread_mutex_lock (&metrics_lock);
962
963   while (c_avl_pick (metrics_tree, &key, &value) == 0)
964   {
965     sfree (key);
966     statsd_metric_free (value);
967   }
968   c_avl_destroy (metrics_tree);
969   metrics_tree = NULL;
970
971   sfree (conf_node);
972   sfree (conf_service);
973
974   pthread_mutex_unlock (&metrics_lock);
975
976   return (0);
977 } /* }}} int statsd_shutdown */
978
979 void module_register (void)
980 {
981   plugin_register_complex_config ("statsd", statsd_config);
982   plugin_register_init ("statsd", statsd_init);
983   plugin_register_read ("statsd", statsd_read);
984   plugin_register_shutdown ("statsd", statsd_shutdown);
985 }
986
987 /* vim: set sw=2 sts=2 et fdm=marker : */