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