Merge pull request #2618 from ajssmith/amqp1_dev1_branch
[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;
73
74 static int ping_af = PING_DEF_AF;
75 static char *ping_source;
76 #ifdef HAVE_OPING_1_3
77 static char *ping_device;
78 #endif
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;
84
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;
90
91 static const char *config_keys[] = {"Host",    "SourceAddress", "AddressFamily",
92 #ifdef HAVE_OPING_1_3
93                                     "Device",
94 #endif
95                                     "Size",    "TTL",           "Interval",
96                                     "Timeout", "MaxMissed"};
97 static int config_keys_num = STATIC_ARRAY_SIZE(config_keys);
98
99 /*
100  * Private functions
101  */
102 /* Assure that `ts->tv_nsec' is in the range 0 .. 999999999 */
103 static void time_normalize(struct timespec *ts) /* {{{ */
104 {
105   while (ts->tv_nsec < 0) {
106     if (ts->tv_sec == 0) {
107       ts->tv_nsec = 0;
108       return;
109     }
110
111     ts->tv_sec -= 1;
112     ts->tv_nsec += 1000000000;
113   }
114
115   while (ts->tv_nsec >= 1000000000) {
116     ts->tv_sec += 1;
117     ts->tv_nsec -= 1000000000;
118   }
119 } /* }}} void time_normalize */
120
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);
130
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;
139   }
140
141   time_normalize(ts_dest);
142 } /* }}} void time_calc */
143
144 static int ping_dispatch_all(pingobj_t *pingobj) /* {{{ */
145 {
146   hostlist_t *hl;
147   int status;
148
149   for (pingobj_iter_t *iter = ping_iterator_get(pingobj); iter != NULL;
150        iter = ping_iterator_next(iter)) { /* {{{ */
151     char userhost[NI_MAXHOST];
152     double latency;
153     size_t param_size;
154
155     param_size = sizeof(userhost);
156     status = ping_iterator_get_info(iter,
157 #ifdef PING_INFO_USERNAME
158                                     PING_INFO_USERNAME,
159 #else
160                                     PING_INFO_HOSTNAME,
161 #endif
162                                     userhost, &param_size);
163     if (status != 0) {
164       WARNING("ping plugin: ping_iterator_get_info failed: %s",
165               ping_get_error(pingobj));
166       continue;
167     }
168
169     for (hl = hostlist_head; hl != NULL; hl = hl->next)
170       if (strcmp(userhost, hl->host) == 0)
171         break;
172
173     if (hl == NULL) {
174       WARNING("ping plugin: Cannot find host %s.", userhost);
175       continue;
176     }
177
178     param_size = sizeof(latency);
179     status = ping_iterator_get_info(iter, PING_INFO_LATENCY, (void *)&latency,
180                                     &param_size);
181     if (status != 0) {
182       WARNING("ping plugin: ping_iterator_get_info failed: %s",
183               ping_get_error(pingobj));
184       continue;
185     }
186
187     hl->pkg_sent++;
188     if (latency >= 0.0) {
189       hl->pkg_recv++;
190       hl->latency_total += latency;
191       hl->latency_squared += (latency * latency);
192
193       /* reset missed packages counter */
194       hl->pkg_missed = 0;
195     } else
196       hl->pkg_missed++;
197
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
203        * missed packages */
204       hl->pkg_missed = 0;
205
206       WARNING("ping plugin: host %s has not answered %d PING requests,"
207               " triggering resolve",
208               hl->host, ping_max_missed);
209
210       /* we trigger the resolv simply be removeing and adding the host to our
211        * ping object */
212       status = ping_host_remove(pingobj, hl->host);
213       if (status != 0) {
214         WARNING("ping plugin: ping_host_remove (%s) failed.", hl->host);
215       } else {
216         status = ping_host_add(pingobj, hl->host);
217         if (status != 0)
218           ERROR("ping plugin: ping_host_add (%s) failed.", hl->host);
219       }
220     } /* }}} ping_max_missed */
221   }   /* }}} for (iter) */
222
223   return 0;
224 } /* }}} int ping_dispatch_all */
225
226 static void *ping_thread(void *arg) /* {{{ */
227 {
228   struct timeval tv_begin;
229   struct timeval tv_end;
230   struct timespec ts_wait;
231   struct timespec ts_int;
232
233   int count;
234
235   c_complain_t complaint = C_COMPLAIN_INIT_STATIC;
236
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);
243     return (void *)-1;
244   }
245
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));
250   }
251
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));
256
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));
261 #endif
262
263   ping_setopt(pingobj, PING_OPT_TIMEOUT, (void *)&ping_timeout);
264   ping_setopt(pingobj, PING_OPT_TTL, (void *)&ping_ttl);
265
266   if (ping_data != NULL)
267     ping_setopt(pingobj, PING_OPT_DATA, (void *)ping_data);
268
269   /* Add all the hosts to the ping object. */
270   count = 0;
271   for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) {
272     int tmp_status;
273     tmp_status = ping_host_add(pingobj, hl->host);
274     if (tmp_status != 0)
275       WARNING("ping plugin: ping_host_add (%s) failed: %s", hl->host,
276               ping_get_error(pingobj));
277     else
278       count++;
279   }
280
281   if (count == 0) {
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);
286     return (void *)-1;
287   }
288
289   /* Set up `ts_int' */
290   {
291     double temp_sec;
292     double temp_nsec;
293
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);
297   }
298
299   pthread_mutex_lock(&ping_lock);
300   while (ping_thread_loop > 0) {
301     bool send_successful = false;
302
303     if (gettimeofday(&tv_begin, NULL) < 0) {
304       ERROR("ping plugin: gettimeofday failed: %s", STRERRNO);
305       ping_thread_error = 1;
306       break;
307     }
308
309     pthread_mutex_unlock(&ping_lock);
310
311     int status = ping_send(pingobj);
312     if (status < 0) {
313       c_complain(LOG_ERR, &complaint, "ping plugin: ping_send failed: %s",
314                  ping_get_error(pingobj));
315     } else {
316       c_release(LOG_NOTICE, &complaint, "ping plugin: ping_send succeeded.");
317       send_successful = true;
318     }
319
320     pthread_mutex_lock(&ping_lock);
321
322     if (ping_thread_loop <= 0)
323       break;
324
325     if (send_successful)
326       (void)ping_dispatch_all(pingobj);
327
328     if (gettimeofday(&tv_end, NULL) < 0) {
329       ERROR("ping plugin: gettimeofday failed: %s", STRERRNO);
330       ping_thread_error = 1;
331       break;
332     }
333
334     /* Calculate the absolute time until which to wait and store it in
335      * `ts_wait'. */
336     time_calc(&ts_wait, &ts_int, &tv_begin, &tv_end);
337
338     pthread_cond_timedwait(&ping_cond, &ping_lock, &ts_wait);
339     if (ping_thread_loop <= 0)
340       break;
341   } /* while (ping_thread_loop > 0) */
342
343   pthread_mutex_unlock(&ping_lock);
344   ping_destroy(pingobj);
345
346   return (void *)0;
347 } /* }}} void *ping_thread */
348
349 static int start_thread(void) /* {{{ */
350 {
351   int status;
352
353   pthread_mutex_lock(&ping_lock);
354
355   if (ping_thread_loop != 0) {
356     pthread_mutex_unlock(&ping_lock);
357     return 0;
358   }
359
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");
364   if (status != 0) {
365     ping_thread_loop = 0;
366     ERROR("ping plugin: Starting thread failed.");
367     pthread_mutex_unlock(&ping_lock);
368     return -1;
369   }
370
371   pthread_mutex_unlock(&ping_lock);
372   return 0;
373 } /* }}} int start_thread */
374
375 static int stop_thread(void) /* {{{ */
376 {
377   int status;
378
379   pthread_mutex_lock(&ping_lock);
380
381   if (ping_thread_loop == 0) {
382     pthread_mutex_unlock(&ping_lock);
383     return -1;
384   }
385
386   ping_thread_loop = 0;
387   pthread_cond_broadcast(&ping_cond);
388   pthread_mutex_unlock(&ping_lock);
389
390   status = pthread_join(ping_thread_id, /* return = */ NULL);
391   if (status != 0) {
392     ERROR("ping plugin: Stopping thread failed.");
393     status = -1;
394   }
395
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);
400
401   return status;
402 } /* }}} int stop_thread */
403
404 static int ping_init(void) /* {{{ */
405 {
406   if (hostlist_head == NULL) {
407     NOTICE("ping plugin: No hosts have been configured.");
408     return -1;
409   }
410
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.",
415             ping_timeout);
416   }
417
418 #if defined(HAVE_SYS_CAPABILITY_H) && defined(CAP_NET_RAW)
419   if (check_capability(CAP_NET_RAW) != 0) {
420     if (getuid() == 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?");
424     else
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.");
428   }
429 #endif
430
431   return start_thread();
432 } /* }}} int ping_init */
433
434 static int config_set_string(const char *name, /* {{{ */
435                              char **var, const char *value) {
436   char *tmp;
437
438   tmp = strdup(value);
439   if (tmp == NULL) {
440     ERROR("ping plugin: Setting `%s' to `%s' failed: strdup failed: %s", name,
441           value, STRERRNO);
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       ERROR("ping plugin: malloc failed: %s", STRERRNO);
460       return 1;
461     }
462
463     host = strdup(value);
464     if (host == NULL) {
465       sfree(hl);
466       ERROR("ping plugin: strdup failed: %s", STRERRNO);
467       return 1;
468     }
469
470     hl->host = host;
471     hl->pkg_sent = 0;
472     hl->pkg_recv = 0;
473     hl->pkg_missed = 0;
474     hl->latency_total = 0.0;
475     hl->latency_squared = 0.0;
476     hl->next = hostlist_head;
477     hostlist_head = hl;
478   } else if (strcasecmp(key, "AddressFamily") == 0) {
479     char *af = NULL;
480     int status = config_set_string(key, &af, value);
481     if (status != 0)
482       return status;
483
484     if (strncmp(af, "any", 3) == 0) {
485       ping_af = AF_UNSPEC;
486     } else if (strncmp(af, "ipv4", 4) == 0) {
487       ping_af = AF_INET;
488     } else if (strncmp(af, "ipv6", 4) == 0) {
489       ping_af = AF_INET6;
490     } else {
491       WARNING("ping plugin: Ignoring invalid AddressFamily value %s", af);
492     }
493     free(af);
494
495   } else if (strcasecmp(key, "SourceAddress") == 0) {
496     int status = config_set_string(key, &ping_source, value);
497     if (status != 0)
498       return status;
499   }
500 #ifdef HAVE_OPING_1_3
501   else if (strcasecmp(key, "Device") == 0) {
502     int status = config_set_string(key, &ping_device, value);
503     if (status != 0)
504       return status;
505   }
506 #endif
507   else if (strcasecmp(key, "TTL") == 0) {
508     int ttl = atoi(value);
509     if ((ttl > 0) && (ttl <= 255))
510       ping_ttl = ttl;
511     else
512       WARNING("ping plugin: Ignoring invalid TTL %i.", ttl);
513   } else if (strcasecmp(key, "Interval") == 0) {
514     double tmp;
515
516     tmp = atof(value);
517     if (tmp > 0.0)
518       ping_interval = tmp;
519     else
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);
523
524     /* Max IP packet size - (IPv6 + ICMP) = 65535 - (40 + 8) = 65487 */
525     if (size <= 65487) {
526       sfree(ping_data);
527       ping_data = malloc(size + 1);
528       if (ping_data == NULL) {
529         ERROR("ping plugin: malloc failed.");
530         return 1;
531       }
532
533       /* Note: By default oping is using constant string
534        * "liboping -- ICMP ping library <http://octo.it/liboping/>"
535        * which is exactly 56 bytes.
536        *
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++) /* {{{ */
541       {
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++) */
546       ping_data[size] = 0;
547     } else
548       WARNING("ping plugin: Ignoring invalid Size %" PRIsz ".", size);
549   } else if (strcasecmp(key, "Timeout") == 0) {
550     double tmp;
551
552     tmp = atof(value);
553     if (tmp > 0.0)
554       ping_timeout = tmp;
555     else
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");
561   } else {
562     return -1;
563   }
564
565   return 0;
566 } /* }}} int ping_config */
567
568 static void submit(const char *host, const char *type, /* {{{ */
569                    gauge_t value) {
570   value_list_t vl = VALUE_LIST_INIT;
571
572   vl.values = &(value_t){.gauge = value};
573   vl.values_len = 1;
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));
577
578   plugin_dispatch_values(&vl);
579 } /* }}} void ping_submit */
580
581 static int ping_read(void) /* {{{ */
582 {
583   if (ping_thread_error != 0) {
584     ERROR("ping plugin: The ping thread had a problem. Restarting it.");
585
586     stop_thread();
587
588     for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) {
589       hl->pkg_sent = 0;
590       hl->pkg_recv = 0;
591       hl->latency_total = 0.0;
592       hl->latency_squared = 0.0;
593     }
594
595     start_thread();
596
597     return -1;
598   } /* if (ping_thread_error != 0) */
599
600   for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
601   {
602     uint32_t pkg_sent;
603     uint32_t pkg_recv;
604     double latency_total;
605     double latency_squared;
606
607     double latency_average;
608     double latency_stddev;
609
610     double droprate;
611
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);
615
616     pkg_sent = hl->pkg_sent;
617     pkg_recv = hl->pkg_recv;
618     latency_total = hl->latency_total;
619     latency_squared = hl->latency_squared;
620
621     hl->pkg_sent = 0;
622     hl->pkg_recv = 0;
623     hl->latency_total = 0.0;
624     hl->latency_squared = 0.0;
625
626     pthread_mutex_unlock(&ping_lock);
627
628     /* This e. g. happens when starting up. */
629     if (pkg_sent == 0) {
630       DEBUG("ping plugin: No packages for host %s have been sent.", hl->host);
631       continue;
632     }
633
634     /* Calculate average. Beware of division by zero. */
635     if (pkg_recv == 0)
636       latency_average = NAN;
637     else
638       latency_average = latency_total / ((double)pkg_recv);
639
640     /* Calculate standard deviation. Beware even more of division by zero. */
641     if (pkg_recv == 0)
642       latency_stddev = NAN;
643     else if (pkg_recv == 1)
644       latency_stddev = 0.0;
645     else
646       latency_stddev = sqrt(((((double)pkg_recv) * latency_squared) -
647                              (latency_total * latency_total)) /
648                             ((double)(pkg_recv * (pkg_recv - 1))));
649
650     /* Calculate drop rate. */
651     droprate = ((double)(pkg_sent - pkg_recv)) / ((double)pkg_sent);
652
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) */
657
658   return 0;
659 } /* }}} int ping_read */
660
661 static int ping_shutdown(void) /* {{{ */
662 {
663   hostlist_t *hl;
664
665   INFO("ping plugin: Shutting down thread.");
666   if (stop_thread() < 0)
667     return -1;
668
669   hl = hostlist_head;
670   while (hl != NULL) {
671     hostlist_t *hl_next;
672
673     hl_next = hl->next;
674
675     sfree(hl->host);
676     sfree(hl);
677
678     hl = hl_next;
679   }
680
681   if (ping_data != NULL) {
682     free(ping_data);
683     ping_data = NULL;
684   }
685
686   return 0;
687 } /* }}} int ping_shutdown */
688
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 */