-
Notifications
You must be signed in to change notification settings - Fork 464
/
pbr.go
76 lines (63 loc) · 2.14 KB
/
pbr.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
package routing
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"strings"
"github.com/cloudnativelabs/kube-router/pkg/utils"
)
// setup a custom routing table that will be used for policy based routing to ensure traffic originating
// on tunnel interface only leaves through tunnel interface irrespective rp_filter enabled/disabled
func (nrc *NetworkRoutingController) enablePolicyBasedRouting() error {
err := rtTablesAdd(customRouteTableID, customRouteTableName)
if err != nil {
return fmt.Errorf("failed to update rt_tables file: %s", err)
}
out, err := exec.Command("ip", "rule", "list").Output()
if err != nil {
return fmt.Errorf("failed to verify if `ip rule` exists: %s", err.Error())
}
if !strings.Contains(string(out), nrc.podCidr) {
err = exec.Command("ip", "rule", "add", "from", nrc.podCidr, "lookup", customRouteTableID).Run()
if err != nil {
return fmt.Errorf("failed to add ip rule due to: %s", err.Error())
}
}
return nil
}
func (nrc *NetworkRoutingController) disablePolicyBasedRouting() error {
err := rtTablesAdd(customRouteTableID, customRouteTableName)
if err != nil {
return fmt.Errorf("failed to update rt_tables file: %s", err)
}
out, err := exec.Command("ip", "rule", "list").Output()
if err != nil {
return fmt.Errorf("failed to verify if `ip rule` exists: %s",
err.Error())
}
if strings.Contains(string(out), nrc.podCidr) {
err = exec.Command("ip", "rule", "del", "from", nrc.podCidr, "table", customRouteTableID).Run()
if err != nil {
return fmt.Errorf("failed to delete ip rule: %s", err.Error())
}
}
return nil
}
func rtTablesAdd(tableNumber, tableName string) error {
b, err := ioutil.ReadFile("/etc/iproute2/rt_tables")
if err != nil {
return fmt.Errorf("failed to read: %s", err.Error())
}
if !strings.Contains(string(b), tableName) {
f, err := os.OpenFile("/etc/iproute2/rt_tables", os.O_APPEND|os.O_WRONLY, 0600)
if err != nil {
return fmt.Errorf("failed to open: %s", err.Error())
}
defer utils.CloseCloserDisregardError(f)
if _, err = f.WriteString(tableNumber + " " + tableName + "\n"); err != nil {
return fmt.Errorf("failed to write: %s", err.Error())
}
}
return nil
}