• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

k8snetworkplumbingwg / sriov-network-operator / 11775513002

11 Nov 2024 09:12AM UTC coverage: 47.024% (+1.4%) from 45.603%
11775513002

Pull #747

github

web-flow
Merge baa41c97a into 92fee7bec
Pull Request #747: Redesign device plugin reset

86 of 118 new or added lines in 4 files covered. (72.88%)

9 existing lines in 2 files now uncovered.

7103 of 15105 relevant lines covered (47.02%)

0.52 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

75.75
/api/v1/helper.go
1
package v1
2

3
import (
4
        "context"
5
        "encoding/json"
6
        "fmt"
7
        "os"
8
        "path/filepath"
9
        "reflect"
10
        "regexp"
11
        "slices"
12
        "sort"
13
        "strconv"
14
        "strings"
15

16
        corev1 "k8s.io/api/core/v1"
17
        metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
18
        uns "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
19
        intstrutil "k8s.io/apimachinery/pkg/util/intstr"
20
        "k8s.io/client-go/kubernetes"
21
        logf "sigs.k8s.io/controller-runtime/pkg/log"
22

23
        "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/consts"
24
        "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/render"
25
        "github.com/k8snetworkplumbingwg/sriov-network-operator/pkg/vars"
26
)
27

28
const (
29
        LASTNETWORKNAMESPACE        = "operator.sriovnetwork.openshift.io/last-network-namespace"
30
        NETATTDEFFINALIZERNAME      = "netattdef.finalizers.sriovnetwork.openshift.io"
31
        POOLCONFIGFINALIZERNAME     = "poolconfig.finalizers.sriovnetwork.openshift.io"
32
        OPERATORCONFIGFINALIZERNAME = "operatorconfig.finalizers.sriovnetwork.openshift.io"
33
        ESwithModeLegacy            = "legacy"
34
        ESwithModeSwitchDev         = "switchdev"
35

36
        SriovCniStateEnable  = "enable"
37
        SriovCniStateDisable = "disable"
38
        SriovCniStateAuto    = "auto"
39
        SriovCniStateOff     = "off"
40
        SriovCniStateOn      = "on"
41
        SriovCniIpam         = "\"ipam\""
42
        SriovCniIpamEmpty    = SriovCniIpam + ":{}"
43
)
44

45
const invalidVfIndex = -1
46

47
var ManifestsPath = "./bindata/manifests/cni-config"
48
var log = logf.Log.WithName("sriovnetwork")
49

50
// NicIDMap contains supported mapping of IDs with each in the format of:
51
// Vendor ID, Physical Function Device ID, Virtual Function Device ID
52
var NicIDMap = []string{}
53

54
var InitialState SriovNetworkNodeState
55

56
// NetFilterType Represents the NetFilter tags to be used
57
type NetFilterType int
58

59
const (
60
        // OpenstackNetworkID network UUID
61
        OpenstackNetworkID NetFilterType = iota
62

63
        SupportedNicIDConfigmap = "supported-nic-ids"
64
)
65

66
type ConfigurationModeType string
67

68
const (
69
        DaemonConfigurationMode  ConfigurationModeType = "daemon"
70
        SystemdConfigurationMode ConfigurationModeType = "systemd"
71
)
72

73
func (e NetFilterType) String() string {
×
74
        switch e {
×
75
        case OpenstackNetworkID:
×
76
                return "openstack/NetworkID"
×
77
        default:
×
78
                return fmt.Sprintf("%d", int(e))
×
79
        }
80
}
81

82
func InitNicIDMapFromConfigMap(client kubernetes.Interface, namespace string) error {
1✔
83
        cm, err := client.CoreV1().ConfigMaps(namespace).Get(
1✔
84
                context.Background(),
1✔
85
                SupportedNicIDConfigmap,
1✔
86
                metav1.GetOptions{},
1✔
87
        )
1✔
88
        // if the configmap does not exist, return false
1✔
89
        if err != nil {
1✔
90
                return err
×
91
        }
×
92
        for _, v := range cm.Data {
2✔
93
                NicIDMap = append(NicIDMap, v)
1✔
94
        }
1✔
95

96
        return nil
1✔
97
}
98

99
func InitNicIDMapFromList(idList []string) {
1✔
100
        NicIDMap = append(NicIDMap, idList...)
1✔
101
}
1✔
102

103
func IsSupportedVendor(vendorID string) bool {
1✔
104
        for _, n := range NicIDMap {
2✔
105
                ids := strings.Split(n, " ")
1✔
106
                if vendorID == ids[0] {
2✔
107
                        return true
1✔
108
                }
1✔
109
        }
110
        return false
1✔
111
}
112

113
func IsSupportedDevice(deviceID string) bool {
1✔
114
        for _, n := range NicIDMap {
2✔
115
                ids := strings.Split(n, " ")
1✔
116
                if deviceID == ids[1] {
1✔
117
                        return true
×
118
                }
×
119
        }
120
        return false
1✔
121
}
122

123
func IsSupportedModel(vendorID, deviceID string) bool {
1✔
124
        for _, n := range NicIDMap {
2✔
125
                ids := strings.Split(n, " ")
1✔
126
                if vendorID == ids[0] && deviceID == ids[1] {
2✔
127
                        return true
1✔
128
                }
1✔
129
        }
130
        log.Info("IsSupportedModel(): found unsupported model", "vendorId:", vendorID, "deviceId:", deviceID)
1✔
131
        return false
1✔
132
}
133

134
func IsVfSupportedModel(vendorID, deviceID string) bool {
1✔
135
        for _, n := range NicIDMap {
2✔
136
                ids := strings.Split(n, " ")
1✔
137
                if vendorID == ids[0] && deviceID == ids[2] {
2✔
138
                        return true
1✔
139
                }
1✔
140
        }
141
        log.Info("IsVfSupportedModel(): found unsupported VF model", "vendorId:", vendorID, "deviceId:", deviceID)
×
142
        return false
×
143
}
144

145
func IsEnabledUnsupportedVendor(vendorID string, unsupportedNicIDMap map[string]string) bool {
×
146
        for _, n := range unsupportedNicIDMap {
×
147
                if IsValidPciString(n) {
×
148
                        ids := strings.Split(n, " ")
×
149
                        if vendorID == ids[0] {
×
150
                                return true
×
151
                        }
×
152
                }
153
        }
154
        return false
×
155
}
156

