Merge pull request #3339 from jkohen/patch-1
[collectd.git] / src / ping.c
1 /**
2  * collectd - src/ping.c
3  * Copyright (C) 2005-2012  Florian octo Forster
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Florian octo Forster <octo at collectd.org>
25  **/
26
27 #include "collectd.h"
28 #include "common.h"
29 #include "plugin.h"
30 #include "configfile.h"
31 #include "utils_complain.h"
32
33 #include <pthread.h>
34 #include <netinet/in.h>
35 #if HAVE_NETDB_H
36 # include <netdb.h> /* NI_MAXHOST */
37 #endif
38
39 #include <oping.h>
40
41 #ifndef NI_MAXHOST
42 # define NI_MAXHOST 1025
43 #endif
44
45 #if defined(OPING_VERSION) && (OPING_VERSION >= 1003000)
46 # define HAVE_OPING_1_3
47 #endif
48
49 /*
50  * Private data types
51  */
52 struct hostlist_s
53 {
54   char *host;
55
56   uint32_t pkg_sent;
57   uint32_t pkg_recv;
58   uint32_t pkg_missed;
59
60   double latency_total;
61   double latency_squared;
62
63   struct hostlist_s *next;
64 };
65 typedef struct hostlist_s hostlist_t;
66
67 /*
68  * Private variables
69  */
70 static hostlist_t *hostlist_head = NULL;
71
72 static char  *ping_source = NULL;
73 #ifdef HAVE_OPING_1_3
74 static char  *ping_device = NULL;
75 #endif
76 static char  *ping_data = NULL;
77 static int    ping_ttl = PING_DEF_TTL;
78 static double ping_interval = 1.0;
79 static double ping_timeout = 0.9;
80 static int    ping_max_missed = -1;
81
82 static int             ping_thread_loop = 0;
83 static int             ping_thread_error = 0;
84 static pthread_t       ping_thread_id;
85 static pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
86 static pthread_cond_t  ping_cond = PTHREAD_COND_INITIALIZER;
87
88 static const char *config_keys[] =
89 {
90   "Host",
91   "SourceAddress",
92 #ifdef HAVE_OPING_1_3
93   "Device",
94 #endif
95   "Size",
96   "TTL",
97   "Interval",
98   "Timeout",
99   "MaxMissed"
100 };
101 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
102
103 /*
104  * Private functions
105  */
106 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
107 static void time_normalize (struct timespec *ts) /* {{{ */
108 {
109   while (ts->tv_nsec < 0)
110   {
111     if (ts->tv_sec == 0)
112     {
113       ts->tv_nsec = 0;
114       return;
115     }
116
117     ts->tv_sec  -= 1;
118     ts->tv_nsec += 1000000000;
119   }
120
121   while (ts->tv_nsec >= 1000000000)
122   {
123     ts->tv_sec  += 1;
124     ts->tv_nsec -= 1000000000;
125   }
126 } /* }}} void time_normalize */
127
128 /* Add `ts_int' to `tv_begin' and store the result in `ts_dest'. If the result
129  * is larger than `tv_end', copy `tv_end' to `ts_dest' instead. */
130 static void time_calc (struct timespec *ts_dest, /* {{{ */
131     const struct timespec *ts_int,
132     const struct timeval  *tv_begin,
133     const struct timeval  *tv_end)
134 {
135   ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
136   ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
137   time_normalize (ts_dest);
138
139   /* Assure that `(begin + interval) > end'.
140    * This may seem overly complicated, but `tv_sec' is of type `time_t'
141    * which may be `unsigned. *sigh* */
142   if ((tv_end->tv_sec > ts_dest->tv_sec)
143       || ((tv_end->tv_sec == ts_dest->tv_sec)
144         && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
145   {
146     ts_dest->tv_sec = tv_end->tv_sec;
147     ts_dest->tv_nsec = 1000 * tv_end->tv_usec;
148   }
149
150   time_normalize (ts_dest);
151 } /* }}} void time_calc */
152
153 static int ping_dispatch_all (pingobj_t *pingobj) /* {{{ */
154 {
155   pingobj_iter_t *iter;
156   hostlist_t *hl;
157   int status;
158
159   for (iter = ping_iterator_get (pingobj);
160       iter != NULL;
161       iter = ping_iterator_next (iter))
162   { /* {{{ */
163     char userhost[NI_MAXHOST];
164     double latency;
165     size_t param_size;
166
167     param_size = sizeof (userhost);
168     status = ping_iterator_get_info (iter,
169 #ifdef PING_INFO_USERNAME
170         PING_INFO_USERNAME,
171 #else
172         PING_INFO_HOSTNAME,
173 #endif
174         userhost, &param_size);
175     if (status != 0)
176     {
177       WARNING ("ping plugin: ping_iterator_get_info failed: %s",
178           ping_get_error (pingobj));
179       continue;
180     }
181
182     for (hl = hostlist_head; hl != NULL; hl = hl->next)
183       if (strcmp (userhost, hl->host) == 0)
184         break;
185
186     if (hl == NULL)
187     {
188       WARNING ("ping plugin: Cannot find host %s.", userhost);
189       continue;
190     }
191
192     param_size = sizeof (latency);
193     status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
194         (void *) &latency, &param_size);
195     if (status != 0)
196     {
197       WARNING ("ping plugin: ping_iterator_get_info failed: %s",
198           ping_get_error (pingobj));
199       continue;
200     }
201
202     hl->pkg_sent++;
203     if (latency >= 0.0)
204     {
205       hl->pkg_recv++;
206       hl->latency_total += latency;
207       hl->latency_squared += (latency * latency);
208
209       /* reset missed packages counter */
210       hl->pkg_missed = 0;
211     } else
212       hl->pkg_missed++;
213
214     /* if the host did not answer our last N packages, trigger a resolv. */
215     if ((ping_max_missed >= 0)
216         && (hl->pkg_missed >= ((uint32_t) ping_max_missed)))
217     { /* {{{ */
218       /* we reset the missed package counter here, since we only want to
219        * trigger a resolv every N packages and not every package _AFTER_ N
220        * missed packages */
221       hl->pkg_missed = 0;
222
223       WARNING ("ping plugin: host %s has not answered %d PING requests,"
224           " triggering resolve", hl->host, ping_max_missed);
225
226       /* we trigger the resolv simply be removeing and adding the host to our
227        * ping object */
228       status = ping_host_remove (pingobj, hl->host);
229       if (status != 0)
230       {
231         WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
232       }
233       else
234       {
235         status = ping_host_add (pingobj, hl->host);
236         if (status != 0)
237           ERROR ("ping plugin: ping_host_add (%s) failed.", hl->host);
238       }
239     } /* }}} ping_max_missed */
240   } /* }}} for (iter) */
241
242   return (0);
243 } /* }}} int ping_dispatch_all */
244
245 static void *ping_thread (void *arg) /* {{{ */
246 {
247   static pingobj_t *pingobj = NULL;
248
249   struct timeval  tv_begin;
250   struct timeval  tv_end;
251   struct timespec ts_wait;
252   struct timespec ts_int;
253
254   hostlist_t *hl;
255   int count;
256
257   c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
258
259   pthread_mutex_lock (&ping_lock);
260
261   pingobj = ping_construct ();
262   if (pingobj == NULL)
263   {
264     ERROR ("ping plugin: ping_construct failed.");
265     ping_thread_error = 1;
266     pthread_mutex_unlock (&ping_lock);
267     return ((void *) -1);
268   }
269
270   if (ping_source != NULL)
271     if (ping_setopt (pingobj, PING_OPT_SOURCE, (void *) ping_source) != 0)
272       ERROR ("ping plugin: Failed to set source address: %s",
273           ping_get_error (pingobj));
274
275 #ifdef HAVE_OPING_1_3
276   if (ping_device != NULL)
277     if (ping_setopt (pingobj, PING_OPT_DEVICE, (void *) ping_device) != 0)
278       ERROR ("ping plugin: Failed to set device: %s",
279           ping_get_error (pingobj));
280 #endif
281
282   ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
283   ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
284
285   if (ping_data != NULL)
286     ping_setopt (pingobj, PING_OPT_DATA, (void *) ping_data);
287
288   /* Add all the hosts to the ping object. */
289   count = 0;
290   for (hl = hostlist_head; hl != NULL; hl = hl->next)
291   {
292     int tmp_status;
293     tmp_status = ping_host_add (pingobj, hl->host);
294     if (tmp_status != 0)
295       WARNING ("ping plugin: ping_host_add (%s) failed: %s",
296           hl->host, ping_get_error (pingobj));
297     else
298       count++;
299   }
300
301   if (count == 0)
302   {
303     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
304     ping_thread_error = 1;
305     pthread_mutex_unlock (&ping_lock);
306     return ((void *) -1);
307   }
308
309   /* Set up `ts_int' */
310   {
311     double temp_sec;
312     double temp_nsec;
313
314     temp_nsec = modf (ping_interval, &temp_sec);
315     ts_int.tv_sec  = (time_t) temp_sec;
316     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
317   }
318
319   while (ping_thread_loop > 0)
320   {
321     int status;
322     _Bool send_successful = 0;
323
324     if (gettimeofday (&tv_begin, NULL) < 0)
325     {
326       char errbuf[1024];
327       ERROR ("ping plugin: gettimeofday failed: %s",
328           sstrerror (errno, errbuf, sizeof (errbuf)));
329       ping_thread_error = 1;
330       break;
331     }
332
333     pthread_mutex_unlock (&ping_lock);
334
335     status = ping_send (pingobj);
336     if (status < 0)
337     {
338       c_complain (LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
339           ping_get_error (pingobj));
340     }
341     else
342     {
343       c_release (LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
344       send_successful = 1;
345     }
346
347     pthread_mutex_lock (&ping_lock);
348
349     if (ping_thread_loop <= 0)
350       break;
351
352     if (send_successful)
353       (void) ping_dispatch_all (pingobj);
354
355     if (gettimeofday (&tv_end, NULL) < 0)
356     {
357       char errbuf[1024];
358       ERROR ("ping plugin: gettimeofday failed: %s",
359           sstrerror (errno, errbuf, sizeof (errbuf)));
360       ping_thread_error = 1;
361       break;
362     }
363
364     /* Calculate the absolute time until which to wait and store it in
365      * `ts_wait'. */
366     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
367
368     pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
369     if (ping_thread_loop <= 0)
370       break;
371   } /* while (ping_thread_loop > 0) */
372
373   pthread_mutex_unlock (&ping_lock);
374   ping_destroy (pingobj);
375
376   return ((void *) 0);
377 } /* }}} void *ping_thread */
378
379 static int start_thread (void) /* {{{ */
380 {
381   int status;
382
383   pthread_mutex_lock (&ping_lock);
384
385   if (ping_thread_loop != 0)
386   {
387     pthread_mutex_unlock (&ping_lock);
388     return (-1);
389   }
390
391   ping_thread_loop = 1;
392   ping_thread_error = 0;
393   status = plugin_thread_create (&ping_thread_id, /* attr = */ NULL,
394       ping_thread, /* arg = */ (void *) 0);
395   if (status != 0)
396   {
397     ping_thread_loop = 0;
398     ERROR ("ping plugin: Starting thread failed.");
399     pthread_mutex_unlock (&ping_lock);
400     return (-1);
401   }
402     
403   pthread_mutex_unlock (&ping_lock);
404   return (0);
405 } /* }}} int start_thread */
406
407 static int stop_thread (void) /* {{{ */
408 {
409   int status;
410
411   pthread_mutex_lock (&ping_lock);
412
413   if (ping_thread_loop == 0)
414   {
415     pthread_mutex_unlock (&ping_lock);
416     return (-1);
417   }
418
419   ping_thread_loop = 0;
420   pthread_cond_broadcast (&ping_cond);
421   pthread_mutex_unlock (&ping_lock);
422
423   status = pthread_join (ping_thread_id, /* return = */ NULL);
424   if (status != 0)
425   {
426     ERROR ("ping plugin: Stopping thread failed.");
427     status = -1;
428   }
429
430   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
431   ping_thread_error = 0;
432
433   return (status);
434 } /* }}} int stop_thread */
435
436 static int ping_init (void) /* {{{ */
437 {
438   if (hostlist_head == NULL)
439   {
440     NOTICE ("ping plugin: No hosts have been configured.");
441     return (-1);
442   }
443
444   if (ping_timeout > ping_interval)
445   {
446     ping_timeout = 0.9 * ping_interval;
447     WARNING ("ping plugin: Timeout is greater than interval. "
448         "Will use a timeout of %gs.", ping_timeout);
449   }
450
451   if (start_thread () != 0)
452     return (-1);
453
454   return (0);
455 } /* }}} int ping_init */
456
457 static int config_set_string (const char *name, /* {{{ */
458     char **var, const char *value)
459 {
460   char *tmp;
461
462   tmp = strdup (value);
463   if (tmp == NULL)
464   {
465     char errbuf[1024];
466     ERROR ("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s",
467         name, value, sstrerror (errno, errbuf, sizeof (errbuf)));
468     return (1);
469   }
470
471   if (*var != NULL)
472     free (*var);
473   *var = tmp;
474   return (0);
475 } /* }}} int config_set_string */
476
477 static int ping_config (const char *key, const char *value) /* {{{ */
478 {
479   if (strcasecmp (key, "Host") == 0)
480   {
481     hostlist_t *hl;
482     char *host;
483
484     hl = (hostlist_t *) malloc (sizeof (hostlist_t));
485     if (hl == NULL)
486     {
487       char errbuf[1024];
488       ERROR ("ping plugin: malloc failed: %s",
489           sstrerror (errno, errbuf, sizeof (errbuf)));
490       return (1);
491     }
492
493     host = strdup (value);
494     if (host == NULL)
495     {
496       char errbuf[1024];
497       sfree (hl);
498       ERROR ("ping plugin: strdup failed: %s",
499           sstrerror (errno, errbuf, sizeof (errbuf)));
500       return (1);
501     }
502
503     hl->host = host;
504     hl->pkg_sent = 0;
505     hl->pkg_recv = 0;
506     hl->pkg_missed = 0;
507     hl->latency_total = 0.0;
508     hl->latency_squared = 0.0;
509     hl->next = hostlist_head;
510     hostlist_head = hl;
511   }
512   else if (strcasecmp (key, "SourceAddress") == 0)
513   {
514     int status = config_set_string (key, &ping_source, value);
515     if (status != 0)
516       return (status);
517   }
518 #ifdef HAVE_OPING_1_3
519   else if (strcasecmp (key, "Device") == 0)
520   {
521     int status = config_set_string (key, &ping_device, value);
522     if (status != 0)
523       return (status);
524   }
525 #endif
526   else if (strcasecmp (key, "TTL") == 0)
527   {
528     int ttl = atoi (value);
529     if ((ttl > 0) && (ttl <= 255))
530       ping_ttl = ttl;
531     else
532       WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
533   }
534   else if (strcasecmp (key, "Interval") == 0)
535   {
536     double tmp;
537
538     tmp = atof (value);
539     if (tmp > 0.0)
540       ping_interval = tmp;
541     else
542       WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
543           tmp, value);
544   }
545   else if (strcasecmp (key, "Size") == 0) {
546     size_t size = (size_t) atoi (value);
547
548     /* Max IP packet size - (IPv6 + ICMP) = 65535 - (40 + 8) = 65487 */
549     if (size <= 65487)
550     {
551       size_t i;
552
553       sfree (ping_data);
554       ping_data = malloc (size + 1);
555       if (ping_data == NULL)
556       {
557         ERROR ("ping plugin: malloc failed.");
558         return (1);
559       }
560
561       /* Note: By default oping is using constant string
562        * "liboping -- ICMP ping library <http://octo.it/liboping/>"
563        * which is exactly 56 bytes.
564        *
565        * Optimally we would follow the ping(1) behaviour, but we
566        * cannot use byte 00 or start data payload at exactly same
567        * location, due to oping library limitations. */
568       for (i = 0; i < size; i++) /* {{{ */
569       {
570         /* This restricts data pattern to be only composed of easily
571          * printable characters, and not NUL character. */
572         ping_data[i] = ('0' + i % 64);
573       }  /* }}} for (i = 0; i < size; i++) */
574       ping_data[size] = 0;
575     } else
576       WARNING ("ping plugin: Ignoring invalid Size %zu.", size);
577   }
578   else if (strcasecmp (key, "Timeout") == 0)
579   {
580     double tmp;
581
582     tmp = atof (value);
583     if (tmp > 0.0)
584       ping_timeout = tmp;
585     else
586       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
587           tmp, value);
588   }
589   else if (strcasecmp (key, "MaxMissed") == 0)
590   {
591     ping_max_missed = atoi (value);
592     if (ping_max_missed < 0)
593       INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
594   }
595   else
596   {
597     return (-1);
598   }
599
600   return (0);
601 } /* }}} int ping_config */
602
603 static void submit (const char *host, const char *type, /* {{{ */
604     gauge_t value)
605 {
606   value_t values[1];
607   value_list_t vl = VALUE_LIST_INIT;
608
609   values[0].gauge = value;
610
611   vl.values = values;
612   vl.values_len = 1;
613   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
614   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
615   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
616   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
617   sstrncpy (vl.type, type, sizeof (vl.type));
618
619   plugin_dispatch_values (&vl);
620 } /* }}} void ping_submit */
621
622 static int ping_read (void) /* {{{ */
623 {
624   hostlist_t *hl;
625
626   if (ping_thread_error != 0)
627   {
628     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
629
630     stop_thread ();
631
632     for (hl = hostlist_head; hl != NULL; hl = hl->next)
633     {
634       hl->pkg_sent = 0;
635       hl->pkg_recv = 0;
636       hl->latency_total = 0.0;
637       hl->latency_squared = 0.0;
638     }
639
640     start_thread ();
641
642     return (-1);
643   } /* if (ping_thread_error != 0) */
644
645   for (hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
646   {
647     uint32_t pkg_sent;
648     uint32_t pkg_recv;
649     double latency_total;
650     double latency_squared;
651
652     double latency_average;
653     double latency_stddev;
654
655     double droprate;
656
657     /* Locking here works, because the structure of the linked list is only
658      * changed during configure and shutdown. */
659     pthread_mutex_lock (&ping_lock);
660
661     pkg_sent = hl->pkg_sent;
662     pkg_recv = hl->pkg_recv;
663     latency_total = hl->latency_total;
664     latency_squared = hl->latency_squared;
665
666     hl->pkg_sent = 0;
667     hl->pkg_recv = 0;
668     hl->latency_total = 0.0;
669     hl->latency_squared = 0.0;
670
671     pthread_mutex_unlock (&ping_lock);
672
673     /* This e. g. happens when starting up. */
674     if (pkg_sent == 0)
675     {
676       DEBUG ("ping plugin: No packages for host %s have been sent.",
677           hl->host);
678       continue;
679     }
680
681     /* Calculate average. Beware of division by zero. */
682     if (pkg_recv == 0)
683       latency_average = NAN;
684     else
685       latency_average = latency_total / ((double) pkg_recv);
686
687     /* Calculate standard deviation. Beware even more of division by zero. */
688     if (pkg_recv == 0)
689       latency_stddev = NAN;
690     else if (pkg_recv == 1)
691       latency_stddev = 0.0;
692     else
693       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
694           - (latency_total * latency_total))
695           / ((double) (pkg_recv * (pkg_recv - 1))));
696
697     /* Calculate drop rate. */
698     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
699
700     submit (hl->host, "ping", latency_average);
701     submit (hl->host, "ping_stddev", latency_stddev);
702     submit (hl->host, "ping_droprate", droprate);
703   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
704
705   return (0);
706 } /* }}} int ping_read */
707
708 static int ping_shutdown (void) /* {{{ */
709 {
710   hostlist_t *hl;
711
712   INFO ("ping plugin: Shutting down thread.");
713   if (stop_thread () < 0)
714     return (-1);
715
716   hl = hostlist_head;
717   while (hl != NULL)
718   {
719     hostlist_t *hl_next;
720
721     hl_next = hl->next;
722
723     sfree (hl->host);
724     sfree (hl);
725
726     hl = hl_next;
727   }
728
729   if (ping_data != NULL) {
730     free (ping_data);
731     ping_data = NULL;
732   }
733
734   return (0);
735 } /* }}} int ping_shutdown */
736
737 void module_register (void)
738 {
739   plugin_register_config ("ping", ping_config,
740       config_keys, config_keys_num);
741   plugin_register_init ("ping", ping_init);
742   plugin_register_read ("ping", ping_read);
743   plugin_register_shutdown ("ping", ping_shutdown);
744 } /* void module_register */
745
746 /* vim: set sw=2 sts=2 et fdm=marker : */