Function to check if a network overlaps with existing routes
This commit is contained in:
1 parent
8e04b135bb
commit
8285046962
2 files changed
+53
No files matched your search
@@ -0,0 +1,28 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
"github.com/vishvananda/netlink"
|
||||
)
|
||||
|
||||
// A network is considered free if it does not overlap any existing
|
||||
// routes on this host. This is the same approach taken by Docker.
|
||||
func CheckNetworkFree(subnet *net.IPNet) error {
|
||||
routes, err := netlink.RouteList(nil, netlink.FAMILY_V4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, route := range routes {
|
||||
if route.Dst != nil && overlaps(route.Dst, subnet) {
|
||||
return fmt.Errorf("network %s would overlap with route %s", subnet, route.Dst)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Two networks overlap if the start-point of one is inside the other.
|
||||
func overlaps(n1, n2 *net.IPNet) bool {
|
||||
return n1.Contains(n2.IP) || n2.Contains(n1.IP)
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package net
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
wt "github.com/weaveworks/weave/testing"
|
||||
)
|
||||
|
||||
func TestOverlap(t *testing.T) {
|
||||
_, subnet1, _ := net.ParseCIDR("10.0.3.0/24")
|
||||
_, subnet2, _ := net.ParseCIDR("10.0.4.0/24")
|
||||
_, subnet3, _ := net.ParseCIDR("10.0.3.128/25")
|
||||
_, subnet4, _ := net.ParseCIDR("10.0.3.192/25")
|
||||
_, universe, _ := net.ParseCIDR("10.0.0.0/8")
|
||||
wt.AssertEquals(t, overlaps(subnet1, subnet2), false)
|
||||
wt.AssertEquals(t, overlaps(subnet2, subnet1), false)
|
||||
wt.AssertEquals(t, overlaps(subnet1, subnet1), true)
|
||||
wt.AssertEquals(t, overlaps(subnet1, subnet3), true)
|
||||
wt.AssertEquals(t, overlaps(subnet1, subnet4), true)
|
||||
wt.AssertEquals(t, overlaps(subnet2, subnet4), false)
|
||||
wt.AssertEquals(t, overlaps(subnet4, subnet2), false)
|
||||
wt.AssertEquals(t, overlaps(universe, subnet1), true)
|
||||
wt.AssertEquals(t, overlaps(subnet1, universe), true)
|
||||
}
|
||||
Reference in new issue
Block a user