157
func IsValidPciString(nicIDString string) bool {
×
158
        ids := strings.Split(nicIDString, " ")
×
159

×
160
        if len(ids) != 3 {
×
161
                log.Info("IsValidPciString(): ", nicIDString)
×
162
                return false
×
163
        }
×
164

165
        if len(ids[0]) != 4 {
×
166
                log.Info("IsValidPciString():", "Invalid vendor PciId ", ids[0])
×
167
                return false
×
168
        }
×
169
        if _, err := strconv.ParseInt(ids[0], 16, 32); err != nil {
×
170
                log.Info("IsValidPciString():", "Invalid vendor PciId ", ids[0])
×
171
        }
×
172

173
        if len(ids[1]) != 4 {
×
174
                log.Info("IsValidPciString():", "Invalid PciId of PF ", ids[1])
×
175
                return false
×
176
        }
×
177
        if _, err := strconv.ParseInt(ids[1], 16, 32); err != nil {
×
178
                log.Info("IsValidPciString():", "Invalid PciId of PF ", ids[1])
×
179
        }
×
180

181
        if len(ids[2]) != 4 {
×
182
                log.Info("IsValidPciString():", "Invalid PciId of VF ", ids[2])
×
183
                return false
×
184
        }
×
185
        if _, err := strconv.ParseInt(ids[2], 16, 32); err != nil {
×
186
                log.Info("IsValidPciString():", "Invalid PciId of VF ", ids[2])
×
187
        }
×
188

189
        return true
×
190
}
191

192
func GetSupportedVfIds() []string {
1✔
193
        var vfIds []string
1✔
194
        for _, n := range NicIDMap {
2✔
195
                ids := strings.Split(n, " ")
1✔
196
                vfID := "0x" + ids[2]
1✔
197
                if !StringInArray(vfID, vfIds) {
2✔
198
                        vfIds = append(vfIds, vfID)
1✔
199
                }
1✔
200
        }
201
        // return a sorted slice so that udev rule is stable
202
        sort.Slice(vfIds, func(i, j int) bool {
2✔
203
                ip, _ := strconv.ParseInt(vfIds[i], 0, 32)
1✔
204
                jp, _ := strconv.ParseInt(vfIds[j], 0, 32)
1✔
205
                return ip < jp
1✔
206
        })
1✔
207
        return vfIds
1✔
208
}
209

210
func GetVfDeviceID(deviceID string) string {
×
211
        for _, n := range NicIDMap {
×
212
                ids := strings.Split(n, " ")
×
213
                if deviceID == ids[1] {
×
214
                        return ids[2]
×
215
                }
×
216
        }
217
        return ""
×
218
}
219

220
func IsSwitchdevModeSpec(spec SriovNetworkNodeStateSpec) bool {
1✔
221
        return ContainsSwitchdevInterface(spec.Interfaces)
1✔
222
}
1✔
223

224
// ContainsSwitchdevInterface returns true if provided interface list contains interface
225
// with switchdev configuration
226
func ContainsSwitchdevInterface(interfaces []Interface) bool {
1✔
227
        for _, iface := range interfaces {
2✔
228
                if iface.EswitchMode == ESwithModeSwitchDev {
2✔
229
                        return true
1✔
230
                }
1✔
231
        }
232
        return false
1✔
233
}
234

235
func FindInterface(interfaces Interfaces, name string) (iface Interface, err error) {
×
236
        for _, i := range interfaces {
×
237
                if i.Name == name {
×
238
                        return i, nil
×
239
                }
×
240
        }
241
        return Interface{}, fmt.Errorf("unable to find interface: %v", name)
×
242
}
243

244
// GetEswitchModeFromSpec returns ESwitchMode from the interface spec, returns legacy if not set
245
func GetEswitchModeFromSpec(ifaceSpec *Interface) string {
1✔
246
        if ifaceSpec.EswitchMode == "" {
2✔
247
                return ESwithModeLegacy
1✔
248
        }
1✔
249
        return ifaceSpec.EswitchMode
1✔
250
}
251

252
// GetEswitchModeFromStatus returns ESwitchMode from the interface status, returns legacy if not set
253
func GetEswitchModeFromStatus(ifaceStatus *InterfaceExt) string {
1✔
254
        if ifaceStatus.EswitchMode == "" {
2✔
255
                return ESwithModeLegacy
1✔
256
        }
1✔
257
        return ifaceStatus.EswitchMode
1✔
258
}
259

