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