2 * ifstat.c handy utility to read net interface statistics
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version
7 * 2 of the License, or (at your option) any later version.
9 * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
22 #include <sys/socket.h>
32 #include <linux/if_link.h>
34 #include "libnetlink.h"
35 #include "json_writer.h"
55 char info_source
[128];
58 #define MAXS (sizeof(struct rtnl_link_stats)/sizeof(__u32))
59 #define NO_SUB_TYPE 0xffff
62 struct ifstat_ent
*next
;
70 static const char *stats
[MAXS
] = {
90 "tx_heartbeat_errors",
96 struct ifstat_ent
*kern_db
;
97 struct ifstat_ent
*hist_db
;
99 static int match(const char *id
)
106 for (i
= 0; i
< npatterns
; i
++) {
107 if (!fnmatch(patterns
[i
], id
, 0))
113 static int get_nlmsg_extended(struct nlmsghdr
*m
, void *arg
)
115 struct if_stats_msg
*ifsm
= NLMSG_DATA(m
);
116 struct rtattr
*tb
[IFLA_STATS_MAX
+1];
117 int len
= m
->nlmsg_len
;
118 struct ifstat_ent
*n
;
120 if (m
->nlmsg_type
!= RTM_NEWSTATS
)
123 len
-= NLMSG_LENGTH(sizeof(*ifsm
));
127 parse_rtattr(tb
, IFLA_STATS_MAX
, IFLA_STATS_RTA(ifsm
), len
);
128 if (tb
[filter_type
] == NULL
)
131 n
= malloc(sizeof(*n
));
135 n
->ifindex
= ifsm
->ifindex
;
136 n
->name
= strdup(ll_index_to_name(ifsm
->ifindex
));
138 if (sub_type
== NO_SUB_TYPE
) {
139 memcpy(&n
->val
, RTA_DATA(tb
[filter_type
]), sizeof(n
->val
));
143 attr
= parse_rtattr_one_nested(sub_type
, tb
[filter_type
]);
148 memcpy(&n
->val
, RTA_DATA(attr
), sizeof(n
->val
));
150 memset(&n
->rate
, 0, sizeof(n
->rate
));
156 static int get_nlmsg(struct nlmsghdr
*m
, void *arg
)
158 struct ifinfomsg
*ifi
= NLMSG_DATA(m
);
159 struct rtattr
*tb
[IFLA_MAX
+1];
160 int len
= m
->nlmsg_len
;
161 struct ifstat_ent
*n
;
164 if (m
->nlmsg_type
!= RTM_NEWLINK
)
167 len
-= NLMSG_LENGTH(sizeof(*ifi
));
171 if (!(ifi
->ifi_flags
&IFF_UP
))
174 parse_rtattr(tb
, IFLA_MAX
, IFLA_RTA(ifi
), len
);
175 if (tb
[IFLA_IFNAME
] == NULL
|| tb
[IFLA_STATS
] == NULL
)
178 n
= malloc(sizeof(*n
));
181 n
->ifindex
= ifi
->ifi_index
;
182 n
->name
= strdup(RTA_DATA(tb
[IFLA_IFNAME
]));
183 memcpy(&n
->ival
, RTA_DATA(tb
[IFLA_STATS
]), sizeof(n
->ival
));
184 memset(&n
->rate
, 0, sizeof(n
->rate
));
185 for (i
= 0; i
< MAXS
; i
++)
186 n
->val
[i
] = n
->ival
[i
];
192 static void load_info(void)
194 struct ifstat_ent
*db
, *n
;
195 struct rtnl_handle rth
;
198 if (rtnl_open(&rth
, 0) < 0)
203 filter_mask
= IFLA_STATS_FILTER_BIT(filter_type
);
204 if (rtnl_statsdump_req_filter(&rth
, AF_UNSPEC
,
206 perror("Cannot send dump request");
210 if (rtnl_dump_filter(&rth
, get_nlmsg_extended
, NULL
) < 0) {
211 fprintf(stderr
, "Dump terminated\n");
215 if (rtnl_linkdump_req(&rth
, AF_INET
) < 0) {
216 perror("Cannot send dump request");
220 if (rtnl_dump_filter(&rth
, get_nlmsg
, NULL
) < 0) {
221 fprintf(stderr
, "Dump terminated\n");
239 static void load_raw_table(FILE *fp
)
242 struct ifstat_ent
*db
= NULL
;
243 struct ifstat_ent
*n
;
245 while (fgets(buf
, sizeof(buf
), fp
) != NULL
) {
251 buf
[strlen(buf
)-1] = 0;
252 if (info_source
[0] && strcmp(info_source
, buf
+1))
254 strncpy(info_source
, buf
+1, sizeof(info_source
)-1);
257 if ((n
= malloc(sizeof(*n
))) == NULL
)
260 if (!(p
= strchr(buf
, ' ')))
264 if (sscanf(buf
, "%d", &n
->ifindex
) != 1)
266 if (!(next
= strchr(p
, ' ')))
273 for (i
= 0; i
< MAXS
; i
++) {
276 if (!(next
= strchr(p
, ' ')))
279 if (sscanf(p
, "%llu", n
->val
+i
) != 1)
281 n
->ival
[i
] = (__u32
)n
->val
[i
];
283 if (!(next
= strchr(p
, ' ')))
286 if (sscanf(p
, "%u", &rate
) != 1)
303 static void dump_raw_db(FILE *fp
, int to_hist
)
305 json_writer_t
*jw
= json_output
? jsonw_new(fp
) : NULL
;
306 struct ifstat_ent
*n
, *h
;
310 jsonw_start_object(jw
);
311 jsonw_pretty(jw
, pretty
);
312 jsonw_name(jw
, info_source
);
313 jsonw_start_object(jw
);
315 fprintf(fp
, "#%s\n", info_source
);
317 for (n
= kern_db
; n
; n
= n
->next
) {
319 unsigned long long *vals
= n
->val
;
320 double *rates
= n
->rate
;
322 if (!match(n
->name
)) {
323 struct ifstat_ent
*h1
;
327 for (h1
= h
; h1
; h1
= h1
->next
) {
328 if (h1
->ifindex
== n
->ifindex
) {
338 jsonw_name(jw
, n
->name
);
339 jsonw_start_object(jw
);
341 for (i
= 0; i
< MAXS
&& stats
[i
]; i
++)
342 jsonw_uint_field(jw
, stats
[i
], vals
[i
]);
343 jsonw_end_object(jw
);
345 fprintf(fp
, "%d %s ", n
->ifindex
, n
->name
);
346 for (i
= 0; i
< MAXS
; i
++)
347 fprintf(fp
, "%llu %u ", vals
[i
],
348 (unsigned int)rates
[i
]);
353 jsonw_end_object(jw
);
355 jsonw_end_object(jw
);
360 /* use communication definitions of meg/kilo etc */
361 static const unsigned long long giga
= 1000000000ull;
362 static const unsigned long long mega
= 1000000;
363 static const unsigned long long kilo
= 1000;
365 static void format_rate(FILE *fp
, const unsigned long long *vals
,
366 const double *rates
, int i
)
371 fprintf(fp
, "%7lluM ", vals
[i
]/mega
);
372 else if (vals
[i
] > mega
)
373 fprintf(fp
, "%7lluK ", vals
[i
]/kilo
);
375 fprintf(fp
, "%8llu ", vals
[i
]);
377 if (rates
[i
] > mega
) {
378 sprintf(temp
, "%uM", (unsigned int)(rates
[i
]/mega
));
379 fprintf(fp
, "%-6s ", temp
);
380 } else if (rates
[i
] > kilo
) {
381 sprintf(temp
, "%uK", (unsigned int)(rates
[i
]/kilo
));
382 fprintf(fp
, "%-6s ", temp
);
384 fprintf(fp
, "%-6u ", (unsigned int)rates
[i
]);
387 static void format_pair(FILE *fp
, const unsigned long long *vals
, int i
, int k
)
392 fprintf(fp
, "%7lluM ", vals
[i
]/mega
);
393 else if (vals
[i
] > mega
)
394 fprintf(fp
, "%7lluK ", vals
[i
]/kilo
);
396 fprintf(fp
, "%8llu ", vals
[i
]);
398 if (vals
[k
] > giga
) {
399 sprintf(temp
, "%uM", (unsigned int)(vals
[k
]/mega
));
400 fprintf(fp
, "%-6s ", temp
);
401 } else if (vals
[k
] > mega
) {
402 sprintf(temp
, "%uK", (unsigned int)(vals
[k
]/kilo
));
403 fprintf(fp
, "%-6s ", temp
);
405 fprintf(fp
, "%-6u ", (unsigned int)vals
[k
]);
408 static void print_head(FILE *fp
)
410 fprintf(fp
, "#%s\n", info_source
);
411 fprintf(fp
, "%-15s ", "Interface");
413 fprintf(fp
, "%8s/%-6s ", "RX Pkts", "Rate");
414 fprintf(fp
, "%8s/%-6s ", "TX Pkts", "Rate");
415 fprintf(fp
, "%8s/%-6s ", "RX Data", "Rate");
416 fprintf(fp
, "%8s/%-6s\n", "TX Data", "Rate");
419 fprintf(fp
, "%-15s ", "");
420 fprintf(fp
, "%8s/%-6s ", "RX Errs", "Drop");
421 fprintf(fp
, "%8s/%-6s ", "TX Errs", "Drop");
422 fprintf(fp
, "%8s/%-6s ", "RX Over", "Rate");
423 fprintf(fp
, "%8s/%-6s\n", "TX Coll", "Rate");
425 fprintf(fp
, "%-15s ", "");
426 fprintf(fp
, "%8s/%-6s ", "RX Errs", "Rate");
427 fprintf(fp
, "%8s/%-6s ", "RX Drop", "Rate");
428 fprintf(fp
, "%8s/%-6s ", "RX Over", "Rate");
429 fprintf(fp
, "%8s/%-6s\n", "RX Leng", "Rate");
431 fprintf(fp
, "%-15s ", "");
432 fprintf(fp
, "%8s/%-6s ", "RX Crc", "Rate");
433 fprintf(fp
, "%8s/%-6s ", "RX Frm", "Rate");
434 fprintf(fp
, "%8s/%-6s ", "RX Fifo", "Rate");
435 fprintf(fp
, "%8s/%-6s\n", "RX Miss", "Rate");
437 fprintf(fp
, "%-15s ", "");
438 fprintf(fp
, "%8s/%-6s ", "TX Errs", "Rate");
439 fprintf(fp
, "%8s/%-6s ", "TX Drop", "Rate");
440 fprintf(fp
, "%8s/%-6s ", "TX Coll", "Rate");
441 fprintf(fp
, "%8s/%-6s\n", "TX Carr", "Rate");
443 fprintf(fp
, "%-15s ", "");
444 fprintf(fp
, "%8s/%-6s ", "TX Abrt", "Rate");
445 fprintf(fp
, "%8s/%-6s ", "TX Fifo", "Rate");
446 fprintf(fp
, "%8s/%-6s ", "TX Hear", "Rate");
447 fprintf(fp
, "%8s/%-6s\n", "TX Wind", "Rate");
451 static void print_one_json(json_writer_t
*jw
, const struct ifstat_ent
*n
,
452 const unsigned long long *vals
)
454 int i
, m
= show_errors
? 20 : 10;
456 jsonw_name(jw
, n
->name
);
457 jsonw_start_object(jw
);
459 for (i
= 0; i
< m
&& stats
[i
]; i
++)
460 jsonw_uint_field(jw
, stats
[i
], vals
[i
]);
462 jsonw_end_object(jw
);
465 static void print_one_if(FILE *fp
, const struct ifstat_ent
*n
,
466 const unsigned long long *vals
)
470 fprintf(fp
, "%-15s ", n
->name
);
471 for (i
= 0; i
< 4; i
++)
472 format_rate(fp
, vals
, n
->rate
, i
);
476 fprintf(fp
, "%-15s ", "");
477 format_pair(fp
, vals
, 4, 6);
478 format_pair(fp
, vals
, 5, 7);
479 format_rate(fp
, vals
, n
->rate
, 11);
480 format_rate(fp
, vals
, n
->rate
, 9);
483 fprintf(fp
, "%-15s ", "");
484 format_rate(fp
, vals
, n
->rate
, 4);
485 format_rate(fp
, vals
, n
->rate
, 6);
486 format_rate(fp
, vals
, n
->rate
, 11);
487 format_rate(fp
, vals
, n
->rate
, 10);
490 fprintf(fp
, "%-15s ", "");
491 format_rate(fp
, vals
, n
->rate
, 12);
492 format_rate(fp
, vals
, n
->rate
, 13);
493 format_rate(fp
, vals
, n
->rate
, 14);
494 format_rate(fp
, vals
, n
->rate
, 15);
497 fprintf(fp
, "%-15s ", "");
498 format_rate(fp
, vals
, n
->rate
, 5);
499 format_rate(fp
, vals
, n
->rate
, 7);
500 format_rate(fp
, vals
, n
->rate
, 9);
501 format_rate(fp
, vals
, n
->rate
, 17);
504 fprintf(fp
, "%-15s ", "");
505 format_rate(fp
, vals
, n
->rate
, 16);
506 format_rate(fp
, vals
, n
->rate
, 18);
507 format_rate(fp
, vals
, n
->rate
, 19);
508 format_rate(fp
, vals
, n
->rate
, 20);
513 static void dump_kern_db(FILE *fp
)
515 json_writer_t
*jw
= json_output
? jsonw_new(fp
) : NULL
;
516 struct ifstat_ent
*n
;
519 jsonw_start_object(jw
);
520 jsonw_pretty(jw
, pretty
);
521 jsonw_name(jw
, info_source
);
522 jsonw_start_object(jw
);
526 for (n
= kern_db
; n
; n
= n
->next
) {
531 print_one_json(jw
, n
, n
->val
);
533 print_one_if(fp
, n
, n
->val
);
536 jsonw_end_object(jw
);
538 jsonw_end_object(jw
);
543 static void dump_incr_db(FILE *fp
)
545 struct ifstat_ent
*n
, *h
;
546 json_writer_t
*jw
= json_output
? jsonw_new(fp
) : NULL
;
550 jsonw_start_object(jw
);
551 jsonw_pretty(jw
, pretty
);
552 jsonw_name(jw
, info_source
);
553 jsonw_start_object(jw
);
557 for (n
= kern_db
; n
; n
= n
->next
) {
559 unsigned long long vals
[MAXS
];
560 struct ifstat_ent
*h1
;
562 memcpy(vals
, n
->val
, sizeof(vals
));
564 for (h1
= h
; h1
; h1
= h1
->next
) {
565 if (h1
->ifindex
== n
->ifindex
) {
566 for (i
= 0; i
< MAXS
; i
++)
567 vals
[i
] -= h1
->val
[i
];
576 print_one_json(jw
, n
, n
->val
);
578 print_one_if(fp
, n
, vals
);
582 jsonw_end_object(jw
);
584 jsonw_end_object(jw
);
591 static void sigchild(int signo
)
595 static void update_db(int interval
)
597 struct ifstat_ent
*n
, *h
;
607 for (n
= kern_db
; n
; n
= n
->next
) {
608 struct ifstat_ent
*h1
;
610 for (h1
= h
; h1
; h1
= h1
->next
) {
611 if (h1
->ifindex
== n
->ifindex
) {
614 for (i
= 0; i
< MAXS
; i
++) {
615 if ((long)(h1
->ival
[i
] - n
->ival
[i
]) < 0) {
616 memset(n
->ival
, 0, sizeof(n
->ival
));
620 for (i
= 0; i
< MAXS
; i
++) {
625 incr
= h1
->val
[i
] - n
->val
[i
];
626 n
->val
[i
] = h1
->val
[i
];
628 incr
= (__u32
) (h1
->ival
[i
] - n
->ival
[i
]);
630 n
->ival
[i
] = h1
->ival
[i
];
633 sample
= (double)(incr
*1000)/interval
;
634 if (interval
>= scan_interval
) {
635 n
->rate
[i
] += W
*(sample
-n
->rate
[i
]);
636 } else if (interval
>= 1000) {
637 if (interval
>= time_constant
) {
640 double w
= W
*(double)interval
/scan_interval
;
642 n
->rate
[i
] += w
*(sample
-n
->rate
[i
]);
648 struct ifstat_ent
*tmp
= h
;
663 #define T_DIFF(a, b) (((a).tv_sec-(b).tv_sec)*1000 + ((a).tv_usec-(b).tv_usec)/1000)
666 static void server_loop(int fd
)
668 struct timeval snaptime
= { 0 };
672 p
.events
= p
.revents
= POLLIN
;
674 sprintf(info_source
, "%d.%lu sampling_interval=%d time_const=%d",
675 getpid(), (unsigned long)random(), scan_interval
/1000, time_constant
/1000);
684 gettimeofday(&now
, NULL
);
685 tdiff
= T_DIFF(now
, snaptime
);
686 if (tdiff
>= scan_interval
) {
692 if (poll(&p
, 1, scan_interval
- tdiff
) > 0
693 && (p
.revents
&POLLIN
)) {
694 int clnt
= accept(fd
, NULL
, NULL
);
701 } else if ((pid
= fork()) != 0) {
706 FILE *fp
= fdopen(clnt
, "w");
714 while (children
&& waitpid(-1, &status
, WNOHANG
) > 0)
719 static int verify_forging(int fd
)
722 socklen_t olen
= sizeof(cred
);
724 if (getsockopt(fd
, SOL_SOCKET
, SO_PEERCRED
, (void *)&cred
, &olen
) ||
727 if (cred
.uid
== getuid() || cred
.uid
== 0)
732 static void xstat_usage(void)
735 "Usage: ifstat supported xstats:\n"
736 " cpu_hits Counts only packets that went via the CPU.\n");
739 struct extended_stats_options_t
{
745 /* Note: if one xstat name is subset of another, it should be before it in this
747 * Name length must be under 64 chars.
749 static const struct extended_stats_options_t extended_stats_options
[] = {
750 {"cpu_hits", IFLA_STATS_LINK_OFFLOAD_XSTATS
, IFLA_OFFLOAD_XSTATS_CPU_HIT
},
753 static const char *get_filter_type(const char *name
)
758 name_len
= strlen(name
);
759 for (i
= 0; i
< ARRAY_SIZE(extended_stats_options
); i
++) {
760 const struct extended_stats_options_t
*xstat
;
762 xstat
= &extended_stats_options
[i
];
763 if (strncmp(name
, xstat
->name
, name_len
) == 0) {
764 filter_type
= xstat
->id
;
765 sub_type
= xstat
->sub_type
;
770 fprintf(stderr
, "invalid ifstat extension %s\n", name
);
775 static void usage(void) __attribute__((noreturn
));
777 static void usage(void)
780 "Usage: ifstat [OPTION] [ PATTERN [ PATTERN ] ]\n"
781 " -h, --help this message\n"
782 " -a, --ignore ignore history\n"
783 " -d, --scan=SECS sample every statistics every SECS\n"
784 " -e, --errors show errors\n"
785 " -j, --json format output in JSON\n"
786 " -n, --nooutput do history only\n"
787 " -p, --pretty pretty print\n"
788 " -r, --reset reset history\n"
789 " -s, --noupdate don't update history\n"
790 " -t, --interval=SECS report average over the last SECS\n"
791 " -V, --version output version information\n"
792 " -z, --zeros show entries with zero activity\n"
793 " -x, --extended=TYPE show extended stats of TYPE\n");
798 static const struct option longopts
[] = {
799 { "help", 0, 0, 'h' },
800 { "ignore", 0, 0, 'a' },
801 { "scan", 1, 0, 'd'},
802 { "errors", 0, 0, 'e' },
803 { "nooutput", 0, 0, 'n' },
804 { "json", 0, 0, 'j' },
805 { "reset", 0, 0, 'r' },
806 { "pretty", 0, 0, 'p' },
807 { "noupdate", 0, 0, 's' },
808 { "interval", 1, 0, 't' },
809 { "version", 0, 0, 'V' },
810 { "zeros", 0, 0, 'z' },
811 { "extended", 1, 0, 'x'},
815 int main(int argc
, char *argv
[])
818 struct sockaddr_un sun
;
819 FILE *hist_fp
= NULL
;
820 const char *stats_type
= NULL
;
825 while ((ch
= getopt_long(argc
, argv
, "hjpvVzrnasd:t:ex:",
826 longopts
, NULL
)) != EOF
) {
853 scan_interval
= atoi(optarg
) * 1000;
854 if (scan_interval
<= 0) {
855 fprintf(stderr
, "ifstat: invalid scan interval\n");
860 time_constant
= atoi(optarg
);
861 if (time_constant
<= 0) {
862 fprintf(stderr
, "ifstat: invalid time constant divisor\n");
872 printf("ifstat utility, iproute2-ss%s\n", SNAPSHOT
);
885 stats_type
= get_filter_type(stats_type
);
890 sun
.sun_family
= AF_UNIX
;
892 sprintf(sun
.sun_path
+1, "ifstat%d", getuid());
894 if (scan_interval
> 0) {
895 if (time_constant
== 0)
897 time_constant
*= 1000;
898 W
= 1 - 1/exp(log(10)*(double)scan_interval
/time_constant
);
899 if ((fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) < 0) {
900 perror("ifstat: socket");
903 if (bind(fd
, (struct sockaddr
*)&sun
, 2+1+strlen(sun
.sun_path
+1)) < 0) {
904 perror("ifstat: bind");
907 if (listen(fd
, 5) < 0) {
908 perror("ifstat: listen");
912 perror("ifstat: daemon");
915 signal(SIGPIPE
, SIG_IGN
);
916 signal(SIGCHLD
, sigchild
);
924 if (getenv("IFSTAT_HISTORY"))
925 snprintf(hist_name
, sizeof(hist_name
),
926 "%s", getenv("IFSTAT_HISTORY"));
929 snprintf(hist_name
, sizeof(hist_name
),
930 "%s/.ifstat.u%d", P_tmpdir
, getuid());
932 snprintf(hist_name
, sizeof(hist_name
),
933 "%s/.%s_ifstat.u%d", P_tmpdir
, stats_type
,
939 if (!ignore_history
|| !no_update
) {
942 fd
= open(hist_name
, O_RDWR
|O_CREAT
|O_NOFOLLOW
, 0600);
944 perror("ifstat: open history file");
947 if ((hist_fp
= fdopen(fd
, "r+")) == NULL
) {
948 perror("ifstat: fdopen history file");
951 if (flock(fileno(hist_fp
), LOCK_EX
)) {
952 perror("ifstat: flock history file");
955 if (fstat(fileno(hist_fp
), &stb
) != 0) {
956 perror("ifstat: fstat history file");
959 if (stb
.st_nlink
!= 1 || stb
.st_uid
!= getuid()) {
960 fprintf(stderr
, "ifstat: something is so wrong with history file, that I prefer not to proceed.\n");
963 if (!ignore_history
) {
967 if ((tfp
= fopen("/proc/uptime", "r")) != NULL
) {
968 if (fscanf(tfp
, "%ld", &uptime
) != 1)
972 if (uptime
>= 0 && time(NULL
) >= stb
.st_mtime
+uptime
) {
973 fprintf(stderr
, "ifstat: history is aged out, resetting\n");
974 if (ftruncate(fileno(hist_fp
), 0))
975 perror("ifstat: ftruncate");
979 load_raw_table(hist_fp
);
985 if ((fd
= socket(AF_UNIX
, SOCK_STREAM
, 0)) >= 0 &&
986 (connect(fd
, (struct sockaddr
*)&sun
, 2+1+strlen(sun
.sun_path
+1)) == 0
987 || (strcpy(sun
.sun_path
+1, "ifstat0"),
988 connect(fd
, (struct sockaddr
*)&sun
, 2+1+strlen(sun
.sun_path
+1)) == 0))
989 && verify_forging(fd
) == 0) {
990 FILE *sfp
= fdopen(fd
, "r");
993 fprintf(stderr
, "ifstat: fdopen failed: %s\n",
998 if (hist_db
&& source_mismatch
) {
999 fprintf(stderr
, "ifstat: history is stale, ignoring it.\n");
1007 if (hist_db
&& info_source
[0] && strcmp(info_source
, "kernel")) {
1008 fprintf(stderr
, "ifstat: history is stale, ignoring it.\n");
1013 if (info_source
[0] == 0)
1014 strcpy(info_source
, "kernel");
1018 if (ignore_history
|| hist_db
== NULL
)
1019 dump_kern_db(stdout
);
1021 dump_incr_db(stdout
);
1025 if (ftruncate(fileno(hist_fp
), 0))
1026 perror("ifstat: ftruncate");
1030 dump_raw_db(hist_fp
, 1);