ping plugin: Add support for drop rate and standard deviation.
[collectd.git] / src / ping.c
1 /**
2  * collectd - src/ping.c
3  * Copyright (C) 2005-2009  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at verplant.org>
20  **/
21
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "configfile.h"
26
27 #include <pthread.h>
28
29 #include <netinet/in.h>
30 #include "liboping/oping.h"
31
32 #if HAVE_NETDB_H
33 # include <netdb.h> /* NI_MAXHOST */
34 #endif
35
36 #ifndef NI_MAXHOST
37 # define NI_MAXHOST 1025
38 #endif
39
40 /*
41  * Private data types
42  */
43 struct hostlist_s
44 {
45   char *host;
46
47   uint32_t pkg_sent;
48   uint32_t pkg_recv;
49
50   double latency_total;
51   double latency_squared;
52
53   struct hostlist_s *next;
54 };
55 typedef struct hostlist_s hostlist_t;
56
57 /*
58  * Private variables
59  */
60 static hostlist_t *hostlist_head = NULL;
61
62 static int    ping_ttl = PING_DEF_TTL;
63 static double ping_interval = 1.0;
64 static double ping_timeout = 0.9;
65
66 static int             ping_thread_loop = 0;
67 static int             ping_thread_error = 0;
68 static pthread_t       ping_thread_id;
69 static pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
70 static pthread_cond_t  ping_cond = PTHREAD_COND_INITIALIZER;
71
72 static const char *config_keys[] =
73 {
74   "Host",
75   "TTL",
76   "Interval",
77   "Timeout"
78 };
79 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
80
81 /*
82  * Private functions
83  */
84 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
85 static void time_normalize (struct timespec *ts) /* {{{ */
86 {
87   while (ts->tv_nsec < 0)
88   {
89     if (ts->tv_sec == 0)
90     {
91       ts->tv_nsec = 0;
92       return;
93     }
94
95     ts->tv_sec  -= 1;
96     ts->tv_nsec += 1000000000;
97   }
98
99   while (ts->tv_nsec >= 1000000000)
100   {
101     ts->tv_sec  += 1;
102     ts->tv_nsec -= 1000000000;
103   }
104 } /* }}} void time_normalize */
105
106 /* Add `ts_int' to `tv_begin' and store the result in `ts_dest'. If the result
107  * is larger than `tv_end', copy `tv_end' to `ts_dest' instead. */
108 static void time_calc (struct timespec *ts_dest, /* {{{ */
109     const struct timespec *ts_int,
110     const struct timeval  *tv_begin,
111     const struct timeval  *tv_end)
112 {
113   ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
114   ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
115   time_normalize (ts_dest);
116
117   /* Assure that `(begin + interval) > end'.
118    * This may seem overly complicated, but `tv_sec' is of type `time_t'
119    * which may be `unsigned. *sigh* */
120   if ((tv_end->tv_sec > ts_dest->tv_sec)
121       || ((tv_end->tv_sec == ts_dest->tv_sec)
122         && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
123   {
124     ts_dest->tv_sec = tv_end->tv_sec;
125     ts_dest->tv_nsec = 1000 * tv_end->tv_usec;
126   }
127
128   time_normalize (ts_dest);
129 } /* }}} void time_calc */
130
131 static void *ping_thread (void *arg) /* {{{ */
132 {
133   static pingobj_t *pingobj = NULL;
134
135   struct timeval  tv_begin;
136   struct timeval  tv_end;
137   struct timespec ts_wait;
138   struct timespec ts_int;
139
140   hostlist_t *hl;
141   int status;
142
143   pthread_mutex_lock (&ping_lock);
144
145   pingobj = ping_construct ();
146   if (pingobj == NULL)
147   {
148     ERROR ("ping plugin: ping_construct failed.");
149     ping_thread_error = 1;
150     pthread_mutex_unlock (&ping_lock);
151     return ((void *) -1);
152   }
153
154   ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
155   ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
156
157   /* Add all the hosts to the ping object. */
158   status = 0;
159   for (hl = hostlist_head; hl != NULL; hl = hl->next)
160   {
161     int tmp_status;
162     tmp_status = ping_host_add (pingobj, hl->host);
163     if (tmp_status != 0)
164       WARNING ("ping plugin: ping_host_add (%s) failed.", hl->host);
165     else
166       status++;
167   }
168
169   if (status == 0)
170   {
171     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
172     ping_thread_error = 1;
173     pthread_mutex_unlock (&ping_lock);
174     return ((void *) -1);
175   }
176
177   /* Set up `ts_int' */
178   {
179     double temp_sec;
180     double temp_nsec;
181
182     temp_nsec = modf (ping_interval, &temp_sec);
183     ts_int.tv_sec  = (time_t) temp_sec;
184     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
185   }
186
187   while (ping_thread_loop > 0)
188   {
189     pingobj_iter_t *iter;
190     int status;
191
192     if (gettimeofday (&tv_begin, NULL) < 0)
193     {
194       ERROR ("ping plugin: gettimeofday failed");
195       ping_thread_error = 1;
196       break;
197     }
198
199     pthread_mutex_unlock (&ping_lock);
200
201     status = ping_send (pingobj);
202     if (status < 0)
203     {
204       ERROR ("ping plugin: ping_send failed: %s", ping_get_error (pingobj));
205       pthread_mutex_lock (&ping_lock);
206       ping_thread_error = 1;
207       break;
208     }
209
210     pthread_mutex_lock (&ping_lock);
211
212     if (ping_thread_loop <= 0)
213       break;
214
215     for (iter = ping_iterator_get (pingobj);
216         iter != NULL;
217         iter = ping_iterator_next (iter))
218     { /* {{{ */
219       char userhost[NI_MAXHOST];
220       double latency;
221       size_t param_size;
222
223       param_size = sizeof (userhost);
224       status = ping_iterator_get_info (iter,
225 #ifdef PING_INFO_USERNAME
226           PING_INFO_USERNAME,
227 #else
228           PING_INFO_HOSTNAME,
229 #endif
230           userhost, &param_size);
231       if (status != 0)
232       {
233         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
234             ping_get_error (pingobj));
235         continue;
236       }
237
238       for (hl = hostlist_head; hl != NULL; hl = hl->next)
239         if (strcmp (userhost, hl->host) == 0)
240           break;
241
242       if (hl == NULL)
243       {
244         WARNING ("ping plugin: Cannot find host %s.", userhost);
245         continue;
246       }
247
248       param_size = sizeof (latency);
249       status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
250           (void *) &latency, &param_size);
251       if (status != 0)
252       {
253         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
254             ping_get_error (pingobj));
255         continue;
256       }
257
258       hl->pkg_sent++;
259       if (latency >= 0.0)
260       {
261         hl->pkg_recv++;
262         hl->latency_total += latency;
263         hl->latency_squared += (latency * latency);
264       }
265     } /* }}} for (iter) */
266
267     if (gettimeofday (&tv_end, NULL) < 0)
268     {
269       ERROR ("ping plugin: gettimeofday failed");
270       ping_thread_error = 1;
271       break;
272     }
273
274     /* Calculate the absolute time until which to wait and store it in
275      * `ts_wait'. */
276     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
277
278     status = pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
279     if (ping_thread_loop <= 0)
280       break;
281   } /* while (ping_thread_loop > 0) */
282
283   pthread_mutex_unlock (&ping_lock);
284   ping_destroy (pingobj);
285
286   return ((void *) 0);
287 } /* }}} void *ping_thread */
288
289 static int start_thread (void) /* {{{ */
290 {
291   int status;
292
293   pthread_mutex_lock (&ping_lock);
294
295   if (ping_thread_loop != 0)
296   {
297     pthread_mutex_unlock (&ping_lock);
298     return (-1);
299   }
300
301   ping_thread_loop = 1;
302   ping_thread_error = 0;
303   status = pthread_create (&ping_thread_id, /* attr = */ NULL,
304       ping_thread, /* arg = */ (void *) 0);
305   if (status != 0)
306   {
307     ping_thread_loop = 0;
308     ERROR ("ping plugin: Starting thread failed.");
309     pthread_mutex_unlock (&ping_lock);
310     return (-1);
311   }
312     
313   pthread_mutex_unlock (&ping_lock);
314   return (0);
315 } /* }}} int start_thread */
316
317 static int stop_thread (void) /* {{{ */
318 {
319   int status;
320
321   pthread_mutex_lock (&ping_lock);
322
323   if (ping_thread_loop == 0)
324   {
325     pthread_mutex_unlock (&ping_lock);
326     return (-1);
327   }
328
329   ping_thread_loop = 0;
330   pthread_cond_broadcast (&ping_cond);
331   pthread_mutex_unlock (&ping_lock);
332
333   status = pthread_join (ping_thread_id, /* return = */ NULL);
334   if (status != 0)
335   {
336     ERROR ("ping plugin: Stopping thread failed.");
337     status = -1;
338   }
339
340   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
341   ping_thread_error = 0;
342
343   return (status);
344 } /* }}} int stop_thread */
345
346 static int ping_init (void) /* {{{ */
347 {
348   if (hostlist_head == NULL)
349   {
350     NOTICE ("ping plugin: No hosts have been configured.");
351     return (-1);
352   }
353
354   if (ping_timeout > ping_interval)
355   {
356     ping_timeout = 0.9 * ping_interval;
357     WARNING ("ping plugin: Timeout is greater than interval. "
358         "Will use a timeout of %gs.", ping_timeout);
359   }
360
361   if (start_thread () != 0)
362     return (-1);
363
364   return (0);
365 } /* }}} int ping_init */
366
367 static int ping_config (const char *key, const char *value) /* {{{ */
368 {
369   if (strcasecmp (key, "Host") == 0)
370   {
371     hostlist_t *hl;
372     char *host;
373
374     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
375     if (hl == NULL)
376     {
377       char errbuf[1024];
378       ERROR ("ping plugin: malloc failed: %s",
379           sstrerror (errno, errbuf, sizeof (errbuf)));
380       return (1);
381     }
382
383     host = strdup (value);
384     if (host == NULL)
385     {
386       char errbuf[1024];
387       sfree (hl);
388       ERROR ("ping plugin: strdup failed: %s",
389           sstrerror (errno, errbuf, sizeof (errbuf)));
390       return (1);
391     }
392
393     hl->host = host;
394     hl->pkg_sent = 0;
395     hl->pkg_recv = 0;
396     hl->latency_total = 0.0;
397     hl->latency_squared = 0.0;
398     hl->next = hostlist_head;
399     hostlist_head = hl;
400   }
401   else if (strcasecmp (key, "TTL") == 0)
402   {
403     int ttl = atoi (value);
404     if ((ttl > 0) && (ttl <= 255))
405       ping_ttl = ttl;
406     else
407       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
408   }
409   else if (strcasecmp (key, "Interval") == 0)
410   {
411     double tmp;
412
413     tmp = atof (value);
414     if (tmp > 0.0)
415       ping_interval = tmp;
416     else
417       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
418           tmp, value);
419   }
420   else if (strcasecmp (key, "Timeout") == 0)
421   {
422     double tmp;
423
424     tmp = atof (value);
425     if (tmp > 0.0)
426       ping_timeout = tmp;
427     else
428       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
429           tmp, value);
430   }
431   else
432   {
433     return (-1);
434   }
435
436   return (0);
437 } /* }}} int ping_config */
438
439 static void submit (const char *host, const char *type, /* {{{ */
440     gauge_t value)
441 {
442   value_t values[1];
443   value_list_t vl = VALUE_LIST_INIT;
444
445   values[0].gauge = value;
446
447   vl.values = values;
448   vl.values_len = 1;
449   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
450   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
451   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
452   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
453   sstrncpy (vl.type, type, sizeof (vl.type));
454
455   plugin_dispatch_values (&vl);
456 } /* }}} void ping_submit */
457
458 static int ping_read (void) /* {{{ */
459 {
460   hostlist_t *hl;
461
462   if (ping_thread_error != 0)
463   {
464     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
465
466     stop_thread ();
467
468     for (hl = hostlist_head; hl != NULL; hl = hl->next)
469     {
470       hl->pkg_sent = 0;
471       hl->pkg_recv = 0;
472       hl->latency_total = 0.0;
473       hl->latency_squared = 0.0;
474     }
475
476     start_thread ();
477
478     return (-1);
479   } /* if (ping_thread_error != 0) */
480
481   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
482   {
483     uint32_t pkg_sent;
484     uint32_t pkg_recv;
485     double latency_total;
486     double latency_squared;
487
488     double latency_average;
489     double latency_stddev;
490
491     double droprate;
492
493     /* Locking here works, because the structure of the linked list is only
494      * changed during configure and shutdown. */
495     pthread_mutex_lock (&ping_lock);
496
497     pkg_sent = hl->pkg_sent;
498     pkg_recv = hl->pkg_recv;
499     latency_total = hl->latency_total;
500     latency_squared = hl->latency_squared;
501
502     hl->pkg_sent = 0;
503     hl->pkg_recv = 0;
504     hl->latency_total = 0.0;
505     hl->latency_squared = 0.0;
506
507     pthread_mutex_unlock (&ping_lock);
508
509     /* This e. g. happens when starting up. */
510     if (pkg_sent == 0)
511     {
512       DEBUG ("ping plugin: No packages for host %s have been sent.",
513           hl->host);
514       continue;
515     }
516
517     /* Calculate average. Beware of division by zero. */
518     if (pkg_recv == 0)
519       latency_average = NAN;
520     else
521       latency_average = latency_total / ((double) pkg_recv);
522
523     /* Calculate standard deviation. Beware even more of division by zero. */
524     if (pkg_recv == 0)
525       latency_stddev = NAN;
526     else if (pkg_recv == 1)
527       latency_stddev = 0.0;
528     else
529       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
530           - (latency_total * latency_total))
531           / ((double) (pkg_recv * (pkg_recv - 1))));
532
533     /* Calculate drop rate. */
534     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
535
536     submit (hl->host, "ping", latency_average);
537     submit (hl->host, "ping_stddev", latency_stddev);
538     submit (hl->host, "ping_droprate", droprate);
539   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
540
541   return (0);
542 } /* }}} int ping_read */
543
544 static int ping_shutdown (void) /* {{{ */
545 {
546   hostlist_t *hl;
547
548   INFO ("ping plugin: Shutting down thread.");
549   if (stop_thread () < 0)
550     return (-1);
551
552   hl = hostlist_head;
553   while (hl != NULL)
554   {
555     hostlist_t *hl_next;
556
557     hl_next = hl->next;
558
559     sfree (hl->host);
560     sfree (hl);
561
562     hl = hl_next;
563   }
564
565   return (0);
566 } /* }}} int ping_shutdown */
567
568 void module_register (void)
569 {
570   plugin_register_config ("ping", ping_config,
571       config_keys, config_keys_num);
572   plugin_register_init ("ping", ping_init);
573   plugin_register_read ("ping", ping_read);
574   plugin_register_shutdown ("ping", ping_shutdown);
575 } /* void module_register */
576
577 /* vim: set sw=2 sts=2 et fdm=marker : */