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