{GPL, other}: Relicense to MIT license.
[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   static 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     status = 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   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
425   ping_thread_error = 0;
426
427   return (status);
428 } /* }}} int stop_thread */
429
430 static int ping_init (void) /* {{{ */
431 {
432   if (hostlist_head == NULL)
433   {
434     NOTICE ("ping plugin: No hosts have been configured.");
435     return (-1);
436   }
437
438   if (ping_timeout > ping_interval)
439   {
440     ping_timeout = 0.9 * ping_interval;
441     WARNING ("ping plugin: Timeout is greater than interval. "
442         "Will use a timeout of %gs.", ping_timeout);
443   }
444
445   if (start_thread () != 0)
446     return (-1);
447
448   return (0);
449 } /* }}} int ping_init */
450
451 static int config_set_string (const char *name, /* {{{ */
452     char **var, const char *value)
453 {
454   char *tmp;
455
456   tmp = strdup (value);
457   if (tmp == NULL)
458   {
459     char errbuf[1024];
460     ERROR ("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s",
461         name, value, sstrerror (errno, errbuf, sizeof (errbuf)));
462     return (1);
463   }
464
465   if (*var != NULL)
466     free (*var);
467   *var = tmp;
468   return (0);
469 } /* }}} int config_set_string */
470
471 static int ping_config (const char *key, const char *value) /* {{{ */
472 {
473   if (strcasecmp (key, "Host") == 0)
474   {
475     hostlist_t *hl;
476     char *host;
477
478     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
479     if (hl == NULL)
480     {
481       char errbuf[1024];
482       ERROR ("ping plugin: malloc failed: %s",
483           sstrerror (errno, errbuf, sizeof (errbuf)));
484       return (1);
485     }
486
487     host = strdup (value);
488     if (host == NULL)
489     {
490       char errbuf[1024];
491       sfree (hl);
492       ERROR ("ping plugin: strdup failed: %s",
493           sstrerror (errno, errbuf, sizeof (errbuf)));
494       return (1);
495     }
496
497     hl->host = host;
498     hl->pkg_sent = 0;
499     hl->pkg_recv = 0;
500     hl->pkg_missed = 0;
501     hl->latency_total = 0.0;
502     hl->latency_squared = 0.0;
503     hl->next = hostlist_head;
504     hostlist_head = hl;
505   }
506   else if (strcasecmp (key, "SourceAddress") == 0)
507   {
508     int status = config_set_string (key, &ping_source, value);
509     if (status != 0)
510       return (status);
511   }
512 #ifdef HAVE_OPING_1_3
513   else if (strcasecmp (key, "Device") == 0)
514   {
515     int status = config_set_string (key, &ping_device, value);
516     if (status != 0)
517       return (status);
518   }
519 #endif
520   else if (strcasecmp (key, "TTL") == 0)
521   {
522     int ttl = atoi (value);
523     if ((ttl > 0) && (ttl <= 255))
524       ping_ttl = ttl;
525     else
526       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
527   }
528   else if (strcasecmp (key, "Interval") == 0)
529   {
530     double tmp;
531
532     tmp = atof (value);
533     if (tmp > 0.0)
534       ping_interval = tmp;
535     else
536       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
537           tmp, value);
538   }
539   else if (strcasecmp (key, "Timeout") == 0)
540   {
541     double tmp;
542
543     tmp = atof (value);
544     if (tmp > 0.0)
545       ping_timeout = tmp;
546     else
547       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
548           tmp, value);
549   }
550   else if (strcasecmp (key, "MaxMissed") == 0)
551   {
552     ping_max_missed = atoi (value);
553     if (ping_max_missed < 0)
554       INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
555   }
556   else
557   {
558     return (-1);
559   }
560
561   return (0);
562 } /* }}} int ping_config */
563
564 static void submit (const char *host, const char *type, /* {{{ */
565     gauge_t value)
566 {
567   value_t values[1];
568   value_list_t vl = VALUE_LIST_INIT;
569
570   values[0].gauge = value;
571
572   vl.values = values;
573   vl.values_len = 1;
574   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
575   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
576   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
577   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
578   sstrncpy (vl.type, type, sizeof (vl.type));
579
580   plugin_dispatch_values (&vl);
581 } /* }}} void ping_submit */
582
583 static int ping_read (void) /* {{{ */
584 {
585   hostlist_t *hl;
586
587   if (ping_thread_error != 0)
588   {
589     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
590
591     stop_thread ();
592
593     for (hl = hostlist_head; hl != NULL; hl = hl->next)
594     {
595       hl->pkg_sent = 0;
596       hl->pkg_recv = 0;
597       hl->latency_total = 0.0;
598       hl->latency_squared = 0.0;
599     }
600
601     start_thread ();
602
603     return (-1);
604   } /* if (ping_thread_error != 0) */
605
606   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
607   {
608     uint32_t pkg_sent;
609     uint32_t pkg_recv;
610     double latency_total;
611     double latency_squared;
612
613     double latency_average;
614     double latency_stddev;
615
616     double droprate;
617
618     /* Locking here works, because the structure of the linked list is only
619      * changed during configure and shutdown. */
620     pthread_mutex_lock (&ping_lock);
621
622     pkg_sent = hl->pkg_sent;
623     pkg_recv = hl->pkg_recv;
624     latency_total = hl->latency_total;
625     latency_squared = hl->latency_squared;
626
627     hl->pkg_sent = 0;
628     hl->pkg_recv = 0;
629     hl->latency_total = 0.0;
630     hl->latency_squared = 0.0;
631
632     pthread_mutex_unlock (&ping_lock);
633
634     /* This e. g. happens when starting up. */
635     if (pkg_sent == 0)
636     {
637       DEBUG ("ping plugin: No packages for host %s have been sent.",
638           hl->host);
639       continue;
640     }
641
642     /* Calculate average. Beware of division by zero. */
643     if (pkg_recv == 0)
644       latency_average = NAN;
645     else
646       latency_average = latency_total / ((double) pkg_recv);
647
648     /* Calculate standard deviation. Beware even more of division by zero. */
649     if (pkg_recv == 0)
650       latency_stddev = NAN;
651     else if (pkg_recv == 1)
652       latency_stddev = 0.0;
653     else
654       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
655           - (latency_total * latency_total))
656           / ((double) (pkg_recv * (pkg_recv - 1))));
657
658     /* Calculate drop rate. */
659     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
660
661     submit (hl->host, "ping", latency_average);
662     submit (hl->host, "ping_stddev", latency_stddev);
663     submit (hl->host, "ping_droprate", droprate);
664   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
665
666   return (0);
667 } /* }}} int ping_read */
668
669 static int ping_shutdown (void) /* {{{ */
670 {
671   hostlist_t *hl;
672
673   INFO ("ping plugin: Shutting down thread.");
674   if (stop_thread () < 0)
675     return (-1);
676
677   hl = hostlist_head;
678   while (hl != NULL)
679   {
680     hostlist_t *hl_next;
681
682     hl_next = hl->next;
683
684     sfree (hl->host);
685     sfree (hl);
686
687     hl = hl_next;
688   }
689
690   return (0);
691 } /* }}} int ping_shutdown */
692
693 void module_register (void)
694 {
695   plugin_register_config ("ping", ping_config,
696       config_keys, config_keys_num);
697   plugin_register_init ("ping", ping_init);
698   plugin_register_read ("ping", ping_read);
699   plugin_register_shutdown ("ping", ping_shutdown);
700 } /* void module_register */
701
702 /* vim: set sw=2 sts=2 et fdm=marker : */