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 status;
188     status = ping_host_add (pingobj, hl->host);
189     if (status != 0)
190       WARNING ("ping plugin: ping_host_add (%s) failed.", hl->host);
191     else
192       count++;
193   }
194
195   if (count == 0)
196   {
197     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
198     ping_thread_error = 1;
199     pthread_mutex_unlock (&ping_lock);
200     return ((void *) -1);
201   }
202
203   /* Set up `ts_int' */
204   {
205     double temp_sec;
206     double temp_nsec;
207
208     temp_nsec = modf (ping_interval, &temp_sec);
209     ts_int.tv_sec  = (time_t) temp_sec;
210     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
211   }
212
213   while (ping_thread_loop > 0)
214   {
215     pingobj_iter_t *iter;
216     int status;
217
218     if (gettimeofday (&tv_begin, NULL) < 0)
219     {
220       ERROR ("ping plugin: gettimeofday failed");
221       ping_thread_error = 1;
222       break;
223     }
224
225     pthread_mutex_unlock (&ping_lock);
226
227     status = ping_send (pingobj);
228     if (status < 0)
229     {
230       ERROR ("ping plugin: ping_send failed: %s", ping_get_error (pingobj));
231       pthread_mutex_lock (&ping_lock);
232       ping_thread_error = 1;
233       break;
234     }
235
236     pthread_mutex_lock (&ping_lock);
237
238     if (ping_thread_loop <= 0)
239       break;
240
241     for (iter = ping_iterator_get (pingobj);
242         iter != NULL;
243         iter = ping_iterator_next (iter))
244     { /* {{{ */
245       char userhost[NI_MAXHOST];
246       double latency;
247       size_t param_size;
248
249       param_size = sizeof (userhost);
250       status = ping_iterator_get_info (iter,
251 #ifdef PING_INFO_USERNAME
252           PING_INFO_USERNAME,
253 #else
254           PING_INFO_HOSTNAME,
255 #endif
256           userhost, &param_size);
257       if (status != 0)
258       {
259         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
260             ping_get_error (pingobj));
261         continue;
262       }
263
264       for (hl = hostlist_head; hl != NULL; hl = hl->next)
265         if (strcmp (userhost, hl->host) == 0)
266           break;
267
268       if (hl == NULL)
269       {
270         WARNING ("ping plugin: Cannot find host %s.", userhost);
271         continue;
272       }
273
274       param_size = sizeof (latency);
275       status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
276           (void *) &latency, &param_size);
277       if (status != 0)
278       {
279         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
280             ping_get_error (pingobj));
281         continue;
282       }
283
284       hl->pkg_sent++;
285       if (latency >= 0.0)
286       {
287         hl->pkg_recv++;
288         hl->latency_total += latency;
289         hl->latency_squared += (latency * latency);
290
291         /* reset missed packages counter */
292         hl->pkg_missed = 0;
293       } else
294         hl->pkg_missed++;
295
296       /* if the host did not answer our last N packages, trigger a resolv. */
297       if (ping_max_missed >= 0 && hl->pkg_missed >= ping_max_missed)
298       { /* {{{ */
299         /* we reset the missed package counter here, since we only want to
300          * trigger a resolv every N packages and not every package _AFTER_ N
301          * missed packages */
302         hl->pkg_missed = 0;
303
304         WARNING ("ping plugin: host %s has not answered %d PING requests,"
305           " triggering resolve", hl->host, ping_max_missed);
306
307         /* we trigger the resolv simply be removeing and adding the host to our
308          * ping object */
309         status = ping_host_remove (pingobj, hl->host);
310         if (status != 0)
311         {
312           WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
313         }
314         else
315         {
316           status = ping_host_add (pingobj, hl->host);
317           if (status != 0)
318             WARNING ("ping plugin: ping_host_add (%s) failed.", hl->host);
319         }
320       } /* }}} ping_max_missed */
321     } /* }}} for (iter) */
322
323     if (gettimeofday (&tv_end, NULL) < 0)
324     {
325       ERROR ("ping plugin: gettimeofday failed");
326       ping_thread_error = 1;
327       break;
328     }
329
330     /* Calculate the absolute time until which to wait and store it in
331      * `ts_wait'. */
332     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
333
334     status = pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
335     if (ping_thread_loop <= 0)
336       break;
337   } /* while (ping_thread_loop > 0) */
338
339   pthread_mutex_unlock (&ping_lock);
340   ping_destroy (pingobj);
341
342   return ((void *) 0);
343 } /* }}} void *ping_thread */
344
345 static int start_thread (void) /* {{{ */
346 {
347   int status;
348
349   pthread_mutex_lock (&ping_lock);
350
351   if (ping_thread_loop != 0)
352   {
353     pthread_mutex_unlock (&ping_lock);
354     return (-1);
355   }
356
357   ping_thread_loop = 1;
358   ping_thread_error = 0;
359   status = pthread_create (&ping_thread_id, /* attr = */ NULL,
360       ping_thread, /* arg = */ (void *) 0);
361   if (status != 0)
362   {
363     ping_thread_loop = 0;
364     ERROR ("ping plugin: Starting thread failed.");
365     pthread_mutex_unlock (&ping_lock);
366     return (-1);
367   }
368     
369   pthread_mutex_unlock (&ping_lock);
370   return (0);
371 } /* }}} int start_thread */
372
373 static int stop_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 = 0;
386   pthread_cond_broadcast (&ping_cond);
387   pthread_mutex_unlock (&ping_lock);
388
389   status = pthread_join (ping_thread_id, /* return = */ NULL);
390   if (status != 0)
391   {
392     ERROR ("ping plugin: Stopping thread failed.");
393     status = -1;
394   }
395
396   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
397   ping_thread_error = 0;
398
399   return (status);
400 } /* }}} int stop_thread */
401
402 static int ping_init (void) /* {{{ */
403 {
404   if (hostlist_head == NULL)
405   {
406     NOTICE ("ping plugin: No hosts have been configured.");
407     return (-1);
408   }
409
410   if (ping_timeout > ping_interval)
411   {
412     ping_timeout = 0.9 * ping_interval;
413     WARNING ("ping plugin: Timeout is greater than interval. "
414         "Will use a timeout of %gs.", ping_timeout);
415   }
416
417   if (start_thread () != 0)
418     return (-1);
419
420   return (0);
421 } /* }}} int ping_init */
422
423 static int config_set_string (const char *name, /* {{{ */
424     char **var, const char *value)
425 {
426   char *tmp;
427
428   tmp = strdup (value);
429   if (tmp == NULL)
430   {
431     char errbuf[1024];
432     ERROR ("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s",
433         name, value, sstrerror (errno, errbuf, sizeof (errbuf)));
434     return (1);
435   }
436
437   if (*var != NULL)
438     free (*var);
439   *var = tmp;
440   return (0);
441 } /* }}} int config_set_string */
442
443 static int ping_config (const char *key, const char *value) /* {{{ */
444 {
445   if (strcasecmp (key, "Host") == 0)
446   {
447     hostlist_t *hl;
448     char *host;
449
450     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
451     if (hl == NULL)
452     {
453       char errbuf[1024];
454       ERROR ("ping plugin: malloc failed: %s",
455           sstrerror (errno, errbuf, sizeof (errbuf)));
456       return (1);
457     }
458
459     host = strdup (value);
460     if (host == NULL)
461     {
462       char errbuf[1024];
463       sfree (hl);
464       ERROR ("ping plugin: strdup failed: %s",
465           sstrerror (errno, errbuf, sizeof (errbuf)));
466       return (1);
467     }
468
469     hl->host = host;
470     hl->pkg_sent = 0;
471     hl->pkg_recv = 0;
472     hl->pkg_missed = 0;
473     hl->latency_total = 0.0;
474     hl->latency_squared = 0.0;
475     hl->next = hostlist_head;
476     hostlist_head = hl;
477   }
478   else if (strcasecmp (key, "SourceAddress") == 0)
479   {
480     int status = config_set_string (key, &ping_source, value);
481     if (status != 0)
482       return (status);
483   }
484 #ifdef HAVE_OPING_1_3
485   else if (strcasecmp (key, "Device") == 0)
486   {
487     int status = config_set_string (key, &ping_device, value);
488     if (status != 0)
489       return (status);
490   }
491 #endif
492   else if (strcasecmp (key, "TTL") == 0)
493   {
494     int ttl = atoi (value);
495     if ((ttl > 0) && (ttl <= 255))
496       ping_ttl = ttl;
497     else
498       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
499   }
500   else if (strcasecmp (key, "Interval") == 0)
501   {
502     double tmp;
503
504     tmp = atof (value);
505     if (tmp > 0.0)
506       ping_interval = tmp;
507     else
508       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
509           tmp, value);
510   }
511   else if (strcasecmp (key, "Timeout") == 0)
512   {
513     double tmp;
514
515     tmp = atof (value);
516     if (tmp > 0.0)
517       ping_timeout = tmp;
518     else
519       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
520           tmp, value);
521   }
522   else if (strcasecmp (key, "MaxMissed") == 0)
523   {
524     ping_max_missed = atoi (value);
525     if (ping_max_missed < 0)
526       INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
527   }
528   else
529   {
530     return (-1);
531   }
532
533   return (0);
534 } /* }}} int ping_config */
535
536 static void submit (const char *host, const char *type, /* {{{ */
537     gauge_t value)
538 {
539   value_t values[1];
540   value_list_t vl = VALUE_LIST_INIT;
541
542   values[0].gauge = value;
543
544   vl.values = values;
545   vl.values_len = 1;
546   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
547   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
548   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
549   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
550   sstrncpy (vl.type, type, sizeof (vl.type));
551
552   plugin_dispatch_values (&vl);
553 } /* }}} void ping_submit */
554
555 static int ping_read (void) /* {{{ */
556 {
557   hostlist_t *hl;
558
559   if (ping_thread_error != 0)
560   {
561     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
562
563     stop_thread ();
564
565     for (hl = hostlist_head; hl != NULL; hl = hl->next)
566     {
567       hl->pkg_sent = 0;
568       hl->pkg_recv = 0;
569       hl->latency_total = 0.0;
570       hl->latency_squared = 0.0;
571     }
572
573     start_thread ();
574
575     return (-1);
576   } /* if (ping_thread_error != 0) */
577
578   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
579   {
580     uint32_t pkg_sent;
581     uint32_t pkg_recv;
582     double latency_total;
583     double latency_squared;
584
585     double latency_average;
586     double latency_stddev;
587
588     double droprate;
589
590     /* Locking here works, because the structure of the linked list is only
591      * changed during configure and shutdown. */
592     pthread_mutex_lock (&ping_lock);
593
594     pkg_sent = hl->pkg_sent;
595     pkg_recv = hl->pkg_recv;
596     latency_total = hl->latency_total;
597     latency_squared = hl->latency_squared;
598
599     hl->pkg_sent = 0;
600     hl->pkg_recv = 0;
601     hl->latency_total = 0.0;
602     hl->latency_squared = 0.0;
603
604     pthread_mutex_unlock (&ping_lock);
605
606     /* This e. g. happens when starting up. */
607     if (pkg_sent == 0)
608     {
609       DEBUG ("ping plugin: No packages for host %s have been sent.",
610           hl->host);
611       continue;
612     }
613
614     /* Calculate average. Beware of division by zero. */
615     if (pkg_recv == 0)
616       latency_average = NAN;
617     else
618       latency_average = latency_total / ((double) pkg_recv);
619
620     /* Calculate standard deviation. Beware even more of division by zero. */
621     if (pkg_recv == 0)
622       latency_stddev = NAN;
623     else if (pkg_recv == 1)
624       latency_stddev = 0.0;
625     else
626       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
627           - (latency_total * latency_total))
628           / ((double) (pkg_recv * (pkg_recv - 1))));
629
630     /* Calculate drop rate. */
631     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
632
633     submit (hl->host, "ping", latency_average);
634     submit (hl->host, "ping_stddev", latency_stddev);
635     submit (hl->host, "ping_droprate", droprate);
636   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
637
638   return (0);
639 } /* }}} int ping_read */
640
641 static int ping_shutdown (void) /* {{{ */
642 {
643   hostlist_t *hl;
644
645   INFO ("ping plugin: Shutting down thread.");
646   if (stop_thread () < 0)
647     return (-1);
648
649   hl = hostlist_head;
650   while (hl != NULL)
651   {
652     hostlist_t *hl_next;
653
654     hl_next = hl->next;
655
656     sfree (hl->host);
657     sfree (hl);
658
659     hl = hl_next;
660   }
661
662   return (0);
663 } /* }}} int ping_shutdown */
664
665 void module_register (void)
666 {
667   plugin_register_config ("ping", ping_config,
668       config_keys, config_keys_num);
669   plugin_register_init ("ping", ping_init);
670   plugin_register_read ("ping", ping_read);
671   plugin_register_shutdown ("ping", ping_shutdown);
672 } /* void module_register */
673
674 /* vim: set sw=2 sts=2 et fdm=marker : */