260
func NeedToUpdateSriov(ifaceSpec *Interface, ifaceStatus *InterfaceExt) bool {
1✔
261
        if ifaceSpec.Mtu > 0 {
2✔
262
                mtu := ifaceSpec.Mtu
1✔
263
                if mtu > ifaceStatus.Mtu {
2✔
264
                        log.V(2).Info("NeedToUpdateSriov(): MTU needs update", "desired", mtu, "current", ifaceStatus.Mtu)
1✔
265
                        return true
1✔
266
                }
1✔
267
        }
268
        currentEswitchMode := GetEswitchModeFromStatus(ifaceStatus)
1✔
269
        desiredEswitchMode := GetEswitchModeFromSpec(ifaceSpec)
1✔
270
        if currentEswitchMode != desiredEswitchMode {
2✔
271
                log.V(2).Info("NeedToUpdateSriov(): EswitchMode needs update", "desired", desiredEswitchMode, "current", currentEswitchMode)
1✔
272
                return true
1✔
273
        }
1✔
274
        if ifaceSpec.NumVfs != ifaceStatus.NumVfs {
2✔
275
                log.V(2).Info("NeedToUpdateSriov(): NumVfs needs update", "desired", ifaceSpec.NumVfs, "current", ifaceStatus.NumVfs)
1✔
276
                return true
1✔
277
        }
1✔
278

279
        if ifaceStatus.LinkAdminState == consts.LinkAdminStateDown {
2✔
280
                log.V(2).Info("NeedToUpdateSriov(): PF link status needs update", "desired to include", "up", "current", ifaceStatus.LinkAdminState)
1✔
281
                return true
1✔
282
        }
1✔
283

284
        if ifaceSpec.NumVfs > 0 {
2✔
285
                for _, vfStatus := range ifaceStatus.VFs {
2✔
286
                        for _, groupSpec := range ifaceSpec.VfGroups {
2✔
287
                                if IndexInRange(vfStatus.VfID, groupSpec.VfRange) {
2✔
288
                                        if vfStatus.Driver == "" {
1✔
289
                                                log.V(2).Info("NeedToUpdateSriov(): Driver needs update - has no driver",
×
290
                                                        "desired", groupSpec.DeviceType)
×
291
                                                return true
×
292
                                        }
×
293
                                        if groupSpec.DeviceType != "" && groupSpec.DeviceType != consts.DeviceTypeNetDevice {
2✔
294
                                                if groupSpec.DeviceType != vfStatus.Driver {
1✔
295
                                                        log.V(2).Info("NeedToUpdateSriov(): Driver needs update",
×
296
                                                                "desired", groupSpec.DeviceType, "current", vfStatus.Driver)
×
297
                                                        return true
×
298
                                                }
×
299
                                        } else {
1✔
300
                                                if StringInArray(vfStatus.Driver, vars.DpdkDrivers) {
2✔
301
                                                        log.V(2).Info("NeedToUpdateSriov(): Driver needs update",
1✔
302
                                                                "desired", groupSpec.DeviceType, "current", vfStatus.Driver)
1✔
303
                                                        return true
1✔
304
                                                }
1✔
305
                                                if vfStatus.Mtu != 0 && groupSpec.Mtu != 0 && vfStatus.Mtu != groupSpec.Mtu {
2✔
306
                                                        log.V(2).Info("NeedToUpdateSriov(): VF MTU needs update",
1✔
307
                                                                "vf", vfStatus.VfID, "desired", groupSpec.Mtu, "current", vfStatus.Mtu)
1✔
308
                                                        return true
1✔
309
                                                }
1✔
310

311
                                                if (strings.EqualFold(ifaceStatus.LinkType, consts.LinkTypeETH) && groupSpec.IsRdma) || strings.EqualFold(ifaceStatus.LinkType, consts.LinkTypeIB) {
2✔
312
                                                        // We do this check only if a Node GUID is set to ensure that we were able to read the
1✔
313
                                                        // Node GUID. We intentionally skip empty Node GUID in vfStatus because this may happen
1✔
314
                                                        // when the VF is allocated to a workload.
1✔
315
                                                        if vfStatus.GUID == consts.UninitializedNodeGUID {
2✔
316
                                                                log.V(2).Info("NeedToUpdateSriov(): VF GUID needs update",
1✔
317
                                                                        "vf", vfStatus.VfID, "current", vfStatus.GUID)
1✔
318
                                                                return true
1✔
319
                                                        }
1✔
320
                                                }
321
                                                // this is needed to be sure the admin mac address is configured as expected
322
                                                if ifaceSpec.ExternallyManaged {
1✔
323
                                                        log.V(2).Info("NeedToUpdateSriov(): need to update the device as it's externally manage",
×
324
                                                                "device", ifaceStatus.PciAddress)
×
325
                                                        return true
×
326
                                                }
×
327
                                        }
328
                                        if groupSpec.VdpaType != vfStatus.VdpaType {
1✔
329
                                                log.V(2).Info("NeedToUpdateSriov(): VF VdpaType mismatch",
×
330
                                                        "desired", groupSpec.VdpaType, "current", vfStatus.VdpaType)
×
331
                                                return true
×
332
                                        }
×
333
                                        break
1✔
334
                                }
335
                        }
336
                }
337
        }
338
        return false
1✔
339
}
340

341
type ByPriority []SriovNetworkNodePolicy
342

343
func (a ByPriority) Len() int {
1✔
344
        return len(a)
1✔
345
}
1✔
346

UNCOV
347
func (a ByPriority) Less(i, j int) bool {
×
UNCOV
348
        if a[i].Spec.Priority != a[j].Spec.Priority {
×
UNCOV
349
                return a[i].Spec.Priority > a[j].Spec.Priority
×
UNCOV
350
        }
×
UNCOV
351
        return a[i].GetName() < a[j].GetName()
×
352
}
353

UNCOV
354
func (a ByPriority) Swap(i, j int) {
×
UNCOV
355
        a[i], a[j] = a[j], a[i]
×
UNCOV
356
}
×
357

358
// Match check if node is selected by NodeSelector
359
func (p *SriovNetworkNodePolicy) Selected(node *corev1.Node) bool {
1✔
360
        for k, v := range p.Spec.NodeSelector {
2✔
361
                if nv, ok := node.Labels[k]; ok && nv == v {
2✔
362
                        continue
1✔
363
                }
364
                return false
×
365
        }
366
        return true
1✔
367
}
368

369
func StringInArray(val string, array []string) bool {
1✔
370
        for i := range array {
2✔
371
                if array[i] == val {
2✔
372
                        return true
1✔
373
                }
1✔
374
        }
375
        return false
1✔
376
}
377

378
func RemoveString(s string, slice []string) (result []string, found bool) {
1✔
379
        if len(slice) != 0 {
2✔
380
                for _, item := range slice {
2✔
381
                        if item == s {
2✔
382
                                found = true
1✔
383
                                continue
1✔
384
                        }
385
                        result = append(result, item)
×
386
                }
387
        }
388
        return
1✔
389
}
390

391
func UniqueAppend(inSlice []string, strings ...string) []string {
×
392
        for _, s := range strings {
×
393
                if !StringInArray(s, inSlice) {
×
394
                        inSlice = append(inSlice, s)
×
395
                }
×
396
        }
397
        return inSlice
×
398
}
399

