forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
routes_searcher_unix.go
64 lines (51 loc) · 1.47 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
// +build !windows
package net
import (
"regexp"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
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
}
func NewRoutesSearcher(runner boshsys.CmdRunner, _ InterfaceManager) RoutesSearcher {
return cmdRoutesSearcher{runner}
}
func parseRoute(ipString string) Route {
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)
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"],
}
}
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
}
routes = append(routes, parseRoute(routeEntry))
}
return routes, nil
}