ping plugin: Improved some error messages.
[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: %s",
164           hl->host, ping_get_error (pingobj));
165     else
166       status++;
167   }
168
169   if (status == 0)
170   {
171     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
172     ping_thread_error = 1;
173     pthread_mutex_unlock (&ping_lock);
174     return ((void *) -1);
175   }
176
177   /* Set up `ts_int' */
178   {
179     double temp_sec;
180     double temp_nsec;
181
182     temp_nsec = modf (ping_interval, &temp_sec);
183     ts_int.tv_sec  = (time_t) temp_sec;
184     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
185   }
186
187   while (ping_thread_loop > 0)
188   {
189     pingobj_iter_t *iter;
190     int status;
191
192     if (gettimeofday (&tv_begin, NULL) < 0)
193     {
194       char errbuf[1024];
195       ERROR ("ping plugin: gettimeofday failed: %s",
196           sstrerror (errno, errbuf, sizeof (errbuf)));
197       ping_thread_error = 1;
198       break;
199     }
200
201     pthread_mutex_unlock (&ping_lock);
202
203     status = ping_send (pingobj);
204     if (status < 0)
205     {
206       ERROR ("ping plugin: ping_send failed: %s", ping_get_error (pingobj));
207       pthread_mutex_lock (&ping_lock);
208       ping_thread_error = 1;
209       break;
210     }
211
212     pthread_mutex_lock (&ping_lock);
213
214     if (ping_thread_loop <= 0)
215       break;
216
217     for (iter = ping_iterator_get (pingobj);
218         iter != NULL;
219         iter = ping_iterator_next (iter))
220     { /* {{{ */
221       char userhost[NI_MAXHOST];
222       double latency;
223       size_t param_size;
224
225       param_size = sizeof (userhost);
226       status = ping_iterator_get_info (iter,
227 #ifdef PING_INFO_USERNAME
228           PING_INFO_USERNAME,
229 #else
230           PING_INFO_HOSTNAME,
231 #endif
232           userhost, &param_size);
233       if (status != 0)
234       {
235         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
236             ping_get_error (pingobj));
237         continue;
238       }
239
240       for (hl = hostlist_head; hl != NULL; hl = hl->next)
241         if (strcmp (userhost, hl->host) == 0)
242           break;
243
244       if (hl == NULL)
245       {
246         WARNING ("ping plugin: Cannot find host %s.", userhost);
247         continue;
248       }
249
250       param_size = sizeof (latency);
251       status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
252           (void *) &latency, &param_size);
253       if (status != 0)
254       {
255         WARNING ("ping plugin: ping_iterator_get_info failed: %s",
256             ping_get_error (pingobj));
257         continue;
258       }
259
260       hl->pkg_sent++;
261       if (latency >= 0.0)
262       {
263         hl->pkg_recv++;
264         hl->latency_total += latency;
265         hl->latency_squared += (latency * latency);
266       }
267     } /* }}} for (iter) */
268
269     if (gettimeofday (&tv_end, NULL) < 0)
270     {
271       char errbuf[1024];
272       ERROR ("ping plugin: gettimeofday failed: %s",
273           sstrerror (errno, errbuf, sizeof (errbuf)));
274       ping_thread_error = 1;
275       break;
276     }
277
278     /* Calculate the absolute time until which to wait and store it in
279      * `ts_wait'. */
280     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
281
282     status = pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
283     if (ping_thread_loop <= 0)
284       break;
285   } /* while (ping_thread_loop > 0) */
286
287   pthread_mutex_unlock (&ping_lock);
288   ping_destroy (pingobj);
289
290   return ((void *) 0);
291 } /* }}} void *ping_thread */
292
293 static int start_thread (void) /* {{{ */
294 {
295   int status;
296
297   pthread_mutex_lock (&ping_lock);
298
299   if (ping_thread_loop != 0)
300   {
301     pthread_mutex_unlock (&ping_lock);
302     return (-1);
303   }
304
305   ping_thread_loop = 1;
306   ping_thread_error = 0;
307   status = pthread_create (&ping_thread_id, /* attr = */ NULL,
308       ping_thread, /* arg = */ (void *) 0);
309   if (status != 0)
310   {
311     ping_thread_loop = 0;
312     ERROR ("ping plugin: Starting thread failed.");
313     pthread_mutex_unlock (&ping_lock);
314     return (-1);
315   }
316     
317   pthread_mutex_unlock (&ping_lock);
318   return (0);
319 } /* }}} int start_thread */
320
321 static int stop_thread (void) /* {{{ */
322 {
323   int status;
324
325   pthread_mutex_lock (&ping_lock);
326
327   if (ping_thread_loop == 0)
328   {
329     pthread_mutex_unlock (&ping_lock);
330     return (-1);
331   }
332
333   ping_thread_loop = 0;
334   pthread_cond_broadcast (&ping_cond);
335   pthread_mutex_unlock (&ping_lock);
336
337   status = pthread_join (ping_thread_id, /* return = */ NULL);
338   if (status != 0)
339   {
340     ERROR ("ping plugin: Stopping thread failed.");
341     status = -1;
342   }
343
344   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
345   ping_thread_error = 0;
346
347   return (status);
348 } /* }}} int stop_thread */
349
350 static int ping_init (void) /* {{{ */
351 {
352   if (hostlist_head == NULL)
353   {
354     NOTICE ("ping plugin: No hosts have been configured.");
355     return (-1);
356   }
357
358   if (ping_timeout > ping_interval)
359   {
360     ping_timeout = 0.9 * ping_interval;
361     WARNING ("ping plugin: Timeout is greater than interval. "
362         "Will use a timeout of %gs.", ping_timeout);
363   }
364
365   if (start_thread () != 0)
366     return (-1);
367
368   return (0);
369 } /* }}} int ping_init */
370
371 static int ping_config (const char *key, const char *value) /* {{{ */
372 {
373   if (strcasecmp (key, "Host") == 0)
374   {
375     hostlist_t *hl;
376     char *host;
377
378     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
379     if (hl == NULL)
380     {
381       char errbuf[1024];
382       ERROR ("ping plugin: malloc failed: %s",
383           sstrerror (errno, errbuf, sizeof (errbuf)));
384       return (1);
385     }
386
387     host = strdup (value);
388     if (host == NULL)
389     {
390       char errbuf[1024];
391       sfree (hl);
392       ERROR ("ping plugin: strdup failed: %s",
393           sstrerror (errno, errbuf, sizeof (errbuf)));
394       return (1);
395     }
396
397     hl->host = host;
398     hl->pkg_sent = 0;
399     hl->pkg_recv = 0;
400     hl->latency_total = 0.0;
401     hl->latency_squared = 0.0;
402     hl->next = hostlist_head;
403     hostlist_head = hl;
404   }
405   else if (strcasecmp (key, "TTL") == 0)
406   {
407     int ttl = atoi (value);
408     if ((ttl > 0) && (ttl <= 255))
409       ping_ttl = ttl;
410     else
411       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
412   }
413   else if (strcasecmp (key, "Interval") == 0)
414   {
415     double tmp;
416
417     tmp = atof (value);
418     if (tmp > 0.0)
419       ping_interval = tmp;
420     else
421       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
422           tmp, value);
423   }
424   else if (strcasecmp (key, "Timeout") == 0)
425   {
426     double tmp;
427
428     tmp = atof (value);
429     if (tmp > 0.0)
430       ping_timeout = tmp;
431     else
432       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
433           tmp, value);
434   }
435   else
436   {
437     return (-1);
438   }
439
440   return (0);
441 } /* }}} int ping_config */
442
443 static void submit (const char *host, const char *type, /* {{{ */
444     gauge_t value)
445 {
446   value_t values[1];
447   value_list_t vl = VALUE_LIST_INIT;
448
449   values[0].gauge = value;
450
451   vl.values = values;
452   vl.values_len = 1;
453   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
454   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
455   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
456   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
457   sstrncpy (vl.type, type, sizeof (vl.type));
458
459   plugin_dispatch_values (&vl);
460 } /* }}} void ping_submit */
461
462 static int ping_read (void) /* {{{ */
463 {
464   hostlist_t *hl;
465
466   if (ping_thread_error != 0)
467   {
468     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
469
470     stop_thread ();
471
472     for (hl = hostlist_head; hl != NULL; hl = hl->next)
473     {
474       hl->pkg_sent = 0;
475       hl->pkg_recv = 0;
476       hl->latency_total = 0.0;
477       hl->latency_squared = 0.0;
478     }
479
480     start_thread ();
481
482     return (-1);
483   } /* if (ping_thread_error != 0) */
484
485   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
486   {
487     uint32_t pkg_sent;
488     uint32_t pkg_recv;
489     double latency_total;
490     double latency_squared;
491
492     double latency_average;
493     double latency_stddev;
494
495     double droprate;
496
497     /* Locking here works, because the structure of the linked list is only
498      * changed during configure and shutdown. */
499     pthread_mutex_lock (&ping_lock);
500
501     pkg_sent = hl->pkg_sent;
502     pkg_recv = hl->pkg_recv;
503     latency_total = hl->latency_total;
504     latency_squared = hl->latency_squared;
505
506     hl->pkg_sent = 0;
507     hl->pkg_recv = 0;
508     hl->latency_total = 0.0;
509     hl->latency_squared = 0.0;
510
511     pthread_mutex_unlock (&ping_lock);
512
513     /* This e. g. happens when starting up. */
514     if (pkg_sent == 0)
515     {
516       DEBUG ("ping plugin: No packages for host %s have been sent.",
517           hl->host);
518       continue;
519     }
520
521     /* Calculate average. Beware of division by zero. */
522     if (pkg_recv == 0)
523       latency_average = NAN;
524     else
525       latency_average = latency_total / ((double) pkg_recv);
526
527     /* Calculate standard deviation. Beware even more of division by zero. */
528     if (pkg_recv == 0)
529       latency_stddev = NAN;
530     else if (pkg_recv == 1)
531       latency_stddev = 0.0;
532     else
533       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
534           - (latency_total * latency_total))
535           / ((double) (pkg_recv * (pkg_recv - 1))));
536
537     /* Calculate drop rate. */
538     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
539
540     submit (hl->host, "ping", latency_average);
541     submit (hl->host, "ping_stddev", latency_stddev);
542     submit (hl->host, "ping_droprate", droprate);
543   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
544
545   return (0);
546 } /* }}} int ping_read */
547
548 static int ping_shutdown (void) /* {{{ */
549 {
550   hostlist_t *hl;
551
552   INFO ("ping plugin: Shutting down thread.");
553   if (stop_thread () < 0)
554     return (-1);
555
556   hl = hostlist_head;
557   while (hl != NULL)
558   {
559     hostlist_t *hl_next;
560
561     hl_next = hl->next;
562
563     sfree (hl->host);
564     sfree (hl);
565
566     hl = hl_next;
567   }
568
569   return (0);
570 } /* }}} int ping_shutdown */
571
572 void module_register (void)
573 {
574   plugin_register_config ("ping", ping_config,
575       config_keys, config_keys_num);
576   plugin_register_init ("ping", ping_init);
577   plugin_register_read ("ping", ping_read);
578   plugin_register_shutdown ("ping", ping_shutdown);
579 } /* void module_register */
580
581 /* vim: set sw=2 sts=2 et fdm=marker : */