Code

ping plugin: Refactor "ping_thread": Move iteration over hosts into a function.
[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  **/
22 #include "collectd.h"
23 #include "common.h"
24 #include "plugin.h"
25 #include "configfile.h"
27 #include <pthread.h>
28 #include <netinet/in.h>
29 #if HAVE_NETDB_H
30 # include <netdb.h> /* NI_MAXHOST */
31 #endif
33 #include <oping.h>
35 #ifndef NI_MAXHOST
36 # define NI_MAXHOST 1025
37 #endif
39 #if defined(OPING_VERSION) && (OPING_VERSION >= 1003000)
40 # define HAVE_OPING_1_3
41 #endif
43 /*
44  * Private data types
45  */
46 struct hostlist_s
47 {
48   char *host;
50   uint32_t pkg_sent;
51   uint32_t pkg_recv;
52   uint32_t pkg_missed;
54   double latency_total;
55   double latency_squared;
57   struct hostlist_s *next;
58 };
59 typedef struct hostlist_s hostlist_t;
61 /*
62  * Private variables
63  */
64 static hostlist_t *hostlist_head = NULL;
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;
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;
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);
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) /* {{{ */
101   while (ts->tv_nsec < 0)
102   {
103     if (ts->tv_sec == 0)
104     {
105       ts->tv_nsec = 0;
106       return;
107     }
109     ts->tv_sec  -= 1;
110     ts->tv_nsec += 1000000000;
111   }
113   while (ts->tv_nsec >= 1000000000)
114   {
115     ts->tv_sec  += 1;
116     ts->tv_nsec -= 1000000000;
117   }
118 } /* }}} void time_normalize */
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)
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);
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   }
142   time_normalize (ts_dest);
143 } /* }}} void time_calc */
145 static int ping_dispatch_all (pingobj_t *pingobj) /* {{{ */
147   pingobj_iter_t *iter;
148   hostlist_t *hl;
149   int status;
151   for (iter = ping_iterator_get (pingobj);
152       iter != NULL;
153       iter = ping_iterator_next (iter))
154   { /* {{{ */
155     char userhost[NI_MAXHOST];
156     double latency;
157     size_t param_size;
159     param_size = sizeof (userhost);
160     status = ping_iterator_get_info (iter,
161 #ifdef PING_INFO_USERNAME
162         PING_INFO_USERNAME,
163 #else
164         PING_INFO_HOSTNAME,
165 #endif
166         userhost, &param_size);
167     if (status != 0)
168     {
169       WARNING ("ping plugin: ping_iterator_get_info failed: %s",
170           ping_get_error (pingobj));
171       continue;
172     }
174     for (hl = hostlist_head; hl != NULL; hl = hl->next)
175       if (strcmp (userhost, hl->host) == 0)
176         break;
178     if (hl == NULL)
179     {
180       WARNING ("ping plugin: Cannot find host %s.", userhost);
181       continue;
182     }
184     param_size = sizeof (latency);
185     status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
186         (void *) &latency, &param_size);
187     if (status != 0)
188     {
189       WARNING ("ping plugin: ping_iterator_get_info failed: %s",
190           ping_get_error (pingobj));
191       continue;
192     }
194     hl->pkg_sent++;
195     if (latency >= 0.0)
196     {
197       hl->pkg_recv++;
198       hl->latency_total += latency;
199       hl->latency_squared += (latency * latency);
201       /* reset missed packages counter */
202       hl->pkg_missed = 0;
203     } else
204       hl->pkg_missed++;
206     /* if the host did not answer our last N packages, trigger a resolv. */
207     if (ping_max_missed >= 0 && hl->pkg_missed >= ping_max_missed)
208     { /* {{{ */
209       /* we reset the missed package counter here, since we only want to
210        * trigger a resolv every N packages and not every package _AFTER_ N
211        * missed packages */
212       hl->pkg_missed = 0;
214       WARNING ("ping plugin: host %s has not answered %d PING requests,"
215           " triggering resolve", hl->host, ping_max_missed);
217       /* we trigger the resolv simply be removeing and adding the host to our
218        * ping object */
219       status = ping_host_remove (pingobj, hl->host);
220       if (status != 0)
221       {
222         WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
223       }
224       else
225       {
226         status = ping_host_add (pingobj, hl->host);
227         if (status != 0)
228           ERROR ("ping plugin: ping_host_add (%s) failed.", hl->host);
229       }
230     } /* }}} ping_max_missed */
231   } /* }}} for (iter) */
233   return (0);
234 } /* }}} int ping_dispatch_all */
236 static void *ping_thread (void *arg) /* {{{ */
238   static pingobj_t *pingobj = NULL;
240   struct timeval  tv_begin;
241   struct timeval  tv_end;
242   struct timespec ts_wait;
243   struct timespec ts_int;
245   hostlist_t *hl;
246   int count;
248   pthread_mutex_lock (&ping_lock);
250   pingobj = ping_construct ();
251   if (pingobj == NULL)
252   {
253     ERROR ("ping plugin: ping_construct failed.");
254     ping_thread_error = 1;
255     pthread_mutex_unlock (&ping_lock);
256     return ((void *) -1);
257   }
259   if (ping_source != NULL)
260     if (ping_setopt (pingobj, PING_OPT_SOURCE, (void *) ping_source) != 0)
261       ERROR ("ping plugin: Failed to set source address: %s",
262           ping_get_error (pingobj));
264 #ifdef HAVE_OPING_1_3
265   if (ping_device != NULL)
266     if (ping_setopt (pingobj, PING_OPT_DEVICE, (void *) ping_device) != 0)
267       ERROR ("ping plugin: Failed to set device: %s",
268           ping_get_error (pingobj));
269 #endif
271   ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
272   ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
274   /* Add all the hosts to the ping object. */
275   count = 0;
276   for (hl = hostlist_head; hl != NULL; hl = hl->next)
277   {
278     int tmp_status;
279     tmp_status = ping_host_add (pingobj, hl->host);
280     if (tmp_status != 0)
281       WARNING ("ping plugin: ping_host_add (%s) failed: %s",
282           hl->host, ping_get_error (pingobj));
283     else
284       count++;
285   }
287   if (count == 0)
288   {
289     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
290     ping_thread_error = 1;
291     pthread_mutex_unlock (&ping_lock);
292     return ((void *) -1);
293   }
295   /* Set up `ts_int' */
296   {
297     double temp_sec;
298     double temp_nsec;
300     temp_nsec = modf (ping_interval, &temp_sec);
301     ts_int.tv_sec  = (time_t) temp_sec;
302     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
303   }
305   while (ping_thread_loop > 0)
306   {
307     int status;
309     if (gettimeofday (&tv_begin, NULL) < 0)
310     {
311       char errbuf[1024];
312       ERROR ("ping plugin: gettimeofday failed: %s",
313           sstrerror (errno, errbuf, sizeof (errbuf)));
314       ping_thread_error = 1;
315       break;
316     }
318     pthread_mutex_unlock (&ping_lock);
320     status = ping_send (pingobj);
321     if (status < 0)
322     {
323       ERROR ("ping plugin: ping_send failed: %s", ping_get_error (pingobj));
324       pthread_mutex_lock (&ping_lock);
325       ping_thread_error = 1;
326       break;
327     }
329     pthread_mutex_lock (&ping_lock);
331     if (ping_thread_loop <= 0)
332       break;
334     (void) ping_dispatch_all (pingobj);
336     if (gettimeofday (&tv_end, NULL) < 0)
337     {
338       char errbuf[1024];
339       ERROR ("ping plugin: gettimeofday failed: %s",
340           sstrerror (errno, errbuf, sizeof (errbuf)));
341       ping_thread_error = 1;
342       break;
343     }
345     /* Calculate the absolute time until which to wait and store it in
346      * `ts_wait'. */
347     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
349     status = pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
350     if (ping_thread_loop <= 0)
351       break;
352   } /* while (ping_thread_loop > 0) */
354   pthread_mutex_unlock (&ping_lock);
355   ping_destroy (pingobj);
357   return ((void *) 0);
358 } /* }}} void *ping_thread */
360 static int start_thread (void) /* {{{ */
362   int status;
364   pthread_mutex_lock (&ping_lock);
366   if (ping_thread_loop != 0)
367   {
368     pthread_mutex_unlock (&ping_lock);
369     return (-1);
370   }
372   ping_thread_loop = 1;
373   ping_thread_error = 0;
374   status = pthread_create (&ping_thread_id, /* attr = */ NULL,
375       ping_thread, /* arg = */ (void *) 0);
376   if (status != 0)
377   {
378     ping_thread_loop = 0;
379     ERROR ("ping plugin: Starting thread failed.");
380     pthread_mutex_unlock (&ping_lock);
381     return (-1);
382   }
383     
384   pthread_mutex_unlock (&ping_lock);
385   return (0);
386 } /* }}} int start_thread */
388 static int stop_thread (void) /* {{{ */
390   int status;
392   pthread_mutex_lock (&ping_lock);
394   if (ping_thread_loop == 0)
395   {
396     pthread_mutex_unlock (&ping_lock);
397     return (-1);
398   }
400   ping_thread_loop = 0;
401   pthread_cond_broadcast (&ping_cond);
402   pthread_mutex_unlock (&ping_lock);
404   status = pthread_join (ping_thread_id, /* return = */ NULL);
405   if (status != 0)
406   {
407     ERROR ("ping plugin: Stopping thread failed.");
408     status = -1;
409   }
411   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
412   ping_thread_error = 0;
414   return (status);
415 } /* }}} int stop_thread */
417 static int ping_init (void) /* {{{ */
419   if (hostlist_head == NULL)
420   {
421     NOTICE ("ping plugin: No hosts have been configured.");
422     return (-1);
423   }
425   if (ping_timeout > ping_interval)
426   {
427     ping_timeout = 0.9 * ping_interval;
428     WARNING ("ping plugin: Timeout is greater than interval. "
429         "Will use a timeout of %gs.", ping_timeout);
430   }
432   if (start_thread () != 0)
433     return (-1);
435   return (0);
436 } /* }}} int ping_init */
438 static int config_set_string (const char *name, /* {{{ */
439     char **var, const char *value)
441   char *tmp;
443   tmp = strdup (value);
444   if (tmp == NULL)
445   {
446     char errbuf[1024];
447     ERROR ("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s",
448         name, value, sstrerror (errno, errbuf, sizeof (errbuf)));
449     return (1);
450   }
452   if (*var != NULL)
453     free (*var);
454   *var = tmp;
455   return (0);
456 } /* }}} int config_set_string */
458 static int ping_config (const char *key, const char *value) /* {{{ */
460   if (strcasecmp (key, "Host") == 0)
461   {
462     hostlist_t *hl;
463     char *host;
465     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
466     if (hl == NULL)
467     {
468       char errbuf[1024];
469       ERROR ("ping plugin: malloc failed: %s",
470           sstrerror (errno, errbuf, sizeof (errbuf)));
471       return (1);
472     }
474     host = strdup (value);
475     if (host == NULL)
476     {
477       char errbuf[1024];
478       sfree (hl);
479       ERROR ("ping plugin: strdup failed: %s",
480           sstrerror (errno, errbuf, sizeof (errbuf)));
481       return (1);
482     }
484     hl->host = host;
485     hl->pkg_sent = 0;
486     hl->pkg_recv = 0;
487     hl->pkg_missed = 0;
488     hl->latency_total = 0.0;
489     hl->latency_squared = 0.0;
490     hl->next = hostlist_head;
491     hostlist_head = hl;
492   }
493   else if (strcasecmp (key, "SourceAddress") == 0)
494   {
495     int status = config_set_string (key, &ping_source, value);
496     if (status != 0)
497       return (status);
498   }
499 #ifdef HAVE_OPING_1_3
500   else if (strcasecmp (key, "Device") == 0)
501   {
502     int status = config_set_string (key, &ping_device, value);
503     if (status != 0)
504       return (status);
505   }
506 #endif
507   else if (strcasecmp (key, "TTL") == 0)
508   {
509     int ttl = atoi (value);
510     if ((ttl > 0) && (ttl <= 255))
511       ping_ttl = ttl;
512     else
513       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
514   }
515   else if (strcasecmp (key, "Interval") == 0)
516   {
517     double tmp;
519     tmp = atof (value);
520     if (tmp > 0.0)
521       ping_interval = tmp;
522     else
523       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
524           tmp, value);
525   }
526   else if (strcasecmp (key, "Timeout") == 0)
527   {
528     double tmp;
530     tmp = atof (value);
531     if (tmp > 0.0)
532       ping_timeout = tmp;
533     else
534       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
535           tmp, value);
536   }
537   else if (strcasecmp (key, "MaxMissed") == 0)
538   {
539     ping_max_missed = atoi (value);
540     if (ping_max_missed < 0)
541       INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
542   }
543   else
544   {
545     return (-1);
546   }
548   return (0);
549 } /* }}} int ping_config */
551 static void submit (const char *host, const char *type, /* {{{ */
552     gauge_t value)
554   value_t values[1];
555   value_list_t vl = VALUE_LIST_INIT;
557   values[0].gauge = value;
559   vl.values = values;
560   vl.values_len = 1;
561   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
562   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
563   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
564   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
565   sstrncpy (vl.type, type, sizeof (vl.type));
567   plugin_dispatch_values (&vl);
568 } /* }}} void ping_submit */
570 static int ping_read (void) /* {{{ */
572   hostlist_t *hl;
574   if (ping_thread_error != 0)
575   {
576     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
578     stop_thread ();
580     for (hl = hostlist_head; hl != NULL; hl = hl->next)
581     {
582       hl->pkg_sent = 0;
583       hl->pkg_recv = 0;
584       hl->latency_total = 0.0;
585       hl->latency_squared = 0.0;
586     }
588     start_thread ();
590     return (-1);
591   } /* if (ping_thread_error != 0) */
593   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
594   {
595     uint32_t pkg_sent;
596     uint32_t pkg_recv;
597     double latency_total;
598     double latency_squared;
600     double latency_average;
601     double latency_stddev;
603     double droprate;
605     /* Locking here works, because the structure of the linked list is only
606      * changed during configure and shutdown. */
607     pthread_mutex_lock (&ping_lock);
609     pkg_sent = hl->pkg_sent;
610     pkg_recv = hl->pkg_recv;
611     latency_total = hl->latency_total;
612     latency_squared = hl->latency_squared;
614     hl->pkg_sent = 0;
615     hl->pkg_recv = 0;
616     hl->latency_total = 0.0;
617     hl->latency_squared = 0.0;
619     pthread_mutex_unlock (&ping_lock);
621     /* This e. g. happens when starting up. */
622     if (pkg_sent == 0)
623     {
624       DEBUG ("ping plugin: No packages for host %s have been sent.",
625           hl->host);
626       continue;
627     }
629     /* Calculate average. Beware of division by zero. */
630     if (pkg_recv == 0)
631       latency_average = NAN;
632     else
633       latency_average = latency_total / ((double) pkg_recv);
635     /* Calculate standard deviation. Beware even more of division by zero. */
636     if (pkg_recv == 0)
637       latency_stddev = NAN;
638     else if (pkg_recv == 1)
639       latency_stddev = 0.0;
640     else
641       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
642           - (latency_total * latency_total))
643           / ((double) (pkg_recv * (pkg_recv - 1))));
645     /* Calculate drop rate. */
646     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
648     submit (hl->host, "ping", latency_average);
649     submit (hl->host, "ping_stddev", latency_stddev);
650     submit (hl->host, "ping_droprate", droprate);
651   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
653   return (0);
654 } /* }}} int ping_read */
656 static int ping_shutdown (void) /* {{{ */
658   hostlist_t *hl;
660   INFO ("ping plugin: Shutting down thread.");
661   if (stop_thread () < 0)
662     return (-1);
664   hl = hostlist_head;
665   while (hl != NULL)
666   {
667     hostlist_t *hl_next;
669     hl_next = hl->next;
671     sfree (hl->host);
672     sfree (hl);
674     hl = hl_next;
675   }
677   return (0);
678 } /* }}} int ping_shutdown */
680 void module_register (void)
682   plugin_register_config ("ping", ping_config,
683       config_keys, config_keys_num);
684   plugin_register_init ("ping", ping_init);
685   plugin_register_read ("ping", ping_read);
686   plugin_register_shutdown ("ping", ping_shutdown);
687 } /* void module_register */
689 /* vim: set sw=2 sts=2 et fdm=marker : */