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