400
// Apply policy to SriovNetworkNodeState CR
401
func (p *SriovNetworkNodePolicy) Apply(state *SriovNetworkNodeState, equalPriority bool) error {
1✔
402
        s := p.Spec.NicSelector
1✔
403
        if s.IsEmpty() {
2✔
404
                // Empty NicSelector match none
1✔
405
                return nil
1✔
406
        }
1✔
407
        for _, iface := range state.Status.Interfaces {
2✔
408
                if s.Selected(&iface) {
2✔
409
                        log.Info("Update interface", "name:", iface.Name)
1✔
410
                        result := Interface{
1✔
411
                                PciAddress:        iface.PciAddress,
1✔
412
                                Mtu:               p.Spec.Mtu,
1✔
413
                                Name:              iface.Name,
1✔
414
                                LinkType:          p.Spec.LinkType,
1✔
415
                                EswitchMode:       p.Spec.EswitchMode,
1✔
416
                                NumVfs:            p.Spec.NumVfs,
1✔
417
                                ExternallyManaged: p.Spec.ExternallyManaged,
1✔
418
                        }
1✔
419
                        if p.Spec.NumVfs > 0 {
2✔
420
                                group, err := p.generatePfNameVfGroup(&iface)
1✔
421
                                if err != nil {
2✔
422
                                        return err
1✔
423
                                }
1✔
424
                                result.VfGroups = []VfGroup{*group}
1✔
425
                                found := false
1✔
426
                                for i := range state.Spec.Interfaces {
2✔
427
                                        if state.Spec.Interfaces[i].PciAddress == result.PciAddress {
2✔
428
                                                found = true
1✔
429
                                                state.Spec.Interfaces[i].mergeConfigs(&result, equalPriority)
1✔
430
                                                state.Spec.Interfaces[i] = result
1✔
431
                                                break
1✔
432
                                        }
433
                                }
434
                                if !found {
2✔
435
                                        state.Spec.Interfaces = append(state.Spec.Interfaces, result)
1✔
436
                                }
1✔
437
                        }
438
                }
439
        }
440
        return nil
1✔
441
}
442

443
// ApplyBridgeConfig applies bridge configuration from the policy to the provided state
444
func (p *SriovNetworkNodePolicy) ApplyBridgeConfig(state *SriovNetworkNodeState) error {
1✔
445
        if p.Spec.NicSelector.IsEmpty() {
2✔
446
                // Empty NicSelector match none
1✔
447
                return nil
1✔
448
        }
1✔
449
        // sanity check the policy
450
        if !p.Spec.Bridge.IsEmpty() {
2✔
451
                if p.Spec.EswitchMode != ESwithModeSwitchDev {
2✔
452
                        return fmt.Errorf("eSwitchMode must be switchdev to use software bridge management")
1✔
453
                }
1✔
454
                if p.Spec.LinkType != "" && !strings.EqualFold(p.Spec.LinkType, consts.LinkTypeETH) {
2✔
455
                        return fmt.Errorf("linkType must be eth or ETH to use software bridge management")
1✔
456
                }
1✔
457
                if p.Spec.ExternallyManaged {
2✔
458
                        return fmt.Errorf("software bridge management can't be used when link is externally managed")
1✔
459
                }
1✔
460
        }
461
        for _, iface := range state.Status.Interfaces {
2✔
462
                if p.Spec.NicSelector.Selected(&iface) {
2✔
463
                        if p.Spec.Bridge.OVS == nil {
2✔
464
                                // The policy has no OVS bridge config, this means that the node's state should have no managed OVS bridges for the interfaces that match the policy.
1✔
465
                                // Currently PF to OVS bridge mapping is always 1 to 1 (bonding is not supported at the moment), meaning we can remove the OVS bridge
1✔
466
                                // config from the node's state if it has the interface (that matches "empty-bridge" policy) in the uplink section.
1✔
467
                                state.Spec.Bridges.OVS = slices.DeleteFunc(state.Spec.Bridges.OVS, func(br OVSConfigExt) bool {
2✔
468
                                        return slices.ContainsFunc(br.Uplinks, func(uplink OVSUplinkConfigExt) bool {
2✔
469
                                                return uplink.PciAddress == iface.PciAddress
1✔
470
                                        })
1✔
471
                                })
472
                                if len(state.Spec.Bridges.OVS) == 0 {
2✔
473
                                        state.Spec.Bridges.OVS = nil
1✔
474
                                }
1✔
475
                                continue
1✔
476
                        }
477
                        ovsBridge := OVSConfigExt{
1✔
478
                                Name:   GenerateBridgeName(&iface),
1✔
479
                                Bridge: p.Spec.Bridge.OVS.Bridge,
1✔
480
                                Uplinks: []OVSUplinkConfigExt{{
1✔
481
                                        PciAddress: iface.PciAddress,
1✔
482
                                        Name:       iface.Name,
1✔
483
                                        Interface:  p.Spec.Bridge.OVS.Uplink.Interface,
1✔
484
                                }},
1✔
485
                        }
1✔
486
                        log.Info("Update bridge for interface", "name", iface.Name, "bridge", ovsBridge.Name)
1✔
487

1✔
488
                        // We need to keep slices with bridges ordered to avoid unnecessary updates in the K8S API.
1✔
489
                        // Use binary search to insert (or update) the bridge config to the right place in the slice to keep it sorted.
1✔
490
                        pos, exist := slices.BinarySearchFunc(state.Spec.Bridges.OVS, ovsBridge, func(x, y OVSConfigExt) int {
2✔
491
                                return strings.Compare(x.Name, y.Name)
1✔
492
                        })
1✔
493
                        if exist {
2✔
494
                                state.Spec.Bridges.OVS[pos] = ovsBridge
1✔
495
                        } else {
2✔
496
                                state.Spec.Bridges.OVS = slices.Insert(state.Spec.Bridges.OVS, pos, ovsBridge)
1✔
497
                        }
1✔
498
                }
499
        }
500
        return nil
1✔
501
}
502

