Skip to content

Commit

Permalink
feat: add a way to filter list of IPs for the machine
Browse files Browse the repository at this point in the history
This will be used to filter out SideroLink IPs on Talos side.

Signed-off-by: Andrey Smirnov <andrey.smirnov@talos-systems.com>
  • Loading branch information
smira committed Nov 29, 2021
1 parent 0abe5bd commit b4b7181
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 0 deletions.
29 changes: 29 additions & 0 deletions net.go
Expand Up @@ -41,6 +41,35 @@ func IPAddrs() (ips []net.IP, err error) {
return ips, nil
}

// IPFilterFunc filters IP addresses.
//
// List of IPFilterFuncs is applied with AND logic: all filters should return true
// for the IP address to be included in the response.
type IPFilterFunc func(ip net.IP) bool

// IPFilter filters list of IP addresses by applying sequence of filters.
//
// If any of the filters returns false, address is skipped.
func IPFilter(addrs []net.IP, filters ...IPFilterFunc) (result []net.IP) {
for _, addr := range addrs {
skip := false

for _, filter := range filters {
if !filter(addr) {
skip = true

break
}
}

if !skip {
result = append(result, addr)
}
}

return result
}

// FormatAddress checks that the address has a consistent format.
func FormatAddress(addr string) string {
addr = strings.Trim(addr, "[]")
Expand Down
66 changes: 66 additions & 0 deletions net_test.go
Expand Up @@ -272,3 +272,69 @@ func TestFilterIPs(t *testing.T) {
})
}
}

func TestIPFilter(t *testing.T) {
t.Parallel()

for _, tt := range []struct { //nolint:govet
name string
ips []string
filters []talosnet.IPFilterFunc
expected string
}{
{
name: "no filters",
ips: []string{
"10.3.4.6",
"2001:db8::1",
},
expected: "[10.3.4.6 2001:db8::1]",
},
{
name: "even",
ips: []string{
"10.3.4.6",
"10.3.4.1",
"172.20.0.1",
"2001:db8::1",
"2001:db8::2",
},
filters: []talosnet.IPFilterFunc{
func(addr net.IP) bool { return addr[len(addr)-1]%2 == 0 },
},
expected: "[10.3.4.6 2001:db8::2]",
},
{
name: "even and not v6",
ips: []string{
"10.3.4.6",
"10.3.4.1",
"172.20.0.1",
"2001:db8::2",
},
filters: []talosnet.IPFilterFunc{
func(addr net.IP) bool { return addr[len(addr)-1]%2 == 0 },
func(addr net.IP) bool { return addr.To4() != nil },
},
expected: "[10.3.4.6]",
},
} {
tt := tt

t.Run(tt.name, func(t *testing.T) {
t.Parallel()

ips := make([]net.IP, len(tt.ips))

for i := range ips {
ips[i] = net.ParseIP(tt.ips[i])

require.NotNil(t, ips[i])
}

result := talosnet.IPFilter(ips, tt.filters...)

assert.Equal(t, tt.expected, fmt.Sprintf("%s", result))
})
}
}

0 comments on commit b4b7181

Please sign in to comment.