net: add get reachable networks: fix sorter closure

argh, perl sorters and nested greps are weird!

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
This commit is contained in:
Thomas Lamprecht 2021-09-17 17:47:14 +02:00
parent d7cafe5124
commit 4e4059580a
2 changed files with 13 additions and 20 deletions

View File

@ -208,7 +208,7 @@ sub generate_usage_str {
my $str = '';
if (ref($def) eq 'HASH') {
my $oldclass = undef;
foreach my $cmd (&$sortfunc($def)) {
foreach my $cmd ($sortfunc->($def)) {
if (ref($def->{$cmd}) eq 'ARRAY') {
my ($class, $name, $arg_param, $fixed_param, undef, $formatter_properties) = @{$def->{$cmd}};

View File

@ -607,28 +607,21 @@ sub is_ip_in_cidr {
sub get_reachable_networks {
my $raw = '';
run_command([qw(ip -j addr show up scope global)], outfunc => sub { $raw .= shift });
my $addrs = decode_json($raw);
# sort by family (IPv4/IPv6) and then by addr, just for some stability
my $addrs_sorter = sub {
my ($a, $b) = @_;
my $family = $a->{family} cmp $b->{family};
return $family if $family != 0;
return $a->{local} cmp $b->{local};
};
my $decoded = decode_json($raw);
my $addrs = []; # filter/transform first so that we can sort correctly more easily below
for my $e ($decoded->@*) {
next if !$e->{addr_info} || grep { $_ eq 'LOOPBACK' } $e->{flags}->@*;
push $addrs->@*, grep { scalar(keys $_->%*) } $e->{addr_info}->@*
}
my $res = [];
for my $addr ($addrs->@*) {
next if !exists $addr->{addr_info};
next if grep { $_ eq 'LOOPBACK' } $addr->{flags}->@*;
for my $info (sort $addrs_sorter grep { $_ && $_->{local}} $addr->{addr_info}->@*) {
for my $info (sort { $a->{family} cmp $b->{family} || $a->{local} cmp $b->{local} } $addrs->@*) {
push $res->@*, {
addr => $info->{local},
cidr => "$info->{local}/$info->{prefixlen}",
family => $info->{family},
};
}
}
return $res;
}