Merge branch 'collectd-4.10' into collectd-5.0
[collectd.git] / src / netlink.c
1 /**
2  * collectd - src/netlink.c
3  * Copyright (C) 2007-2010  Florian octo Forster
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the
7  * Free Software Foundation; only version 2 of the License is applicable.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
17  *
18  * Authors:
19  *   Florian octo Forster <octo at collectd.org>
20  **/
21
22 #include "collectd.h"
23 #include "plugin.h"
24 #include "common.h"
25
26 #include <asm/types.h>
27 #include <sys/socket.h>
28
29 #include <linux/netlink.h>
30 #include <linux/rtnetlink.h>
31 #if HAVE_LINUX_GEN_STATS_H
32 # include <linux/gen_stats.h>
33 #endif
34 #if HAVE_LINUX_PKT_SCHED_H
35 # include <linux/pkt_sched.h>
36 #endif
37
38 #if HAVE_LIBNETLINK_H
39 # include <libnetlink.h>
40 #elif HAVE_IPROUTE_LIBNETLINK_H
41 # include <iproute/libnetlink.h>
42 #elif HAVE_LINUX_LIBNETLINK_H
43 # include <linux/libnetlink.h>
44 #endif
45
46 typedef struct ir_ignorelist_s
47 {
48   char *device;
49   char *type;
50   char *inst;
51   struct ir_ignorelist_s *next;
52 } ir_ignorelist_t;
53
54 static int ir_ignorelist_invert = 1;
55 static ir_ignorelist_t *ir_ignorelist_head = NULL;
56
57 static struct rtnl_handle rth;
58
59 static char **iflist = NULL;
60 static size_t iflist_len = 0;
61
62 static const char *config_keys[] =
63 {
64         "Interface",
65         "VerboseInterface",
66         "QDisc",
67         "Class",
68         "Filter",
69         "IgnoreSelected"
70 };
71 static int config_keys_num = STATIC_ARRAY_SIZE (config_keys);
72
73 static int add_ignorelist (const char *dev, const char *type,
74     const char *inst)
75 {
76   ir_ignorelist_t *entry;
77
78   entry = (ir_ignorelist_t *) malloc (sizeof (ir_ignorelist_t));
79   if (entry == NULL)
80     return (-1);
81
82   memset (entry, '\0', sizeof (ir_ignorelist_t));
83
84   if (strcasecmp (dev, "All") != 0)
85   {
86     entry->device = strdup (dev);
87     if (entry->device == NULL)
88     {
89       sfree (entry);
90       return (-1);
91     }
92   }
93
94   entry->type = strdup (type);
95   if (entry->type == NULL)
96   {
97     sfree (entry->device);
98     sfree (entry);
99     return (-1);
100   }
101
102   if (inst != NULL)
103   {
104     entry->inst = strdup (inst);
105     if (entry->inst == NULL)
106     {
107       sfree (entry->type);
108       sfree (entry->device);
109       sfree (entry);
110       return (-1);
111     }
112   }
113
114   entry->next = ir_ignorelist_head;
115   ir_ignorelist_head = entry;
116
117   return (0);
118 } /* int add_ignorelist */
119
120 /* 
121  * Checks wether a data set should be ignored. Returns `true' is the value
122  * should be ignored, `false' otherwise.
123  */
124 static int check_ignorelist (const char *dev,
125     const char *type, const char *type_instance)
126 {
127   ir_ignorelist_t *i;
128
129   assert ((dev != NULL) && (type != NULL));
130
131   if (ir_ignorelist_head == NULL)
132     return (ir_ignorelist_invert ? 0 : 1);
133
134   for (i = ir_ignorelist_head; i != NULL; i = i->next)
135   {
136     /* i->device == NULL  =>  match all devices */
137     if ((i->device != NULL)
138         && (strcasecmp (i->device, dev) != 0))
139       continue;
140
141     if (strcasecmp (i->type, type) != 0)
142       continue;
143
144     if ((i->inst != NULL) && (type_instance != NULL)
145         && (strcasecmp (i->inst, type_instance) != 0))
146       continue;
147
148     DEBUG ("netlink plugin: check_ignorelist: "
149         "(dev = %s; type = %s; inst = %s) matched "
150         "(dev = %s; type = %s; inst = %s)",
151         dev, type,
152         type_instance == NULL ? "(nil)" : type_instance,
153         i->device == NULL ? "(nil)" : i->device,
154         i->type,
155         i->inst == NULL ? "(nil)" : i->inst);
156
157     return (ir_ignorelist_invert ? 0 : 1);
158   } /* for i */
159
160   return (ir_ignorelist_invert);
161 } /* int check_ignorelist */
162
163 static void submit_one (const char *dev, const char *type,
164     const char *type_instance, derive_t value)
165 {
166   value_t values[1];
167   value_list_t vl = VALUE_LIST_INIT;
168
169   values[0].derive = value;
170
171   vl.values = values;
172   vl.values_len = 1;
173   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
174   sstrncpy (vl.plugin, "netlink", sizeof (vl.plugin));
175   sstrncpy (vl.plugin_instance, dev, sizeof (vl.plugin_instance));
176   sstrncpy (vl.type, type, sizeof (vl.type));
177
178   if (type_instance != NULL)
179     sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
180
181   plugin_dispatch_values (&vl);
182 } /* void submit_one */
183
184 static void submit_two (const char *dev, const char *type,
185     const char *type_instance,
186     derive_t rx, derive_t tx)
187 {
188   value_t values[2];
189   value_list_t vl = VALUE_LIST_INIT;
190
191   values[0].derive = rx;
192   values[1].derive = tx;
193
194   vl.values = values;
195   vl.values_len = 2;
196   sstrncpy (vl.host, hostname_g, sizeof (vl.host));
197   sstrncpy (vl.plugin, "netlink", sizeof (vl.plugin));
198   sstrncpy (vl.plugin_instance, dev, sizeof (vl.plugin_instance));
199   sstrncpy (vl.type, type, sizeof (vl.type));
200
201   if (type_instance != NULL)
202     sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance));
203
204   plugin_dispatch_values (&vl);
205 } /* void submit_two */
206
207 static int link_filter (const struct sockaddr_nl __attribute__((unused)) *sa,
208     struct nlmsghdr *nmh, void __attribute__((unused)) *args)
209 {
210   struct ifinfomsg *msg;
211   int msg_len;
212   struct rtattr *attrs[IFLA_MAX + 1];
213   struct rtnl_link_stats *stats;
214
215   const char *dev;
216
217   if (nmh->nlmsg_type != RTM_NEWLINK)
218   {
219     ERROR ("netlink plugin: link_filter: Don't know how to handle type %i.",
220         nmh->nlmsg_type);
221     return (-1);
222   }
223
224   msg = NLMSG_DATA (nmh);
225
226   msg_len = nmh->nlmsg_len - NLMSG_LENGTH(sizeof (struct ifinfomsg));
227   if (msg_len < 0)
228   {
229     ERROR ("netlink plugin: link_filter: msg_len = %i < 0;", msg_len);
230     return (-1);
231   }
232
233   memset (attrs, '\0', sizeof (attrs));
234   if (parse_rtattr (attrs, IFLA_MAX, IFLA_RTA (msg), msg_len) != 0)
235   {
236     ERROR ("netlink plugin: link_filter: parse_rtattr failed.");
237     return (-1);
238   }
239
240   if (attrs[IFLA_IFNAME] == NULL)
241   {
242     ERROR ("netlink plugin: link_filter: attrs[IFLA_IFNAME] == NULL");
243     return (-1);
244   }
245   dev = RTA_DATA (attrs[IFLA_IFNAME]);
246
247   /* Update the `iflist'. It's used to know which interfaces exist and query
248    * them later for qdiscs and classes. */
249   if ((msg->ifi_index >= 0) && ((size_t) msg->ifi_index >= iflist_len))
250   {
251     char **temp;
252
253     temp = (char **) realloc (iflist, (msg->ifi_index + 1) * sizeof (char *));
254     if (temp == NULL)
255     {
256       ERROR ("netlink plugin: link_filter: realloc failed.");
257       return (-1);
258     }
259
260     memset (temp + iflist_len, '\0',
261         (msg->ifi_index + 1 - iflist_len) * sizeof (char *));
262     iflist = temp;
263     iflist_len = msg->ifi_index + 1;
264   }
265   if ((iflist[msg->ifi_index] == NULL)
266       || (strcmp (iflist[msg->ifi_index], dev) != 0))
267   {
268     sfree (iflist[msg->ifi_index]);
269     iflist[msg->ifi_index] = strdup (dev);
270   }
271
272   if (attrs[IFLA_STATS] == NULL)
273   {
274     DEBUG ("netlink plugin: link_filter: No statistics for interface %s.", dev);
275     return (0);
276   }
277   stats = RTA_DATA (attrs[IFLA_STATS]);
278
279   if (check_ignorelist (dev, "interface", NULL) == 0)
280   {
281     submit_two (dev, "if_octets", NULL, stats->rx_bytes, stats->tx_bytes);
282     submit_two (dev, "if_packets", NULL, stats->rx_packets, stats->tx_packets);
283     submit_two (dev, "if_errors", NULL, stats->rx_errors, stats->tx_errors);
284   }
285   else
286   {
287     DEBUG ("netlink plugin: Ignoring %s/interface.", dev);
288   }
289
290   if (check_ignorelist (dev, "if_detail", NULL) == 0)
291   {
292     submit_two (dev, "if_dropped", NULL, stats->rx_dropped, stats->tx_dropped);
293     submit_one (dev, "if_multicast", NULL, stats->multicast);
294     submit_one (dev, "if_collisions", NULL, stats->collisions);
295
296     submit_one (dev, "if_rx_errors", "length", stats->rx_length_errors);
297     submit_one (dev, "if_rx_errors", "over", stats->rx_over_errors);
298     submit_one (dev, "if_rx_errors", "crc", stats->rx_crc_errors);
299     submit_one (dev, "if_rx_errors", "frame", stats->rx_frame_errors);
300     submit_one (dev, "if_rx_errors", "fifo", stats->rx_fifo_errors);
301     submit_one (dev, "if_rx_errors", "missed", stats->rx_missed_errors);
302
303     submit_one (dev, "if_tx_errors", "aborted", stats->tx_aborted_errors);
304     submit_one (dev, "if_tx_errors", "carrier", stats->tx_carrier_errors);
305     submit_one (dev, "if_tx_errors", "fifo", stats->tx_fifo_errors);
306     submit_one (dev, "if_tx_errors", "heartbeat", stats->tx_heartbeat_errors);
307     submit_one (dev, "if_tx_errors", "window", stats->tx_window_errors);
308   }
309   else
310   {
311     DEBUG ("netlink plugin: Ignoring %s/if_detail.", dev);
312   }
313
314   return (0);
315 } /* int link_filter */
316
317 static int qos_filter (const struct sockaddr_nl __attribute__((unused)) *sa,
318     struct nlmsghdr *nmh, void *args)
319 {
320   struct tcmsg *msg;
321   int msg_len;
322   struct rtattr *attrs[TCA_MAX + 1];
323
324   int wanted_ifindex = *((int *) args);
325
326   const char *dev;
327
328   /* char *type_instance; */
329   char *tc_type;
330   char tc_inst[DATA_MAX_NAME_LEN];
331
332   if (nmh->nlmsg_type == RTM_NEWQDISC)
333     tc_type = "qdisc";
334   else if (nmh->nlmsg_type == RTM_NEWTCLASS)
335     tc_type = "class";
336   else if (nmh->nlmsg_type == RTM_NEWTFILTER)
337     tc_type = "filter";
338   else
339   {
340     ERROR ("netlink plugin: qos_filter: Don't know how to handle type %i.",
341         nmh->nlmsg_type);
342     return (-1);
343   }
344
345   msg = NLMSG_DATA (nmh);
346
347   msg_len = nmh->nlmsg_len - sizeof (struct tcmsg);
348   if (msg_len < 0)
349   {
350     ERROR ("netlink plugin: qos_filter: msg_len = %i < 0;", msg_len);
351     return (-1);
352   }
353
354   if (msg->tcm_ifindex != wanted_ifindex)
355   {
356     DEBUG ("netlink plugin: qos_filter: Got %s for interface #%i, "
357         "but expected #%i.",
358         tc_type, msg->tcm_ifindex, wanted_ifindex);
359     return (0);
360   }
361
362   if ((msg->tcm_ifindex >= 0)
363       && ((size_t) msg->tcm_ifindex >= iflist_len))
364   {
365     ERROR ("netlink plugin: qos_filter: msg->tcm_ifindex = %i "
366         ">= iflist_len = %zu",
367         msg->tcm_ifindex, iflist_len);
368     return (-1);
369   }
370
371   dev = iflist[msg->tcm_ifindex];
372   if (dev == NULL)
373   {
374     ERROR ("netlink plugin: qos_filter: iflist[%i] == NULL",
375         msg->tcm_ifindex);
376     return (-1);
377   }
378
379   memset (attrs, '\0', sizeof (attrs));
380   if (parse_rtattr (attrs, TCA_MAX, TCA_RTA (msg), msg_len) != 0)
381   {
382     ERROR ("netlink plugin: qos_filter: parse_rtattr failed.");
383     return (-1);
384   }
385
386   if (attrs[TCA_KIND] == NULL)
387   {
388     ERROR ("netlink plugin: qos_filter: attrs[TCA_KIND] == NULL");
389     return (-1);
390   }
391
392   { /* The the ID */
393     uint32_t numberic_id;
394
395     numberic_id = msg->tcm_handle;
396     if (strcmp (tc_type, "filter") == 0)
397       numberic_id = msg->tcm_parent;
398
399     ssnprintf (tc_inst, sizeof (tc_inst), "%s-%x:%x",
400         (const char *) RTA_DATA (attrs[TCA_KIND]),
401         numberic_id >> 16,
402         numberic_id & 0x0000FFFF);
403   }
404
405   DEBUG ("netlink plugin: qos_filter: got %s for %s (%i).",
406       tc_type, dev, msg->tcm_ifindex);
407   
408   if (check_ignorelist (dev, tc_type, tc_inst))
409     return (0);
410
411 #if HAVE_TCA_STATS2
412   if (attrs[TCA_STATS2])
413   {
414     struct rtattr *attrs_stats[TCA_STATS_MAX + 1];
415
416     memset (attrs_stats, '\0', sizeof (attrs_stats));
417     parse_rtattr_nested (attrs_stats, TCA_STATS_MAX, attrs[TCA_STATS2]);
418
419     if (attrs_stats[TCA_STATS_BASIC])
420     {
421       struct gnet_stats_basic bs;
422       char type_instance[DATA_MAX_NAME_LEN];
423
424       ssnprintf (type_instance, sizeof (type_instance), "%s-%s",
425           tc_type, tc_inst);
426
427       memset (&bs, '\0', sizeof (bs));
428       memcpy (&bs, RTA_DATA (attrs_stats[TCA_STATS_BASIC]),
429           MIN (RTA_PAYLOAD (attrs_stats[TCA_STATS_BASIC]), sizeof(bs)));
430
431       submit_one (dev, "ipt_bytes", type_instance, bs.bytes);
432       submit_one (dev, "ipt_packets", type_instance, bs.packets);
433     }
434   }
435 #endif /* TCA_STATS2 */
436 #if HAVE_TCA_STATS && HAVE_TCA_STATS2
437   else
438 #endif
439 #if HAVE_TCA_STATS
440   if (attrs[TCA_STATS] != NULL)
441   {
442     struct tc_stats ts;
443     char type_instance[DATA_MAX_NAME_LEN];
444
445     ssnprintf (type_instance, sizeof (type_instance), "%s-%s",
446         tc_type, tc_inst);
447
448     memset(&ts, '\0', sizeof (ts));
449     memcpy(&ts, RTA_DATA (attrs[TCA_STATS]),
450         MIN (RTA_PAYLOAD (attrs[TCA_STATS]), sizeof (ts)));
451
452     submit_one (dev, "ipt_bytes", type_instance, ts.bytes);
453     submit_one (dev, "ipt_packets", type_instance, ts.packets);
454   }
455 #endif /* TCA_STATS */
456 #if HAVE_TCA_STATS || HAVE_TCA_STATS2
457   else
458 #endif
459   {
460     DEBUG ("netlink plugin: qos_filter: Have neither TCA_STATS2 nor "
461         "TCA_STATS.");
462   }
463
464   return (0);
465 } /* int qos_filter */
466
467 static int ir_config (const char *key, const char *value)
468 {
469   char *new_val;
470   char *fields[8];
471   int fields_num;
472   int status = 1;
473
474   new_val = strdup (value);
475   if (new_val == NULL)
476     return (-1);
477
478   fields_num = strsplit (new_val, fields, STATIC_ARRAY_SIZE (fields));
479   if ((fields_num < 1) || (fields_num > 8))
480   {
481     sfree (new_val);
482     return (-1);
483   }
484
485   if ((strcasecmp (key, "Interface") == 0)
486       || (strcasecmp (key, "VerboseInterface") == 0))
487   {
488     if (fields_num != 1)
489     {
490       ERROR ("netlink plugin: Invalid number of fields for option "
491           "`%s'. Got %i, expected 1.", key, fields_num);
492       status = -1;
493     }
494     else
495     {
496       add_ignorelist (fields[0], "interface", NULL);
497       if (strcasecmp (key, "VerboseInterface") == 0)
498         add_ignorelist (fields[0], "if_detail", NULL);
499       status = 0;
500     }
501   }
502   else if ((strcasecmp (key, "QDisc") == 0)
503       || (strcasecmp (key, "Class") == 0)
504       || (strcasecmp (key, "Filter") == 0))
505   {
506     if ((fields_num < 1) || (fields_num > 2))
507     {
508       ERROR ("netlink plugin: Invalid number of fields for option "
509           "`%s'. Got %i, expected 1 or 2.", key, fields_num);
510       return (-1);
511     }
512     else
513     {
514       add_ignorelist (fields[0], key,
515           (fields_num == 2) ? fields[1] : NULL);
516       status = 0;
517     }
518   }
519   else if (strcasecmp (key, "IgnoreSelected") == 0)
520   {
521     if (fields_num != 1)
522     {
523       ERROR ("netlink plugin: Invalid number of fields for option "
524           "`IgnoreSelected'. Got %i, expected 1.", fields_num);
525       status = -1;
526     }
527     else
528     {
529       if (IS_TRUE (fields[0]))
530         ir_ignorelist_invert = 0;
531       else
532         ir_ignorelist_invert = 1;
533       status = 0;
534     }
535   }
536
537   sfree (new_val);
538
539   return (status);
540 } /* int ir_config */
541
542 static int ir_init (void)
543 {
544   memset (&rth, '\0', sizeof (rth));
545
546   if (rtnl_open (&rth, 0) != 0)
547   {
548     ERROR ("netlink plugin: ir_init: rtnl_open failed.");
549     return (-1);
550   }
551
552   return (0);
553 } /* int ir_init */
554
555 static int ir_read (void)
556 {
557   struct tcmsg tm;
558   int ifindex;
559
560   static const int type_id[] = { RTM_GETQDISC, RTM_GETTCLASS, RTM_GETTFILTER };
561   static const char *type_name[] = { "qdisc", "class", "filter" };
562
563   if (rtnl_wilddump_request (&rth, AF_UNSPEC, RTM_GETLINK) < 0)
564   {
565     ERROR ("netlink plugin: ir_read: rtnl_wilddump_request failed.");
566     return (-1);
567   }
568
569 #ifdef RTNL_DUMP_FILTER_FIVE_ARGS
570   if (rtnl_dump_filter (&rth, link_filter, /* arg1 = */ NULL,
571         NULL, NULL) != 0)
572 #elif defined(RTNL_DUMP_FILTER_THREE_ARGS)
573   if (rtnl_dump_filter (&rth, link_filter, /* arg = */ NULL) != 0)
574 #else
575 #error "Failed to determine the number of arguments to 'rtnl_dump_filter'!"
576 #endif
577   {
578     ERROR ("netlink plugin: ir_read: rtnl_dump_filter failed.");
579     return (-1);
580   }
581
582   /* `link_filter' will update `iflist' which is used here to iterate over all
583    * interfaces. */
584   for (ifindex = 0; (size_t) ifindex < iflist_len; ifindex++)
585   {
586     size_t type_index;
587
588     if (iflist[ifindex] == NULL)
589       continue;
590
591     for (type_index = 0; type_index < STATIC_ARRAY_SIZE (type_id); type_index++)
592     {
593       if (check_ignorelist (iflist[ifindex], type_name[type_index], NULL))
594       {
595         DEBUG ("netlink plugin: ir_read: check_ignorelist (%s, %s, (nil)) "
596             "== TRUE", iflist[ifindex], type_name[type_index]);
597         continue;
598       }
599
600       DEBUG ("netlink plugin: ir_read: querying %s from %s (%i).",
601           type_name[type_index], iflist[ifindex], ifindex);
602
603       memset (&tm, '\0', sizeof (tm));
604       tm.tcm_family = AF_UNSPEC;
605       tm.tcm_ifindex = ifindex;
606
607       if (rtnl_dump_request (&rth, type_id[type_index], &tm, sizeof (tm)) < 0)
608       {
609         ERROR ("netlink plugin: ir_read: rtnl_dump_request failed.");
610         continue;
611       }
612
613 #ifdef RTNL_DUMP_FILTER_FIVE_ARGS
614       if (rtnl_dump_filter (&rth, qos_filter, (void *) &ifindex,
615             NULL, NULL) != 0)
616 #elif defined(RTNL_DUMP_FILTER_THREE_ARGS)
617       if (rtnl_dump_filter (&rth, qos_filter, /* arg = */ &ifindex) != 0)
618 #else
619 #error "Failed to determine the number of arguments to 'rtnl_dump_filter'!"
620 #endif
621       {
622         ERROR ("netlink plugin: ir_read: rtnl_dump_filter failed.");
623         continue;
624       }
625     } /* for (type_index) */
626   } /* for (if_index) */
627
628   return (0);
629 } /* int ir_read */
630
631 static int ir_shutdown (void)
632 {
633   if ((rth.fd != 0) || (rth.seq != 0) || (rth.dump != 0))
634   {
635     rtnl_close(&rth);
636     memset (&rth, '\0', sizeof (rth));
637   }
638   
639   return (0);
640 } /* int ir_shutdown */
641
642 void module_register (void)
643 {
644   plugin_register_config ("netlink", ir_config, config_keys, config_keys_num);
645   plugin_register_init ("netlink", ir_init);
646   plugin_register_read ("netlink", ir_read);
647   plugin_register_shutdown ("netlink", ir_shutdown);
648 } /* void module_register */
649
650 /*
651  * vim: set shiftwidth=2 softtabstop=2 tabstop=8 :
652  */