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