-
Notifications
You must be signed in to change notification settings - Fork 115
/
routes_searcher_unix.go
77 lines (64 loc) · 1.84 KB
/
routes_searcher_unix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// +build !windows
package net
import (
"regexp"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
// cmdRoutesSearcher uses `route -n` command to list routes
// which routes in a same format on Ubuntu and CentOS
type cmdRoutesSearcher struct {
runner boshsys.CmdRunner
logger boshlog.Logger
}
func NewRoutesSearcher(logger boshlog.Logger, runner boshsys.CmdRunner, _ InterfaceManager) RoutesSearcher {
return cmdRoutesSearcher{
runner: runner,
logger: logger,
}
}
func parseRoute(ipString string) (Route, error) {
var r = regexp.MustCompile(`(?P<destination>[a-z0-9.]+)(/[0-9]+)?( via (?P<gateway>[0-9.]+))? dev (?P<interfaceName>[a-z0-9]+)`)
match := r.FindStringSubmatch(ipString)
if len(match) == 0 {
return Route{}, bosherr.Error("unexpected route")
}
matches := make(map[string]string)
for i, name := range r.SubexpNames() {
matches[name] = match[i]
}
gateway := DefaultAddress
if len(matches["gateway"]) > 0 {
gateway = matches["gateway"]
}
destination := matches["destination"]
if destination == "default" {
destination = DefaultAddress
}
return Route{
Destination: destination,
Gateway: gateway,
InterfaceName: matches["interfaceName"],
}, nil
}
func (s cmdRoutesSearcher) SearchRoutes() ([]Route, error) {
var routes []Route
stdout, _, _, err := s.runner.RunCommandQuietly("ip", "r")
if err != nil {
return routes, bosherr.WrapError(err, "Running route")
}
for _, routeEntry := range strings.Split(stdout, "\n") {
if len(routeEntry) == 0 {
continue
}
route, err := parseRoute(routeEntry)
if err != nil {
s.logger.Warn("SearchRoutes", "parseRoute error for route '%s': %s", routeEntry, err.Error())
continue
}
routes = append(routes, route)
}
return routes, nil
}