move more stats into innodb namespace
[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
29 #include "common.h"
30 #include "plugin.h"
31 #include "configfile.h"
32 #include "utils_complain.h"
33
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   hostlist_t *hl;
156   int status;
157
158   for (pingobj_iter_t *iter = ping_iterator_get (pingobj);
159       iter != NULL;
160       iter = ping_iterator_next (iter))
161   { /* {{{ */
162     char userhost[NI_MAXHOST];
163     double latency;
164     size_t param_size;
165
166     param_size = sizeof (userhost);
167     status = ping_iterator_get_info (iter,
168 #ifdef PING_INFO_USERNAME
169         PING_INFO_USERNAME,
170 #else
171         PING_INFO_HOSTNAME,
172 #endif
173         userhost, &param_size);
174     if (status != 0)
175     {
176       WARNING ("ping plugin: ping_iterator_get_info failed: %s",
177           ping_get_error (pingobj));
178       continue;
179     }
180
181     for (hl = hostlist_head; hl != NULL; hl = hl->next)
182       if (strcmp (userhost, hl->host) == 0)
183         break;
184
185     if (hl == NULL)
186     {
187       WARNING ("ping plugin: Cannot find host %s.", userhost);
188       continue;
189     }
190
191     param_size = sizeof (latency);
192     status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
193         (void *) &latency, &param_size);
194     if (status != 0)
195     {
196       WARNING ("ping plugin: ping_iterator_get_info failed: %s",
197           ping_get_error (pingobj));
198       continue;
199     }
200
201     hl->pkg_sent++;
202     if (latency >= 0.0)
203     {
204       hl->pkg_recv++;
205       hl->latency_total += latency;
206       hl->latency_squared += (latency * latency);
207
208       /* reset missed packages counter */
209       hl->pkg_missed = 0;
210     } else
211       hl->pkg_missed++;
212
213     /* if the host did not answer our last N packages, trigger a resolv. */
214     if ((ping_max_missed >= 0)
215         && (hl->pkg_missed >= ((uint32_t) ping_max_missed)))
216     { /* {{{ */
217       /* we reset the missed package counter here, since we only want to
218        * trigger a resolv every N packages and not every package _AFTER_ N
219        * missed packages */
220       hl->pkg_missed = 0;
221
222       WARNING ("ping plugin: host %s has not answered %d PING requests,"
223           " triggering resolve", hl->host, ping_max_missed);
224
225       /* we trigger the resolv simply be removeing and adding the host to our
226        * ping object */
227       status = ping_host_remove (pingobj, hl->host);
228       if (status != 0)
229       {
230         WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
231       }
232       else
233       {
234         status = ping_host_add (pingobj, hl->host);
235         if (status != 0)
236           ERROR ("ping plugin: ping_host_add (%s) failed.", hl->host);
237       }
238     } /* }}} ping_max_missed */
239   } /* }}} for (iter) */
240
241   return (0);
242 } /* }}} int ping_dispatch_all */
243
244 static void *ping_thread (void *arg) /* {{{ */
245 {
246   pingobj_t *pingobj = NULL;
247
248   struct timeval  tv_begin;
249   struct timeval  tv_end;
250   struct timespec ts_wait;
251   struct timespec ts_int;
252
253   int count;
254
255   c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
256
257   pthread_mutex_lock (&ping_lock);
258
259   pingobj = ping_construct ();
260   if (pingobj == NULL)
261   {
262     ERROR ("ping plugin: ping_construct failed.");
263     ping_thread_error = 1;
264     pthread_mutex_unlock (&ping_lock);
265     return ((void *) -1);
266   }
267
268   if (ping_source != NULL)
269     if (ping_setopt (pingobj, PING_OPT_SOURCE, (void *) ping_source) != 0)
270       ERROR ("ping plugin: Failed to set source address: %s",
271           ping_get_error (pingobj));
272
273 #ifdef HAVE_OPING_1_3
274   if (ping_device != NULL)
275     if (ping_setopt (pingobj, PING_OPT_DEVICE, (void *) ping_device) != 0)
276       ERROR ("ping plugin: Failed to set device: %s",
277           ping_get_error (pingobj));
278 #endif
279
280   ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
281   ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
282
283   if (ping_data != NULL)
284     ping_setopt (pingobj, PING_OPT_DATA, (void *) ping_data);
285
286   /* Add all the hosts to the ping object. */
287   count = 0;
288   for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next)
289   {
290     int tmp_status;
291     tmp_status = ping_host_add (pingobj, hl->host);
292     if (tmp_status != 0)
293       WARNING ("ping plugin: ping_host_add (%s) failed: %s",
294           hl->host, ping_get_error (pingobj));
295     else
296       count++;
297   }
298
299   if (count == 0)
300   {
301     ERROR ("ping plugin: No host could be added to ping object. Giving up.");
302     ping_thread_error = 1;
303     pthread_mutex_unlock (&ping_lock);
304     return ((void *) -1);
305   }
306
307   /* Set up `ts_int' */
308   {
309     double temp_sec;
310     double temp_nsec;
311
312     temp_nsec = modf (ping_interval, &temp_sec);
313     ts_int.tv_sec  = (time_t) temp_sec;
314     ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
315   }
316
317   while (ping_thread_loop > 0)
318   {
319     int status;
320     _Bool send_successful = 0;
321
322     if (gettimeofday (&tv_begin, NULL) < 0)
323     {
324       char errbuf[1024];
325       ERROR ("ping plugin: gettimeofday failed: %s",
326           sstrerror (errno, errbuf, sizeof (errbuf)));
327       ping_thread_error = 1;
328       break;
329     }
330
331     pthread_mutex_unlock (&ping_lock);
332
333     status = ping_send (pingobj);
334     if (status < 0)
335     {
336       c_complain (LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
337           ping_get_error (pingobj));
338     }
339     else
340     {
341       c_release (LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
342       send_successful = 1;
343     }
344
345     pthread_mutex_lock (&ping_lock);
346
347     if (ping_thread_loop <= 0)
348       break;
349
350     if (send_successful)
351       (void) ping_dispatch_all (pingobj);
352
353     if (gettimeofday (&tv_end, NULL) < 0)
354     {
355       char errbuf[1024];
356       ERROR ("ping plugin: gettimeofday failed: %s",
357           sstrerror (errno, errbuf, sizeof (errbuf)));
358       ping_thread_error = 1;
359       break;
360     }
361
362     /* Calculate the absolute time until which to wait and store it in
363      * `ts_wait'. */
364     time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
365
366     pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
367     if (ping_thread_loop <= 0)
368       break;
369   } /* while (ping_thread_loop > 0) */
370
371   pthread_mutex_unlock (&ping_lock);
372   ping_destroy (pingobj);
373
374   return ((void *) 0);
375 } /* }}} void *ping_thread */
376
377 static int start_thread (void) /* {{{ */
378 {
379   int status;
380
381   pthread_mutex_lock (&ping_lock);
382
383   if (ping_thread_loop != 0)
384   {
385     pthread_mutex_unlock (&ping_lock);
386     return (-1);
387   }
388
389   ping_thread_loop = 1;
390   ping_thread_error = 0;
391   status = plugin_thread_create (&ping_thread_id, /* attr = */ NULL,
392       ping_thread, /* arg = */ (void *) 0);
393   if (status != 0)
394   {
395     ping_thread_loop = 0;
396     ERROR ("ping plugin: Starting thread failed.");
397     pthread_mutex_unlock (&ping_lock);
398     return (-1);
399   }
400
401   pthread_mutex_unlock (&ping_lock);
402   return (0);
403 } /* }}} int start_thread */
404
405 static int stop_thread (void) /* {{{ */
406 {
407   int status;
408
409   pthread_mutex_lock (&ping_lock);
410
411   if (ping_thread_loop == 0)
412   {
413     pthread_mutex_unlock (&ping_lock);
414     return (-1);
415   }
416
417   ping_thread_loop = 0;
418   pthread_cond_broadcast (&ping_cond);
419   pthread_mutex_unlock (&ping_lock);
420
421   status = pthread_join (ping_thread_id, /* return = */ NULL);
422   if (status != 0)
423   {
424     ERROR ("ping plugin: Stopping thread failed.");
425     status = -1;
426   }
427
428   pthread_mutex_lock (&ping_lock);
429   memset (&ping_thread_id, 0, sizeof (ping_thread_id));
430   ping_thread_error = 0;
431   pthread_mutex_unlock (&ping_lock);
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 = malloc (sizeof (*hl));
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       sfree (ping_data);
552       ping_data = malloc (size + 1);
553       if (ping_data == NULL)
554       {
555         ERROR ("ping plugin: malloc failed.");
556         return (1);
557       }
558
559       /* Note: By default oping is using constant string
560        * "liboping -- ICMP ping library <http://octo.it/liboping/>"
561        * which is exactly 56 bytes.
562        *
563        * Optimally we would follow the ping(1) behaviour, but we
564        * cannot use byte 00 or start data payload at exactly same
565        * location, due to oping library limitations. */
566       for (size_t i = 0; i < size; i++) /* {{{ */
567       {
568         /* This restricts data pattern to be only composed of easily
569          * printable characters, and not NUL character. */
570         ping_data[i] = ('0' + i % 64);
571       }  /* }}} for (i = 0; i < size; i++) */
572       ping_data[size] = 0;
573     } else
574       WARNING ("ping plugin: Ignoring invalid Size %zu.", size);
575   }
576   else if (strcasecmp (key, "Timeout") == 0)
577   {
578     double tmp;
579
580     tmp = atof (value);
581     if (tmp > 0.0)
582       ping_timeout = tmp;
583     else
584       WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
585           tmp, value);
586   }
587   else if (strcasecmp (key, "MaxMissed") == 0)
588   {
589     ping_max_missed = atoi (value);
590     if (ping_max_missed < 0)
591       INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
592   }
593   else
594   {
595     return (-1);
596   }
597
598   return (0);
599 } /* }}} int ping_config */
600
601 static void submit (const char *host, const char *type, /* {{{ */
602     gauge_t value)
603 {
604   value_t values[1];
605   value_list_t vl = VALUE_LIST_INIT;
606
607   values[0].gauge = value;
608
609   vl.values = values;
610   vl.values_len = 1;
611   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
612   sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
613   sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
614   sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
615   sstrncpy (vl.type, type, sizeof (vl.type));
616
617   plugin_dispatch_values (&vl);
618 } /* }}} void ping_submit */
619
620 static int ping_read (void) /* {{{ */
621 {
622   if (ping_thread_error != 0)
623   {
624     ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
625
626     stop_thread ();
627
628     for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next)
629     {
630       hl->pkg_sent = 0;
631       hl->pkg_recv = 0;
632       hl->latency_total = 0.0;
633       hl->latency_squared = 0.0;
634     }
635
636     start_thread ();
637
638     return (-1);
639   } /* if (ping_thread_error != 0) */
640
641   for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
642   {
643     uint32_t pkg_sent;
644     uint32_t pkg_recv;
645     double latency_total;
646     double latency_squared;
647
648     double latency_average;
649     double latency_stddev;
650
651     double droprate;
652
653     /* Locking here works, because the structure of the linked list is only
654      * changed during configure and shutdown. */
655     pthread_mutex_lock (&ping_lock);
656
657     pkg_sent = hl->pkg_sent;
658     pkg_recv = hl->pkg_recv;
659     latency_total = hl->latency_total;
660     latency_squared = hl->latency_squared;
661
662     hl->pkg_sent = 0;
663     hl->pkg_recv = 0;
664     hl->latency_total = 0.0;
665     hl->latency_squared = 0.0;
666
667     pthread_mutex_unlock (&ping_lock);
668
669     /* This e. g. happens when starting up. */
670     if (pkg_sent == 0)
671     {
672       DEBUG ("ping plugin: No packages for host %s have been sent.",
673           hl->host);
674       continue;
675     }
676
677     /* Calculate average. Beware of division by zero. */
678     if (pkg_recv == 0)
679       latency_average = NAN;
680     else
681       latency_average = latency_total / ((double) pkg_recv);
682
683     /* Calculate standard deviation. Beware even more of division by zero. */
684     if (pkg_recv == 0)
685       latency_stddev = NAN;
686     else if (pkg_recv == 1)
687       latency_stddev = 0.0;
688     else
689       latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
690           - (latency_total * latency_total))
691           / ((double) (pkg_recv * (pkg_recv - 1))));
692
693     /* Calculate drop rate. */
694     droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
695
696     submit (hl->host, "ping", latency_average);
697     submit (hl->host, "ping_stddev", latency_stddev);
698     submit (hl->host, "ping_droprate", droprate);
699   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
700
701   return (0);
702 } /* }}} int ping_read */
703
704 static int ping_shutdown (void) /* {{{ */
705 {
706   hostlist_t *hl;
707
708   INFO ("ping plugin: Shutting down thread.");
709   if (stop_thread () < 0)
710     return (-1);
711
712   hl = hostlist_head;
713   while (hl != NULL)
714   {
715     hostlist_t *hl_next;
716
717     hl_next = hl->next;
718
719     sfree (hl->host);
720     sfree (hl);
721
722     hl = hl_next;
723   }
724
725   if (ping_data != NULL) {
726     free (ping_data);
727     ping_data = NULL;
728   }
729
730   return (0);
731 } /* }}} int ping_shutdown */
732
733 void module_register (void)
734 {
735   plugin_register_config ("ping", ping_config,
736       config_keys, config_keys_num);
737   plugin_register_init ("ping", ping_init);
738   plugin_register_read ("ping", ping_read);
739   plugin_register_shutdown ("ping", ping_shutdown);
740 } /* void module_register */
741
742 /* vim: set sw=2 sts=2 et fdm=marker : */