Merge branch 'collectd-4.6' into collectd-4.7
[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 /*
40  * Private data types
41  */
42 struct hostlist_s
43 {
44   char *host;
45
46   uint32_t pkg_sent;
47   uint32_t pkg_recv;
48
49   double latency_total;
50   double latency_squared;
51
52   struct hostlist_s *next;
53 };
54 typedef struct hostlist_s hostlist_t;
55
56 /*
57  * Private variables
58  */
59 static hostlist_t *hostlist_head = NULL;
60
61 static int    ping_ttl = PING_DEF_TTL;
62 static double ping_interval = 1.0;
63 static double ping_timeout = 0.9;
64
65 static int             ping_thread_loop = 0;
66 static int             ping_thread_error = 0;
67 static pthread_t       ping_thread_id;
68 static pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
69 static pthread_cond_t  ping_cond = PTHREAD_COND_INITIALIZER;
70
71 static const char *config_keys[] =
72 {
73   "Host",
74   "TTL",
75   "Interval",
76   "Timeout"
77 };
78 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
79
80 /*
81  * Private functions
82  */
83 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
84 static void time_normalize (struct timespec *ts) /* {{{ */
85 {
86   while (ts->tv_nsec < 0)
87   {
88     if (ts->tv_sec == 0)
89     {
90       ts->tv_nsec = 0;
91       return;
92     }
93
94     ts->tv_sec  -= 1;
95     ts->tv_nsec += 1000000000;
96   }
97
98   while (ts->tv_nsec >= 1000000000)
99   {
100     ts->tv_sec  += 1;
101     ts->tv_nsec -= 1000000000;
102   }
103 } /* }}} void time_normalize */
104
105 /* Add `ts_int' to `tv_begin' and store the result in `ts_dest'. If the result
106  * is larger than `tv_end', copy `tv_end' to `ts_dest' instead. */
107 static void time_calc (struct timespec *ts_dest, /* {{{ */
108     const struct timespec *ts_int,
109     const struct timeval  *tv_begin,
110     const struct timeval  *tv_end)
111 {
112   ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
113   ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
114   time_normalize (ts_dest);
115
116   /* Assure that `(begin + interval) > end'.
117    * This may seem overly complicated, but `tv_sec' is of type `time_t'
118    * which may be `unsigned. *sigh* */
119   if ((tv_end->tv_sec > ts_dest->tv_sec)
120       || ((tv_end->tv_sec == ts_dest->tv_sec)
121         && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
122   {
123     ts_dest->tv_sec = tv_end->tv_sec;
124     ts_dest->tv_nsec = 1000 * tv_end->tv_usec;
125   }
126
127   time_normalize (ts_dest);
128 } /* }}} void time_calc */
129
130 static void *ping_thread (void *arg) /* {{{ */
131 {
132   static pingobj_t *pingobj = NULL;
133
134   struct timeval  tv_begin;
135   struct timeval  tv_end;
136   struct timespec ts_wait;
137   struct timespec ts_int;
138
139   hostlist_t *hl;
140   int status;
141
142   pthread_mutex_lock (&ping_lock);
143
144   pingobj = ping_construct ();
145   if (pingobj == NULL)
146   {
147     ERROR ("ping plugin: ping_construct failed.");
148     ping_thread_error = 1;
149     pthread_mutex_unlock (&ping_lock);
150     return ((void *) -1);
151   }
152
153   ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
154   ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
155
156   /* Add all the hosts to the ping object. */
157   status = 0;
158   for (hl = hostlist_head; hl != NULL; hl = hl->next)
159   {
160     int tmp_status;
161     tmp_status = ping_host_add (pingobj, hl->host);
162     if (tmp_status != 0)
163       WARNING ("ping plugin: ping_host_add (%s) failed.", hl->host);
164     else
165       status++;
166   }
167
168   if (status == 0)
169   {
170     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
171     ping_thread_error = 1;
172     pthread_mutex_unlock (&ping_lock);
173     return ((void *) -1);
174   }
175
176   /* Set up `ts_int' */
177   {
178     double temp_sec;
179     double temp_nsec;
180
181     temp_nsec = modf (ping_interval, &temp_sec);
182     ts_int.tv_sec  = (time_t) temp_sec;
183     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
184   }
185
186   while (ping_thread_loop > 0)
187   {
188     pingobj_iter_t *iter;
189     int status;
190
191     if (gettimeofday (&tv_begin, NULL) < 0)
192     {
193       ERROR ("ping plugin: gettimeofday failed");
194       ping_thread_error = 1;
195       break;
196     }
197
198     pthread_mutex_unlock (&ping_lock);
199
200     status = ping_send (pingobj);
201     if (status < 0)
202     {
203       ERROR ("ping plugin: ping_send failed: %s", ping_get_error (pingobj));
204       pthread_mutex_lock (&ping_lock);
205       ping_thread_error = 1;
206       break;
207     }
208
209     pthread_mutex_lock (&ping_lock);
210
211     if (ping_thread_loop <= 0)
212       break;
213
214     for (iter = ping_iterator_get (pingobj);
215         iter != NULL;
216         iter = ping_iterator_next (iter))
217     { /* {{{ */
218       char userhost[NI_MAXHOST];
219       double latency;
220       size_t param_size;
221
222       param_size = sizeof (userhost);
223       status = ping_iterator_get_info (iter,
224 #ifdef PING_INFO_USERNAME
225           PING_INFO_USERNAME,
226 #else
227           PING_INFO_HOSTNAME,
228 #endif
229           userhost, &param_size);
230       if (status != 0)
231       {
232         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
233             ping_get_error (pingobj));
234         continue;
235       }
236
237       for (hl = hostlist_head; hl != NULL; hl = hl->next)
238         if (strcmp (userhost, hl->host) == 0)
239           break;
240
241       if (hl == NULL)
242       {
243         WARNING ("ping plugin: Cannot find host %s.", userhost);
244         continue;
245       }
246
247       param_size = sizeof (latency);
248       status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
249           (void *) &latency, &param_size);
250       if (status != 0)
251       {
252         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
253             ping_get_error (pingobj));
254         continue;
255       }
256
257       hl->pkg_sent++;
258       if (latency >= 0.0)
259       {
260         hl->pkg_recv++;
261         hl->latency_total += latency;
262         hl->latency_squared += (latency * latency);
263       }
264     } /* }}} for (iter) */
265
266     if (gettimeofday (&tv_end, NULL) < 0)
267     {
268       ERROR ("ping plugin: gettimeofday failed");
269       ping_thread_error = 1;
270       break;
271     }
272
273     /* Calculate the absolute time until which to wait and store it in
274      * `ts_wait'. */
275     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
276
277     status = pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
278     if (ping_thread_loop <= 0)
279       break;
280   } /* while (ping_thread_loop > 0) */
281
282   pthread_mutex_unlock (&ping_lock);
283   ping_destroy (pingobj);
284
285   return ((void *) 0);
286 } /* }}} void *ping_thread */
287
288 static int start_thread (void) /* {{{ */
289 {
290   int status;
291
292   pthread_mutex_lock (&ping_lock);
293
294   if (ping_thread_loop != 0)
295   {
296     pthread_mutex_unlock (&ping_lock);
297     return (-1);
298   }
299
300   ping_thread_loop = 1;
301   ping_thread_error = 0;
302   status = pthread_create (&ping_thread_id, /* attr = */ NULL,
303       ping_thread, /* arg = */ (void *) 0);
304   if (status != 0)
305   {
306     ping_thread_loop = 0;
307     ERROR ("ping plugin: Starting thread failed.");
308     pthread_mutex_unlock (&ping_lock);
309     return (-1);
310   }
311     
312   pthread_mutex_unlock (&ping_lock);
313   return (0);
314 } /* }}} int start_thread */
315
316 static int stop_thread (void) /* {{{ */
317 {
318   int status;
319
320   pthread_mutex_lock (&ping_lock);
321
322   if (ping_thread_loop == 0)
323   {
324     pthread_mutex_unlock (&ping_lock);
325     return (-1);
326   }
327
328   ping_thread_loop = 0;
329   pthread_cond_broadcast (&ping_cond);
330   pthread_mutex_unlock (&ping_lock);
331
332   status = pthread_join (ping_thread_id, /* return = */ NULL);
333   if (status != 0)
334   {
335     ERROR ("ping plugin: Stopping thread failed.");
336     status = -1;
337   }
338
339   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
340   ping_thread_error = 0;
341
342   return (status);
343 } /* }}} int stop_thread */
344
345 static int ping_init (void) /* {{{ */
346 {
347   if (hostlist_head == NULL)
348   {
349     NOTICE ("ping plugin: No hosts have been configured.");
350     return (-1);
351   }
352
353   if (ping_timeout > ping_interval)
354   {
355     ping_timeout = 0.9 * ping_interval;
356     WARNING ("ping plugin: Timeout is greater than interval. "
357         "Will use a timeout of %gs.", ping_timeout);
358   }
359
360   if (start_thread () != 0)
361     return (-1);
362
363   return (0);
364 } /* }}} int ping_init */
365
366 static int ping_config (const char *key, const char *value) /* {{{ */
367 {
368   if (strcasecmp (key, "Host") == 0)
369   {
370     hostlist_t *hl;
371     char *host;
372
373     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
374     if (hl == NULL)
375     {
376       char errbuf[1024];
377       ERROR ("ping plugin: malloc failed: %s",
378           sstrerror (errno, errbuf, sizeof (errbuf)));
379       return (1);
380     }
381
382     host = strdup (value);
383     if (host == NULL)
384     {
385       char errbuf[1024];
386       sfree (hl);
387       ERROR ("ping plugin: strdup failed: %s",
388           sstrerror (errno, errbuf, sizeof (errbuf)));
389       return (1);
390     }
391
392     hl->host = host;
393     hl->pkg_sent = 0;
394     hl->pkg_recv = 0;
395     hl->latency_total = 0.0;
396     hl->latency_squared = 0.0;
397     hl->next = hostlist_head;
398     hostlist_head = hl;
399   }
400   else if (strcasecmp (key, "TTL") == 0)
401   {
402     int ttl = atoi (value);
403     if ((ttl > 0) && (ttl <= 255))
404       ping_ttl = ttl;
405     else
406       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
407   }
408   else if (strcasecmp (key, "Interval") == 0)
409   {
410     double tmp;
411
412     tmp = atof (value);
413     if (tmp > 0.0)
414       ping_interval = tmp;
415     else
416       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
417           tmp, value);
418   }
419   else if (strcasecmp (key, "Timeout") == 0)
420   {
421     double tmp;
422
423     tmp = atof (value);
424     if (tmp > 0.0)
425       ping_timeout = tmp;
426     else
427       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
428           tmp, value);
429   }
430   else
431   {
432     return (-1);
433   }
434
435   return (0);
436 } /* }}} int ping_config */
437
438 static void submit (const char *host, const char *type, /* {{{ */
439     gauge_t value)
440 {
441   value_t values[1];
442   value_list_t vl = VALUE_LIST_INIT;
443
444   values[0].gauge = value;
445
446   vl.values = values;
447   vl.values_len = 1;
448   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
449   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
450   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
451   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
452   sstrncpy (vl.type, type, sizeof (vl.type));
453
454   plugin_dispatch_values (&vl);
455 } /* }}} void ping_submit */
456
457 static int ping_read (void) /* {{{ */
458 {
459   hostlist_t *hl;
460
461   if (ping_thread_error != 0)
462   {
463     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
464
465     stop_thread ();
466
467     for (hl = hostlist_head; hl != NULL; hl = hl->next)
468     {
469       hl->pkg_sent = 0;
470       hl->pkg_recv = 0;
471       hl->latency_total = 0.0;
472       hl->latency_squared = 0.0;
473     }
474
475     start_thread ();
476
477     return (-1);
478   } /* if (ping_thread_error != 0) */
479
480   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
481   {
482     uint32_t pkg_sent;
483     uint32_t pkg_recv;
484     double latency_total;
485     double latency_squared;
486
487     double latency_average;
488     double latency_stddev;
489
490     double droprate;
491
492     /* Locking here works, because the structure of the linked list is only
493      * changed during configure and shutdown. */
494     pthread_mutex_lock (&ping_lock);
495
496     pkg_sent = hl->pkg_sent;
497     pkg_recv = hl->pkg_recv;
498     latency_total = hl->latency_total;
499     latency_squared = hl->latency_squared;
500
501     hl->pkg_sent = 0;
502     hl->pkg_recv = 0;
503     hl->latency_total = 0.0;
504     hl->latency_squared = 0.0;
505
506     pthread_mutex_unlock (&ping_lock);
507
508     /* This e. g. happens when starting up. */
509     if (pkg_sent == 0)
510     {
511       DEBUG ("ping plugin: No packages for host %s have been sent.",
512           hl->host);
513       continue;
514     }
515
516     /* Calculate average. Beware of division by zero. */
517     if (pkg_recv == 0)
518       latency_average = NAN;
519     else
520       latency_average = latency_total / ((double) pkg_recv);
521
522     /* Calculate standard deviation. Beware even more of division by zero. */
523     if (pkg_recv == 0)
524       latency_stddev = NAN;
525     else if (pkg_recv == 1)
526       latency_stddev = 0.0;
527     else
528       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
529           - (latency_total * latency_total))
530           / ((double) (pkg_recv * (pkg_recv - 1))));
531
532     /* Calculate drop rate. */
533     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
534
535     submit (hl->host, "ping", latency_average);
536     submit (hl->host, "ping_stddev", latency_stddev);
537     submit (hl->host, "ping_droprate", droprate);
538   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
539
540   return (0);
541 } /* }}} int ping_read */
542
543 static int ping_shutdown (void) /* {{{ */
544 {
545   hostlist_t *hl;
546
547   INFO ("ping plugin: Shutting down thread.");
548   if (stop_thread () < 0)
549     return (-1);
550
551   hl = hostlist_head;
552   while (hl != NULL)
553   {
554     hostlist_t *hl_next;
555
556     hl_next = hl->next;
557
558     sfree (hl->host);
559     sfree (hl);
560
561     hl = hl_next;
562   }
563
564   return (0);
565 } /* }}} int ping_shutdown */
566
567 void module_register (void)
568 {
569   plugin_register_config ("ping", ping_config,
570       config_keys, config_keys_num);
571   plugin_register_init ("ping", ping_init);
572   plugin_register_read ("ping", ping_read);
573   plugin_register_shutdown ("ping", ping_shutdown);
574 } /* void module_register */
575
576 /* vim: set sw=2 sts=2 et fdm=marker : */