503
// mergeConfigs merges configs from multiple polices where the last one has the
504
// highest priority. This merge is dependent on: 1. SR-IOV partition is
505
// configured with the #-notation in pfName, 2. The VF groups are
506
// non-overlapping or SR-IOV policies have the same priority.
507
func (iface Interface) mergeConfigs(input *Interface, equalPriority bool) {
1✔
508
        m := false
1✔
509
        // merge VF groups (input.VfGroups already contains the highest priority):
1✔
510
        // - skip group with same ResourceName,
1✔
511
        // - skip overlapping groups (use only highest priority)
1✔
512
        for _, gr := range iface.VfGroups {
2✔
513
                if gr.ResourceName == input.VfGroups[0].ResourceName || gr.isVFRangeOverlapping(input.VfGroups[0]) {
2✔
514
                        continue
1✔
515
                }
516
                m = true
1✔
517
                input.VfGroups = append(input.VfGroups, gr)
1✔
518
        }
519

520
        if !equalPriority && !m {
2✔
521
                return
1✔
522
        }
1✔
523

524
        // mtu configuration we take the highest value
525
        if input.Mtu < iface.Mtu {
2✔
526
                input.Mtu = iface.Mtu
1✔
527
        }
1✔
528
        if input.NumVfs < iface.NumVfs {
2✔
529
                input.NumVfs = iface.NumVfs
1✔
530
        }
1✔
531
}
532

533
func (gr VfGroup) isVFRangeOverlapping(group VfGroup) bool {
1✔
534
        rngSt, rngEnd, err := parseRange(gr.VfRange)
1✔
535
        if err != nil {
1✔
536
                return false
×
537
        }
×
538
        rngSt2, rngEnd2, err := parseRange(group.VfRange)
1✔
539
        if err != nil {
1✔
540
                return false
×
541
        }
×
542
        // compare minimal range has overlap
543
        if rngSt < rngSt2 {
2✔
544
                return IndexInRange(rngSt2, gr.VfRange) || IndexInRange(rngEnd2, gr.VfRange)
1✔
545
        }
1✔
546
        return IndexInRange(rngSt, group.VfRange) || IndexInRange(rngEnd, group.VfRange)
1✔
547
}
548

549
func (p *SriovNetworkNodePolicy) generatePfNameVfGroup(iface *InterfaceExt) (*VfGroup, error) {
1✔
550
        var err error
1✔
551
        pfName := ""
1✔
552
        var rngStart, rngEnd int
1✔
553
        found := false
1✔
554
        for _, selector := range p.Spec.NicSelector.PfNames {
2✔
555
                pfName, rngStart, rngEnd, err = ParseVfRange(selector)
1✔
556
                if err != nil {
2✔
557
                        log.Error(err, "Unable to parse PF Name.")
1✔
558
                        return nil, err
1✔
559
                }
1✔
560
                if pfName == iface.Name {
2✔
561
                        found = true
1✔
562
                        if rngStart == invalidVfIndex && rngEnd == invalidVfIndex {
2✔
563
                                rngStart, rngEnd = 0, p.Spec.NumVfs-1
1✔
564
                        }
1✔
565
                        break
1✔
566
                }
567
        }
568
        if !found {
2✔
569
                // assign the default vf index range if the pfName is not specified by the nicSelector
1✔
570
                rngStart, rngEnd = 0, p.Spec.NumVfs-1
1✔
571
        }
1✔
572
        rng := strconv.Itoa(rngStart) + "-" + strconv.Itoa(rngEnd)
1✔
573
        return &VfGroup{
1✔
574
                ResourceName: p.Spec.ResourceName,
1✔
575
                DeviceType:   p.Spec.DeviceType,
1✔
576
                VfRange:      rng,
1✔
577
                PolicyName:   p.GetName(),
1✔
578
                Mtu:          p.Spec.Mtu,
1✔
579
                IsRdma:       p.Spec.IsRdma,
1✔
580
                VdpaType:     p.Spec.VdpaType,
1✔
581
        }, nil
1✔
582
}
583

584
func IndexInRange(i int, r string) bool {
1✔
585
        rngSt, rngEnd, err := parseRange(r)
1✔
586
        if err != nil {
1✔
587
                return false
×
588
        }
×
589
        if i <= rngEnd && i >= rngSt {
2✔
590
                return true
1✔
591
        }
1✔
592
        return false
1✔
593
}
594

595
func parseRange(r string) (rngSt, rngEnd int, err error) {
1✔
596
        rng := strings.Split(r, "-")
1✔
597
        rngSt, err = strconv.Atoi(rng[0])
1✔
598
        if err != nil {
2✔
599
                return
1✔
600
        }
1✔
601
        rngEnd, err = strconv.Atoi(rng[1])
1✔
602
        if err != nil {
1✔
603
                return
×
604
        }
×
605
        return
1✔
606
}
607

608
// SplitDeviceFromRange return the device name and the range.
609
// the split is base on #
610
func SplitDeviceFromRange(device string) (string, string) {
1✔
611
        if strings.Contains(device, "#") {
2✔
612
                fields := strings.Split(device, "#")
1✔
613
                return fields[0], fields[1]
1✔
614
        }
1✔
615

616
        return device, ""
1✔
617
}
618

619
// ParseVfRange: parse a device with VF range
620
// this can be rootDevices or PFName
621
// if no range detect we just return the device name
622
func ParseVfRange(device string) (rootDeviceName string, rngSt, rngEnd int, err error) {
1✔
623
        rngSt, rngEnd = invalidVfIndex, invalidVfIndex
1✔
624
        rootDeviceName, splitRange := SplitDeviceFromRange(device)
1✔
625
        if splitRange != "" {
2✔
626
                rngSt, rngEnd, err = parseRange(splitRange)
1✔
627
        } else {
2✔
628
                rootDeviceName = device
1✔
629
        }
1✔
630
        return
1✔
631
}
632

633
// IsEmpty returns true if nicSelector is empty
634
func (selector *SriovNetworkNicSelector) IsEmpty() bool {
1✔
635
        return selector.Vendor == "" &&
1✔
636
                selector.DeviceID == "" &&
1✔
637
                len(selector.RootDevices) == 0 &&
1✔
638
                len(selector.PfNames) == 0 &&
1✔
639
                len(selector.NetFilter) == 0
1✔
640
}
1✔
641

