2 * collectd - src/ping.c
3 * Copyright (C) 2005-2012 Florian octo Forster
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:
12 * The above copyright notice and this permission notice shall be included in
13 * all copies or substantial portions of the Software.
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.
24 * Florian octo Forster <octo at collectd.org>
31 #include "utils_complain.h"
33 #include <netinet/in.h>
35 # include <netdb.h> /* NI_MAXHOST */
38 #ifdef HAVE_SYS_CAPABILITY_H
39 # include <sys/capability.h>
45 # define NI_MAXHOST 1025
48 #if defined(OPING_VERSION) && (OPING_VERSION >= 1003000)
49 # define HAVE_OPING_1_3
64 double latency_squared;
66 struct hostlist_s *next;
68 typedef struct hostlist_s hostlist_t;
73 static hostlist_t *hostlist_head = NULL;
75 static char *ping_source = NULL;
77 static char *ping_device = NULL;
79 static char *ping_data = NULL;
80 static int ping_ttl = PING_DEF_TTL;
81 static double ping_interval = 1.0;
82 static double ping_timeout = 0.9;
83 static int ping_max_missed = -1;
85 static int ping_thread_loop = 0;
86 static int ping_thread_error = 0;
87 static pthread_t ping_thread_id;
88 static pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
89 static pthread_cond_t ping_cond = PTHREAD_COND_INITIALIZER;
91 static const char *config_keys[] =
104 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
109 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
110 static void time_normalize (struct timespec *ts) /* {{{ */
112 while (ts->tv_nsec < 0)
121 ts->tv_nsec += 1000000000;
124 while (ts->tv_nsec >= 1000000000)
127 ts->tv_nsec -= 1000000000;
129 } /* }}} void time_normalize */
131 /* Add `ts_int' to `tv_begin' and store the result in `ts_dest'. If the result
132 * is larger than `tv_end', copy `tv_end' to `ts_dest' instead. */
133 static void time_calc (struct timespec *ts_dest, /* {{{ */
134 const struct timespec *ts_int,
135 const struct timeval *tv_begin,
136 const struct timeval *tv_end)
138 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
139 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
140 time_normalize (ts_dest);
142 /* Assure that `(begin + interval) > end'.
143 * This may seem overly complicated, but `tv_sec' is of type `time_t'
144 * which may be `unsigned. *sigh* */
145 if ((tv_end->tv_sec > ts_dest->tv_sec)
146 || ((tv_end->tv_sec == ts_dest->tv_sec)
147 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
149 ts_dest->tv_sec = tv_end->tv_sec;
150 ts_dest->tv_nsec = 1000 * tv_end->tv_usec;
153 time_normalize (ts_dest);
154 } /* }}} void time_calc */
156 static int ping_dispatch_all (pingobj_t *pingobj) /* {{{ */
161 for (pingobj_iter_t *iter = ping_iterator_get (pingobj);
163 iter = ping_iterator_next (iter))
165 char userhost[NI_MAXHOST];
169 param_size = sizeof (userhost);
170 status = ping_iterator_get_info (iter,
171 #ifdef PING_INFO_USERNAME
176 userhost, ¶m_size);
179 WARNING ("ping plugin: ping_iterator_get_info failed: %s",
180 ping_get_error (pingobj));
184 for (hl = hostlist_head; hl != NULL; hl = hl->next)
185 if (strcmp (userhost, hl->host) == 0)
190 WARNING ("ping plugin: Cannot find host %s.", userhost);
194 param_size = sizeof (latency);
195 status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
196 (void *) &latency, ¶m_size);
199 WARNING ("ping plugin: ping_iterator_get_info failed: %s",
200 ping_get_error (pingobj));
208 hl->latency_total += latency;
209 hl->latency_squared += (latency * latency);
211 /* reset missed packages counter */
216 /* if the host did not answer our last N packages, trigger a resolv. */
217 if ((ping_max_missed >= 0)
218 && (hl->pkg_missed >= ((uint32_t) ping_max_missed)))
220 /* we reset the missed package counter here, since we only want to
221 * trigger a resolv every N packages and not every package _AFTER_ N
225 WARNING ("ping plugin: host %s has not answered %d PING requests,"
226 " triggering resolve", hl->host, ping_max_missed);
228 /* we trigger the resolv simply be removeing and adding the host to our
230 status = ping_host_remove (pingobj, hl->host);
233 WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
237 status = ping_host_add (pingobj, hl->host);
239 ERROR ("ping plugin: ping_host_add (%s) failed.", hl->host);
241 } /* }}} ping_max_missed */
242 } /* }}} for (iter) */
245 } /* }}} int ping_dispatch_all */
247 static void *ping_thread (void *arg) /* {{{ */
249 pingobj_t *pingobj = NULL;
251 struct timeval tv_begin;
252 struct timeval tv_end;
253 struct timespec ts_wait;
254 struct timespec ts_int;
258 c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
260 pthread_mutex_lock (&ping_lock);
262 pingobj = ping_construct ();
265 ERROR ("ping plugin: ping_construct failed.");
266 ping_thread_error = 1;
267 pthread_mutex_unlock (&ping_lock);
268 return ((void *) -1);
271 if (ping_source != NULL)
272 if (ping_setopt (pingobj, PING_OPT_SOURCE, (void *) ping_source) != 0)
273 ERROR ("ping plugin: Failed to set source address: %s",
274 ping_get_error (pingobj));
276 #ifdef HAVE_OPING_1_3
277 if (ping_device != NULL)
278 if (ping_setopt (pingobj, PING_OPT_DEVICE, (void *) ping_device) != 0)
279 ERROR ("ping plugin: Failed to set device: %s",
280 ping_get_error (pingobj));
283 ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
284 ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
286 if (ping_data != NULL)
287 ping_setopt (pingobj, PING_OPT_DATA, (void *) ping_data);
289 /* Add all the hosts to the ping object. */
291 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next)
294 tmp_status = ping_host_add (pingobj, hl->host);
296 WARNING ("ping plugin: ping_host_add (%s) failed: %s",
297 hl->host, ping_get_error (pingobj));
304 ERROR ("ping plugin: No host could be added to ping object. Giving up.");
305 ping_thread_error = 1;
306 pthread_mutex_unlock (&ping_lock);
307 return ((void *) -1);
310 /* Set up `ts_int' */
315 temp_nsec = modf (ping_interval, &temp_sec);
316 ts_int.tv_sec = (time_t) temp_sec;
317 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
320 while (ping_thread_loop > 0)
323 _Bool send_successful = 0;
325 if (gettimeofday (&tv_begin, NULL) < 0)
328 ERROR ("ping plugin: gettimeofday failed: %s",
329 sstrerror (errno, errbuf, sizeof (errbuf)));
330 ping_thread_error = 1;
334 pthread_mutex_unlock (&ping_lock);
336 status = ping_send (pingobj);
339 c_complain (LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
340 ping_get_error (pingobj));
344 c_release (LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
348 pthread_mutex_lock (&ping_lock);
350 if (ping_thread_loop <= 0)
354 (void) ping_dispatch_all (pingobj);
356 if (gettimeofday (&tv_end, NULL) < 0)
359 ERROR ("ping plugin: gettimeofday failed: %s",
360 sstrerror (errno, errbuf, sizeof (errbuf)));
361 ping_thread_error = 1;
365 /* Calculate the absolute time until which to wait and store it in
367 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
369 pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
370 if (ping_thread_loop <= 0)
372 } /* while (ping_thread_loop > 0) */
374 pthread_mutex_unlock (&ping_lock);
375 ping_destroy (pingobj);
378 } /* }}} void *ping_thread */
380 static int start_thread (void) /* {{{ */
384 pthread_mutex_lock (&ping_lock);
386 if (ping_thread_loop != 0)
388 pthread_mutex_unlock (&ping_lock);
392 ping_thread_loop = 1;
393 ping_thread_error = 0;
394 status = plugin_thread_create (&ping_thread_id, /* attr = */ NULL,
395 ping_thread, /* arg = */ (void *) 0);
398 ping_thread_loop = 0;
399 ERROR ("ping plugin: Starting thread failed.");
400 pthread_mutex_unlock (&ping_lock);
404 pthread_mutex_unlock (&ping_lock);
406 } /* }}} int start_thread */
408 static int stop_thread (void) /* {{{ */
412 pthread_mutex_lock (&ping_lock);
414 if (ping_thread_loop == 0)
416 pthread_mutex_unlock (&ping_lock);
420 ping_thread_loop = 0;
421 pthread_cond_broadcast (&ping_cond);
422 pthread_mutex_unlock (&ping_lock);
424 status = pthread_join (ping_thread_id, /* return = */ NULL);
427 ERROR ("ping plugin: Stopping thread failed.");
431 pthread_mutex_lock (&ping_lock);
432 memset (&ping_thread_id, 0, sizeof (ping_thread_id));
433 ping_thread_error = 0;
434 pthread_mutex_unlock (&ping_lock);
437 } /* }}} int stop_thread */
439 static int ping_init (void) /* {{{ */
441 if (hostlist_head == NULL)
443 NOTICE ("ping plugin: No hosts have been configured.");
447 if (ping_timeout > ping_interval)
449 ping_timeout = 0.9 * ping_interval;
450 WARNING ("ping plugin: Timeout is greater than interval. "
451 "Will use a timeout of %gs.", ping_timeout);
454 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_NET_RAW)
455 if (check_capability (CAP_NET_RAW) != 0)
458 WARNING ("ping plugin: Running collectd as root, but the CAP_NET_RAW "
459 "capability is missing. The plugin's read function will probably "
460 "fail. Is your init system dropping capabilities?");
462 WARNING ("ping plugin: collectd doesn't have the CAP_NET_RAW capability. "
463 "If you don't want to run collectd as root, try running \"setcap "
464 "cap_net_raw=ep\" on the collectd binary.");
468 return (start_thread ());
469 } /* }}} int ping_init */
471 static int config_set_string (const char *name, /* {{{ */
472 char **var, const char *value)
476 tmp = strdup (value);
480 ERROR ("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s",
481 name, value, sstrerror (errno, errbuf, sizeof (errbuf)));
489 } /* }}} int config_set_string */
491 static int ping_config (const char *key, const char *value) /* {{{ */
493 if (strcasecmp (key, "Host") == 0)
498 hl = malloc (sizeof (*hl));
502 ERROR ("ping plugin: malloc failed: %s",
503 sstrerror (errno, errbuf, sizeof (errbuf)));
507 host = strdup (value);
512 ERROR ("ping plugin: strdup failed: %s",
513 sstrerror (errno, errbuf, sizeof (errbuf)));
521 hl->latency_total = 0.0;
522 hl->latency_squared = 0.0;
523 hl->next = hostlist_head;
526 else if (strcasecmp (key, "SourceAddress") == 0)
528 int status = config_set_string (key, &ping_source, value);
532 #ifdef HAVE_OPING_1_3
533 else if (strcasecmp (key, "Device") == 0)
535 int status = config_set_string (key, &ping_device, value);
540 else if (strcasecmp (key, "TTL") == 0)
542 int ttl = atoi (value);
543 if ((ttl > 0) && (ttl <= 255))
546 WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
548 else if (strcasecmp (key, "Interval") == 0)
556 WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
559 else if (strcasecmp (key, "Size") == 0) {
560 size_t size = (size_t) atoi (value);
562 /* Max IP packet size - (IPv6 + ICMP) = 65535 - (40 + 8) = 65487 */
566 ping_data = malloc (size + 1);
567 if (ping_data == NULL)
569 ERROR ("ping plugin: malloc failed.");
573 /* Note: By default oping is using constant string
574 * "liboping -- ICMP ping library <http://octo.it/liboping/>"
575 * which is exactly 56 bytes.
577 * Optimally we would follow the ping(1) behaviour, but we
578 * cannot use byte 00 or start data payload at exactly same
579 * location, due to oping library limitations. */
580 for (size_t i = 0; i < size; i++) /* {{{ */
582 /* This restricts data pattern to be only composed of easily
583 * printable characters, and not NUL character. */
584 ping_data[i] = ('0' + i % 64);
585 } /* }}} for (i = 0; i < size; i++) */
588 WARNING ("ping plugin: Ignoring invalid Size %zu.", size);
590 else if (strcasecmp (key, "Timeout") == 0)
598 WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
601 else if (strcasecmp (key, "MaxMissed") == 0)
603 ping_max_missed = atoi (value);
604 if (ping_max_missed < 0)
605 INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
613 } /* }}} int ping_config */
615 static void submit (const char *host, const char *type, /* {{{ */
619 value_list_t vl = VALUE_LIST_INIT;
621 values[0].gauge = value;
625 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
626 sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
627 sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
628 sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
629 sstrncpy (vl.type, type, sizeof (vl.type));
631 plugin_dispatch_values (&vl);
632 } /* }}} void ping_submit */
634 static int ping_read (void) /* {{{ */
636 if (ping_thread_error != 0)
638 ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
642 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next)
646 hl->latency_total = 0.0;
647 hl->latency_squared = 0.0;
653 } /* if (ping_thread_error != 0) */
655 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
659 double latency_total;
660 double latency_squared;
662 double latency_average;
663 double latency_stddev;
667 /* Locking here works, because the structure of the linked list is only
668 * changed during configure and shutdown. */
669 pthread_mutex_lock (&ping_lock);
671 pkg_sent = hl->pkg_sent;
672 pkg_recv = hl->pkg_recv;
673 latency_total = hl->latency_total;
674 latency_squared = hl->latency_squared;
678 hl->latency_total = 0.0;
679 hl->latency_squared = 0.0;
681 pthread_mutex_unlock (&ping_lock);
683 /* This e. g. happens when starting up. */
686 DEBUG ("ping plugin: No packages for host %s have been sent.",
691 /* Calculate average. Beware of division by zero. */
693 latency_average = NAN;
695 latency_average = latency_total / ((double) pkg_recv);
697 /* Calculate standard deviation. Beware even more of division by zero. */
699 latency_stddev = NAN;
700 else if (pkg_recv == 1)
701 latency_stddev = 0.0;
703 latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
704 - (latency_total * latency_total))
705 / ((double) (pkg_recv * (pkg_recv - 1))));
707 /* Calculate drop rate. */
708 droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
710 submit (hl->host, "ping", latency_average);
711 submit (hl->host, "ping_stddev", latency_stddev);
712 submit (hl->host, "ping_droprate", droprate);
713 } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
716 } /* }}} int ping_read */
718 static int ping_shutdown (void) /* {{{ */
722 INFO ("ping plugin: Shutting down thread.");
723 if (stop_thread () < 0)
739 if (ping_data != NULL) {
745 } /* }}} int ping_shutdown */
747 void module_register (void)
749 plugin_register_config ("ping", ping_config,
750 config_keys, config_keys_num);
751 plugin_register_init ("ping", ping_init);
752 plugin_register_read ("ping", ping_read);
753 plugin_register_shutdown ("ping", ping_shutdown);
754 } /* void module_register */
756 /* vim: set sw=2 sts=2 et fdm=marker : */