[PATCH ethtool-next 2/5] stats: factor out one stat field printing

From: Alexander Lobakin
Date: Tue Aug 03 2021 - 12:52:20 EST


Move the code that takes one stat field nlattr, validates and prints
it in either stdout or JSON, into a separate function.
It will later be reused by per-channel statistics printing.

Signed-off-by: Alexander Lobakin <alexandr.lobakin@xxxxxxxxx>
Reviewed-by: Jesse Brandeburg <jesse.brandeburg@xxxxxxxxx>
---
netlink/stats.c | 53 +++++++++++++++++++++++++++++++------------------
1 file changed, 34 insertions(+), 19 deletions(-)

diff --git a/netlink/stats.c b/netlink/stats.c
index 9f609a4ec550..9d950b77d656 100644
--- a/netlink/stats.c
+++ b/netlink/stats.c
@@ -87,6 +87,36 @@ err_close_rmon:
return 1;
}

+static int parse_stat(const struct nlattr *attr, const char *grp_name,
+ const struct stringset *stat_str)
+{
+ const struct nlattr *stat;
+ unsigned long long val;
+ const char *name;
+ unsigned int s;
+ int ret;
+
+ stat = mnl_attr_get_payload(attr);
+ ret = mnl_attr_validate(stat, MNL_TYPE_U64);
+ if (ret) {
+ fprintf(stderr, "invalid kernel response - bad statistic entry\n");
+ return 1;
+ }
+
+ s = mnl_attr_get_type(stat);
+ name = get_string(stat_str, s);
+ if (!name || !name[0])
+ return 0;
+
+ if (!is_json_context())
+ fprintf(stdout, "%s-%s: ", grp_name, name);
+
+ val = mnl_attr_get_u64(stat);
+ print_u64(PRINT_ANY, name, "%llu\n", val);
+
+ return 0;
+}
+
static int parse_grp(struct nl_context *nlctx, const struct nlattr *grp,
const struct stringset *std_str)
{
@@ -94,10 +124,9 @@ static int parse_grp(struct nl_context *nlctx, const struct nlattr *grp,
DECLARE_ATTR_TB_INFO(tb);
bool hist_rx = false, hist_tx = false;
const struct stringset *stat_str;
- const struct nlattr *attr, *stat;
- const char *std_name, *name;
- unsigned int ss_id, id, s;
- unsigned long long val;
+ const struct nlattr *attr;
+ unsigned int ss_id, id;
+ const char *std_name;
int ret;

ret = mnl_attr_parse_nested(grp, attr_cb, &tb_info);
@@ -131,22 +160,8 @@ static int parse_grp(struct nl_context *nlctx, const struct nlattr *grp,
continue;
}

- stat = mnl_attr_get_payload(attr);
- ret = mnl_attr_validate(stat, MNL_TYPE_U64);
- if (ret) {
- fprintf(stderr, "invalid kernel response - bad statistic entry\n");
+ if (parse_stat(attr, NULL, std_name, stat_str))
goto err_close_grp;
- }
- s = mnl_attr_get_type(stat);
- name = get_string(stat_str, s);
- if (!name || !name[0])
- continue;
-
- if (!is_json_context())
- fprintf(stdout, "%s-%s: ", std_name, name);
-
- val = mnl_attr_get_u64(stat);
- print_u64(PRINT_ANY, name, "%llu\n", val);
}

if (hist_rx)
--
2.31.1