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 "configfile.h"
32 #include "utils_complain.h"
34 #include <netinet/in.h>
36 # include <netdb.h> /* NI_MAXHOST */
39 #ifdef HAVE_SYS_CAPABILITY_H
40 # include <sys/capability.h>
46 # define NI_MAXHOST 1025
49 #if defined(OPING_VERSION) && (OPING_VERSION >= 1003000)
50 # define HAVE_OPING_1_3
65 double latency_squared;
67 struct hostlist_s *next;
69 typedef struct hostlist_s hostlist_t;
74 static hostlist_t *hostlist_head = NULL;
76 static char *ping_source = NULL;
78 static char *ping_device = NULL;
80 static char *ping_data = NULL;
81 static int ping_ttl = PING_DEF_TTL;
82 static double ping_interval = 1.0;
83 static double ping_timeout = 0.9;
84 static int ping_max_missed = -1;
86 static int ping_thread_loop = 0;
87 static int ping_thread_error = 0;
88 static pthread_t ping_thread_id;
89 static pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
90 static pthread_cond_t ping_cond = PTHREAD_COND_INITIALIZER;
92 static const char *config_keys[] =
105 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
110 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
111 static void time_normalize (struct timespec *ts) /* {{{ */
113 while (ts->tv_nsec < 0)
122 ts->tv_nsec += 1000000000;
125 while (ts->tv_nsec >= 1000000000)
128 ts->tv_nsec -= 1000000000;
130 } /* }}} void time_normalize */
132 /* Add `ts_int' to `tv_begin' and store the result in `ts_dest'. If the result
133 * is larger than `tv_end', copy `tv_end' to `ts_dest' instead. */
134 static void time_calc (struct timespec *ts_dest, /* {{{ */
135 const struct timespec *ts_int,
136 const struct timeval *tv_begin,
137 const struct timeval *tv_end)
139 ts_dest->tv_sec = tv_begin->tv_sec + ts_int->tv_sec;
140 ts_dest->tv_nsec = (tv_begin->tv_usec * 1000) + ts_int->tv_nsec;
141 time_normalize (ts_dest);
143 /* Assure that `(begin + interval) > end'.
144 * This may seem overly complicated, but `tv_sec' is of type `time_t'
145 * which may be `unsigned. *sigh* */
146 if ((tv_end->tv_sec > ts_dest->tv_sec)
147 || ((tv_end->tv_sec == ts_dest->tv_sec)
148 && ((tv_end->tv_usec * 1000) > ts_dest->tv_nsec)))
150 ts_dest->tv_sec = tv_end->tv_sec;
151 ts_dest->tv_nsec = 1000 * tv_end->tv_usec;
154 time_normalize (ts_dest);
155 } /* }}} void time_calc */
157 static int ping_dispatch_all (pingobj_t *pingobj) /* {{{ */
162 for (pingobj_iter_t *iter = ping_iterator_get (pingobj);
164 iter = ping_iterator_next (iter))
166 char userhost[NI_MAXHOST];
170 param_size = sizeof (userhost);
171 status = ping_iterator_get_info (iter,
172 #ifdef PING_INFO_USERNAME
177 userhost, ¶m_size);
180 WARNING ("ping plugin: ping_iterator_get_info failed: %s",
181 ping_get_error (pingobj));
185 for (hl = hostlist_head; hl != NULL; hl = hl->next)
186 if (strcmp (userhost, hl->host) == 0)
191 WARNING ("ping plugin: Cannot find host %s.", userhost);
195 param_size = sizeof (latency);
196 status = ping_iterator_get_info (iter, PING_INFO_LATENCY,
197 (void *) &latency, ¶m_size);
200 WARNING ("ping plugin: ping_iterator_get_info failed: %s",
201 ping_get_error (pingobj));
209 hl->latency_total += latency;
210 hl->latency_squared += (latency * latency);
212 /* reset missed packages counter */
217 /* if the host did not answer our last N packages, trigger a resolv. */
218 if ((ping_max_missed >= 0)
219 && (hl->pkg_missed >= ((uint32_t) ping_max_missed)))
221 /* we reset the missed package counter here, since we only want to
222 * trigger a resolv every N packages and not every package _AFTER_ N
226 WARNING ("ping plugin: host %s has not answered %d PING requests,"
227 " triggering resolve", hl->host, ping_max_missed);
229 /* we trigger the resolv simply be removeing and adding the host to our
231 status = ping_host_remove (pingobj, hl->host);
234 WARNING ("ping plugin: ping_host_remove (%s) failed.", hl->host);
238 status = ping_host_add (pingobj, hl->host);
240 ERROR ("ping plugin: ping_host_add (%s) failed.", hl->host);
242 } /* }}} ping_max_missed */
243 } /* }}} for (iter) */
246 } /* }}} int ping_dispatch_all */
248 static void *ping_thread (void *arg) /* {{{ */
250 pingobj_t *pingobj = NULL;
252 struct timeval tv_begin;
253 struct timeval tv_end;
254 struct timespec ts_wait;
255 struct timespec ts_int;
259 c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
261 pthread_mutex_lock (&ping_lock);
263 pingobj = ping_construct ();
266 ERROR ("ping plugin: ping_construct failed.");
267 ping_thread_error = 1;
268 pthread_mutex_unlock (&ping_lock);
269 return ((void *) -1);
272 if (ping_source != NULL)
273 if (ping_setopt (pingobj, PING_OPT_SOURCE, (void *) ping_source) != 0)
274 ERROR ("ping plugin: Failed to set source address: %s",
275 ping_get_error (pingobj));
277 #ifdef HAVE_OPING_1_3
278 if (ping_device != NULL)
279 if (ping_setopt (pingobj, PING_OPT_DEVICE, (void *) ping_device) != 0)
280 ERROR ("ping plugin: Failed to set device: %s",
281 ping_get_error (pingobj));
284 ping_setopt (pingobj, PING_OPT_TIMEOUT, (void *) &ping_timeout);
285 ping_setopt (pingobj, PING_OPT_TTL, (void *) &ping_ttl);
287 if (ping_data != NULL)
288 ping_setopt (pingobj, PING_OPT_DATA, (void *) ping_data);
290 /* Add all the hosts to the ping object. */
292 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next)
295 tmp_status = ping_host_add (pingobj, hl->host);
297 WARNING ("ping plugin: ping_host_add (%s) failed: %s",
298 hl->host, ping_get_error (pingobj));
305 ERROR ("ping plugin: No host could be added to ping object. Giving up.");
306 ping_thread_error = 1;
307 pthread_mutex_unlock (&ping_lock);
308 return ((void *) -1);
311 /* Set up `ts_int' */
316 temp_nsec = modf (ping_interval, &temp_sec);
317 ts_int.tv_sec = (time_t) temp_sec;
318 ts_int.tv_nsec = (long) (temp_nsec * 1000000000L);
321 while (ping_thread_loop > 0)
324 _Bool send_successful = 0;
326 if (gettimeofday (&tv_begin, NULL) < 0)
329 ERROR ("ping plugin: gettimeofday failed: %s",
330 sstrerror (errno, errbuf, sizeof (errbuf)));
331 ping_thread_error = 1;
335 pthread_mutex_unlock (&ping_lock);
337 status = ping_send (pingobj);
340 c_complain (LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
341 ping_get_error (pingobj));
345 c_release (LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
349 pthread_mutex_lock (&ping_lock);
351 if (ping_thread_loop <= 0)
355 (void) ping_dispatch_all (pingobj);
357 if (gettimeofday (&tv_end, NULL) < 0)
360 ERROR ("ping plugin: gettimeofday failed: %s",
361 sstrerror (errno, errbuf, sizeof (errbuf)));
362 ping_thread_error = 1;
366 /* Calculate the absolute time until which to wait and store it in
368 time_calc (&ts_wait, &ts_int, &tv_begin, &tv_end);
370 pthread_cond_timedwait (&ping_cond, &ping_lock, &ts_wait);
371 if (ping_thread_loop <= 0)
373 } /* while (ping_thread_loop > 0) */
375 pthread_mutex_unlock (&ping_lock);
376 ping_destroy (pingobj);
379 } /* }}} void *ping_thread */
381 static int start_thread (void) /* {{{ */
385 pthread_mutex_lock (&ping_lock);
387 if (ping_thread_loop != 0)
389 pthread_mutex_unlock (&ping_lock);
393 ping_thread_loop = 1;
394 ping_thread_error = 0;
395 status = plugin_thread_create (&ping_thread_id, /* attr = */ NULL,
396 ping_thread, /* arg = */ (void *) 0);
399 ping_thread_loop = 0;
400 ERROR ("ping plugin: Starting thread failed.");
401 pthread_mutex_unlock (&ping_lock);
405 pthread_mutex_unlock (&ping_lock);
407 } /* }}} int start_thread */
409 static int stop_thread (void) /* {{{ */
413 pthread_mutex_lock (&ping_lock);
415 if (ping_thread_loop == 0)
417 pthread_mutex_unlock (&ping_lock);
421 ping_thread_loop = 0;
422 pthread_cond_broadcast (&ping_cond);
423 pthread_mutex_unlock (&ping_lock);
425 status = pthread_join (ping_thread_id, /* return = */ NULL);
428 ERROR ("ping plugin: Stopping thread failed.");
432 pthread_mutex_lock (&ping_lock);
433 memset (&ping_thread_id, 0, sizeof (ping_thread_id));
434 ping_thread_error = 0;
435 pthread_mutex_unlock (&ping_lock);
438 } /* }}} int stop_thread */
440 static int ping_init (void) /* {{{ */
442 if (hostlist_head == NULL)
444 NOTICE ("ping plugin: No hosts have been configured.");
448 if (ping_timeout > ping_interval)
450 ping_timeout = 0.9 * ping_interval;
451 WARNING ("ping plugin: Timeout is greater than interval. "
452 "Will use a timeout of %gs.", ping_timeout);
455 #ifdef HAVE_SYS_CAPABILITY_H
456 if (check_capability (CAP_NET_RAW) != 0)
459 WARNING ("ping plugin: Running collectd as root, but the CAP_NET_RAW "
460 "capability is missing. The plugin's read function will probably "
461 "fail. Is your init system dropping capabilities ?");
463 WARNING ("ping plugin: collectd doesn't have the CAP_NET_RAW capability. "
464 "If you don't want to run collectd as root, try running \"setcap "
465 "cap_net_raw=ep\" on the collectd binary.");
469 return (start_thread ());
470 } /* }}} int ping_init */
472 static int config_set_string (const char *name, /* {{{ */
473 char **var, const char *value)
477 tmp = strdup (value);
481 ERROR ("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s",
482 name, value, sstrerror (errno, errbuf, sizeof (errbuf)));
490 } /* }}} int config_set_string */
492 static int ping_config (const char *key, const char *value) /* {{{ */
494 if (strcasecmp (key, "Host") == 0)
499 hl = malloc (sizeof (*hl));
503 ERROR ("ping plugin: malloc failed: %s",
504 sstrerror (errno, errbuf, sizeof (errbuf)));
508 host = strdup (value);
513 ERROR ("ping plugin: strdup failed: %s",
514 sstrerror (errno, errbuf, sizeof (errbuf)));
522 hl->latency_total = 0.0;
523 hl->latency_squared = 0.0;
524 hl->next = hostlist_head;
527 else if (strcasecmp (key, "SourceAddress") == 0)
529 int status = config_set_string (key, &ping_source, value);
533 #ifdef HAVE_OPING_1_3
534 else if (strcasecmp (key, "Device") == 0)
536 int status = config_set_string (key, &ping_device, value);
541 else if (strcasecmp (key, "TTL") == 0)
543 int ttl = atoi (value);
544 if ((ttl > 0) && (ttl <= 255))
547 WARNING ("ping plugin: Ignoring invalid TTL %i.", ttl);
549 else if (strcasecmp (key, "Interval") == 0)
557 WARNING ("ping plugin: Ignoring invalid interval %g (%s)",
560 else if (strcasecmp (key, "Size") == 0) {
561 size_t size = (size_t) atoi (value);
563 /* Max IP packet size - (IPv6 + ICMP) = 65535 - (40 + 8) = 65487 */
567 ping_data = malloc (size + 1);
568 if (ping_data == NULL)
570 ERROR ("ping plugin: malloc failed.");
574 /* Note: By default oping is using constant string
575 * "liboping -- ICMP ping library <http://octo.it/liboping/>"
576 * which is exactly 56 bytes.
578 * Optimally we would follow the ping(1) behaviour, but we
579 * cannot use byte 00 or start data payload at exactly same
580 * location, due to oping library limitations. */
581 for (size_t i = 0; i < size; i++) /* {{{ */
583 /* This restricts data pattern to be only composed of easily
584 * printable characters, and not NUL character. */
585 ping_data[i] = ('0' + i % 64);
586 } /* }}} for (i = 0; i < size; i++) */
589 WARNING ("ping plugin: Ignoring invalid Size %zu.", size);
591 else if (strcasecmp (key, "Timeout") == 0)
599 WARNING ("ping plugin: Ignoring invalid timeout %g (%s)",
602 else if (strcasecmp (key, "MaxMissed") == 0)
604 ping_max_missed = atoi (value);
605 if (ping_max_missed < 0)
606 INFO ("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
614 } /* }}} int ping_config */
616 static void submit (const char *host, const char *type, /* {{{ */
620 value_list_t vl = VALUE_LIST_INIT;
622 values[0].gauge = value;
626 sstrncpy (vl.host, hostname_g, sizeof (vl.host));
627 sstrncpy (vl.plugin, "ping", sizeof (vl.plugin));
628 sstrncpy (vl.plugin_instance, "", sizeof (vl.plugin_instance));
629 sstrncpy (vl.type_instance, host, sizeof (vl.type_instance));
630 sstrncpy (vl.type, type, sizeof (vl.type));
632 plugin_dispatch_values (&vl);
633 } /* }}} void ping_submit */
635 static int ping_read (void) /* {{{ */
637 if (ping_thread_error != 0)
639 ERROR ("ping plugin: The ping thread had a problem. Restarting it.");
643 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next)
647 hl->latency_total = 0.0;
648 hl->latency_squared = 0.0;
654 } /* if (ping_thread_error != 0) */
656 for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
660 double latency_total;
661 double latency_squared;
663 double latency_average;
664 double latency_stddev;
668 /* Locking here works, because the structure of the linked list is only
669 * changed during configure and shutdown. */
670 pthread_mutex_lock (&ping_lock);
672 pkg_sent = hl->pkg_sent;
673 pkg_recv = hl->pkg_recv;
674 latency_total = hl->latency_total;
675 latency_squared = hl->latency_squared;
679 hl->latency_total = 0.0;
680 hl->latency_squared = 0.0;
682 pthread_mutex_unlock (&ping_lock);
684 /* This e. g. happens when starting up. */
687 DEBUG ("ping plugin: No packages for host %s have been sent.",
692 /* Calculate average. Beware of division by zero. */
694 latency_average = NAN;
696 latency_average = latency_total / ((double) pkg_recv);
698 /* Calculate standard deviation. Beware even more of division by zero. */
700 latency_stddev = NAN;
701 else if (pkg_recv == 1)
702 latency_stddev = 0.0;
704 latency_stddev = sqrt (((((double) pkg_recv) * latency_squared)
705 - (latency_total * latency_total))
706 / ((double) (pkg_recv * (pkg_recv - 1))));
708 /* Calculate drop rate. */
709 droprate = ((double) (pkg_sent - pkg_recv)) / ((double) pkg_sent);
711 submit (hl->host, "ping", latency_average);
712 submit (hl->host, "ping_stddev", latency_stddev);
713 submit (hl->host, "ping_droprate", droprate);
714 } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
717 } /* }}} int ping_read */
719 static int ping_shutdown (void) /* {{{ */
723 INFO ("ping plugin: Shutting down thread.");
724 if (stop_thread () < 0)
740 if (ping_data != NULL) {
746 } /* }}} int ping_shutdown */
748 void module_register (void)
750 plugin_register_config ("ping", ping_config,
751 config_keys, config_keys_num);
752 plugin_register_init ("ping", ping_init);
753 plugin_register_read ("ping", ping_read);
754 plugin_register_shutdown ("ping", ping_shutdown);
755 } /* void module_register */
757 /* vim: set sw=2 sts=2 et fdm=marker : */