642
func (selector *SriovNetworkNicSelector) Selected(iface *InterfaceExt) bool {
1✔
643
        if selector.Vendor != "" && selector.Vendor != iface.Vendor {
1✔
644
                return false
×
645
        }
×
646
        if selector.DeviceID != "" && selector.DeviceID != iface.DeviceID {
1✔
647
                return false
×
648
        }
×
649
        if len(selector.RootDevices) > 0 && !StringInArray(iface.PciAddress, selector.RootDevices) {
2✔
650
                return false
1✔
651
        }
1✔
652
        if len(selector.PfNames) > 0 {
2✔
653
                var pfNames []string
1✔
654
                for _, p := range selector.PfNames {
2✔
655
                        if strings.Contains(p, "#") {
2✔
656
                                fields := strings.Split(p, "#")
1✔
657
                                pfNames = append(pfNames, fields[0])
1✔
658
                        } else {
2✔
659
                                pfNames = append(pfNames, p)
1✔
660
                        }
1✔
661
                }
662
                if !StringInArray(iface.Name, pfNames) {
1✔
663
                        return false
×
664
                }
×
665
        }
666
        if selector.NetFilter != "" && !NetFilterMatch(selector.NetFilter, iface.NetFilter) {
1✔
667
                return false
×
668
        }
×
669

670
        return true
1✔
671
}
672

673
func (s *SriovNetworkNodeState) GetInterfaceStateByPciAddress(addr string) *InterfaceExt {
1✔
674
        for _, iface := range s.Status.Interfaces {
1✔
675
                if addr == iface.PciAddress {
×
676
                        return &iface
×
677
                }
×
678
        }
679
        return nil
1✔
680
}
681

682
func (s *SriovNetworkNodeState) GetDriverByPciAddress(addr string) string {
×
683
        for _, iface := range s.Status.Interfaces {
×
684
                if addr == iface.PciAddress {
×
685
                        return iface.Driver
×
686
                }
×
687
        }
688
        return ""
×
689
}
690

691
// RenderNetAttDef renders a net-att-def for ib-sriov CNI
692
func (cr *SriovIBNetwork) RenderNetAttDef() (*uns.Unstructured, error) {
1✔
693
        logger := log.WithName("RenderNetAttDef")
1✔
694
        logger.Info("Start to render IB SRIOV CNI NetworkAttachmentDefinition")
1✔
695

1✔
696
        // render RawCNIConfig manifests
1✔
697
        data := render.MakeRenderData()
1✔
698
        data.Data["CniType"] = "ib-sriov"
1✔
699
        data.Data["SriovNetworkName"] = cr.Name
1✔
700
        if cr.Spec.NetworkNamespace == "" {
2✔
701
                data.Data["SriovNetworkNamespace"] = cr.Namespace
1✔
702
        } else {
2✔
703
                data.Data["SriovNetworkNamespace"] = cr.Spec.NetworkNamespace
1✔
704
        }
1✔
705
        data.Data["SriovCniResourceName"] = os.Getenv("RESOURCE_PREFIX") + "/" + cr.Spec.ResourceName
1✔
706

1✔
707
        data.Data["StateConfigured"] = true
1✔
708
        switch cr.Spec.LinkState {
1✔
709
        case SriovCniStateEnable:
1✔
710
                data.Data["SriovCniState"] = SriovCniStateEnable
1✔
711
        case SriovCniStateDisable:
×
712
                data.Data["SriovCniState"] = SriovCniStateDisable
×
713
        case SriovCniStateAuto:
×
714
                data.Data["SriovCniState"] = SriovCniStateAuto
×
715
        default:
1✔
716
                data.Data["StateConfigured"] = false
1✔
717
        }
718

719
        if cr.Spec.Capabilities == "" {
2✔
720
                data.Data["CapabilitiesConfigured"] = false
1✔
721
        } else {
2✔
722
                data.Data["CapabilitiesConfigured"] = true
1✔
723
                data.Data["SriovCniCapabilities"] = cr.Spec.Capabilities
1✔
724
        }
1✔
725

726
        if cr.Spec.IPAM != "" {
2✔
727
                data.Data["SriovCniIpam"] = SriovCniIpam + ":" + strings.Join(strings.Fields(cr.Spec.IPAM), "")
1✔
728
        } else {
2✔
729
                data.Data["SriovCniIpam"] = SriovCniIpamEmpty
1✔
730
        }
1✔
731

732
        // metaplugins for the infiniband cni
733
        data.Data["MetaPluginsConfigured"] = false
1✔
734
        if cr.Spec.MetaPluginsConfig != "" {
1✔
735
                data.Data["MetaPluginsConfigured"] = true
×
736
                data.Data["MetaPlugins"] = cr.Spec.MetaPluginsConfig
×
737
        }
×
738

739
        // logLevel and logFile are currently not supports by the ip-sriov-cni -> hardcode them to false.
740
        data.Data["LogLevelConfigured"] = false
1✔
741
        data.Data["LogFileConfigured"] = false
1✔
742

1✔
743
        objs, err := render.RenderDir(filepath.Join(ManifestsPath, "sriov"), &data)
1✔
744
        if err != nil {
1✔
745
                return nil, err
×
746
        }
×
747
        for _, obj := range objs {
2✔
748
                raw, _ := json.Marshal(obj)
1✔
749
                logger.Info("render NetworkAttachmentDefinition output", "raw", string(raw))
1✔
750
        }
1✔
751
        return objs[0], nil
1✔
752
}
753

754
// NetworkNamespace returns target network namespace for the network
755
func (cr *SriovIBNetwork) NetworkNamespace() string {
1✔
756
        return cr.Spec.NetworkNamespace
1✔
757
}
1✔
758

