forked from ligato/vpp-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.go
476 lines (432 loc) · 16.3 KB
/
route.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
// Copyright (c) 2018 Cisco and/or its affiliates.
//
// 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 descriptor
import (
"bytes"
"net"
"strings"
"github.com/gogo/protobuf/proto"
prototypes "github.com/gogo/protobuf/types"
"github.com/pkg/errors"
"github.com/vishvananda/netlink"
"github.com/ligato/cn-infra/logging"
"github.com/ligato/cn-infra/utils/addrs"
ifmodel "github.com/ligato/vpp-agent/api/models/linux/interfaces"
"github.com/ligato/vpp-agent/api/models/linux/l3"
netalloc_api "github.com/ligato/vpp-agent/api/models/netalloc"
"github.com/ligato/vpp-agent/pkg/models"
kvs "github.com/ligato/vpp-agent/plugins/kvscheduler/api"
"github.com/ligato/vpp-agent/plugins/linux/ifplugin"
ifdescriptor "github.com/ligato/vpp-agent/plugins/linux/ifplugin/descriptor"
"github.com/ligato/vpp-agent/plugins/linux/l3plugin/descriptor/adapter"
l3linuxcalls "github.com/ligato/vpp-agent/plugins/linux/l3plugin/linuxcalls"
"github.com/ligato/vpp-agent/plugins/linux/nsplugin"
nslinuxcalls "github.com/ligato/vpp-agent/plugins/linux/nsplugin/linuxcalls"
"github.com/ligato/vpp-agent/plugins/netalloc"
netalloc_descr "github.com/ligato/vpp-agent/plugins/netalloc/descriptor"
)
const (
// RouteDescriptorName is the name of the descriptor for Linux routes.
RouteDescriptorName = "linux-route"
// dependency labels
routeOutInterfaceDep = "outgoing-interface-is-up"
routeOutInterfaceIPAddrDep = "outgoing-interface-has-ip-address"
routeGwReachabilityDep = "gw-reachable"
allocatedAddrAttached = "allocated-addr-attached"
)
// A list of non-retriable errors:
var (
// ErrRouteWithoutInterface is returned when Linux Route configuration is missing
// outgoing interface reference.
ErrRouteWithoutInterface = errors.New("Linux Route defined without outgoing interface reference")
// ErrRouteWithUndefinedScope is returned when Linux Route is configured without scope.
ErrRouteWithUndefinedScope = errors.New("Linux Route defined without scope")
// ErrRouteLinkWithGw is returned when link-local Linux route has gateway address
// specified - it shouldn't be since destination is already neighbour by definition.
ErrRouteLinkWithGw = errors.New("Link-local Linux Route was defined with non-empty GW address")
)
// RouteDescriptor teaches KVScheduler how to configure Linux routes.
type RouteDescriptor struct {
log logging.Logger
l3Handler l3linuxcalls.NetlinkAPI
ifPlugin ifplugin.API
nsPlugin nsplugin.API
addrAlloc netalloc.AddressAllocator
scheduler kvs.KVScheduler
// parallelization of the Retrieve operation
goRoutinesCnt int
}
// NewRouteDescriptor creates a new instance of the Route descriptor.
func NewRouteDescriptor(
scheduler kvs.KVScheduler, ifPlugin ifplugin.API, nsPlugin nsplugin.API, addrAlloc netalloc.AddressAllocator,
l3Handler l3linuxcalls.NetlinkAPI, log logging.PluginLogger, goRoutinesCnt int) *kvs.KVDescriptor {
ctx := &RouteDescriptor{
scheduler: scheduler,
l3Handler: l3Handler,
ifPlugin: ifPlugin,
nsPlugin: nsPlugin,
addrAlloc: addrAlloc,
goRoutinesCnt: goRoutinesCnt,
log: log.NewLogger("route-descriptor"),
}
typedDescr := &adapter.RouteDescriptor{
Name: RouteDescriptorName,
NBKeyPrefix: linux_l3.ModelRoute.KeyPrefix(),
ValueTypeName: linux_l3.ModelRoute.ProtoName(),
KeySelector: linux_l3.ModelRoute.IsKeyValid,
KeyLabel: linux_l3.ModelRoute.StripKeyPrefix,
ValueComparator: ctx.EquivalentRoutes,
Validate: ctx.Validate,
Create: ctx.Create,
Delete: ctx.Delete,
Update: ctx.Update,
Retrieve: ctx.Retrieve,
DerivedValues: ctx.DerivedValues,
Dependencies: ctx.Dependencies,
RetrieveDependencies: []string{
netalloc_descr.IPAllocDescriptorName,
ifdescriptor.InterfaceDescriptorName},
}
return adapter.NewRouteDescriptor(typedDescr)
}
// EquivalentRoutes is case-insensitive comparison function for l3.LinuxRoute.
func (d *RouteDescriptor) EquivalentRoutes(key string, oldRoute, newRoute *linux_l3.Route) bool {
// attributes compared as usually:
if oldRoute.OutgoingInterface != newRoute.OutgoingInterface ||
oldRoute.Scope != newRoute.Scope ||
oldRoute.Metric != newRoute.Metric {
return false
}
// compare IP addresses converted to net.IP(Net)
if !equalNetworks(oldRoute.DstNetwork, newRoute.DstNetwork) {
return false
}
return equalAddrs(getGwAddr(oldRoute), getGwAddr(newRoute))
}
// Validate validates static route configuration.
func (d *RouteDescriptor) Validate(key string, route *linux_l3.Route) (err error) {
if route.OutgoingInterface == "" {
return kvs.NewInvalidValueError(ErrRouteWithoutInterface, "outgoing_interface")
}
if route.Scope == linux_l3.Route_LINK && route.GwAddr != "" {
return kvs.NewInvalidValueError(ErrRouteLinkWithGw, "scope", "gw_addr")
}
err = d.addrAlloc.ValidateIPAddress(route.DstNetwork, "", "dst_network",
netalloc.GWRefAllowed)
if err != nil {
return err
}
return d.addrAlloc.ValidateIPAddress(getGwAddr(route), route.OutgoingInterface,
"gw_addr", netalloc.GWRefRequired)
}
// Create adds Linux route.
func (d *RouteDescriptor) Create(key string, route *linux_l3.Route) (metadata interface{}, err error) {
err = d.updateRoute(route, "add", d.l3Handler.AddRoute)
return nil, err
}
// Delete removes Linux route.
func (d *RouteDescriptor) Delete(key string, route *linux_l3.Route, metadata interface{}) error {
return d.updateRoute(route, "delete", d.l3Handler.DelRoute)
}
// Update is able to change route scope, metric and GW address.
func (d *RouteDescriptor) Update(key string, oldRoute, newRoute *linux_l3.Route, oldMetadata interface{}) (newMetadata interface{}, err error) {
err = d.updateRoute(newRoute, "modify", d.l3Handler.ReplaceRoute)
return nil, err
}
// updateRoute adds, modifies or deletes a Linux route.
func (d *RouteDescriptor) updateRoute(route *linux_l3.Route, actionName string, actionClb func(route *netlink.Route) error) error {
var err error
// Prepare Netlink Route object
netlinkRoute := &netlink.Route{}
// Get interface metadata
ifMeta, found := d.ifPlugin.GetInterfaceIndex().LookupByName(route.OutgoingInterface)
if !found || ifMeta == nil {
err = errors.Errorf("failed to obtain metadata for interface %s", route.OutgoingInterface)
d.log.Error(err)
return err
}
// set link index
netlinkRoute.LinkIndex = ifMeta.LinuxIfIndex
// set destination network
dstNet, err := d.addrAlloc.GetOrParseIPAddress(route.DstNetwork, "",
netalloc_api.IPAddressForm_ADDR_NET)
if err != nil {
d.log.Error(err)
return err
}
netlinkRoute.Dst = dstNet
// set gateway address
if route.GwAddr != "" {
gwAddr, err := d.addrAlloc.GetOrParseIPAddress(route.GwAddr, route.OutgoingInterface,
netalloc_api.IPAddressForm_ADDR_ONLY)
if err != nil {
d.log.Error(err)
return err
}
netlinkRoute.Gw = gwAddr.IP
}
// set route scope
scope, err := rtScopeFromNBToNetlink(route.Scope)
if err != nil {
d.log.Error(err)
return err
}
netlinkRoute.Scope = scope
// set route metric
netlinkRoute.Priority = int(route.Metric)
// move to the namespace of the associated interface
nsCtx := nslinuxcalls.NewNamespaceMgmtCtx()
revertNs, err := d.nsPlugin.SwitchToNamespace(nsCtx, ifMeta.Namespace)
if err != nil {
err = errors.Errorf("failed to switch namespace: %v", err)
d.log.Error(err)
return err
}
defer revertNs()
// update route in the interface namespace
err = actionClb(netlinkRoute)
if err != nil {
err = errors.Errorf("failed to %s linux route: %v", actionName, err)
d.log.Error(err)
return err
}
return nil
}
// Dependencies lists dependencies for a Linux route.
func (d *RouteDescriptor) Dependencies(key string, route *linux_l3.Route) []kvs.Dependency {
var dependencies []kvs.Dependency
// the outgoing interface must exist and be UP
if route.OutgoingInterface != "" {
dependencies = append(dependencies, kvs.Dependency{
Label: routeOutInterfaceDep,
Key: ifmodel.InterfaceStateKey(route.OutgoingInterface, true),
})
}
// if destination network is netalloc reference, then the address must be allocated first
allocDep, hasAllocDep := d.addrAlloc.GetAddressAllocDep(route.DstNetwork, "",
"dst_network-")
if hasAllocDep {
dependencies = append(dependencies, allocDep)
}
// if GW is netalloc reference, then the address must be allocated first
allocDep, hasAllocDep = d.addrAlloc.GetAddressAllocDep(route.GwAddr, route.OutgoingInterface,
"gw_addr-")
if hasAllocDep {
dependencies = append(dependencies, allocDep)
}
// GW must be routable
network, iface, _, isRef, _ := d.addrAlloc.ParseAddressAllocRef(route.GwAddr, route.OutgoingInterface)
if isRef {
// GW is netalloc reference
dependencies = append(dependencies, kvs.Dependency{
Label: routeGwReachabilityDep,
AnyOf: kvs.AnyOfDependency{
KeyPrefixes: []string{
netalloc_api.NeighGwKey(network, iface),
linux_l3.StaticLinkLocalRouteKey(
d.addrAlloc.CreateAddressAllocRef(network, iface, true),
route.OutgoingInterface),
},
},
})
dependencies = append(dependencies, kvs.Dependency{
Label: allocatedAddrAttached,
Key: ifmodel.InterfaceAddressKey(
route.OutgoingInterface, d.addrAlloc.CreateAddressAllocRef(network, "", false),
netalloc_api.IPAddressSource_ALLOC_REF),
})
} else if gwAddr := net.ParseIP(getGwAddr(route)); gwAddr != nil && !gwAddr.IsUnspecified() {
// GW is not netalloc reference but an actual IP
dependencies = append(dependencies, kvs.Dependency{
Label: routeGwReachabilityDep,
AnyOf: kvs.AnyOfDependency{
KeyPrefixes: []string{
ifmodel.InterfaceAddressPrefix(route.OutgoingInterface),
linux_l3.StaticLinkLocalRoutePrefix(route.OutgoingInterface),
},
KeySelector: func(key string) bool {
dstAddr, ifName, isRouteKey := linux_l3.ParseStaticLinkLocalRouteKey(key)
if isRouteKey && ifName == route.OutgoingInterface {
if _, dstNet, err := net.ParseCIDR(dstAddr); err == nil && dstNet.Contains(gwAddr) {
// GW address is neighbour as told by another link-local route
return true
}
return false
}
ifName, address, source, _, isAddrKey := ifmodel.ParseInterfaceAddressKey(key)
if isAddrKey && source != netalloc_api.IPAddressSource_ALLOC_REF {
if _, network, err := net.ParseCIDR(address); err == nil && network.Contains(gwAddr) {
// GW address is inside the local network of the outgoing interface
// as given by the assigned IP address
return true
}
}
return false
},
},
})
} else if route.OutgoingInterface != "" {
// route also requires the interface to be in the L3 mode (have at least one
// IP address assigned) - we set this only for routes without GW and other
// routes will inherit this dependency transitively through GW-reachability dep.
dependencies = append(dependencies, kvs.Dependency{
Label: routeOutInterfaceIPAddrDep,
AnyOf: kvs.AnyOfDependency{
KeyPrefixes: []string{
ifmodel.InterfaceAddressPrefix(route.OutgoingInterface),
},
},
})
}
return dependencies
}
// DerivedValues derives empty value under StaticLinkLocalRouteKey if route is link-local.
// It is used in dependencies for network reachability of a route gateway (see above).
func (d *RouteDescriptor) DerivedValues(key string, route *linux_l3.Route) (derValues []kvs.KeyValuePair) {
if route.Scope == linux_l3.Route_LINK {
derValues = append(derValues, kvs.KeyValuePair{
Key: linux_l3.StaticLinkLocalRouteKey(route.DstNetwork, route.OutgoingInterface),
Value: &prototypes.Empty{},
})
}
return derValues
}
// Retrieve returns all routes associated with interfaces managed by this agent.
func (d *RouteDescriptor) Retrieve(correlate []adapter.RouteKVWithMetadata) ([]adapter.RouteKVWithMetadata, error) {
var values []adapter.RouteKVWithMetadata
// prepare expected configuration with de-referenced netalloc links
nbCfg := make(map[string]*linux_l3.Route)
expCfg := make(map[string]*linux_l3.Route)
for _, kv := range correlate {
dstNetwork := kv.Value.DstNetwork
parsed, err := d.addrAlloc.GetOrParseIPAddress(kv.Value.DstNetwork,
"", netalloc_api.IPAddressForm_ADDR_NET)
if err == nil {
dstNetwork = parsed.String()
}
gwAddr := kv.Value.GwAddr
parsed, err = d.addrAlloc.GetOrParseIPAddress(getGwAddr(kv.Value),
kv.Value.OutgoingInterface, netalloc_api.IPAddressForm_ADDR_ONLY)
if err == nil {
gwAddr = parsed.IP.String()
}
route := proto.Clone(kv.Value).(*linux_l3.Route)
route.DstNetwork = dstNetwork
route.GwAddr = gwAddr
key := models.Key(route)
expCfg[key] = route
nbCfg[key] = kv.Value
}
routeDetails, err := d.l3Handler.DumpRoutes()
if err != nil {
return nil, errors.Errorf("Failed to retrieve linux ARPs: %v", err)
}
// correlate with the expected configuration
for _, routeDetails := range routeDetails {
// Convert to key-value object with metadata
scope, err := rtScopeFromNetlinkToNB(routeDetails.Meta.NetlinkScope)
if err != nil {
// route not configured by the agent
continue
}
route := adapter.RouteKVWithMetadata{
Key: linux_l3.RouteKey(routeDetails.Route.DstNetwork, routeDetails.Route.OutgoingInterface),
Value: &linux_l3.Route{
OutgoingInterface: routeDetails.Route.OutgoingInterface,
Scope: scope,
DstNetwork: routeDetails.Route.DstNetwork,
GwAddr: routeDetails.Route.GwAddr,
Metric: routeDetails.Route.Metric,
},
Origin: kvs.UnknownOrigin, // let the scheduler to determine the origin
}
key := linux_l3.RouteKey(routeDetails.Route.DstNetwork, routeDetails.Route.OutgoingInterface)
if expCfg, hasExpCfg := expCfg[key]; hasExpCfg {
if d.EquivalentRoutes(key, route.Value, expCfg) {
route.Value = nbCfg[key]
// recreate the key in case the dest. IP was replaced with netalloc link
route.Key = models.Key(route.Value)
}
}
values = append(values, route)
}
return values, nil
}
// rtScopeFromNBToNetlink convert Route scope from NB configuration
// to the corresponding Netlink constant.
func rtScopeFromNBToNetlink(scope linux_l3.Route_Scope) (netlink.Scope, error) {
switch scope {
case linux_l3.Route_GLOBAL:
return netlink.SCOPE_UNIVERSE, nil
case linux_l3.Route_HOST:
return netlink.SCOPE_HOST, nil
case linux_l3.Route_LINK:
return netlink.SCOPE_LINK, nil
case linux_l3.Route_SITE:
return netlink.SCOPE_SITE, nil
}
return 0, ErrRouteWithUndefinedScope
}
// rtScopeFromNetlinkToNB converts Route scope from Netlink constant
// to the corresponding NB constant.
func rtScopeFromNetlinkToNB(scope netlink.Scope) (linux_l3.Route_Scope, error) {
switch scope {
case netlink.SCOPE_UNIVERSE:
return linux_l3.Route_GLOBAL, nil
case netlink.SCOPE_HOST:
return linux_l3.Route_HOST, nil
case netlink.SCOPE_LINK:
return linux_l3.Route_LINK, nil
case netlink.SCOPE_SITE:
return linux_l3.Route_SITE, nil
}
return 0, ErrRouteWithUndefinedScope
}
// equalAddrs compares two IP addresses for equality.
func equalAddrs(addr1, addr2 string) bool {
if strings.HasPrefix(addr1, netalloc_api.AllocRefPrefix) {
return addr1 == addr2
}
a1 := net.ParseIP(addr1)
a2 := net.ParseIP(addr2)
if a1 == nil || a2 == nil {
// if parsing fails, compare as strings
return strings.ToLower(addr1) == strings.ToLower(addr2)
}
return a1.Equal(a2)
}
// equalNetworks compares two IP networks for equality.
func equalNetworks(net1, net2 string) bool {
if strings.HasPrefix(net1, netalloc_api.AllocRefPrefix) {
return net1 == net2
}
_, n1, err1 := net.ParseCIDR(net1)
_, n2, err2 := net.ParseCIDR(net2)
if err1 != nil || err2 != nil {
// if parsing fails, compare as strings
return strings.ToLower(net1) == strings.ToLower(net2)
}
return n1.IP.Equal(n2.IP) && bytes.Equal(n1.Mask, n2.Mask)
}
// getGwAddr returns the GW address chosen in the given route, handling the cases
// when it is left undefined.
func getGwAddr(route *linux_l3.Route) string {
if route.GwAddr == "" {
if ipv6, _ := addrs.IsIPv6(route.DstNetwork); ipv6 {
return l3linuxcalls.IPv6AddrAny
}
return l3linuxcalls.IPv4AddrAny
}
return route.GwAddr
}