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