759
// RenderNetAttDef renders a net-att-def for sriov CNI
760
func (cr *SriovNetwork) RenderNetAttDef() (*uns.Unstructured, error) {
1✔
761
        logger := log.WithName("RenderNetAttDef")
1✔
762
        logger.Info("Start to render SRIOV CNI NetworkAttachmentDefinition")
1✔
763

1✔
764
        // render RawCNIConfig manifests
1✔
765
        data := render.MakeRenderData()
1✔
766
        data.Data["CniType"] = "sriov"
1✔
767
        data.Data["SriovNetworkName"] = cr.Name
1✔
768
        if cr.Spec.NetworkNamespace == "" {
2✔
769
                data.Data["SriovNetworkNamespace"] = cr.Namespace
1✔
770
        } else {
2✔
771
                data.Data["SriovNetworkNamespace"] = cr.Spec.NetworkNamespace
1✔
772
        }
1✔
773
        data.Data["SriovCniResourceName"] = os.Getenv("RESOURCE_PREFIX") + "/" + cr.Spec.ResourceName
1✔
774
        data.Data["SriovCniVlan"] = cr.Spec.Vlan
1✔
775

1✔
776
        if cr.Spec.VlanQoS <= 7 && cr.Spec.VlanQoS >= 0 {
2✔
777
                data.Data["VlanQoSConfigured"] = true
1✔
778
                data.Data["SriovCniVlanQoS"] = cr.Spec.VlanQoS
1✔
779
        } else {
1✔
780
                data.Data["VlanQoSConfigured"] = false
×
781
        }
×
782

783
        data.Data["VlanProtoConfigured"] = false
1✔
784
        if cr.Spec.VlanProto != "" {
2✔
785
                data.Data["VlanProtoConfigured"] = true
1✔
786
                data.Data["SriovCniVlanProto"] = cr.Spec.VlanProto
1✔
787
        }
1✔
788

789
        if cr.Spec.Capabilities == "" {
2✔
790
                data.Data["CapabilitiesConfigured"] = false
1✔
791
        } else {
1✔
792
                data.Data["CapabilitiesConfigured"] = true
×
793
                data.Data["SriovCniCapabilities"] = cr.Spec.Capabilities
×
794
        }
×
795

796
        data.Data["SpoofChkConfigured"] = true
1✔
797
        switch cr.Spec.SpoofChk {
1✔
798
        case SriovCniStateOff:
×
799
                data.Data["SriovCniSpoofChk"] = SriovCniStateOff
×
800
        case SriovCniStateOn:
1✔
801
                data.Data["SriovCniSpoofChk"] = SriovCniStateOn
1✔
802
        default:
1✔
803
                data.Data["SpoofChkConfigured"] = false
1✔
804
        }
805

806
        data.Data["TrustConfigured"] = true
1✔
807
        switch cr.Spec.Trust {
1✔
808
        case SriovCniStateOn:
1✔
809
                data.Data["SriovCniTrust"] = SriovCniStateOn
1✔
810
        case SriovCniStateOff:
×
811
                data.Data["SriovCniTrust"] = SriovCniStateOff
×
812
        default:
1✔
813
                data.Data["TrustConfigured"] = false
1✔
814
        }
815

816
        data.Data["StateConfigured"] = true
1✔
817
        switch cr.Spec.LinkState {
1✔
818
        case SriovCniStateEnable:
×
819
                data.Data["SriovCniState"] = SriovCniStateEnable
×
820
        case SriovCniStateDisable:
×
821
                data.Data["SriovCniState"] = SriovCniStateDisable
×
822
        case SriovCniStateAuto:
×
823
                data.Data["SriovCniState"] = SriovCniStateAuto
×
824
        default:
1✔
825
                data.Data["StateConfigured"] = false
1✔
826
        }
827

828
        data.Data["MinTxRateConfigured"] = false
1✔
829
        if cr.Spec.MinTxRate != nil {
1✔
830
                if *cr.Spec.MinTxRate >= 0 {
×
831
                        data.Data["MinTxRateConfigured"] = true
×
832
                        data.Data["SriovCniMinTxRate"] = *cr.Spec.MinTxRate
×
833
                }
×
834
        }
835

836
        data.Data["MaxTxRateConfigured"] = false
1✔
837
        if cr.Spec.MaxTxRate != nil {
1✔
838
                if *cr.Spec.MaxTxRate >= 0 {
×
839
                        data.Data["MaxTxRateConfigured"] = true
×
840
                        data.Data["SriovCniMaxTxRate"] = *cr.Spec.MaxTxRate
×
841
                }
×
842
        }
843

844
        if cr.Spec.IPAM != "" {
2✔
845
                data.Data["SriovCniIpam"] = SriovCniIpam + ":" + strings.Join(strings.Fields(cr.Spec.IPAM), "")
1✔
846
        } else {
2✔
847
                data.Data["SriovCniIpam"] = SriovCniIpamEmpty
1✔
848
        }
1✔
849

850
        data.Data["MetaPluginsConfigured"] = false
1✔
851
        if cr.Spec.MetaPluginsConfig != "" {
2✔
852
                data.Data["MetaPluginsConfigured"] = true
1✔
853
                data.Data["MetaPlugins"] = cr.Spec.MetaPluginsConfig
1✔
854
        }
1✔
855

856
        data.Data["LogLevelConfigured"] = (cr.Spec.LogLevel != "")
1✔
857
        data.Data["LogLevel"] = cr.Spec.LogLevel
1✔
858
        data.Data["LogFileConfigured"] = (cr.Spec.LogFile != "")
1✔
859
        data.Data["LogFile"] = cr.Spec.LogFile
1✔
860

1✔
861
        objs, err := render.RenderDir(filepath.Join(ManifestsPath, "sriov"), &data)
1✔
862
        if err != nil {
1✔
863
                return nil, err
×
864
        }
×
865
        for _, obj := range objs {
2✔
866
                raw, _ := json.Marshal(obj)
1✔
867
                logger.Info("render NetworkAttachmentDefinition output", "raw", string(raw))
1✔
868
        }
1✔
869
        return objs[0], nil
1✔
870
}
871

872
// NetworkNamespace returns target network namespace for the network
873
func (cr *SriovNetwork) NetworkNamespace() string {
1✔
874
        return cr.Spec.NetworkNamespace
1✔
875
}
1✔
876

