6e056e4640bdd1caf701654a8127de5915b55adf
[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 int ping_thread_loop = 0;
85 static int ping_thread_error = 0;
86 static pthread_t ping_thread_id;
87 static pthread_mutex_t ping_lock = PTHREAD_MUTEX_INITIALIZER;
88 static pthread_cond_t ping_cond = PTHREAD_COND_INITIALIZER;
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   pingobj_t *pingobj = NULL;
228
229   struct timeval tv_begin;
230   struct timeval tv_end;
231   struct timespec ts_wait;
232   struct timespec ts_int;
233
234   int count;
235
236   c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
237
238   pthread_mutex_lock(&ping_lock);
239
240   pingobj = ping_construct();
241   if (pingobj == NULL) {
242     ERROR("ping plugin: ping_construct failed.");
243     ping_thread_error = 1;
244     pthread_mutex_unlock(&ping_lock);
245     return (void *)-1;
246   }
247
248   if (ping_source != NULL)
249     if (ping_setopt(pingobj, PING_OPT_SOURCE, (void *)ping_source) != 0)
250       ERROR("ping plugin: Failed to set source address: %s",
251             ping_get_error(pingobj));
252
253 #ifdef HAVE_OPING_1_3
254   if (ping_device != NULL)
255     if (ping_setopt(pingobj, PING_OPT_DEVICE, (void *)ping_device) != 0)
256       ERROR("ping plugin: Failed to set device: %s", ping_get_error(pingobj));
257 #endif
258
259   ping_setopt(pingobj, PING_OPT_TIMEOUT, (void *)&ping_timeout);
260   ping_setopt(pingobj, PING_OPT_TTL, (void *)&ping_ttl);
261
262   if (ping_data != NULL)
263     ping_setopt(pingobj, PING_OPT_DATA, (void *)ping_data);
264
265   /* Add all the hosts to the ping object. */
266   count = 0;
267   for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) {
268     int tmp_status;
269     tmp_status = ping_host_add(pingobj, hl->host);
270     if (tmp_status != 0)
271       WARNING("ping plugin: ping_host_add (%s) failed: %s", hl->host,
272               ping_get_error(pingobj));
273     else
274       count++;
275   }
276
277   if (count == 0) {
278     ERROR("ping plugin: No host could be added to ping object. Giving up.");
279     ping_thread_error = 1;
280     pthread_mutex_unlock(&ping_lock);
281     return (void *)-1;
282   }
283
284   /* Set up `ts_int' */
285   {
286     double temp_sec;
287     double temp_nsec;
288
289     temp_nsec = modf(ping_interval, &temp_sec);
290     ts_int.tv_sec = (time_t)temp_sec;
291     ts_int.tv_nsec = (long)(temp_nsec * 1000000000L);
292   }
293
294   while (ping_thread_loop > 0) {
295     int status;
296     _Bool send_successful = 0;
297
298     if (gettimeofday(&tv_begin, NULL) < 0) {
299       char errbuf[1024];
300       ERROR("ping plugin: gettimeofday failed: %s",
301             sstrerror(errno, errbuf, sizeof(errbuf)));
302       ping_thread_error = 1;
303       break;
304     }
305
306     pthread_mutex_unlock(&ping_lock);
307
308     status = ping_send(pingobj);
309     if (status < 0) {
310       c_complain(LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
311                  ping_get_error(pingobj));
312     } else {
313       c_release(LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
314       send_successful = 1;
315     }
316
317     pthread_mutex_lock(&ping_lock);
318
319     if (ping_thread_loop <= 0)
320       break;
321
322     if (send_successful)
323       (void)ping_dispatch_all(pingobj);
324
325     if (gettimeofday(&tv_end, NULL) < 0) {
326       char errbuf[1024];
327       ERROR("ping plugin: gettimeofday failed: %s",
328             sstrerror(errno, errbuf, sizeof(errbuf)));
329       ping_thread_error = 1;
330       break;
331     }
332
333     /* Calculate the absolute time until which to wait and store it in
334      * `ts_wait'. */
335     time_calc(&ts_wait, &ts_int, &tv_begin, &tv_end);
336
337     pthread_cond_timedwait(&ping_cond, &ping_lock, &ts_wait);
338     if (ping_thread_loop <= 0)
339       break;
340   } /* while (ping_thread_loop > 0) */
341
342   pthread_mutex_unlock(&ping_lock);
343   ping_destroy(pingobj);
344
345   return (void *)0;
346 } /* }}} void *ping_thread */
347
348 static int start_thread(void) /* {{{ */
349 {
350   int status;
351
352   pthread_mutex_lock(&ping_lock);
353
354   if (ping_thread_loop != 0) {
355     pthread_mutex_unlock(&ping_lock);
356     return 0;
357   }
358
359   ping_thread_loop = 1;
360   ping_thread_error = 0;
361   status = plugin_thread_create(&ping_thread_id, /* attr = */ NULL, ping_thread,
362                                 /* arg = */ (void *)0, "ping");
363   if (status != 0) {
364     ping_thread_loop = 0;
365     ERROR("ping plugin: Starting thread failed.");
366     pthread_mutex_unlock(&ping_lock);
367     return -1;
368   }
369
370   pthread_mutex_unlock(&ping_lock);
371   return 0;
372 } /* }}} int start_thread */
373
374 static int stop_thread(void) /* {{{ */
375 {
376   int status;
377
378   pthread_mutex_lock(&ping_lock);
379
380   if (ping_thread_loop == 0) {
381     pthread_mutex_unlock(&ping_lock);
382     return -1;
383   }
384
385   ping_thread_loop = 0;
386   pthread_cond_broadcast(&ping_cond);
387   pthread_mutex_unlock(&ping_lock);
388
389   status = pthread_join(ping_thread_id, /* return = */ NULL);
390   if (status != 0) {
391     ERROR("ping plugin: Stopping thread failed.");
392     status = -1;
393   }
394
395   pthread_mutex_lock(&ping_lock);
396   memset(&ping_thread_id, 0, sizeof(ping_thread_id));
397   ping_thread_error = 0;
398   pthread_mutex_unlock(&ping_lock);
399
400   return status;
401 } /* }}} int stop_thread */
402
403 static int ping_init(void) /* {{{ */
404 {
405   if (hostlist_head == NULL) {
406     NOTICE("ping plugin: No hosts have been configured.");
407     return -1;
408   }
409
410   if (ping_timeout > ping_interval) {
411     ping_timeout = 0.9 * ping_interval;
412     WARNING("ping plugin: Timeout is greater than interval. "
413             "Will use a timeout of %gs.",
414             ping_timeout);
415   }
416
417 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_NET_RAW)
418   if (check_capability(CAP_NET_RAW) != 0) {
419     if (getuid() == 0)
420       WARNING("ping plugin: Running collectd as root, but the CAP_NET_RAW "
421               "capability is missing. The plugin's read function will probably "
422               "fail. Is your init system dropping capabilities?");
423     else
424       WARNING("ping plugin: collectd doesn't have the CAP_NET_RAW capability. "
425               "If you don't want to run collectd as root, try running \"setcap "
426               "cap_net_raw=ep\" on the collectd binary.");
427   }
428 #endif
429
430   return start_thread();
431 } /* }}} int ping_init */
432
433 static int config_set_string(const char *name, /* {{{ */
434                              char **var, const char *value) {
435   char *tmp;
436
437   tmp = strdup(value);
438   if (tmp == NULL) {
439     char errbuf[1024];
440     ERROR("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s", name,
441           value, sstrerror(errno, errbuf, sizeof(errbuf)));
442     return 1;
443   }
444
445   if (*var != NULL)
446     free(*var);
447   *var = tmp;
448   return 0;
449 } /* }}} int config_set_string */
450
451 static int ping_config(const char *key, const char *value) /* {{{ */
452 {
453   if (strcasecmp(key, "Host") == 0) {
454     hostlist_t *hl;
455     char *host;
456
457     hl = malloc(sizeof(*hl));
458     if (hl == NULL) {
459       char errbuf[1024];
460       ERROR("ping plugin: malloc failed: %s",
461             sstrerror(errno, errbuf, sizeof(errbuf)));
462       return 1;
463     }
464
465     host = strdup(value);
466     if (host == NULL) {
467       char errbuf[1024];
468       sfree(hl);
469       ERROR("ping plugin: strdup failed: %s",
470             sstrerror(errno, errbuf, sizeof(errbuf)));
471       return 1;
472     }
473
474     hl->host = host;
475     hl->pkg_sent = 0;
476     hl->pkg_recv = 0;
477     hl->pkg_missed = 0;
478     hl->latency_total = 0.0;
479     hl->latency_squared = 0.0;
480     hl->next = hostlist_head;
481     hostlist_head = hl;
482   } else if (strcasecmp(key, "SourceAddress") == 0) {
483     int status = config_set_string(key, &ping_source, value);
484     if (status != 0)
485       return status;
486   }
487 #ifdef HAVE_OPING_1_3
488   else if (strcasecmp(key, "Device") == 0) {
489     int status = config_set_string(key, &ping_device, value);
490     if (status != 0)
491       return status;
492   }
493 #endif
494   else if (strcasecmp(key, "TTL") == 0) {
495     int ttl = atoi(value);
496     if ((ttl > 0) && (ttl <= 255))
497       ping_ttl = ttl;
498     else
499       WARNING("ping plugin: Ignoring invalid TTL %i.", ttl);
500   } else if (strcasecmp(key, "Interval") == 0) {
501     double tmp;
502
503     tmp = atof(value);
504     if (tmp > 0.0)
505       ping_interval = tmp;
506     else
507       WARNING("ping plugin: Ignoring invalid interval %g (%s)", tmp, value);
508   } else if (strcasecmp(key, "Size") == 0) {
509     size_t size = (size_t)atoi(value);
510
511     /* Max IP packet size - (IPv6 + ICMP) = 65535 - (40 + 8) = 65487 */
512     if (size <= 65487) {
513       sfree(ping_data);
514       ping_data = malloc(size + 1);
515       if (ping_data == NULL) {
516         ERROR("ping plugin: malloc failed.");
517         return 1;
518       }
519
520       /* Note: By default oping is using constant string
521        * "liboping -- ICMP ping library <http://octo.it/liboping/>"
522        * which is exactly 56 bytes.
523        *
524        * Optimally we would follow the ping(1) behaviour, but we
525        * cannot use byte 00 or start data payload at exactly same
526        * location, due to oping library limitations. */
527       for (size_t i = 0; i < size; i++) /* {{{ */
528       {
529         /* This restricts data pattern to be only composed of easily
530          * printable characters, and not NUL character. */
531         ping_data[i] = ('0' + i % 64);
532       } /* }}} for (i = 0; i < size; i++) */
533       ping_data[size] = 0;
534     } else
535       WARNING("ping plugin: Ignoring invalid Size %zu.", size);
536   } else if (strcasecmp(key, "Timeout") == 0) {
537     double tmp;
538
539     tmp = atof(value);
540     if (tmp > 0.0)
541       ping_timeout = tmp;
542     else
543       WARNING("ping plugin: Ignoring invalid timeout %g (%s)", tmp, value);
544   } else if (strcasecmp(key, "MaxMissed") == 0) {
545     ping_max_missed = atoi(value);
546     if (ping_max_missed < 0)
547       INFO("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
548   } else {
549     return -1;
550   }
551
552   return 0;
553 } /* }}} int ping_config */
554
555 static void submit(const char *host, const char *type, /* {{{ */
556                    gauge_t value) {
557   value_list_t vl = VALUE_LIST_INIT;
558
559   vl.values = &(value_t){.gauge = value};
560   vl.values_len = 1;
561   sstrncpy(vl.plugin, "ping", sizeof(vl.plugin));
562   sstrncpy(vl.type_instance, host, sizeof(vl.type_instance));
563   sstrncpy(vl.type, type, sizeof(vl.type));
564
565   plugin_dispatch_values(&vl);
566 } /* }}} void ping_submit */
567
568 static int ping_read(void) /* {{{ */
569 {
570   if (ping_thread_error != 0) {
571     ERROR("ping plugin: The ping thread had a problem. Restarting it.");
572
573     stop_thread();
574
575     for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) {
576       hl->pkg_sent = 0;
577       hl->pkg_recv = 0;
578       hl->latency_total = 0.0;
579       hl->latency_squared = 0.0;
580     }
581
582     start_thread();
583
584     return -1;
585   } /* if (ping_thread_error != 0) */
586
587   for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
588   {
589     uint32_t pkg_sent;
590     uint32_t pkg_recv;
591     double latency_total;
592     double latency_squared;
593
594     double latency_average;
595     double latency_stddev;
596
597     double droprate;
598
599     /* Locking here works, because the structure of the linked list is only
600      * changed during configure and shutdown. */
601     pthread_mutex_lock(&ping_lock);
602
603     pkg_sent = hl->pkg_sent;
604     pkg_recv = hl->pkg_recv;
605     latency_total = hl->latency_total;
606     latency_squared = hl->latency_squared;
607
608     hl->pkg_sent = 0;
609     hl->pkg_recv = 0;
610     hl->latency_total = 0.0;
611     hl->latency_squared = 0.0;
612
613     pthread_mutex_unlock(&ping_lock);
614
615     /* This e. g. happens when starting up. */
616     if (pkg_sent == 0) {
617       DEBUG("ping plugin: No packages for host %s have been sent.", hl->host);
618       continue;
619     }
620
621     /* Calculate average. Beware of division by zero. */
622     if (pkg_recv == 0)
623       latency_average = NAN;
624     else
625       latency_average = latency_total / ((double)pkg_recv);
626
627     /* Calculate standard deviation. Beware even more of division by zero. */
628     if (pkg_recv == 0)
629       latency_stddev = NAN;
630     else if (pkg_recv == 1)
631       latency_stddev = 0.0;
632     else
633       latency_stddev = sqrt(((((double)pkg_recv) * latency_squared) -
634                              (latency_total * latency_total)) /
635                             ((double)(pkg_recv * (pkg_recv - 1))));
636
637     /* Calculate drop rate. */
638     droprate = ((double)(pkg_sent - pkg_recv)) / ((double)pkg_sent);
639
640     submit(hl->host, "ping", latency_average);
641     submit(hl->host, "ping_stddev", latency_stddev);
642     submit(hl->host, "ping_droprate", droprate);
643   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
644
645   return 0;
646 } /* }}} int ping_read */
647
648 static int ping_shutdown(void) /* {{{ */
649 {
650   hostlist_t *hl;
651
652   INFO("ping plugin: Shutting down thread.");
653   if (stop_thread() < 0)
654     return -1;
655
656   hl = hostlist_head;
657   while (hl != NULL) {
658     hostlist_t *hl_next;
659
660     hl_next = hl->next;
661
662     sfree(hl->host);
663     sfree(hl);
664
665     hl = hl_next;
666   }
667
668   if (ping_data != NULL) {
669     free(ping_data);
670     ping_data = NULL;
671   }
672
673   return 0;
674 } /* }}} int ping_shutdown */
675
676 void module_register(void) {
677   plugin_register_config("ping", ping_config, config_keys, config_keys_num);
678   plugin_register_init("ping", ping_init);
679   plugin_register_read("ping", ping_read);
680   plugin_register_shutdown("ping", ping_shutdown);
681 } /* void module_register */