forked from flannel-io/flannel
/
hostgw_network.go
221 lines (190 loc) · 5.56 KB
/
hostgw_network.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
// Copyright 2015 flannel authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package hostgw
import (
"bytes"
"net"
"sync"
"time"
log "github.com/golang/glog"
"github.com/vishvananda/netlink"
"golang.org/x/net/context"
"github.com/coreos/flannel/backend"
"github.com/coreos/flannel/subnet"
)
type network struct {
name string
extIface *backend.ExternalInterface
rl []netlink.Route
lease *subnet.Lease
sm subnet.Manager
}
func (n *network) Lease() *subnet.Lease {
return n.lease
}
func (n *network) MTU() int {
return n.extIface.Iface.MTU
}
func (n *network) LinkIndex() int {
return n.extIface.Iface.Index
}
func (n *network) Run(ctx context.Context) {
wg := sync.WaitGroup{}
log.Info("Watching for new subnet leases")
evts := make(chan []subnet.Event)
wg.Add(1)
go func() {
subnet.WatchLeases(ctx, n.sm, n.lease, evts)
wg.Done()
}()
// Store a list of routes, initialized to capacity of 10.
n.rl = make([]netlink.Route, 0, 10)
wg.Add(1)
// Start a goroutine which periodically checks that the right routes are created
go func() {
n.routeCheck(ctx)
wg.Done()
}()
defer wg.Wait()
for {
select {
case evtBatch := <-evts:
n.handleSubnetEvents(evtBatch)
case <-ctx.Done():
return
}
}
}
func (n *network) handleSubnetEvents(batch []subnet.Event) {
for _, evt := range batch {
switch evt.Type {
case subnet.EventAdded:
log.Infof("Subnet added: %v via %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
if evt.Lease.Attrs.BackendType != "host-gw" {
log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
continue
}
route := netlink.Route{
Dst: evt.Lease.Subnet.ToIPNet(),
Gw: evt.Lease.Attrs.PublicIP.ToIP(),
LinkIndex: n.LinkIndex(),
}
// Always add the route to the route list.
n.addToRouteList(route)
// Check if route exists before attempting to add it
routeList, err := netlink.RouteListFiltered(netlink.FAMILY_V4, &netlink.Route{
Dst: route.Dst,
}, netlink.RT_FILTER_DST)
if err != nil {
log.Warningf("Unable to list routes: %v", err)
}
// Check match on Dst for match on Gw
if len(routeList) > 0 && !routeList[0].Gw.Equal(route.Gw) {
// Same Dst different Gw. Remove it, correct route will be added below.
log.Warningf("Replacing existing route to %v via %v with %v via %v.", evt.Lease.Subnet, routeList[0].Gw, evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
if err := netlink.RouteDel(&routeList[0]); err != nil {
log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
continue
}
}
if len(routeList) > 0 && routeList[0].Gw.Equal(route.Gw) {
// Same Dst and same Gw, keep it and do not attempt to add it.
log.Infof("Route to %v via %v already exists, skipping.", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP)
} else if err := netlink.RouteAdd(&route); err != nil {
log.Errorf("Error adding route to %v via %v: %v", evt.Lease.Subnet, evt.Lease.Attrs.PublicIP, err)
continue
}
case subnet.EventRemoved:
log.Info("Subnet removed: ", evt.Lease.Subnet)
if evt.Lease.Attrs.BackendType != "host-gw" {
log.Warningf("Ignoring non-host-gw subnet: type=%v", evt.Lease.Attrs.BackendType)
continue
}
route := netlink.Route{
Dst: evt.Lease.Subnet.ToIPNet(),
Gw: evt.Lease.Attrs.PublicIP.ToIP(),
LinkIndex: n.LinkIndex(),
}
// Always remove the route from the route list.
n.removeFromRouteList(route)
if err := netlink.RouteDel(&route); err != nil {
log.Errorf("Error deleting route to %v: %v", evt.Lease.Subnet, err)
continue
}
default:
log.Error("Internal error: unknown event type: ", int(evt.Type))
}
}
}
func (n *network) addToRouteList(route netlink.Route) {
for _, r := range n.rl {
if routeEqual(r, route) {
return
}
}
n.rl = append(n.rl, route)
}
func (n *network) removeFromRouteList(route netlink.Route) {
for index, r := range n.rl {
if routeEqual(r, route) {
n.rl = append(n.rl[:index], n.rl[index+1:]...)
return
}
}
}
func (n *network) routeCheck(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case <-time.After(routeCheckRetries * time.Second):
n.checkSubnetExistInRoutes()
}
}
}
func (n *network) checkSubnetExistInRoutes() {
routeList, err := netlink.RouteList(nil, netlink.FAMILY_V4)
if err == nil {
for _, route := range n.rl {
exist := false
for _, r := range routeList {
if r.Dst == nil {
continue
}
if routeEqual(r, route) {
exist = true
break
}
}
if !exist {
if err := netlink.RouteAdd(&route); err != nil {
if nerr, ok := err.(net.Error); !ok {
log.Errorf("Error recovering route to %v: %v, %v", route.Dst, route.Gw, nerr)
}
continue
} else {
log.Infof("Route recovered %v : %v", route.Dst, route.Gw)
}
}
}
} else {
log.Errorf("Error fetching route list. Will automatically retry: %v", err)
}
}
func routeEqual(x, y netlink.Route) bool {
if x.Dst.IP.Equal(y.Dst.IP) && x.Gw.Equal(y.Gw) && bytes.Equal(x.Dst.Mask, y.Dst.Mask) {
return true
}
return false
}