-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
l2responder.go
373 lines (304 loc) · 9.38 KB
/
l2responder.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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package l2responder
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"runtime/pprof"
"time"
"github.com/cilium/cilium/pkg/datapath/garp"
"github.com/cilium/cilium/pkg/datapath/tables"
"github.com/cilium/cilium/pkg/ebpf"
"github.com/cilium/cilium/pkg/hive"
"github.com/cilium/cilium/pkg/hive/cell"
"github.com/cilium/cilium/pkg/hive/job"
"github.com/cilium/cilium/pkg/maps/l2respondermap"
"github.com/cilium/cilium/pkg/statedb"
"github.com/cilium/cilium/pkg/types"
"github.com/sirupsen/logrus"
"github.com/vishvananda/netlink"
)
// Cell provides the L2 Responder Reconciler. This component takes the desired state, calculated by
// the L2 announcer component from the StateDB table and reconciles it with the L2 responder map.
// The L2 Responder Reconciler watches for incremental changes in the table and applies these
// incremental changes immediately and it periodically perform full reconciliation as redundancy.
var Cell = cell.Module(
"l2-responder",
"L2 Responder Reconciler",
cell.Invoke(NewL2ResponderReconciler),
cell.Provide(newNeighborNetlink),
)
type params struct {
cell.In
Lifecycle hive.Lifecycle
Logger logrus.FieldLogger
L2AnnouncementTable statedb.Table[*tables.L2AnnounceEntry]
StateDB statedb.DB
L2ResponderMap l2respondermap.Map
NetLink linkByNamer
JobRegistry job.Registry
}
type linkByNamer interface {
LinkByName(name string) (netlink.Link, error)
}
func newNeighborNetlink() linkByNamer {
return &netlink.Handle{}
}
type l2ResponderReconciler struct {
params params
}
func NewL2ResponderReconciler(params params) *l2ResponderReconciler {
reconciler := l2ResponderReconciler{
params: params,
}
group := params.JobRegistry.NewGroup(
job.WithLogger(params.Logger),
job.WithPprofLabels(pprof.Labels("cell", "l2-responder-reconciler")),
)
params.Lifecycle.Append(group)
group.Add(job.OneShot("l2-responder-reconciler", reconciler.run))
return &reconciler
}
func (p *l2ResponderReconciler) run(ctx context.Context) error {
log := p.params.Logger
// This timer triggers full reconciliation once in a while, in case partial reconciliation
// got out of sync or the map was changed underneath us.
ticker := time.NewTicker(5 * time.Minute)
// At startup, do an initial full reconciliation
maxRev, err := p.fullReconciliation()
if err != nil {
log.WithError(err).Error("Error(s) while reconciling l2 responder map")
}
for ctx.Err() == nil {
maxRev = p.cycle(ctx, maxRev, ticker.C)
}
return nil
}
func (p *l2ResponderReconciler) cycle(
ctx context.Context,
maxRevIn uint64,
fullReconciliation <-chan time.Time,
) (maxRev uint64) {
tbl := p.params.L2AnnouncementTable
db := p.params.StateDB
log := p.params.Logger
// Get an `iter` which invalidates on any changes.
r := tbl.Reader(db.ReadTxn())
iter, err := r.Get(statedb.All)
if err != nil {
log.WithError(err).Error("Error getting all desired proxy table entries")
}
select {
case <-ctx.Done():
return 0
case <-iter.Invalidated():
maxRev, err = p.partialReconciliation(maxRevIn)
if err != nil {
log.WithError(err).Error("Error(s) while partial reconciling l2 responder map")
}
return maxRev
case <-fullReconciliation:
// The existing `iter` is the result of a `All` query, so this will return all
// entries in the table for full reconciliation.
maxRev, err = p.fullReconciliation()
if err != nil {
log.WithError(err).Error("Error(s) while full reconciling l2 responder map")
}
return maxRev
}
}
func (p *l2ResponderReconciler) partialReconciliation(maxRevIn uint64) (maxRev uint64, err error) {
var errs error
maxRev = maxRevIn
arMap := p.params.L2ResponderMap
tbl := p.params.L2AnnouncementTable
db := p.params.StateDB
log := p.params.Logger
lr := cachingLinkResolver{nl: p.params.NetLink}
log.Debug("l2 announcer table invalidated, performing partial reconciliation")
// Get all changes since the revision we processes
r := tbl.Reader(db.ReadTxn())
iter, err := r.LowerBound(statedb.ByRevision(maxRevIn))
if err != nil {
log.WithError(err).Error("Error getting last changes")
}
// A list of desired entries which have been soft deleted
var toDelete []*tables.L2AnnounceEntry
statedb.ProcessEach(iter, func(e *tables.L2AnnounceEntry) error {
if e.Revision > maxRev {
maxRev = e.Revision
}
// Ignore IPv6 addresses, L2 is IPv4 only
if e.IP.To4() == nil {
return nil
}
idx, err := lr.LinkIndex(e.NetworkInterface)
if err != nil {
errs = errors.Join(errs, fmt.Errorf("link index: %w", err))
return nil
}
if e.Deleted {
toDelete = append(toDelete, e)
err = arMap.Delete(e.IP, uint32(idx))
if err != nil {
errs = errors.Join(errs, fmt.Errorf("delete %s@%d: %w", e.IP, idx, err))
}
return nil
}
err = garpOnNewEntry(arMap, e.IP, idx)
if err != nil {
errs = errors.Join(errs, err)
}
err = arMap.Create(e.IP, uint32(idx))
if err != nil {
errs = errors.Join(errs, fmt.Errorf("create %s@%d: %w", e.IP, idx, err))
}
return nil
})
// Hard delete, soft deleted entries
if len(toDelete) > 0 {
txn := db.WriteTxn()
w := tbl.Writer(txn)
for _, e := range toDelete {
if err = w.Delete(e); err != nil {
errs = errors.Join(errs, fmt.Errorf("delete from table: %w", err))
}
}
if err = txn.Commit(); err != nil {
errs = errors.Join(errs, fmt.Errorf("commit deletion to table: %w", err))
}
}
return maxRev, errs
}
func (p *l2ResponderReconciler) fullReconciliation() (maxRev uint64, err error) {
var errs error
log := p.params.Logger
tbl := p.params.L2AnnouncementTable
db := p.params.StateDB
arMap := p.params.L2ResponderMap
lr := cachingLinkResolver{nl: p.params.NetLink}
log.Debug("l2 announcer table full reconciliation")
// Get all desired entries in the table
r := tbl.Reader(db.ReadTxn())
iter, err := r.Get(statedb.All)
if err != nil {
log.WithError(err).Error("Error getting all desired proxy table entries")
}
// Prepare index for desired entries based on map key
type desiredEntry struct {
satisfied bool
entry *tables.L2AnnounceEntry
}
desiredMap := make(map[l2respondermap.L2ResponderKey]desiredEntry)
// A list of desired entries which have been soft deleted
var tblEntriesToDelete []*tables.L2AnnounceEntry
statedb.ProcessEach(iter, func(e *tables.L2AnnounceEntry) error {
// Track the max revision number, used for partial reconciliation afterwards
if e.Revision > maxRev {
maxRev = e.Revision
}
if e.Deleted {
tblEntriesToDelete = append(tblEntriesToDelete, e)
return nil
}
// Ignore IPv6 addresses, L2 is IPv4 only
if e.IP.To4() == nil {
return nil
}
idx, err := lr.LinkIndex(e.NetworkInterface)
if err != nil {
errs = errors.Join(errs, err)
return nil
}
desiredMap[l2respondermap.L2ResponderKey{
IP: types.IPv4(e.IP.To4()),
IfIndex: uint32(idx),
}] = desiredEntry{
entry: e,
}
return nil
})
// Hard delete, soft deleted entries
if len(tblEntriesToDelete) > 0 {
txn := db.WriteTxn()
w := tbl.Writer(txn)
for _, e := range tblEntriesToDelete {
if err = w.Delete(e); err != nil {
errs = errors.Join(errs, fmt.Errorf("delete from table: %w", err))
}
}
if err = txn.Commit(); err != nil {
errs = errors.Join(errs, fmt.Errorf("commit deletion to table: %w", err))
}
}
// Loop over all map values, use the desired entries index to see which we want to delete.
var toDelete []*l2respondermap.L2ResponderKey
arMap.IterateWithCallback(func(key *l2respondermap.L2ResponderKey, _ *l2respondermap.L2ResponderStats) {
e, found := desiredMap[*key]
if !found {
toDelete = append(toDelete, key)
return
}
e.satisfied = true
})
// Delete all unwanted map values
for _, del := range toDelete {
if err := arMap.Delete(del.IP[:], del.IfIndex); err != nil {
errs = errors.Join(errs, fmt.Errorf("delete %s@%d: %w", del.IP, del.IfIndex, err))
}
}
// Add map values that do not yet exist
for key, entry := range desiredMap {
if entry.satisfied {
continue
}
err = garpOnNewEntry(arMap, key.IP[:], int(key.IfIndex))
if err != nil {
errs = errors.Join(errs, err)
}
if err := arMap.Create(key.IP[:], key.IfIndex); err != nil {
errs = errors.Join(errs, fmt.Errorf("create %s@%d: %w", key.IP, key.IfIndex, err))
}
}
return maxRev, errs
}
// If the given IP and network interface index does not yet exist in the l2 responder map,
// a failover might have taken place. Therefor we should send out a gARP reply to let
// the local network know the IP has moved to minimize downtime due to ARP caching.
func garpOnNewEntry(arMap l2respondermap.Map, ip net.IP, ifIndex int) error {
_, err := arMap.Lookup(ip, uint32(ifIndex))
if !errors.Is(err, ebpf.ErrKeyNotExist) {
return nil
}
if netIP, ok := netip.AddrFromSlice(ip); ok {
err = garp.SendOnInterfaceIdx(ifIndex, netIP)
if err != nil {
return fmt.Errorf("garp %s@%d: %w", ip, ifIndex, err)
}
}
return nil
}
type cachingLinkResolver struct {
nl linkByNamer
cache map[string]int
}
// LinkIndex returns the link index for a given netdev name, from its cache or netlink
func (clr *cachingLinkResolver) LinkIndex(name string) (int, error) {
if clr.cache == nil {
clr.cache = make(map[string]int)
}
idx, found := clr.cache[name]
if found {
return idx, nil
}
link, err := clr.nl.LinkByName(name)
if err != nil {
return 0, err
}
idx = link.Attrs().Index
clr.cache[name] = idx
return idx, nil
}