877
// RenderNetAttDef renders a net-att-def for sriov CNI
878
func (cr *OVSNetwork) RenderNetAttDef() (*uns.Unstructured, error) {
1✔
879
        logger := log.WithName("RenderNetAttDef")
1✔
880
        logger.Info("Start to render OVS CNI NetworkAttachmentDefinition")
1✔
881

1✔
882
        // render RawCNIConfig manifests
1✔
883
        data := render.MakeRenderData()
1✔
884
        data.Data["CniType"] = "ovs"
1✔
885
        data.Data["NetworkName"] = cr.Name
1✔
886
        if cr.Spec.NetworkNamespace == "" {
2✔
887
                data.Data["NetworkNamespace"] = cr.Namespace
1✔
888
        } else {
2✔
889
                data.Data["NetworkNamespace"] = cr.Spec.NetworkNamespace
1✔
890
        }
1✔
891
        data.Data["CniResourceName"] = os.Getenv("RESOURCE_PREFIX") + "/" + cr.Spec.ResourceName
1✔
892

1✔
893
        if cr.Spec.Capabilities == "" {
2✔
894
                data.Data["CapabilitiesConfigured"] = false
1✔
895
        } else {
2✔
896
                data.Data["CapabilitiesConfigured"] = true
1✔
897
                data.Data["CniCapabilities"] = cr.Spec.Capabilities
1✔
898
        }
1✔
899

900
        data.Data["Bridge"] = cr.Spec.Bridge
1✔
901
        data.Data["VlanTag"] = cr.Spec.Vlan
1✔
902
        data.Data["MTU"] = cr.Spec.MTU
1✔
903
        if len(cr.Spec.Trunk) > 0 {
2✔
904
                trunkConfRaw, _ := json.Marshal(cr.Spec.Trunk)
1✔
905
                data.Data["Trunk"] = string(trunkConfRaw)
1✔
906
        } else {
2✔
907
                data.Data["Trunk"] = ""
1✔
908
        }
1✔
909
        data.Data["InterfaceType"] = cr.Spec.InterfaceType
1✔
910

1✔
911
        if cr.Spec.IPAM != "" {
2✔
912
                data.Data["CniIpam"] = SriovCniIpam + ":" + strings.Join(strings.Fields(cr.Spec.IPAM), "")
1✔
913
        } else {
2✔
914
                data.Data["CniIpam"] = SriovCniIpamEmpty
1✔
915
        }
1✔
916

917
        data.Data["MetaPluginsConfigured"] = false
1✔
918
        if cr.Spec.MetaPluginsConfig != "" {
2✔
919
                data.Data["MetaPluginsConfigured"] = true
1✔
920
                data.Data["MetaPlugins"] = cr.Spec.MetaPluginsConfig
1✔
921
        }
1✔
922

923
        objs, err := render.RenderDir(filepath.Join(ManifestsPath, "ovs"), &data)
1✔
924
        if err != nil {
1✔
925
                return nil, err
×
926
        }
×
927
        for _, obj := range objs {
2✔
928
                raw, _ := json.Marshal(obj)
1✔
929
                logger.Info("render NetworkAttachmentDefinition output", "raw", string(raw))
1✔
930
        }
1✔
931
        return objs[0], nil
1✔
932
}
933

934
// NetworkNamespace returns target network namespace for the network
935
func (cr *OVSNetwork) NetworkNamespace() string {
1✔
936
        return cr.Spec.NetworkNamespace
1✔
937
}
1✔
938

939
// NetFilterMatch -- parse netFilter and check for a match
940
func NetFilterMatch(netFilter string, netValue string) (isMatch bool) {
×
941
        logger := log.WithName("NetFilterMatch")
×
942

×
943
        var re = regexp.MustCompile(`(?m)^\s*([^\s]+)\s*:\s*([^\s]+)`)
×
944

×
945
        netFilterResult := re.FindAllStringSubmatch(netFilter, -1)
×
946

×
947
        if netFilterResult == nil {
×
948
                logger.Info("Invalid NetFilter spec...", "netFilter", netFilter)
×
949
                return false
×
950
        }
×
951

952
        netValueResult := re.FindAllStringSubmatch(netValue, -1)
×
953

×
954
        if netValueResult == nil {
×
955
                logger.Info("Invalid netValue...", "netValue", netValue)
×
956
                return false
×
957
        }
×
958

959
        return netFilterResult[0][1] == netValueResult[0][1] && netFilterResult[0][2] == netValueResult[0][2]
×
960
}
961

962
// MaxUnavailable calculate the max number of unavailable nodes to represent the number of nodes
963
// we can drain in parallel
964
func (s *SriovNetworkPoolConfig) MaxUnavailable(numOfNodes int) (int, error) {
1✔
965
        // this means we want to drain all the nodes in parallel
1✔
966
        if s.Spec.MaxUnavailable == nil {
2✔
967
                return -1, nil
1✔
968
        }
1✔
969
        intOrPercent := *s.Spec.MaxUnavailable
1✔
970

1✔
971
        if intOrPercent.Type == intstrutil.String {
2✔
972
                if strings.HasSuffix(intOrPercent.StrVal, "%") {
2✔
973
                        i := strings.TrimSuffix(intOrPercent.StrVal, "%")
1✔
974
                        v, err := strconv.Atoi(i)
1✔
975
                        if err != nil {
1✔
976
                                return 0, fmt.Errorf("invalid value %q: %v", intOrPercent.StrVal, err)
×
977
                        }
×
978
                        if v > 100 || v < 1 {
2✔
979
                                return 0, fmt.Errorf("invalid value: percentage needs to be between 1 and 100")
1✔
980
                        }
1✔
981
                } else {
1✔
982
                        return 0, fmt.Errorf("invalid type: strings needs to be a percentage")
1✔
983
                }
1✔
984
        }
985

986
        maxunavail, err := intstrutil.GetScaledValueFromIntOrPercent(&intOrPercent, numOfNodes, false)
1✔
987
        if err != nil {
1✔
988
                return 0, err
×
989
        }
×
990

991
        if maxunavail < 0 {
2✔
992
                return 0, fmt.Errorf("negative number is not allowed")
1✔
993
        }
1✔
994

995
        return maxunavail, nil
1✔
996
}
997

998
// GenerateBridgeName generate predictable name for the software bridge
999
// current format is: br-0000_00_03.0
1000
func GenerateBridgeName(iface *InterfaceExt) string {
1✔
1001
        return fmt.Sprintf("br-%s", strings.ReplaceAll(iface.PciAddress, ":", "_"))
1✔
1002
}
1✔
1003

1004
// NeedToUpdateBridges returns true if bridge for the host requires update
1005
func NeedToUpdateBridges(bridgeSpec, bridgeStatus *Bridges) bool {
1✔
1006
        return !reflect.DeepEqual(bridgeSpec, bridgeStatus)
1✔
1007
}
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc