statsd plugin: Correctly free metrics at shutdown.
[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 void statsd_metric_free (statsd_metric_t *metric) /* {{{ */
194 {
195   if (metric == NULL)
196     return;
197
198   if (metric->latency != NULL)
199   {
200     latency_counter_destroy (metric->latency);
201     metric->latency = NULL;
202   }
203
204   if (metric->set != NULL)
205   {
206     void *key;
207     void *value;
208
209     while (c_avl_pick (metric->set, &key, &value) == 0)
210     {
211       sfree (key);
212       assert (value == NULL);
213     }
214
215     c_avl_destroy (metric->set);
216     metric->set = NULL;
217   }
218
219   sfree (metric);
220 } /* }}} void statsd_metric_free */
221
222 static int statsd_parse_value (char const *str, value_t *ret_value) /* {{{ */
223 {
224   char *endptr = NULL;
225
226   ret_value->gauge = (gauge_t) strtod (str, &endptr);
227   if ((str == endptr) || ((endptr != NULL) && (*endptr != 0)))
228     return (-1);
229
230   return (0);
231 } /* }}} int statsd_parse_value */
232
233 static int statsd_handle_counter (char const *name, /* {{{ */
234     char const *value_str,
235     char const *extra)
236 {
237   value_t value;
238   value_t scale;
239   int status;
240
241   if ((extra != NULL) && (extra[0] != '@'))
242     return (-1);
243
244   scale.gauge = 1.0;
245   if (extra != NULL)
246   {
247     status = statsd_parse_value (extra + 1, &scale);
248     if (status != 0)
249       return (status);
250
251     if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
252       return (-1);
253   }
254
255   value.gauge = 1.0;
256   status = statsd_parse_value (value_str, &value);
257   if (status != 0)
258     return (status);
259
260   return (statsd_metric_add (name, (double) (value.gauge / scale.gauge),
261         STATSD_COUNTER));
262 } /* }}} int statsd_handle_counter */
263
264 static int statsd_handle_gauge (char const *name, /* {{{ */
265     char const *value_str)
266 {
267   value_t value;
268   int status;
269
270   value.gauge = 0;
271   status = statsd_parse_value (value_str, &value);
272   if (status != 0)
273     return (status);
274
275   if ((value_str[0] == '+') || (value_str[0] == '-'))
276     return (statsd_metric_add (name, (double) value.gauge, STATSD_GAUGE));
277   else
278     return (statsd_metric_set (name, (double) value.gauge, STATSD_GAUGE));
279 } /* }}} int statsd_handle_gauge */
280
281 static int statsd_handle_timer (char const *name, /* {{{ */
282     char const *value_str,
283     char const *extra)
284 {
285   statsd_metric_t *metric;
286   value_t value_ms;
287   value_t scale;
288   cdtime_t value;
289   int status;
290
291   if ((extra != NULL) && (extra[0] != '@'))
292     return (-1);
293
294   scale.gauge = 1.0;
295   if (extra != NULL)
296   {
297     status = statsd_parse_value (extra + 1, &scale);
298     if (status != 0)
299       return (status);
300
301     if (!isfinite (scale.gauge) || (scale.gauge <= 0.0) || (scale.gauge > 1.0))
302       return (-1);
303   }
304
305   value_ms.derive = 0;
306   status = statsd_parse_value (value_str, &value_ms);
307   if (status != 0)
308     return (status);
309
310   value = MS_TO_CDTIME_T (value_ms.gauge / scale.gauge);
311
312   pthread_mutex_lock (&metrics_lock);
313
314   metric = statsd_metric_lookup_unsafe (name, STATSD_TIMER);
315   if (metric == NULL)
316   {
317     pthread_mutex_unlock (&metrics_lock);
318     return (-1);
319   }
320
321   if (metric->latency == NULL)
322     metric->latency = latency_counter_create ();
323   if (metric->latency == NULL)
324   {
325     pthread_mutex_unlock (&metrics_lock);
326     return (-1);
327   }
328
329   latency_counter_add (metric->latency, value);
330   metric->updates_num++;
331
332   pthread_mutex_unlock (&metrics_lock);
333   return (0);
334 } /* }}} int statsd_handle_timer */
335
336 static int statsd_handle_set (char const *name, /* {{{ */
337     char const *set_key_orig)
338 {
339   statsd_metric_t *metric = NULL;
340   char *set_key;
341   int status;
342
343   pthread_mutex_lock (&metrics_lock);
344
345   metric = statsd_metric_lookup_unsafe (name, STATSD_SET);
346   if (metric == NULL)
347   {
348     pthread_mutex_unlock (&metrics_lock);
349     return (-1);
350   }
351
352   /* Make sure metric->set exists. */
353   if (metric->set == NULL)
354     metric->set = c_avl_create ((void *) strcmp);
355
356   if (metric->set == NULL)
357   {
358     pthread_mutex_unlock (&metrics_lock);
359     ERROR ("statsd plugin: c_avl_create failed.");
360     return (-1);
361   }
362
363   set_key = strdup (set_key_orig);
364   if (set_key == NULL)
365   {
366     pthread_mutex_unlock (&metrics_lock);
367     ERROR ("statsd plugin: strdup failed.");
368     return (-1);
369   }
370
371   status = c_avl_insert (metric->set, set_key, /* value = */ NULL);
372   if (status < 0)
373   {
374     pthread_mutex_unlock (&metrics_lock);
375     if (status < 0)
376       ERROR ("statsd plugin: c_avl_insert (\"%s\") failed with status %i.",
377           set_key, status);
378     sfree (set_key);
379     return (-1);
380   }
381   else if (status > 0) /* key already exists */
382   {
383     sfree (set_key);
384   }
385
386   metric->updates_num++;
387
388   pthread_mutex_unlock (&metrics_lock);
389   return (0);
390 } /* }}} int statsd_handle_set */
391
392 static int statsd_parse_line (char *buffer) /* {{{ */
393 {
394   char *name = buffer;
395   char *value;
396   char *type;
397   char *extra;
398
399   type = strchr (name, '|');
400   if (type == NULL)
401     return (-1);
402   *type = 0;
403   type++;
404
405   value = strrchr (name, ':');
406   if (value == NULL)
407     return (-1);
408   *value = 0;
409   value++;
410
411   extra = strchr (type, '|');
412   if (extra != NULL)
413   {
414     *extra = 0;
415     extra++;
416   }
417
418   if (strcmp ("c", type) == 0)
419     return (statsd_handle_counter (name, value, extra));
420   else if (strcmp ("ms", type) == 0)
421     return (statsd_handle_timer (name, value, extra));
422
423   /* extra is only valid for counters and timers */
424   if (extra != NULL)
425     return (-1);
426
427   if (strcmp ("g", type) == 0)
428     return (statsd_handle_gauge (name, value));
429   else if (strcmp ("s", type) == 0)
430     return (statsd_handle_set (name, value));
431   else
432     return (-1);
433 } /* }}} void statsd_parse_line */
434
435 static void statsd_parse_buffer (char *buffer) /* {{{ */
436 {
437   while (buffer != NULL)
438   {
439     char orig[64];
440     char *next;
441     int status;
442
443     next = strchr (buffer, '\n');
444     if (next != NULL)
445     {
446       *next = 0;
447       next++;
448     }
449
450     if (*buffer == 0)
451     {
452       buffer = next;
453       continue;
454     }
455
456     sstrncpy (orig, buffer, sizeof (orig));
457
458     status = statsd_parse_line (buffer);
459     if (status != 0)
460       ERROR ("statsd plugin: Unable to parse line: \"%s\"", orig);
461
462     buffer = next;
463   }
464 } /* }}} void statsd_parse_buffer */
465
466 static void statsd_network_read (int fd) /* {{{ */
467 {
468   char buffer[4096];
469   size_t buffer_size;
470   ssize_t status;
471
472   status = recv (fd, buffer, sizeof (buffer), /* flags = */ MSG_DONTWAIT);
473   if (status < 0)
474   {
475     char errbuf[1024];
476
477     if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
478       return;
479
480     ERROR ("statsd plugin: recv(2) failed: %s",
481         sstrerror (errno, errbuf, sizeof (errbuf)));
482     return;
483   }
484
485   buffer_size = (size_t) status;
486   if (buffer_size >= sizeof (buffer))
487     buffer_size = sizeof (buffer) - 1;
488   buffer[buffer_size] = 0;
489
490   statsd_parse_buffer (buffer);
491 } /* }}} void statsd_network_read */
492
493 static int statsd_network_init (struct pollfd **ret_fds, /* {{{ */
494     size_t *ret_fds_num)
495 {
496   struct pollfd *fds = NULL;
497   size_t fds_num = 0;
498
499   struct addrinfo ai_hints;
500   struct addrinfo *ai_list = NULL;
501   struct addrinfo *ai_ptr;
502   int status;
503
504   char const *node = (conf_node != NULL) ? conf_node : STATSD_DEFAULT_NODE;
505   char const *service = (conf_service != NULL)
506     ? conf_service : STATSD_DEFAULT_SERVICE;
507
508   memset (&ai_hints, 0, sizeof (ai_hints));
509   ai_hints.ai_flags = AI_PASSIVE;
510 #ifdef AI_ADDRCONFIG
511   ai_hints.ai_flags |= AI_ADDRCONFIG;
512 #endif
513   ai_hints.ai_family = AF_UNSPEC;
514   ai_hints.ai_socktype = SOCK_DGRAM;
515
516   status = getaddrinfo (node, service, &ai_hints, &ai_list);
517   if (status != 0)
518   {
519     ERROR ("statsd plugin: getaddrinfo (\"%s\", \"%s\") failed: %s",
520         node, service, gai_strerror (status));
521     return (status);
522   }
523
524   for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next)
525   {
526     int fd;
527     struct pollfd *tmp;
528
529     char dbg_node[NI_MAXHOST];
530     char dbg_service[NI_MAXSERV];
531
532     fd = socket (ai_ptr->ai_family, ai_ptr->ai_socktype, ai_ptr->ai_protocol);
533     if (fd < 0)
534     {
535       char errbuf[1024];
536       ERROR ("statsd plugin: socket(2) failed: %s",
537           sstrerror (errno, errbuf, sizeof (errbuf)));
538       continue;
539     }
540
541     getnameinfo (ai_ptr->ai_addr, ai_ptr->ai_addrlen,
542         dbg_node, sizeof (dbg_node), dbg_service, sizeof (dbg_service),
543         NI_DGRAM | NI_NUMERICHOST | NI_NUMERICSERV);
544     DEBUG ("statsd plugin: Trying to bind to [%s]:%s ...", dbg_node, dbg_service);
545
546     status = bind (fd, ai_ptr->ai_addr, ai_ptr->ai_addrlen);
547     if (status != 0)
548     {
549       char errbuf[1024];
550       ERROR ("statsd plugin: bind(2) failed: %s",
551           sstrerror (errno, errbuf, sizeof (errbuf)));
552       close (fd);
553       continue;
554     }
555
556     tmp = realloc (fds, sizeof (*fds) * (fds_num + 1));
557     if (tmp == NULL)
558     {
559       ERROR ("statsd plugin: realloc failed.");
560       continue;
561     }
562     fds = tmp;
563     tmp = fds + fds_num;
564     fds_num++;
565
566     memset (tmp, 0, sizeof (*tmp));
567     tmp->fd = fd;
568     tmp->events = POLLIN | POLLPRI;
569   }
570
571   freeaddrinfo (ai_list);
572
573   if (fds_num == 0)
574   {
575     ERROR ("statsd plugin: Unable to create listening socket for [%s]:%s.",
576         (node != NULL) ? node : "::", service);
577     return (ENOENT);
578   }
579
580   *ret_fds = fds;
581   *ret_fds_num = fds_num;
582   return (0);
583 } /* }}} int statsd_network_init */
584
585 static void *statsd_network_thread (void *args) /* {{{ */
586 {
587   struct pollfd *fds = NULL;
588   size_t fds_num = 0;
589   int status;
590   size_t i;
591
592   status = statsd_network_init (&fds, &fds_num);
593   if (status != 0)
594   {
595     ERROR ("statsd plugin: Unable to open listening sockets.");
596     pthread_exit ((void *) 0);
597   }
598
599   while (!network_thread_shutdown)
600   {
601     status = poll (fds, (nfds_t) fds_num, /* timeout = */ -1);
602     if (status < 0)
603     {
604       char errbuf[1024];
605
606       if ((errno == EINTR) || (errno == EAGAIN))
607         continue;
608
609       ERROR ("statsd plugin: poll(2) failed: %s",
610           sstrerror (errno, errbuf, sizeof (errbuf)));
611       break;
612     }
613
614     for (i = 0; i < fds_num; i++)
615     {
616       if ((fds[i].revents & (POLLIN | POLLPRI)) == 0)
617         continue;
618
619       statsd_network_read (fds[i].fd);
620       fds[i].revents = 0;
621     }
622   } /* while (!network_thread_shutdown) */
623
624   /* Clean up */
625   for (i = 0; i < fds_num; i++)
626     close (fds[i].fd);
627   sfree (fds);
628
629   return ((void *) 0);
630 } /* }}} void *statsd_network_thread */
631
632 static int statsd_config_timer_percentile (oconfig_item_t *ci) /* {{{ */
633 {
634   double percent = NAN;
635   double *tmp;
636   int status;
637
638   status = cf_util_get_double (ci, &percent);
639   if (status != 0)
640     return (status);
641
642   if ((percent <= 0.0) || (percent >= 100))
643   {
644     ERROR ("statsd plugin: The value for \"%s\" must be between 0 and 100, "
645         "exclusively.", ci->key);
646     return (ERANGE);
647   }
648
649   tmp = realloc (conf_timer_percentile,
650       sizeof (*conf_timer_percentile) * (conf_timer_percentile_num + 1));
651   if (tmp == NULL)
652   {
653     ERROR ("statsd plugin: realloc failed.");
654     return (ENOMEM);
655   }
656   conf_timer_percentile = tmp;
657   conf_timer_percentile[conf_timer_percentile_num] = percent;
658   conf_timer_percentile_num++;
659
660   return (0);
661 } /* }}} int statsd_config_timer_percentile */
662
663 static int statsd_config (oconfig_item_t *ci) /* {{{ */
664 {
665   int i;
666
667   for (i = 0; i < ci->children_num; i++)
668   {
669     oconfig_item_t *child = ci->children + i;
670
671     if (strcasecmp ("Host", child->key) == 0)
672       cf_util_get_string (child, &conf_node);
673     else if (strcasecmp ("Port", child->key) == 0)
674       cf_util_get_service (child, &conf_service);
675     else if (strcasecmp ("DeleteCounters", child->key) == 0)
676       cf_util_get_boolean (child, &conf_delete_counters);
677     else if (strcasecmp ("DeleteTimers", child->key) == 0)
678       cf_util_get_boolean (child, &conf_delete_timers);
679     else if (strcasecmp ("DeleteGauges", child->key) == 0)
680       cf_util_get_boolean (child, &conf_delete_gauges);
681     else if (strcasecmp ("DeleteSets", child->key) == 0)
682       cf_util_get_boolean (child, &conf_delete_sets);
683     else if (strcasecmp ("TimerLower", child->key) == 0)
684       cf_util_get_boolean (child, &conf_timer_lower);
685     else if (strcasecmp ("TimerUpper", child->key) == 0)
686       cf_util_get_boolean (child, &conf_timer_upper);
687     else if (strcasecmp ("TimerSum", child->key) == 0)
688       cf_util_get_boolean (child, &conf_timer_sum);
689     else if (strcasecmp ("TimerCount", child->key) == 0)
690       cf_util_get_boolean (child, &conf_timer_count);
691     else if (strcasecmp ("TimerPercentile", child->key) == 0)
692       statsd_config_timer_percentile (child);
693     else
694       ERROR ("statsd plugin: The \"%s\" config option is not valid.",
695           child->key);
696   }
697
698   return (0);
699 } /* }}} int statsd_config */
700
701 static int statsd_init (void) /* {{{ */
702 {
703   pthread_mutex_lock (&metrics_lock);
704   if (metrics_tree == NULL)
705     metrics_tree = c_avl_create ((void *) strcmp);
706
707   if (!network_thread_running)
708   {
709     int status;
710
711     status = pthread_create (&network_thread,
712         /* attr = */ NULL,
713         statsd_network_thread,
714         /* args = */ NULL);
715     if (status != 0)
716     {
717       char errbuf[1024];
718       pthread_mutex_unlock (&metrics_lock);
719       ERROR ("statsd plugin: pthread_create failed: %s",
720           sstrerror (errno, errbuf, sizeof (errbuf)));
721       return (status);
722     }
723   }
724   network_thread_running = 1;
725
726   pthread_mutex_unlock (&metrics_lock);
727
728   return (0);
729 } /* }}} int statsd_init */
730
731 /* Must hold metrics_lock when calling this function. */
732 static int statsd_metric_clear_set_unsafe (statsd_metric_t *metric) /* {{{ */
733 {
734   void *key;
735   void *value;
736
737   if ((metric == NULL) || (metric->type != STATSD_SET))
738     return (EINVAL);
739
740   if (metric->set == NULL)
741     return (0);
742
743   while (c_avl_pick (metric->set, &key, &value) == 0)
744   {
745     sfree (key);
746     sfree (value);
747   }
748
749   return (0);
750 } /* }}} int statsd_metric_clear_set_unsafe */
751
752 /* Must hold metrics_lock when calling this function. */
753 static int statsd_metric_submit_unsafe (char const *name, /* {{{ */
754     statsd_metric_t const *metric)
755 {
756   value_t values[1];
757   value_list_t vl = VALUE_LIST_INIT;
758
759   vl.values = values;
760   vl.values_len = 1;
761   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
762   sstrncpy (vl.plugin, "statsd", sizeof (vl.plugin));
763
764   if (metric->type == STATSD_GAUGE)
765     sstrncpy (vl.type, "gauge", sizeof (vl.type));
766   else if (metric->type == STATSD_TIMER)
767     sstrncpy (vl.type, "latency", sizeof (vl.type));
768   else if (metric->type == STATSD_SET)
769     sstrncpy (vl.type, "objects", sizeof (vl.type));
770   else /* if (metric->type == STATSD_COUNTER) */
771     sstrncpy (vl.type, "derive", sizeof (vl.type));
772
773   sstrncpy (vl.type_instance, name, sizeof (vl.type_instance));
774
775   if (metric->type == STATSD_GAUGE)
776     values[0].gauge = (gauge_t) metric->value;
777   else if (metric->type == STATSD_TIMER)
778   {
779     size_t i;
780     _Bool have_events = (metric->updates_num > 0);
781
782     /* Make sure all timer metrics share the *same* timestamp. */
783     vl.time = cdtime ();
784
785     ssnprintf (vl.type_instance, sizeof (vl.type_instance),
786         "%s-average", name);
787     values[0].gauge = have_events
788       ? CDTIME_T_TO_DOUBLE (latency_counter_get_average (metric->latency))
789       : NAN;
790     plugin_dispatch_values (&vl);
791
792     if (conf_timer_lower) {
793       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
794           "%s-lower", name);
795       values[0].gauge = have_events
796         ? CDTIME_T_TO_DOUBLE (latency_counter_get_min (metric->latency))
797         : NAN;
798       plugin_dispatch_values (&vl);
799     }
800
801     if (conf_timer_upper) {
802       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
803           "%s-upper", name);
804       values[0].gauge = have_events
805         ? CDTIME_T_TO_DOUBLE (latency_counter_get_max (metric->latency))
806         : NAN;
807       plugin_dispatch_values (&vl);
808     }
809
810     if (conf_timer_sum) {
811       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
812           "%s-sum", name);
813       values[0].gauge = have_events
814         ? CDTIME_T_TO_DOUBLE (latency_counter_get_sum (metric->latency))
815         : NAN;
816       plugin_dispatch_values (&vl);
817     }
818
819     for (i = 0; i < conf_timer_percentile_num; i++)
820     {
821       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
822           "%s-percentile-%.0f", name, conf_timer_percentile[i]);
823       values[0].gauge = have_events
824         ? CDTIME_T_TO_DOUBLE (latency_counter_get_percentile (metric->latency, conf_timer_percentile[i]))
825         : NAN;
826       plugin_dispatch_values (&vl);
827     }
828
829     /* Keep this at the end, since vl.type is set to "gauge" here. The
830      * vl.type's above are implicitly set to "latency". */
831     if (conf_timer_count) {
832       sstrncpy (vl.type, "gauge", sizeof (vl.type));
833       ssnprintf (vl.type_instance, sizeof (vl.type_instance),
834           "%s-count", name);
835       values[0].gauge = latency_counter_get_num (metric->latency);
836       plugin_dispatch_values (&vl);
837     }
838
839     latency_counter_reset (metric->latency);
840     return (0);
841   }
842   else if (metric->type == STATSD_SET)
843   {
844     if (metric->set == NULL)
845       values[0].gauge = 0.0;
846     else
847       values[0].gauge = (gauge_t) c_avl_size (metric->set);
848   }
849   else { /* STATSD_COUNTER */
850       /*
851        * Expand a single value to two metrics:
852        *
853        * - The absolute counter, as a gauge
854        * - A derived rate for this counter
855        */
856       values[0].derive = (derive_t) metric->value;
857       plugin_dispatch_values(&vl);
858
859       sstrncpy(vl.type, "gauge", sizeof (vl.type));
860       values[0].gauge = (gauge_t) metric->value;
861   }
862
863   return (plugin_dispatch_values (&vl));
864 } /* }}} int statsd_metric_submit_unsafe */
865
866 static int statsd_read (void) /* {{{ */
867 {
868   c_avl_iterator_t *iter;
869   char *name;
870   statsd_metric_t *metric;
871
872   char **to_be_deleted = NULL;
873   size_t to_be_deleted_num = 0;
874   size_t i;
875
876   pthread_mutex_lock (&metrics_lock);
877
878   if (metrics_tree == NULL)
879   {
880     pthread_mutex_unlock (&metrics_lock);
881     return (0);
882   }
883
884   iter = c_avl_get_iterator (metrics_tree);
885   while (c_avl_iterator_next (iter, (void *) &name, (void *) &metric) == 0)
886   {
887     if ((metric->updates_num == 0)
888         && ((conf_delete_counters && (metric->type == STATSD_COUNTER))
889           || (conf_delete_timers && (metric->type == STATSD_TIMER))
890           || (conf_delete_gauges && (metric->type == STATSD_GAUGE))
891           || (conf_delete_sets && (metric->type == STATSD_SET))))
892     {
893       DEBUG ("statsd plugin: Deleting metric \"%s\".", name);
894       strarray_add (&to_be_deleted, &to_be_deleted_num, name);
895       continue;
896     }
897
898     /* Names have a prefix, e.g. "c:", which determines the (statsd) type.
899      * Remove this here. */
900     statsd_metric_submit_unsafe (name + 2, metric);
901
902     /* Reset the metric. */
903     metric->updates_num = 0;
904     if (metric->type == STATSD_SET)
905       statsd_metric_clear_set_unsafe (metric);
906   }
907   c_avl_iterator_destroy (iter);
908
909   for (i = 0; i < to_be_deleted_num; i++)
910   {
911     int status;
912
913     status = c_avl_remove (metrics_tree, to_be_deleted[i],
914         (void *) &name, (void *) &metric);
915     if (status != 0)
916     {
917       ERROR ("stats plugin: c_avl_remove (\"%s\") failed with status %i.",
918           to_be_deleted[i], status);
919       continue;
920     }
921
922     sfree (name);
923     statsd_metric_free (metric);
924   }
925
926   pthread_mutex_unlock (&metrics_lock);
927
928   strarray_free (to_be_deleted, to_be_deleted_num);
929
930   return (0);
931 } /* }}} int statsd_read */
932
933 static int statsd_shutdown (void) /* {{{ */
934 {
935   void *key;
936   void *value;
937
938   pthread_mutex_lock (&metrics_lock);
939
940   if (network_thread_running)
941   {
942     network_thread_shutdown = 1;
943     pthread_kill (network_thread, SIGTERM);
944     pthread_join (network_thread, /* retval = */ NULL);
945   }
946   network_thread_running = 0;
947
948   while (c_avl_pick (metrics_tree, &key, &value) == 0)
949   {
950     sfree (key);
951     statsd_metric_free (value);
952   }
953   c_avl_destroy (metrics_tree);
954   metrics_tree = NULL;
955
956   sfree (conf_node);
957   sfree (conf_service);
958
959   pthread_mutex_unlock (&metrics_lock);
960
961   return (0);
962 } /* }}} int statsd_shutdown */
963
964 void module_register (void)
965 {
966   plugin_register_complex_config ("statsd", statsd_config);
967   plugin_register_init ("statsd", statsd_init);
968   plugin_register_read ("statsd", statsd_read);
969   plugin_register_shutdown ("statsd", statsd_shutdown);
970 }
971
972 /* vim: set sw=2 sts=2 et fdm=marker : */