forked from flannel-io/flannel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
vxlan.go
358 lines (298 loc) · 8.63 KB
/
vxlan.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// Copyright 2015 CoreOS, Inc.
//
// 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 vxlan
import (
"bytes"
"encoding/json"
"fmt"
"net"
"sync"
"time"
log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
"github.com/coreos/flannel/Godeps/_workspace/src/github.com/vishvananda/netlink"
"github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
"github.com/coreos/flannel/backend"
"github.com/coreos/flannel/pkg/ip"
"github.com/coreos/flannel/subnet"
)
const (
defaultVNI = 1
)
type VXLANBackend struct {
sm subnet.Manager
network string
config *subnet.Config
cfg struct {
VNI int
Port int
}
lease *subnet.Lease
dev *vxlanDevice
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
rts routes
}
func New(sm subnet.Manager, network string, config *subnet.Config) backend.Backend {
ctx, cancel := context.WithCancel(context.Background())
vb := &VXLANBackend{
sm: sm,
network: network,
config: config,
ctx: ctx,
cancel: cancel,
}
vb.cfg.VNI = defaultVNI
return vb
}
func newSubnetAttrs(extEaddr net.IP, mac net.HardwareAddr) (*subnet.LeaseAttrs, error) {
data, err := json.Marshal(&vxlanLeaseAttrs{hardwareAddr(mac)})
if err != nil {
return nil, err
}
return &subnet.LeaseAttrs{
PublicIP: ip.FromIP(extEaddr),
BackendType: "vxlan",
BackendData: json.RawMessage(data),
}, nil
}
func (vb *VXLANBackend) Init(extIface *net.Interface, extIaddr net.IP, extEaddr net.IP) (*backend.SubnetDef, error) {
// Parse our configuration
if len(vb.config.Backend) > 0 {
if err := json.Unmarshal(vb.config.Backend, &vb.cfg); err != nil {
return nil, fmt.Errorf("error decoding VXLAN backend config: %v", err)
}
}
devAttrs := vxlanDeviceAttrs{
vni: uint32(vb.cfg.VNI),
name: fmt.Sprintf("flannel.%v", vb.cfg.VNI),
vtepIndex: extIface.Index,
vtepAddr: extIaddr,
vtepPort: vb.cfg.Port,
}
var err error
for {
vb.dev, err = newVXLANDevice(&devAttrs)
if err == nil {
break
} else {
log.Error("VXLAN init: ", err)
log.Info("Retrying in 1 second...")
// wait 1 sec before retrying
time.Sleep(1 * time.Second)
}
}
sa, err := newSubnetAttrs(extEaddr, vb.dev.MACAddr())
if err != nil {
return nil, err
}
l, err := vb.sm.AcquireLease(vb.ctx, vb.network, sa)
switch err {
case nil:
vb.lease = l
case context.Canceled, context.DeadlineExceeded:
return nil, err
default:
return nil, fmt.Errorf("failed to acquire lease: %v", err)
}
// vxlan's subnet is that of the whole overlay network (e.g. /16)
// and not that of the individual host (e.g. /24)
vxlanNet := ip.IP4Net{
IP: l.Subnet.IP,
PrefixLen: vb.config.Network.PrefixLen,
}
if err = vb.dev.Configure(vxlanNet); err != nil {
return nil, err
}
return &backend.SubnetDef{
Net: l.Subnet,
MTU: vb.dev.MTU(),
}, nil
}
func (vb *VXLANBackend) Run() {
vb.wg.Add(1)
go func() {
subnet.LeaseRenewer(vb.ctx, vb.sm, vb.network, vb.lease)
log.Info("LeaseRenewer exited")
vb.wg.Done()
}()
log.Info("Watching for L3 misses")
misses := make(chan *netlink.Neigh, 100)
// Unfrtunately MonitorMisses does not take a cancel channel
// as there's no wait to interrupt netlink socket recv
go vb.dev.MonitorMisses(misses)
log.Info("Watching for new subnet leases")
evts := make(chan []subnet.Event)
vb.wg.Add(1)
go func() {
subnet.WatchLeases(vb.ctx, vb.sm, vb.network, vb.lease, evts)
log.Info("WatchLeases exited")
vb.wg.Done()
}()
defer vb.wg.Wait()
initialEvtsBatch := <-evts
for {
err := vb.handleInitialSubnetEvents(initialEvtsBatch)
if err == nil {
break
}
log.Error(err, " About to retry")
time.Sleep(time.Second)
}
for {
select {
case miss := <-misses:
vb.handleMiss(miss)
case evtBatch := <-evts:
vb.handleSubnetEvents(evtBatch)
case <-vb.ctx.Done():
return
}
}
}
func (vb *VXLANBackend) Stop() {
vb.cancel()
}
func (vb *VXLANBackend) Name() string {
return "VXLAN"
}
// So we can make it JSON (un)marshalable
type hardwareAddr net.HardwareAddr
func (hw hardwareAddr) MarshalJSON() ([]byte, error) {
return []byte(fmt.Sprintf("%q", net.HardwareAddr(hw))), nil
}
func (hw *hardwareAddr) UnmarshalJSON(b []byte) error {
if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
return fmt.Errorf("error parsing hardware addr")
}
b = b[1 : len(b)-1]
mac, err := net.ParseMAC(string(b))
if err != nil {
return err
}
*hw = hardwareAddr(mac)
return nil
}
type vxlanLeaseAttrs struct {
VtepMAC hardwareAddr
}
func (vb *VXLANBackend) handleSubnetEvents(batch []subnet.Event) {
for _, evt := range batch {
switch evt.Type {
case subnet.SubnetAdded:
log.Info("Subnet added: ", evt.Lease.Subnet)
if evt.Lease.Attrs.BackendType != "vxlan" {
log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
continue
}
var attrs vxlanLeaseAttrs
if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
log.Error("Error decoding subnet lease JSON: ", err)
continue
}
vb.rts.set(evt.Lease.Subnet, net.HardwareAddr(attrs.VtepMAC))
vb.dev.AddL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})
case subnet.SubnetRemoved:
log.Info("Subnet removed: ", evt.Lease.Subnet)
if evt.Lease.Attrs.BackendType != "vxlan" {
log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
continue
}
var attrs vxlanLeaseAttrs
if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &attrs); err != nil {
log.Error("Error decoding subnet lease JSON: ", err)
continue
}
if len(attrs.VtepMAC) > 0 {
vb.dev.DelL2(neigh{IP: evt.Lease.Attrs.PublicIP, MAC: net.HardwareAddr(attrs.VtepMAC)})
}
vb.rts.remove(evt.Lease.Subnet)
default:
log.Error("Internal error: unknown event type: ", int(evt.Type))
}
}
}
func (vb *VXLANBackend) handleInitialSubnetEvents(batch []subnet.Event) error {
log.Infof("Handling initial subnet events")
fdbTable, err := vb.dev.GetL2List()
if err != nil {
return fmt.Errorf("Error fetching L2 table: %v", err)
}
for _, fdbEntry := range fdbTable {
log.Infof("fdb already populated with: %s %s ", fdbEntry.IP, fdbEntry.HardwareAddr)
}
evtMarker := make([]bool, len(batch))
leaseAttrsList := make([]vxlanLeaseAttrs, len(batch))
fdbEntryMarker := make([]bool, len(fdbTable))
for i, evt := range batch {
if evt.Lease.Attrs.BackendType != "vxlan" {
log.Warningf("Ignoring non-vxlan subnet: type=%v", evt.Lease.Attrs.BackendType)
evtMarker[i] = true
continue
}
if err := json.Unmarshal(evt.Lease.Attrs.BackendData, &leaseAttrsList[i]); err != nil {
log.Error("Error decoding subnet lease JSON: ", err)
evtMarker[i] = true
continue
}
for j, fdbEntry := range fdbTable {
if evt.Lease.Attrs.PublicIP.ToIP().Equal(fdbEntry.IP) && bytes.Equal([]byte(leaseAttrsList[i].VtepMAC), []byte(fdbEntry.HardwareAddr)) {
evtMarker[i] = true
fdbEntryMarker[j] = true
break
}
}
vb.rts.set(evt.Lease.Subnet, net.HardwareAddr(leaseAttrsList[i].VtepMAC))
}
for j, marker := range fdbEntryMarker {
if !marker && fdbTable[j].IP != nil {
err := vb.dev.DelL2(neigh{IP: ip.FromIP(fdbTable[j].IP), MAC: fdbTable[j].HardwareAddr})
if err != nil {
log.Error("Delete L2 failed: ", err)
}
}
}
for i, marker := range evtMarker {
if !marker {
err := vb.dev.AddL2(neigh{IP: batch[i].Lease.Attrs.PublicIP, MAC: net.HardwareAddr(leaseAttrsList[i].VtepMAC)})
if err != nil {
log.Error("Add L2 failed: ", err)
}
}
}
return nil
}
func (vb *VXLANBackend) handleMiss(miss *netlink.Neigh) {
switch {
case len(miss.IP) == 0 && len(miss.HardwareAddr) == 0:
log.Info("Ignoring nil miss")
case len(miss.HardwareAddr) == 0:
vb.handleL3Miss(miss)
default:
log.Infof("Ignoring not a miss: %v, %v", miss.HardwareAddr, miss.IP)
}
}
func (vb *VXLANBackend) handleL3Miss(miss *netlink.Neigh) {
log.Infof("L3 miss: %v", miss.IP)
rt := vb.rts.findByNetwork(ip.FromIP(miss.IP))
if rt == nil {
log.Infof("Route for %v not found", miss.IP)
return
}
if err := vb.dev.AddL3(neigh{IP: ip.FromIP(miss.IP), MAC: rt.vtepMAC}); err != nil {
log.Errorf("AddL3 failed: %v", err)
} else {
log.Info("AddL3 succeeded")
}
}