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