netutils2: replace GetRoutes with netlink call

This commit is contained in:
Yousong Zhou
2020-01-16 20:47:50 +08:00
parent 1a5f6ee0f6
commit 5cd60db1b4
3 changed files with 24 additions and 41 deletions
-24
View File
@@ -19,7 +19,6 @@ import (
"fmt"
"net"
"reflect"
"regexp"
"strconv"
"strings"
"unicode"
@@ -32,7 +31,6 @@ import (
"yunion.io/x/onecloud/pkg/cloudcommon/types"
"yunion.io/x/onecloud/pkg/util/procutils"
"yunion.io/x/onecloud/pkg/util/regutils2"
)
var PSEUDO_VIP = "169.254.169.231"
@@ -370,28 +368,6 @@ func GetSecretInterfaceAddress() (string, int) {
return addr, SECRET_MASK_LEN
}
func (n *SNetInterface) GetRoutes(gwOnly bool) [][]string {
output, err := procutils.NewCommand("route", "-n").Output()
if err != nil {
return nil
}
return n.getRoutes(gwOnly, strings.Split(string(output), "\n"))
}
func (n *SNetInterface) getRoutes(gwOnly bool, outputs []string) [][]string {
re := regexp.MustCompile(`(?P<dest>[0-9.]+)\s+(?P<gw>[0-9.]+)\s+(?P<mask>[0-9.]+)` +
`\s+[A-Z!]+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+` + n.name)
var res [][]string = make([][]string, 0)
for _, line := range outputs {
m := regutils2.GetParams(re, line)
if len(m) > 0 && (!gwOnly || m["gw"] != "0.0.0.0") {
res = append(res, []string{m["dest"], m["gw"], m["mask"]})
}
}
return res
}
func (n *SNetInterface) GetSlaveAddresses() [][]string {
addrs := n.GetAddresses()
var slaves = make([][]string, 0)
+24
View File
@@ -30,6 +30,30 @@ func (n *SNetInterface) GetAddresses() [][]string {
return r
}
func (n *SNetInterface) GetRoutes(gwOnly bool) [][]string {
rs, err := iproute2.NewRoute(n.name).List4()
if err != nil {
return nil
}
res := [][]string{}
for i := range rs {
r := &rs[i]
ok := true
if masklen, _ := r.Dst.Mask.Size(); gwOnly && masklen != 0 {
ok = false
}
if ok {
res = append(res, []string{
r.Dst.IP.String(),
r.Gw.String(),
net.IP(r.Dst.Mask).String(),
})
}
}
return res
}
func DefaultSrcIpDev() (srcIp net.IP, ifname string, err error) {
destIp := net.ParseIP("114.114.114.114")
routes, err := netlink.RouteGet(destIp)
-17
View File
@@ -15,26 +15,9 @@
package netutils2
import (
"reflect"
"testing"
)
func TestSNetInterface_getRoutes(t *testing.T) {
n := SNetInterface{name: "br0"}
routes := []string{"Kernel IP routing table",
"Destination Gateway Genmask Flags Metric Ref Use Iface",
"0.0.0.0 10.168.222.1 0.0.0.0 UG 0 0 0 br0",
"10.168.222.0 0.0.0.0 255.255.255.0 U 0 0 0 br0",
"169.254.169.254 10.168.222.1 255.255.255.255 UGH 0 0 0 br0",
""}
want := [][]string{{"0.0.0.0", "10.168.222.1", "0.0.0.0"}, {"169.254.169.254", "10.168.222.1", "255.255.255.255"}}
if got := n.getRoutes(true, routes); !reflect.DeepEqual(got, want) {
t.Errorf("getParams() = %v, want %v", got, want)
}
}
func TestNetlen2Mask(t *testing.T) {
type args struct {
netmasklen int