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>
30 #include "utils/common/common.h"
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
63 double latency_squared;
65 struct hostlist_s *next;
67 typedef struct hostlist_s hostlist_t;
72 static hostlist_t *hostlist_head;
74 static int ping_af = PING_DEF_AF;
75 static char *ping_source;
77 static char *ping_device;
79 static char *ping_data;
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 pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
86 static pthread_cond_t ping_cond = PTHREAD_COND_INITIALIZER;
87 static int ping_thread_loop;
88 static int ping_thread_error;
89 static pthread_t ping_thread_id;
91 static const char *config_keys[] = {"Host", "SourceAddress", "AddressFamily",
95 "Size", "TTL", "Interval",
96 "Timeout", "MaxMissed"};
97 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
102 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
103 static void time_normalize(struct timespec *ts) /* {{{ */
105 while (ts->tv_nsec < 0) {
106 if (ts->tv_sec == 0) {
112 ts->tv_nsec += 1000000000;
115 while (ts->tv_nsec >= 1000000000) {
117 ts->tv_nsec -= 1000000000;
119 } /* }}} void time_normalize */
121 /* Add `ts_int' to `tv_begin' and store the result in `ts_dest'. If the result
122 * is larger than `tv_end', copy `tv_end' to `ts_dest' instead. */
123 static void time_calc(struct timespec *ts_dest, /* {{{ */
124 const struct timespec *ts_int,
125 const struct timeval *tv_begin,
126 const struct timeval *tv_end) {
127 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
128 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
129 time_normalize(ts_dest);
131 /* Assure that `(begin + interval) > end'.
132 * This may seem overly complicated, but `tv_sec' is of type `time_t'
133 * which may be `unsigned. *sigh* */
134 if ((tv_end->tv_sec > ts_dest->tv_sec) ||
135 ((tv_end->tv_sec == ts_dest->tv_sec) &&
136 ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec))) {
137 ts_dest->tv_sec = tv_end->tv_sec;
138 ts_dest->tv_nsec = 1000 * tv_end->tv_usec;
141 time_normalize(ts_dest);
142 } /* }}} void time_calc */
144 static int ping_dispatch_all(pingobj_t *pingobj) /* {{{ */
149 for (pingobj_iter_t *iter = ping_iterator_get(pingobj); iter != NULL;
150 iter = ping_iterator_next(iter)) { /* {{{ */
151 char userhost[NI_MAXHOST];
155 param_size = sizeof(userhost);
156 status = ping_iterator_get_info(iter,
157 #ifdef PING_INFO_USERNAME
162 userhost, ¶m_size);
164 WARNING("ping plugin: ping_iterator_get_info failed: %s",
165 ping_get_error(pingobj));
169 for (hl = hostlist_head; hl != NULL; hl = hl->next)
170 if (strcmp(userhost, hl->host) == 0)
174 WARNING("ping plugin: Cannot find host %s.", userhost);
178 param_size = sizeof(latency);
179 status = ping_iterator_get_info(iter, PING_INFO_LATENCY, (void *)&latency,
182 WARNING("ping plugin: ping_iterator_get_info failed: %s",
183 ping_get_error(pingobj));
188 if (latency >= 0.0) {
190 hl->latency_total += latency;
191 hl->latency_squared += (latency * latency);
193 /* reset missed packages counter */
198 /* if the host did not answer our last N packages, trigger a resolv. */
199 if ((ping_max_missed >= 0) &&
200 (hl->pkg_missed >= ((uint32_t)ping_max_missed))) { /* {{{ */
201 /* we reset the missed package counter here, since we only want to
202 * trigger a resolv every N packages and not every package _AFTER_ N
206 WARNING("ping plugin: host %s has not answered %d PING requests,"
207 " triggering resolve",
208 hl->host, ping_max_missed);
210 /* we trigger the resolv simply be removeing and adding the host to our
212 status = ping_host_remove(pingobj, hl->host);
214 WARNING("ping plugin: ping_host_remove (%s) failed.", hl->host);
216 status = ping_host_add(pingobj, hl->host);
218 ERROR("ping plugin: ping_host_add (%s) failed.", hl->host);
220 } /* }}} ping_max_missed */
221 } /* }}} for (iter) */
224 } /* }}} int ping_dispatch_all */
226 static void *ping_thread(void *arg) /* {{{ */
228 struct timeval tv_begin;
229 struct timeval tv_end;
230 struct timespec ts_wait;
231 struct timespec ts_int;
235 c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
237 pingobj_t *pingobj = ping_construct();
238 if (pingobj == NULL) {
239 ERROR("ping plugin: ping_construct failed.");
240 pthread_mutex_lock(&ping_lock);
241 ping_thread_error = 1;
242 pthread_mutex_unlock(&ping_lock);
246 if (ping_af != PING_DEF_AF) {
247 if (ping_setopt(pingobj, PING_OPT_AF, &ping_af) != 0)
248 ERROR("ping plugin: Failed to set address family: %s",
249 ping_get_error(pingobj));
252 if (ping_source != NULL)
253 if (ping_setopt(pingobj, PING_OPT_SOURCE, (void *)ping_source) != 0)
254 ERROR("ping plugin: Failed to set source address: %s",
255 ping_get_error(pingobj));
257 #ifdef HAVE_OPING_1_3
258 if (ping_device != NULL)
259 if (ping_setopt(pingobj, PING_OPT_DEVICE, (void *)ping_device) != 0)
260 ERROR("ping plugin: Failed to set device: %s", ping_get_error(pingobj));
263 ping_setopt(pingobj, PING_OPT_TIMEOUT, (void *)&ping_timeout);
264 ping_setopt(pingobj, PING_OPT_TTL, (void *)&ping_ttl);
266 if (ping_data != NULL)
267 ping_setopt(pingobj, PING_OPT_DATA, (void *)ping_data);
269 /* Add all the hosts to the ping object. */
271 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) {
273 tmp_status = ping_host_add(pingobj, hl->host);
275 WARNING("ping plugin: ping_host_add (%s) failed: %s", hl->host,
276 ping_get_error(pingobj));
282 ERROR("ping plugin: No host could be added to ping object. Giving up.");
283 pthread_mutex_lock(&ping_lock);
284 ping_thread_error = 1;
285 pthread_mutex_unlock(&ping_lock);
289 /* Set up `ts_int' */
294 temp_nsec = modf(ping_interval, &temp_sec);
295 ts_int.tv_sec = (time_t)temp_sec;
296 ts_int.tv_nsec = (long)(temp_nsec * 1000000000L);
299 pthread_mutex_lock(&ping_lock);
300 while (ping_thread_loop > 0) {
301 bool send_successful = false;
303 if (gettimeofday(&tv_begin, NULL) < 0) {
304 ERROR("ping plugin: gettimeofday failed: %s", STRERRNO);
305 ping_thread_error = 1;
309 pthread_mutex_unlock(&ping_lock);
311 int status = ping_send(pingobj);
313 c_complain(LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
314 ping_get_error(pingobj));
316 c_release(LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
317 send_successful = true;
320 pthread_mutex_lock(&ping_lock);
322 if (ping_thread_loop <= 0)
326 (void)ping_dispatch_all(pingobj);
328 if (gettimeofday(&tv_end, NULL) < 0) {
329 ERROR("ping plugin: gettimeofday failed: %s", STRERRNO);
330 ping_thread_error = 1;
334 /* Calculate the absolute time until which to wait and store it in
336 time_calc(&ts_wait, &ts_int, &tv_begin, &tv_end);
338 pthread_cond_timedwait(&ping_cond, &ping_lock, &ts_wait);
339 if (ping_thread_loop <= 0)
341 } /* while (ping_thread_loop > 0) */
343 pthread_mutex_unlock(&ping_lock);
344 ping_destroy(pingobj);
347 } /* }}} void *ping_thread */
349 static int start_thread(void) /* {{{ */
353 pthread_mutex_lock(&ping_lock);
355 if (ping_thread_loop != 0) {
356 pthread_mutex_unlock(&ping_lock);
360 ping_thread_loop = 1;
361 ping_thread_error = 0;
362 status = plugin_thread_create(&ping_thread_id, /* attr = */ NULL, ping_thread,
363 /* arg = */ (void *)0, "ping");
365 ping_thread_loop = 0;
366 ERROR("ping plugin: Starting thread failed.");
367 pthread_mutex_unlock(&ping_lock);
371 pthread_mutex_unlock(&ping_lock);
373 } /* }}} int start_thread */
375 static int stop_thread(void) /* {{{ */
379 pthread_mutex_lock(&ping_lock);
381 if (ping_thread_loop == 0) {
382 pthread_mutex_unlock(&ping_lock);
386 ping_thread_loop = 0;
387 pthread_cond_broadcast(&ping_cond);
388 pthread_mutex_unlock(&ping_lock);
390 status = pthread_join(ping_thread_id, /* return = */ NULL);
392 ERROR("ping plugin: Stopping thread failed.");
396 pthread_mutex_lock(&ping_lock);
397 memset(&ping_thread_id, 0, sizeof(ping_thread_id));
398 ping_thread_error = 0;
399 pthread_mutex_unlock(&ping_lock);
402 } /* }}} int stop_thread */
404 static int ping_init(void) /* {{{ */
406 if (hostlist_head == NULL) {
407 NOTICE("ping plugin: No hosts have been configured.");
411 if (ping_timeout > ping_interval) {
412 ping_timeout = 0.9 * ping_interval;
413 WARNING("ping plugin: Timeout is greater than interval. "
414 "Will use a timeout of %gs.",
418 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_NET_RAW)
419 if (check_capability(CAP_NET_RAW) != 0) {
421 WARNING("ping plugin: Running collectd as root, but the CAP_NET_RAW "
422 "capability is missing. The plugin's read function will probably "
423 "fail. Is your init system dropping capabilities?");
425 WARNING("ping plugin: collectd doesn't have the CAP_NET_RAW capability. "
426 "If you don't want to run collectd as root, try running \"setcap "
427 "cap_net_raw=ep\" on the collectd binary.");
431 return start_thread();
432 } /* }}} int ping_init */
434 static int config_set_string(const char *name, /* {{{ */
435 char **var, const char *value) {
440 ERROR("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s", name,
449 } /* }}} int config_set_string */
451 static int ping_config(const char *key, const char *value) /* {{{ */
453 if (strcasecmp(key, "Host") == 0) {
457 hl = malloc(sizeof(*hl));
459 ERROR("ping plugin: malloc failed: %s", STRERRNO);
463 host = strdup(value);
466 ERROR("ping plugin: strdup failed: %s", STRERRNO);
474 hl->latency_total = 0.0;
475 hl->latency_squared = 0.0;
476 hl->next = hostlist_head;
478 } else if (strcasecmp(key, "AddressFamily") == 0) {
480 int status = config_set_string(key, &af, value);
484 if (strncmp(af, "any", 3) == 0) {
486 } else if (strncmp(af, "ipv4", 4) == 0) {
488 } else if (strncmp(af, "ipv6", 4) == 0) {
491 WARNING("ping plugin: Ignoring invalid AddressFamily value %s", af);
495 } else if (strcasecmp(key, "SourceAddress") == 0) {
496 int status = config_set_string(key, &ping_source, value);
500 #ifdef HAVE_OPING_1_3
501 else if (strcasecmp(key, "Device") == 0) {
502 int status = config_set_string(key, &ping_device, value);
507 else if (strcasecmp(key, "TTL") == 0) {
508 int ttl = atoi(value);
509 if ((ttl > 0) && (ttl <= 255))
512 WARNING("ping plugin: Ignoring invalid TTL %i.", ttl);
513 } else if (strcasecmp(key, "Interval") == 0) {
520 WARNING("ping plugin: Ignoring invalid interval %g (%s)", tmp, value);
521 } else if (strcasecmp(key, "Size") == 0) {
522 size_t size = (size_t)atoi(value);
524 /* Max IP packet size - (IPv6 + ICMP) = 65535 - (40 + 8) = 65487 */
527 ping_data = malloc(size + 1);
528 if (ping_data == NULL) {
529 ERROR("ping plugin: malloc failed.");
533 /* Note: By default oping is using constant string
534 * "liboping -- ICMP ping library <http://octo.it/liboping/>"
535 * which is exactly 56 bytes.
537 * Optimally we would follow the ping(1) behaviour, but we
538 * cannot use byte 00 or start data payload at exactly same
539 * location, due to oping library limitations. */
540 for (size_t i = 0; i < size; i++) /* {{{ */
542 /* This restricts data pattern to be only composed of easily
543 * printable characters, and not NUL character. */
544 ping_data[i] = ('0' + i % 64);
545 } /* }}} for (i = 0; i < size; i++) */
548 WARNING("ping plugin: Ignoring invalid Size %" PRIsz ".", size);
549 } else if (strcasecmp(key, "Timeout") == 0) {
556 WARNING("ping plugin: Ignoring invalid timeout %g (%s)", tmp, value);
557 } else if (strcasecmp(key, "MaxMissed") == 0) {
558 ping_max_missed = atoi(value);
559 if (ping_max_missed < 0)
560 INFO("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
566 } /* }}} int ping_config */
568 static void submit(const char *host, const char *type, /* {{{ */
570 value_list_t vl = VALUE_LIST_INIT;
572 vl.values = &(value_t){.gauge = value};
574 sstrncpy(vl.plugin, "ping", sizeof(vl.plugin));
575 sstrncpy(vl.type_instance, host, sizeof(vl.type_instance));
576 sstrncpy(vl.type, type, sizeof(vl.type));
578 plugin_dispatch_values(&vl);
579 } /* }}} void ping_submit */
581 static int ping_read(void) /* {{{ */
583 if (ping_thread_error != 0) {
584 ERROR("ping plugin: The ping thread had a problem. Restarting it.");
588 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) {
591 hl->latency_total = 0.0;
592 hl->latency_squared = 0.0;
598 } /* if (ping_thread_error != 0) */
600 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
604 double latency_total;
605 double latency_squared;
607 double latency_average;
608 double latency_stddev;
612 /* Locking here works, because the structure of the linked list is only
613 * changed during configure and shutdown. */
614 pthread_mutex_lock(&ping_lock);
616 pkg_sent = hl->pkg_sent;
617 pkg_recv = hl->pkg_recv;
618 latency_total = hl->latency_total;
619 latency_squared = hl->latency_squared;
623 hl->latency_total = 0.0;
624 hl->latency_squared = 0.0;
626 pthread_mutex_unlock(&ping_lock);
628 /* This e. g. happens when starting up. */
630 DEBUG("ping plugin: No packages for host %s have been sent.", hl->host);
634 /* Calculate average. Beware of division by zero. */
636 latency_average = NAN;
638 latency_average = latency_total / ((double)pkg_recv);
640 /* Calculate standard deviation. Beware even more of division by zero. */
642 latency_stddev = NAN;
643 else if (pkg_recv == 1)
644 latency_stddev = 0.0;
646 latency_stddev = sqrt(((((double)pkg_recv) * latency_squared) -
647 (latency_total * latency_total)) /
648 ((double)(pkg_recv * (pkg_recv - 1))));
650 /* Calculate drop rate. */
651 droprate = ((double)(pkg_sent - pkg_recv)) / ((double)pkg_sent);
653 submit(hl->host, "ping", latency_average);
654 submit(hl->host, "ping_stddev", latency_stddev);
655 submit(hl->host, "ping_droprate", droprate);
656 } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
659 } /* }}} int ping_read */
661 static int ping_shutdown(void) /* {{{ */
665 INFO("ping plugin: Shutting down thread.");
666 if (stop_thread() < 0)
681 if (ping_data != NULL) {
687 } /* }}} int ping_shutdown */
689 void module_register(void) {
690 plugin_register_config("ping", ping_config, config_keys, config_keys_num);
691 plugin_register_init("ping", ping_init);
692 plugin_register_read("ping", ping_read);
693 plugin_register_shutdown("ping", ping_shutdown);
694 } /* void module_register */