ping plugin: reformat
[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 int ping_af = PING_DEF_AF;
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 != 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 = 0;
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 = 1;
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       ERROR("ping plugin: Bad address family: %s", af);
492       free(af);
493       return 1;
494     }
495     free(af);
496
497   } else if (strcasecmp(key, "SourceAddress") == 0) {
498     int status = config_set_string(key, &ping_source, value);
499     if (status != 0)
500       return status;
501   }
502 #ifdef HAVE_OPING_1_3
503   else if (strcasecmp(key, "Device") == 0) {
504     int status = config_set_string(key, &ping_device, value);
505     if (status != 0)
506       return status;
507   }
508 #endif
509   else if (strcasecmp(key, "TTL") == 0) {
510     int ttl = atoi(value);
511     if ((ttl > 0) && (ttl <= 255))
512       ping_ttl = ttl;
513     else
514       WARNING("ping plugin: Ignoring invalid TTL %i.", ttl);
515   } else if (strcasecmp(key, "Interval") == 0) {
516     double tmp;
517
518     tmp = atof(value);
519     if (tmp > 0.0)
520       ping_interval = tmp;
521     else
522       WARNING("ping plugin: Ignoring invalid interval %g (%s)", tmp, value);
523   } else if (strcasecmp(key, "Size") == 0) {
524     size_t size = (size_t)atoi(value);
525
526     /* Max IP packet size - (IPv6 + ICMP) = 65535 - (40 + 8) = 65487 */
527     if (size <= 65487) {
528       sfree(ping_data);
529       ping_data = malloc(size + 1);
530       if (ping_data == NULL) {
531         ERROR("ping plugin: malloc failed.");
532         return 1;
533       }
534
535       /* Note: By default oping is using constant string
536        * "liboping -- ICMP ping library <http://octo.it/liboping/>"
537        * which is exactly 56 bytes.
538        *
539        * Optimally we would follow the ping(1) behaviour, but we
540        * cannot use byte 00 or start data payload at exactly same
541        * location, due to oping library limitations. */
542       for (size_t i = 0; i < size; i++) /* {{{ */
543       {
544         /* This restricts data pattern to be only composed of easily
545          * printable characters, and not NUL character. */
546         ping_data[i] = ('0' + i % 64);
547       } /* }}} for (i = 0; i < size; i++) */
548       ping_data[size] = 0;
549     } else
550       WARNING("ping plugin: Ignoring invalid Size %" PRIsz ".", size);
551   } else if (strcasecmp(key, "Timeout") == 0) {
552     double tmp;
553
554     tmp = atof(value);
555     if (tmp > 0.0)
556       ping_timeout = tmp;
557     else
558       WARNING("ping plugin: Ignoring invalid timeout %g (%s)", tmp, value);
559   } else if (strcasecmp(key, "MaxMissed") == 0) {
560     ping_max_missed = atoi(value);
561     if (ping_max_missed < 0)
562       INFO("ping plugin: MaxMissed < 0, disabled re-resolving of hosts");
563   } else {
564     return -1;
565   }
566
567   return 0;
568 } /* }}} int ping_config */
569
570 static void submit(const char *host, const char *type, /* {{{ */
571                    gauge_t value) {
572   value_list_t vl = VALUE_LIST_INIT;
573
574   vl.values = &(value_t){.gauge = value};
575   vl.values_len = 1;
576   sstrncpy(vl.plugin, "ping", sizeof(vl.plugin));
577   sstrncpy(vl.type_instance, host, sizeof(vl.type_instance));
578   sstrncpy(vl.type, type, sizeof(vl.type));
579
580   plugin_dispatch_values(&vl);
581 } /* }}} void ping_submit */
582
583 static int ping_read(void) /* {{{ */
584 {
585   if (ping_thread_error != 0) {
586     ERROR("ping plugin: The ping thread had a problem. Restarting it.");
587
588     stop_thread();
589
590     for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) {
591       hl->pkg_sent = 0;
592       hl->pkg_recv = 0;
593       hl->latency_total = 0.0;
594       hl->latency_squared = 0.0;
595     }
596
597     start_thread();
598
599     return -1;
600   } /* if (ping_thread_error != 0) */
601
602   for (hostlist_t *hl = hostlist_head; hl != NULL; hl = hl->next) /* {{{ */
603   {
604     uint32_t pkg_sent;
605     uint32_t pkg_recv;
606     double latency_total;
607     double latency_squared;
608
609     double latency_average;
610     double latency_stddev;
611
612     double droprate;
613
614     /* Locking here works, because the structure of the linked list is only
615      * changed during configure and shutdown. */
616     pthread_mutex_lock(&ping_lock);
617
618     pkg_sent = hl->pkg_sent;
619     pkg_recv = hl->pkg_recv;
620     latency_total = hl->latency_total;
621     latency_squared = hl->latency_squared;
622
623     hl->pkg_sent = 0;
624     hl->pkg_recv = 0;
625     hl->latency_total = 0.0;
626     hl->latency_squared = 0.0;
627
628     pthread_mutex_unlock(&ping_lock);
629
630     /* This e. g. happens when starting up. */
631     if (pkg_sent == 0) {
632       DEBUG("ping plugin: No packages for host %s have been sent.", hl->host);
633       continue;
634     }
635
636     /* Calculate average. Beware of division by zero. */
637     if (pkg_recv == 0)
638       latency_average = NAN;
639     else
640       latency_average = latency_total / ((double)pkg_recv);
641
642     /* Calculate standard deviation. Beware even more of division by zero. */
643     if (pkg_recv == 0)
644       latency_stddev = NAN;
645     else if (pkg_recv == 1)
646       latency_stddev = 0.0;
647     else
648       latency_stddev = sqrt(((((double)pkg_recv) * latency_squared) -
649                              (latency_total * latency_total)) /
650                             ((double)(pkg_recv * (pkg_recv - 1))));
651
652     /* Calculate drop rate. */
653     droprate = ((double)(pkg_sent - pkg_recv)) / ((double)pkg_sent);
654
655     submit(hl->host, "ping", latency_average);
656     submit(hl->host, "ping_stddev", latency_stddev);
657     submit(hl->host, "ping_droprate", droprate);
658   } /* }}} for (hl = hostlist_head; hl != NULL; hl = hl->next) */
659
660   return 0;
661 } /* }}} int ping_read */
662
663 static int ping_shutdown(void) /* {{{ */
664 {
665   hostlist_t *hl;
666
667   INFO("ping plugin: Shutting down thread.");
668   if (stop_thread() < 0)
669     return -1;
670
671   hl = hostlist_head;
672   while (hl != NULL) {
673     hostlist_t *hl_next;
674
675     hl_next = hl->next;
676
677     sfree(hl->host);
678     sfree(hl);
679
680     hl = hl_next;
681   }
682
683   if (ping_data != NULL) {
684     free(ping_data);
685     ping_data = NULL;
686   }
687
688   return 0;
689 } /* }}} int ping_shutdown */
690
691 void module_register(void) {
692   plugin_register_config("ping", ping_config, config_keys, config_keys_num);
693   plugin_register_init("ping", ping_init);
694   plugin_register_read("ping", ping_read);
695   plugin_register_shutdown("ping", ping_shutdown);
696 } /* void module_register */