Merge branch 'collectd-4.8' into collectd-4.9
[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 #include <netinet/in.h>
29 #if HAVE_NETDB_H
30 # include <netdb.h> /* NI_MAXHOST */
31 #endif
32
33 #include <oping.h>
34
35 #ifndef NI_MAXHOST
36 # define NI_MAXHOST 1025
37 #endif
38
39 #if defined(OPING_VERSION) && (OPING_VERSION >= 1003000)
40 # define HAVE_OPING_1_3
41 #endif
42
43 /*
44  * Private data types
45  */
46 struct hostlist_s
47 {
48   char *host;
49
50   uint32_t pkg_sent;
51   uint32_t pkg_recv;
52   uint32_t pkg_missed;
53
54   double latency_total;
55   double latency_squared;
56
57   struct hostlist_s *next;
58 };
59 typedef struct hostlist_s hostlist_t;
60
61 /*
62  * Private variables
63  */
64 static hostlist_t *hostlist_head = NULL;
65
66 static char  *ping_source = NULL;
67 #ifdef HAVE_OPING_1_3
68 static char  *ping_device = NULL;
69 #endif
70 static int    ping_ttl = PING_DEF_TTL;
71 static double ping_interval = 1.0;
72 static double ping_timeout = 0.9;
73 static int    ping_max_missed = -1;
74
75 static int             ping_thread_loop = 0;
76 static int             ping_thread_error = 0;
77 static pthread_t       ping_thread_id;
78 static pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
79 static pthread_cond_t  ping_cond = PTHREAD_COND_INITIALIZER;
80
81 static const char *config_keys[] =
82 {
83   "Host",
84   "SourceAddress",
85 #ifdef HAVE_OPING_1_3
86   "Device",
87 #endif
88   "TTL",
89   "Interval",
90   "Timeout",
91   "MaxMissed"
92 };
93 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
94
95 /*
96  * Private functions
97  */
98 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
99 static void time_normalize (struct timespec *ts) /* {{{ */
100 {
101   while (ts->tv_nsec < 0)
102   {
103     if (ts->tv_sec == 0)
104     {
105       ts->tv_nsec = 0;
106       return;
107     }
108
109     ts->tv_sec  -= 1;
110     ts->tv_nsec += 1000000000;
111   }
112
113   while (ts->tv_nsec >= 1000000000)
114   {
115     ts->tv_sec  += 1;
116     ts->tv_nsec -= 1000000000;
117   }
118 } /* }}} void time_normalize */
119
120 /* Add `ts_int' to `tv_begin' and store the result in `ts_dest'. If the result
121  * is larger than `tv_end', copy `tv_end' to `ts_dest' instead. */
122 static void time_calc (struct timespec *ts_dest, /* {{{ */
123     const struct timespec *ts_int,
124     const struct timeval  *tv_begin,
125     const struct timeval  *tv_end)
126 {
127   ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
128   ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
129   time_normalize (ts_dest);
130
131   /* Assure that `(begin + interval) > end'.
132    * This may seem overly complicated, but `tv_sec' is of type `time_t'
133    * which may be `unsigned. *sigh* */
134   if ((tv_end->tv_sec > ts_dest->tv_sec)
135       || ((tv_end->tv_sec == ts_dest->tv_sec)
136         && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
137   {
138     ts_dest->tv_sec = tv_end->tv_sec;
139     ts_dest->tv_nsec = 1000 * tv_end->tv_usec;
140   }
141
142   time_normalize (ts_dest);
143 } /* }}} void time_calc */
144
145 static void *ping_thread (void *arg) /* {{{ */
146 {
147   static pingobj_t *pingobj = NULL;
148
149   struct timeval  tv_begin;
150   struct timeval  tv_end;
151   struct timespec ts_wait;
152   struct timespec ts_int;
153
154   hostlist_t *hl;
155   int count;
156
157   pthread_mutex_lock (&ping_lock);
158
159   pingobj = ping_construct ();
160   if (pingobj == NULL)
161   {
162     ERROR ("ping plugin: ping_construct failed.");
163     ping_thread_error = 1;
164     pthread_mutex_unlock (&ping_lock);
165     return ((void *) -1);
166   }
167
168   if (ping_source != NULL)
169     if (ping_setopt (pingobj, PING_OPT_SOURCE, (void *) ping_source) != 0)
170       ERROR ("ping plugin: Failed to set source address: %s",
171           ping_get_error (pingobj));
172
173 #ifdef HAVE_OPING_1_3
174   if (ping_device != NULL)
175     if (ping_setopt (pingobj, PING_OPT_DEVICE, (void *) ping_device) != 0)
176       ERROR ("ping plugin: Failed to set device: %s",
177           ping_get_error (pingobj));
178 #endif
179
180   ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
181   ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
182
183   /* Add all the hosts to the ping object. */
184   count = 0;
185   for (hl = hostlist_head; hl != NULL; hl = hl->next)
186   {
187     int tmp_status;
188     tmp_status = ping_host_add (pingobj, hl->host);
189     if (tmp_status != 0)
190       WARNING ("ping plugin: ping_host_add (%s) failed: %s",
191           hl->host, ping_get_error (pingobj));
192     else
193       count++;
194   }
195
196   if (count == 0)
197   {
198     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
199     ping_thread_error = 1;
200     pthread_mutex_unlock (&ping_lock);
201     return ((void *) -1);
202   }
203
204   /* Set up `ts_int' */
205   {
206     double temp_sec;
207     double temp_nsec;
208
209     temp_nsec = modf (ping_interval, &temp_sec);
210     ts_int.tv_sec  = (time_t) temp_sec;
211     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
212   }
213
214   while (ping_thread_loop > 0)
215   {
216     pingobj_iter_t *iter;
217     int status;
218
219     if (gettimeofday (&tv_begin, NULL) < 0)
220     {
221       char errbuf[1024];
222       ERROR ("ping plugin: gettimeofday failed: %s",
223           sstrerror (errno, errbuf, sizeof (errbuf)));
224       ping_thread_error = 1;
225       break;
226     }
227
228     pthread_mutex_unlock (&ping_lock);
229
230     status = ping_send (pingobj);
231     if (status < 0)
232     {
233       ERROR ("ping plugin: ping_send failed: %s", ping_get_error (pingobj));
234       pthread_mutex_lock (&ping_lock);
235       ping_thread_error = 1;
236       break;
237     }
238
239     pthread_mutex_lock (&ping_lock);
240
241     if (ping_thread_loop <= 0)
242       break;
243
244     for (iter = ping_iterator_get (pingobj);
245         iter != NULL;
246         iter = ping_iterator_next (iter))
247     { /* {{{ */
248       char userhost[NI_MAXHOST];
249       double latency;
250       size_t param_size;
251
252       param_size = sizeof (userhost);
253       status = ping_iterator_get_info (iter,
254 #ifdef PING_INFO_USERNAME
255           PING_INFO_USERNAME,
256 #else
257           PING_INFO_HOSTNAME,
258 #endif
259           userhost, &param_size);
260       if (status != 0)
261       {
262         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
263             ping_get_error (pingobj));
264         continue;
265       }
266
267       for (hl = hostlist_head; hl != NULL; hl = hl->next)
268         if (strcmp (userhost, hl->host) == 0)
269           break;
270
271       if (hl == NULL)
272       {
273         WARNING ("ping plugin: Cannot find host %s.", userhost);
274         continue;
275       }
276
277       param_size = sizeof (latency);
278       status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
279           (void *) &latency, &param_size);
280       if (status != 0)
281       {
282         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
283             ping_get_error (pingobj));
284         continue;
285       }
286
287       hl->pkg_sent++;
288       if (latency >= 0.0)
289       {
290         hl->pkg_recv++;
291         hl->latency_total += latency;
292         hl->latency_squared += (latency * latency);
293
294         /* reset missed packages counter */
295         hl->pkg_missed = 0;
296       } else
297         hl->pkg_missed++;
298
299       /* if the host did not answer our last N packages, trigger a resolv. */
300       if (ping_max_missed >= 0 && hl->pkg_missed >= ping_max_missed)
301       { /* {{{ */
302         /* we reset the missed package counter here, since we only want to
303          * trigger a resolv every N packages and not every package _AFTER_ N
304          * missed packages */
305         hl->pkg_missed = 0;
306
307         WARNING ("ping plugin: host %s has not answered %d PING requests,"
308           " triggering resolve", hl->host, ping_max_missed);
309
310         /* we trigger the resolv simply be removeing and adding the host to our
311          * ping object */
312         status = ping_host_remove (pingobj, hl->host);
313         if (status != 0)
314         {
315           WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
316         }
317         else
318         {
319           status = ping_host_add (pingobj, hl->host);
320           if (status != 0)
321             WARNING ("ping plugin: ping_host_add (%s) failed.", hl->host);
322         }
323       } /* }}} ping_max_missed */
324     } /* }}} for (iter) */
325
326     if (gettimeofday (&tv_end, NULL) < 0)
327     {
328       char errbuf[1024];
329       ERROR ("ping plugin: gettimeofday failed: %s",
330           sstrerror (errno, errbuf, sizeof (errbuf)));
331       ping_thread_error = 1;
332       break;
333     }
334
335     /* Calculate the absolute time until which to wait and store it in
336      * `ts_wait'. */
337     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
338
339     status = pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
340     if (ping_thread_loop <= 0)
341       break;
342   } /* while (ping_thread_loop > 0) */
343
344   pthread_mutex_unlock (&ping_lock);
345   ping_destroy (pingobj);
346
347   return ((void *) 0);
348 } /* }}} void *ping_thread */
349
350 static int start_thread (void) /* {{{ */
351 {
352   int status;
353
354   pthread_mutex_lock (&ping_lock);
355
356   if (ping_thread_loop != 0)
357   {
358     pthread_mutex_unlock (&ping_lock);
359     return (-1);
360   }
361
362   ping_thread_loop = 1;
363   ping_thread_error = 0;
364   status = pthread_create (&ping_thread_id, /* attr = */ NULL,
365       ping_thread, /* arg = */ (void *) 0);
366   if (status != 0)
367   {
368     ping_thread_loop = 0;
369     ERROR ("ping plugin: Starting thread failed.");
370     pthread_mutex_unlock (&ping_lock);
371     return (-1);
372   }
373     
374   pthread_mutex_unlock (&ping_lock);
375   return (0);
376 } /* }}} int start_thread */
377
378 static int stop_thread (void) /* {{{ */
379 {
380   int status;
381
382   pthread_mutex_lock (&ping_lock);
383
384   if (ping_thread_loop == 0)
385   {
386     pthread_mutex_unlock (&ping_lock);
387     return (-1);
388   }
389
390   ping_thread_loop = 0;
391   pthread_cond_broadcast (&ping_cond);
392   pthread_mutex_unlock (&ping_lock);
393
394   status = pthread_join (ping_thread_id, /* return = */ NULL);
395   if (status != 0)
396   {
397     ERROR ("ping plugin: Stopping thread failed.");
398     status = -1;
399   }
400
401   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
402   ping_thread_error = 0;
403
404   return (status);
405 } /* }}} int stop_thread */
406
407 static int ping_init (void) /* {{{ */
408 {
409   if (hostlist_head == NULL)
410   {
411     NOTICE ("ping plugin: No hosts have been configured.");
412     return (-1);
413   }
414
415   if (ping_timeout > ping_interval)
416   {
417     ping_timeout = 0.9 * ping_interval;
418     WARNING ("ping plugin: Timeout is greater than interval. "
419         "Will use a timeout of %gs.", ping_timeout);
420   }
421
422   if (start_thread () != 0)
423     return (-1);
424
425   return (0);
426 } /* }}} int ping_init */
427
428 static int config_set_string (const char *name, /* {{{ */
429     char **var, const char *value)
430 {
431   char *tmp;
432
433   tmp = strdup (value);
434   if (tmp == NULL)
435   {
436     char errbuf[1024];
437     ERROR ("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s",
438         name, value, sstrerror (errno, errbuf, sizeof (errbuf)));
439     return (1);
440   }
441
442   if (*var != NULL)
443     free (*var);
444   *var = tmp;
445   return (0);
446 } /* }}} int config_set_string */
447
448 static int ping_config (const char *key, const char *value) /* {{{ */
449 {
450   if (strcasecmp (key, "Host") == 0)
451   {
452     hostlist_t *hl;
453     char *host;
454
455     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
456     if (hl == NULL)
457     {
458       char errbuf[1024];
459       ERROR ("ping plugin: malloc failed: %s",
460           sstrerror (errno, errbuf, sizeof (errbuf)));
461       return (1);
462     }
463
464     host = strdup (value);
465     if (host == NULL)
466     {
467       char errbuf[1024];
468       sfree (hl);
469       ERROR ("ping plugin: strdup failed: %s",
470           sstrerror (errno, errbuf, sizeof (errbuf)));
471       return (1);
472     }
473
474     hl->host = host;
475     hl->pkg_sent = 0;
476     hl->pkg_recv = 0;
477     hl->pkg_missed = 0;
478     hl->latency_total = 0.0;
479     hl->latency_squared = 0.0;
480     hl->next = hostlist_head;
481     hostlist_head = hl;
482   }
483   else if (strcasecmp (key, "SourceAddress") == 0)
484   {
485     int status = config_set_string (key, &ping_source, value);
486     if (status != 0)
487       return (status);
488   }
489 #ifdef HAVE_OPING_1_3
490   else if (strcasecmp (key, "Device") == 0)
491   {
492     int status = config_set_string (key, &ping_device, value);
493     if (status != 0)
494       return (status);
495   }
496 #endif
497   else if (strcasecmp (key, "TTL") == 0)
498   {
499     int ttl = atoi (value);
500     if ((ttl > 0) && (ttl <= 255))
501       ping_ttl = ttl;
502     else
503       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
504   }
505   else if (strcasecmp (key, "Interval") == 0)
506   {
507     double tmp;
508
509     tmp = atof (value);
510     if (tmp > 0.0)
511       ping_interval = tmp;
512     else
513       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
514           tmp, value);
515   }
516   else if (strcasecmp (key, "Timeout") == 0)
517   {
518     double tmp;
519
520     tmp = atof (value);
521     if (tmp > 0.0)
522       ping_timeout = tmp;
523     else
524       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
525           tmp, value);
526   }
527   else if (strcasecmp (key, "MaxMissed") == 0)
528   {
529     ping_max_missed = atoi (value);
530     if (ping_max_missed < 0)
531       INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
532   }
533   else
534   {
535     return (-1);
536   }
537
538   return (0);
539 } /* }}} int ping_config */
540
541 static void submit (const char *host, const char *type, /* {{{ */
542     gauge_t value)
543 {
544   value_t values[1];
545   value_list_t vl = VALUE_LIST_INIT;
546
547   values[0].gauge = value;
548
549   vl.values = values;
550   vl.values_len = 1;
551   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
552   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
553   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
554   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
555   sstrncpy (vl.type, type, sizeof (vl.type));
556
557   plugin_dispatch_values (&vl);
558 } /* }}} void ping_submit */
559
560 static int ping_read (void) /* {{{ */
561 {
562   hostlist_t *hl;
563
564   if (ping_thread_error != 0)
565   {
566     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
567
568     stop_thread ();
569
570     for (hl = hostlist_head; hl != NULL; hl = hl->next)
571     {
572       hl->pkg_sent = 0;
573       hl->pkg_recv = 0;
574       hl->latency_total = 0.0;
575       hl->latency_squared = 0.0;
576     }
577
578     start_thread ();
579
580     return (-1);
581   } /* if (ping_thread_error != 0) */
582
583   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
584   {
585     uint32_t pkg_sent;
586     uint32_t pkg_recv;
587     double latency_total;
588     double latency_squared;
589
590     double latency_average;
591     double latency_stddev;
592
593     double droprate;
594
595     /* Locking here works, because the structure of the linked list is only
596      * changed during configure and shutdown. */
597     pthread_mutex_lock (&ping_lock);
598
599     pkg_sent = hl->pkg_sent;
600     pkg_recv = hl->pkg_recv;
601     latency_total = hl->latency_total;
602     latency_squared = hl->latency_squared;
603
604     hl->pkg_sent = 0;
605     hl->pkg_recv = 0;
606     hl->latency_total = 0.0;
607     hl->latency_squared = 0.0;
608
609     pthread_mutex_unlock (&ping_lock);
610
611     /* This e. g. happens when starting up. */
612     if (pkg_sent == 0)
613     {
614       DEBUG ("ping plugin: No packages for host %s have been sent.",
615           hl->host);
616       continue;
617     }
618
619     /* Calculate average. Beware of division by zero. */
620     if (pkg_recv == 0)
621       latency_average = NAN;
622     else
623       latency_average = latency_total / ((double) pkg_recv);
624
625     /* Calculate standard deviation. Beware even more of division by zero. */
626     if (pkg_recv == 0)
627       latency_stddev = NAN;
628     else if (pkg_recv == 1)
629       latency_stddev = 0.0;
630     else
631       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
632           - (latency_total * latency_total))
633           / ((double) (pkg_recv * (pkg_recv - 1))));
634
635     /* Calculate drop rate. */
636     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
637
638     submit (hl->host, "ping", latency_average);
639     submit (hl->host, "ping_stddev", latency_stddev);
640     submit (hl->host, "ping_droprate", droprate);
641   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
642
643   return (0);
644 } /* }}} int ping_read */
645
646 static int ping_shutdown (void) /* {{{ */
647 {
648   hostlist_t *hl;
649
650   INFO ("ping plugin: Shutting down thread.");
651   if (stop_thread () < 0)
652     return (-1);
653
654   hl = hostlist_head;
655   while (hl != NULL)
656   {
657     hostlist_t *hl_next;
658
659     hl_next = hl->next;
660
661     sfree (hl->host);
662     sfree (hl);
663
664     hl = hl_next;
665   }
666
667   return (0);
668 } /* }}} int ping_shutdown */
669
670 void module_register (void)
671 {
672   plugin_register_config ("ping", ping_config,
673       config_keys, config_keys_num);
674   plugin_register_init ("ping", ping_init);
675   plugin_register_read ("ping", ping_read);
676   plugin_register_shutdown ("ping", ping_shutdown);
677 } /* void module_register */
678
679 /* vim: set sw=2 sts=2 et fdm=marker : */