-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathsriovenv.go
More file actions
801 lines (633 loc) · 26.5 KB
/
sriovenv.go
File metadata and controls
801 lines (633 loc) · 26.5 KB
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
// Package sriovenv provides SR-IOV test environment helpers for OCP tests.
// This package follows the CNF sriovenv pattern and uses eco-goinfra directly.
package sriovenv
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/rh-ecosystem-edge/eco-goinfra/pkg/nad"
"github.com/rh-ecosystem-edge/eco-goinfra/pkg/namespace"
"github.com/rh-ecosystem-edge/eco-goinfra/pkg/nodes"
"github.com/rh-ecosystem-edge/eco-goinfra/pkg/pod"
"github.com/rh-ecosystem-edge/eco-goinfra/pkg/sriov"
"github.com/rh-ecosystem-edge/eco-gotests/tests/internal/cluster"
"github.com/rh-ecosystem-edge/eco-gotests/tests/internal/sriovoperator"
. "github.com/rh-ecosystem-edge/eco-gotests/tests/ocp/sriov/internal/ocpsriovinittools"
"github.com/rh-ecosystem-edge/eco-gotests/tests/ocp/sriov/internal/tsparams"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/klog/v2"
)
const (
// DefaultMcpLabel is the default MachineConfigPool label for worker nodes.
DefaultMcpLabel = "machineconfiguration.openshift.io/role=worker"
)
// ============================================================================
// Operator & Cluster Stability
// ============================================================================
// CheckSriovOperatorStatus checks if SR-IOV operator is running and healthy.
func CheckSriovOperatorStatus() error {
return sriovoperator.IsSriovDeployed(APIClient, SriovOcpConfig.OcpSriovOperatorNamespace)
}
// WaitForSriovPolicyReady waits for SR-IOV policy to be ready and MCP stable.
// Uses the existing sriovoperator.WaitForSriovAndMCPStable function.
func WaitForSriovPolicyReady(timeout time.Duration) error {
return sriovoperator.WaitForSriovAndMCPStable(
APIClient,
timeout,
tsparams.MCPStableInterval,
"worker",
SriovOcpConfig.OcpSriovOperatorNamespace,
)
}
// ============================================================================
// Network Creation (using eco-goinfra directly)
// ============================================================================
// NetworkOption is a function that modifies a NetworkBuilder.
type NetworkOption func(*sriov.NetworkBuilder) *sriov.NetworkBuilder
// WithSpoof sets spoof checking on the network.
func WithSpoof(enabled bool) NetworkOption {
return func(nb *sriov.NetworkBuilder) *sriov.NetworkBuilder {
return nb.WithSpoof(enabled)
}
}
// WithTrust sets trust flag on the network.
func WithTrust(enabled bool) NetworkOption {
return func(nb *sriov.NetworkBuilder) *sriov.NetworkBuilder {
return nb.WithTrustFlag(enabled)
}
}
// WithVLAN sets VLAN ID on the network.
func WithVLAN(vlanID uint16) NetworkOption {
return func(nb *sriov.NetworkBuilder) *sriov.NetworkBuilder {
return nb.WithVLAN(vlanID)
}
}
// WithVlanQoS sets VLAN QoS on the network.
func WithVlanQoS(qos uint16) NetworkOption {
return func(nb *sriov.NetworkBuilder) *sriov.NetworkBuilder {
return nb.WithVlanQoS(qos)
}
}
// WithMinTxRate sets minimum TX rate on the network.
func WithMinTxRate(rate uint16) NetworkOption {
return func(nb *sriov.NetworkBuilder) *sriov.NetworkBuilder {
return nb.WithMinTxRate(rate)
}
}
// WithMaxTxRate sets maximum TX rate on the network.
func WithMaxTxRate(rate uint16) NetworkOption {
return func(nb *sriov.NetworkBuilder) *sriov.NetworkBuilder {
return nb.WithMaxTxRate(rate)
}
}
// WithLinkState sets link state on the network.
func WithLinkState(state string) NetworkOption {
return func(nb *sriov.NetworkBuilder) *sriov.NetworkBuilder {
return nb.WithLinkState(state)
}
}
// CreateSriovNetwork creates a SRIOV network and waits for NAD.
func CreateSriovNetwork(name, resourceName, targetNs string, opts ...NetworkOption) error {
sriovOpNs := SriovOcpConfig.OcpSriovOperatorNamespace
networkBuilder := sriov.NewNetworkBuilder(APIClient, name, sriovOpNs, targetNs, resourceName).
WithStaticIpam().WithMacAddressSupport().WithIPAddressSupport().WithLogLevel("debug")
for _, opt := range opts {
networkBuilder = opt(networkBuilder)
}
if _, err := networkBuilder.Create(); err != nil {
return fmt.Errorf("failed to create network %q: %w", name, err)
}
return WaitForNADCreation(name, targetNs, tsparams.NADTimeout)
}
// WaitForNADCreation waits for NetworkAttachmentDefinition to be created.
func WaitForNADCreation(name, namespace string, timeout time.Duration) error {
return wait.PollUntilContextTimeout(context.Background(), tsparams.PollingInterval, timeout, true,
func(ctx context.Context) (bool, error) {
_, err := nad.Pull(APIClient, name, namespace)
return err == nil, nil
})
}
// RemoveSriovNetwork removes a SRIOV network by name.
func RemoveSriovNetwork(name string, timeout time.Duration) error {
sriovOpNs := SriovOcpConfig.OcpSriovOperatorNamespace
network, err := sriov.PullNetwork(APIClient, name, sriovOpNs)
if err != nil {
// eco-goinfra's PullNetwork returns custom error, not k8s NotFound
if strings.Contains(err.Error(), "does not exist") {
return nil // Already deleted
}
return fmt.Errorf("failed to pull network %q: %w", name, err)
}
return network.DeleteAndWait(timeout)
}
// ============================================================================
// Policy Management
// ============================================================================
// RemoveSriovPolicy removes a SRIOV policy by name and waits for deletion.
func RemoveSriovPolicy(name string, timeout time.Duration) error {
sriovOpNs := SriovOcpConfig.OcpSriovOperatorNamespace
policy, err := sriov.PullPolicy(APIClient, name, sriovOpNs)
if err != nil {
// eco-goinfra's PullPolicy returns custom error, not k8s NotFound
// See: https://github.com/rh-ecosystem-edge/eco-goinfra/blob/main/pkg/sriov/policy.go#L289
if strings.Contains(err.Error(), "does not exist") {
return nil // Already deleted
}
return fmt.Errorf("failed to pull policy %q: %w", name, err)
}
if err := policy.Delete(); err != nil {
return fmt.Errorf("failed to delete policy %q: %w", name, err)
}
// Wait for policy to be deleted
return wait.PollUntilContextTimeout(context.Background(), tsparams.PollingInterval, timeout, true,
func(ctx context.Context) (bool, error) {
_, pullErr := sriov.PullPolicy(APIClient, name, sriovOpNs)
return pullErr != nil, nil // Policy is gone when pull fails
})
}
// InitVF initializes VF for the given device using netdevice driver.
// Note: This function creates a policy on the first node where the device is found
// and returns immediately. It does not create policies on multiple nodes.
// This is suitable for single-node testing or when only one node needs the VF.
func InitVF(name, deviceID, interfaceName, vendor string, vfNum int, workerNodes []*nodes.Builder) (bool, error) {
return initVFWithDevType(name, deviceID, interfaceName, vendor, "netdevice", vfNum, workerNodes)
}
// InitDpdkVF initializes DPDK VF for the given device using vfio-pci driver.
// Note: This function creates a policy on the first node where the device is found
// and returns immediately. It does not create policies on multiple nodes.
// This is suitable for single-node testing or when only one node needs the VF.
func InitDpdkVF(name, deviceID, interfaceName, vendor string, vfNum int, workerNodes []*nodes.Builder) (bool, error) {
return initVFWithDevType(name, deviceID, interfaceName, vendor, "vfio-pci", vfNum, workerNodes)
}
// initVFWithDevType creates an SR-IOV policy for the specified device type.
// It iterates through worker nodes and creates a policy on the first node where
// the device is successfully discovered. Returns (true, nil) on success.
func initVFWithDevType(name, deviceID, interfaceName, vendor, devType string, vfNum int,
workerNodes []*nodes.Builder) (bool, error) {
if vfNum <= 0 {
return false, fmt.Errorf("vfNum must be > 0, got %d", vfNum)
}
sriovOpNs := SriovOcpConfig.OcpSriovOperatorNamespace
// Cleanup existing policy
_ = RemoveSriovPolicy(name, tsparams.NamespaceTimeout)
for _, node := range workerNodes {
nodeName := node.Definition.Name
// Try to discover the actual interface name
actualInterface := interfaceName
// Only discover interface if not explicitly provided
// This allows users to specify exact interface for multi-port NICs
if interfaceName == "" && vendor != "" && deviceID != "" {
if discovered, err := discoverInterfaceName(nodeName, vendor, deviceID); err == nil {
actualInterface = discovered
}
}
if actualInterface == "" {
klog.V(90).Infof("No interface resolved on node %q (vendor=%q deviceID=%q)", nodeName, vendor, deviceID)
continue
}
pfSelector := fmt.Sprintf("%s#0-%d", actualInterface, vfNum-1)
policy := sriov.NewPolicyBuilder(APIClient, name, sriovOpNs, name, vfNum,
[]string{pfSelector}, map[string]string{"kubernetes.io/hostname": nodeName}).
WithDevType(devType)
if vendor != "" {
policy.Definition.Spec.NicSelector.Vendor = vendor
}
if deviceID != "" {
policy.Definition.Spec.NicSelector.DeviceID = deviceID
}
policy.Definition.Spec.EswitchMode = "legacy"
if _, err := policy.Create(); err != nil {
klog.V(90).Infof("Failed to create policy on node %q: %v", nodeName, err)
continue
}
if err := WaitForSriovPolicyReady(tsparams.PolicyApplicationTimeout); err != nil {
klog.V(90).Infof("Policy not ready on node %q: %v", nodeName, err)
_ = policy.Delete()
continue
}
klog.V(90).Infof("Successfully created policy %q on node %q", name, nodeName)
return true, nil
}
return false, fmt.Errorf("failed to create policy %q on any node", name)
}
// discoverInterfaceName discovers the actual interface name on a node by matching Vendor and DeviceID.
func discoverInterfaceName(nodeName, vendor, deviceID string) (string, error) {
sriovOpNs := SriovOcpConfig.OcpSriovOperatorNamespace
nodeState := sriov.NewNetworkNodeStateBuilder(APIClient, nodeName, sriovOpNs)
if err := nodeState.Discover(); err != nil {
return "", err
}
if nodeState.Objects == nil || nodeState.Objects.Status.Interfaces == nil {
return "", fmt.Errorf("no interfaces found on node %q", nodeName)
}
for _, iface := range nodeState.Objects.Status.Interfaces {
if iface.Vendor == vendor && iface.DeviceID == deviceID {
return iface.Name, nil
}
}
return "", fmt.Errorf("no interface found matching vendor %q deviceID %q", vendor, deviceID)
}
// UpdateSriovPolicyMTU updates the MTU of an existing SR-IOV policy.
// PolicyBuilder does not have Update method, so we delete and recreate.
// Note: This causes brief service disruption as VFs are deallocated and reallocated.
func UpdateSriovPolicyMTU(policyName string, mtuValue int) error {
sriovOpNs := SriovOcpConfig.OcpSriovOperatorNamespace
policy, err := sriov.PullPolicy(APIClient, policyName, sriovOpNs)
if err != nil {
return err
}
// Store a deep copy of the entire spec to preserve all fields
// (IsRdma, LinkType, ESwitchMode, ExternallyManaged, VdpaType, etc.)
spec := policy.Definition.Spec.DeepCopy()
spec.Mtu = mtuValue
// Delete the existing policy
if err = policy.Delete(); err != nil {
return fmt.Errorf("failed to delete policy %q for MTU update: %w", policyName, err)
}
// Recreate with the full spec (preserving all original settings)
newPolicy := sriov.NewPolicyBuilder(
APIClient,
policyName,
sriovOpNs,
spec.ResourceName,
spec.NumVfs,
spec.NicSelector.PfNames,
spec.NodeSelector,
)
// Copy the entire spec to preserve all fields
newPolicy.Definition.Spec = *spec
_, err = newPolicy.Create()
if err != nil {
return fmt.Errorf("failed to recreate policy %q with new MTU: %w", policyName, err)
}
return nil
}
// ============================================================================
// Pod Creation (following CNF pattern)
// ============================================================================
// CreateTestPod creates a test pod with SRIOV network.
func CreateTestPod(name, namespace, networkName, ip, mac string) (*pod.Builder, error) {
secNetwork := pod.StaticIPAnnotationWithMacAddress(networkName, []string{ip}, mac)
podBuilder := pod.NewBuilder(APIClient, name, namespace, SriovOcpConfig.OcpSriovTestContainer).
WithPrivilegedFlag().
WithSecondaryNetwork(secNetwork)
createdPod, err := podBuilder.Create()
if err != nil {
return nil, fmt.Errorf("failed to create pod %q: %w", name, err)
}
if err := createdPod.WaitUntilReady(tsparams.PodReadyTimeout); err != nil {
return createdPod, fmt.Errorf("pod %q not ready: %w", name, err)
}
return createdPod, nil
}
// CreateDpdkTestPod creates a DPDK test pod with SR-IOV network.
func CreateDpdkTestPod(name, namespace, networkName string) (*pod.Builder, error) {
secNetwork := pod.StaticIPAnnotationWithMacAddress(networkName,
[]string{tsparams.TestPodClientIP}, tsparams.TestPodClientMAC)
podBuilder := pod.NewBuilder(APIClient, name, namespace, SriovOcpConfig.OcpSriovTestContainer).
WithPrivilegedFlag().
WithSecondaryNetwork(secNetwork).
WithLabel("name", "sriov-dpdk")
createdPod, err := podBuilder.Create()
if err != nil {
return nil, fmt.Errorf("failed to create DPDK pod %q: %w", name, err)
}
if err := createdPod.WaitUntilReady(tsparams.PodReadyTimeout); err != nil {
return createdPod, fmt.Errorf("DPDK pod %q not ready: %w", name, err)
}
return createdPod, nil
}
// DeleteDpdkTestPod deletes a DPDK test pod.
func DeleteDpdkTestPod(name, namespace string, timeout time.Duration) error {
podBuilder, err := pod.Pull(APIClient, name, namespace)
if err != nil {
// Check both API error and eco-goinfra's custom error message
if apierrors.IsNotFound(err) || strings.Contains(err.Error(), "does not exist") {
return nil // Already deleted
}
return fmt.Errorf("failed to pull pod %q: %w", name, err)
}
_, err = podBuilder.DeleteAndWait(timeout)
return err
}
// WaitForPodWithLabelReady waits for a pod with specific label to be ready.
func WaitForPodWithLabelReady(namespace, labelSelector string, timeout time.Duration) error {
return wait.PollUntilContextTimeout(context.Background(), tsparams.PollingInterval, timeout, true,
func(ctx context.Context) (bool, error) {
podList, err := pod.List(APIClient, namespace, metav1.ListOptions{LabelSelector: labelSelector})
if err != nil || len(podList) == 0 {
return false, nil
}
// Check if all pods are ready
for _, podItem := range podList {
if podItem.Object == nil {
return false, nil
}
// Check pod phase
if podItem.Object.Status.Phase != corev1.PodRunning {
return false, nil
}
// Check container ready conditions
allReady := true
for _, containerStatus := range podItem.Object.Status.ContainerStatuses {
if !containerStatus.Ready {
allReady = false
break
}
}
if !allReady {
return false, nil
}
}
return true, nil
})
}
// ============================================================================
// Interface Verification
// ============================================================================
// VerifyInterfaceReady verifies that a pod's network interface is ready.
func VerifyInterfaceReady(podObj *pod.Builder, interfaceName string) error {
output, err := podObj.ExecCommand([]string{"ip", "link", "show", interfaceName})
if err != nil {
return fmt.Errorf("failed to check interface %q: %w", interfaceName, err)
}
if !strings.Contains(output.String(), "UP") {
return fmt.Errorf("interface %q is not UP", interfaceName)
}
return nil
}
// CheckInterfaceCarrier checks if interface has carrier.
func CheckInterfaceCarrier(podObj *pod.Builder, interfaceName string) (bool, error) {
output, err := podObj.ExecCommand([]string{"ip", "link", "show", interfaceName})
if err != nil {
return false, err
}
return !strings.Contains(output.String(), "NO-CARRIER"), nil
}
// ExtractPodInterfaceMAC extracts the MAC address from a pod's interface.
func ExtractPodInterfaceMAC(podObj *pod.Builder, interfaceName string) (string, error) {
output, err := podObj.ExecCommand([]string{"ip", "link", "show", interfaceName})
if err != nil {
return "", err
}
for _, line := range strings.Split(output.String(), "\n") {
if strings.Contains(line, "link/ether") {
parts := strings.Fields(line)
for i, p := range parts {
if p == "link/ether" && i+1 < len(parts) {
return parts[i+1], nil
}
}
}
}
return "", fmt.Errorf("MAC not found for %q", interfaceName)
}
// ============================================================================
// Traffic & Connectivity Tests
// ============================================================================
// CheckVFStatusWithPassTraffic creates test pods and verifies connectivity.
func CheckVFStatusWithPassTraffic(networkName, interfaceName, namespace, description string,
timeout time.Duration) error {
klog.V(90).Infof("Checking VF status: %q (network: %q, ns: %q)", description, networkName, namespace)
// Generate unique suffix for pod names to avoid collisions
suffix := fmt.Sprintf("%d", time.Now().UnixNano()%100000)
// Create client and server pods with unique names
clientPodName := fmt.Sprintf("client-%s", suffix)
serverPodName := fmt.Sprintf("server-%s", suffix)
clientPod, err := CreateTestPod(clientPodName, namespace, networkName,
tsparams.TestPodClientIP, tsparams.TestPodClientMAC)
if err != nil {
return fmt.Errorf("failed to create client pod: %w", err)
}
defer func() {
if clientPod != nil {
_, _ = clientPod.DeleteAndWait(tsparams.CleanupTimeout)
}
}()
serverPod, err := CreateTestPod(serverPodName, namespace, networkName,
tsparams.TestPodServerIP, tsparams.TestPodServerMAC)
if err != nil {
return fmt.Errorf("failed to create server pod: %w", err)
}
defer func() {
if serverPod != nil {
_, _ = serverPod.DeleteAndWait(tsparams.CleanupTimeout)
}
}()
// Verify interfaces
if err := VerifyInterfaceReady(clientPod, "net1"); err != nil {
return fmt.Errorf("client interface not ready: %w", err)
}
if err := VerifyInterfaceReady(serverPod, "net1"); err != nil {
return fmt.Errorf("server interface not ready: %w", err)
}
// Check carrier
hasCarrier, err := CheckInterfaceCarrier(clientPod, "net1")
if err != nil {
return fmt.Errorf("failed to check carrier: %w", err)
}
if !hasCarrier {
return fmt.Errorf("NO-CARRIER: no physical connection")
}
// Verify spoof checking if in description
if strings.Contains(description, "spoof checking") {
expectedState := "on"
if strings.Contains(description, "off") {
expectedState = "off"
}
if err := verifySpoofCheck(clientPod, interfaceName, expectedState); err != nil {
return fmt.Errorf("spoof check verification failed: %w", err)
}
}
// Test connectivity
serverIP := strings.Split(tsparams.TestPodServerIP, "/")[0]
_, err = clientPod.ExecCommand([]string{"ping", "-c", "3", serverIP})
if err != nil {
return fmt.Errorf("ping failed: %w", err)
}
klog.V(90).Infof("VF status verification completed successfully: %q", description)
return nil
}
// VerifyLinkStateConfiguration verifies link state configuration without requiring connectivity.
// It waits up to CarrierWaitTimeout for carrier status to be established before returning.
func VerifyLinkStateConfiguration(networkName, namespace, description string,
timeout time.Duration) (bool, error) {
klog.V(90).Infof("Verifying link state: %q (network: %q, ns: %q)", description, networkName, namespace)
// Generate unique pod name to avoid collisions
podName := fmt.Sprintf("linkstate-test-%d", time.Now().UnixNano()%100000)
testPod, err := CreateTestPod(podName, namespace, networkName,
tsparams.TestPodClientIP, tsparams.TestPodClientMAC)
if err != nil {
return false, fmt.Errorf("failed to create test pod: %w", err)
}
defer func() {
if testPod != nil {
_, _ = testPod.DeleteAndWait(tsparams.CleanupTimeout)
}
}()
if err := VerifyInterfaceReady(testPod, "net1"); err != nil {
return false, fmt.Errorf("interface not ready: %w", err)
}
// Wait for carrier status with retry - VF link state may take time to propagate
var hasCarrier bool
err = wait.PollUntilContextTimeout(context.Background(), tsparams.PollingInterval,
tsparams.CarrierWaitTimeout, true, func(ctx context.Context) (bool, error) {
carrier, checkErr := CheckInterfaceCarrier(testPod, "net1")
if checkErr != nil {
klog.V(90).Infof("Carrier check failed (will retry): %v", checkErr)
return false, nil
}
hasCarrier = carrier
if !carrier {
klog.V(90).Infof("Interface has NO-CARRIER, waiting for link...")
return false, nil
}
return true, nil
})
if err != nil {
// Timeout waiting for carrier - return false but no error (let test decide to skip)
klog.V(90).Infof("Carrier wait timed out after %v", tsparams.CarrierWaitTimeout)
return false, nil
}
return hasCarrier, nil
}
// ============================================================================
// Spoof Check Verification
// ============================================================================
func verifySpoofCheck(clientPod *pod.Builder, interfaceName, expectedState string) error {
// Get node name
refreshedPod, err := pod.Pull(APIClient, clientPod.Definition.Name, clientPod.Definition.Namespace)
if err != nil {
return fmt.Errorf("failed to refresh pod: %w", err)
}
nodeName := refreshedPod.Definition.Spec.NodeName
if nodeName == "" {
return fmt.Errorf("pod node name is empty")
}
// Execute on node via cluster helper
outputMap, err := cluster.ExecCmdWithStdout(APIClient, fmt.Sprintf("ip link show %s", interfaceName),
metav1.ListOptions{LabelSelector: fmt.Sprintf("kubernetes.io/hostname=%s", nodeName)})
if err != nil {
return fmt.Errorf("failed to execute on node: %w", err)
}
output, ok := outputMap[nodeName]
if !ok {
// Try to find by short hostname
for host, out := range outputMap {
if strings.HasPrefix(nodeName, host) || strings.HasPrefix(host, nodeName) {
output = out
break
}
}
if output == "" {
return fmt.Errorf("no output from node %s", nodeName)
}
}
// Search VF lines for the expected spoof check state.
// Note: In switchdev mode (e.g., Mellanox CX6-DX), `ip link show <PF>` reports VF MACs as
// 00:00:00:00:00:00 regardless of the MAC assigned inside the pod, so matching by MAC address
// is unreliable. Instead, we check any VF line for the expected state, since the SR-IOV policy
// applies a uniform spoof checking configuration to all VFs it creates.
vfLinesFound := 0
for _, line := range strings.Split(output, "\n") {
if !strings.Contains(line, "vf ") {
continue
}
vfLinesFound++
if strings.Contains(line, fmt.Sprintf("spoof checking %s", expectedState)) ||
strings.Contains(line, fmt.Sprintf("spoofchk %s", expectedState)) {
klog.V(90).Infof("Spoof check verified: %s on interface %s", expectedState, interfaceName)
return nil
}
}
if vfLinesFound == 0 {
return fmt.Errorf("no VF information found in ip link show output for interface %s", interfaceName)
}
return fmt.Errorf("spoof check %s not found for interface %s", expectedState, interfaceName)
}
// ============================================================================
// PCI Address
// ============================================================================
// GetPciAddress gets the PCI address for a pod interface from network status annotation.
// The podInterface parameter should be the interface name (e.g., "net1", "net2") which is unique per pod.
func GetPciAddress(namespace, podName, podInterface string) (string, error) {
podObj, err := pod.Pull(APIClient, podName, namespace)
if err != nil {
return "", fmt.Errorf("failed to pull pod: %w", err)
}
annotation := podObj.Object.Annotations["k8s.v1.cni.cncf.io/network-status"]
if annotation == "" {
return "", fmt.Errorf("no network status annotation")
}
var status []struct {
Interface string `json:"interface"`
DeviceInfo struct {
Pci struct {
PciAddress string `json:"pci-address"`
} `json:"pci"`
} `json:"device-info"`
}
if err := json.Unmarshal([]byte(annotation), &status); err != nil {
return "", fmt.Errorf("failed to parse network status: %w", err)
}
for _, networkStatus := range status {
if networkStatus.Interface == podInterface {
if networkStatus.DeviceInfo.Pci.PciAddress != "" {
return networkStatus.DeviceInfo.Pci.PciAddress, nil
}
return "", fmt.Errorf("PCI address not present for interface %s", podInterface)
}
}
return "", fmt.Errorf("interface %s not found in pod %s", podInterface, podName)
}
// ============================================================================
// Cleanup Functions
// ============================================================================
// CleanupLeftoverResources cleans up leftover test resources.
// Uses existing sriovoperator functions to remove all networks and policies.
func CleanupLeftoverResources() error {
sriovOpNs := SriovOcpConfig.OcpSriovOperatorNamespace
klog.V(90).Info("Cleaning up leftover test resources")
// Cleanup test namespaces using label selector for safety in shared clusters.
// Falls back to name-based matching (e2e- prefix) for backwards compatibility.
labelSelector := fmt.Sprintf("%s=%s", tsparams.TestResourceLabelKey, tsparams.TestResourceLabelValue)
namespaces, err := namespace.List(APIClient, metav1.ListOptions{LabelSelector: labelSelector})
if err != nil {
klog.V(90).Infof("Warning: failed to list namespaces with label selector: %v", err)
}
for _, ns := range namespaces {
klog.V(90).Infof("Removing labeled test namespace %q", ns.Definition.Name)
if delErr := ns.DeleteAndWait(tsparams.CleanupTimeout); delErr != nil {
klog.V(90).Infof("Warning: failed to delete namespace %q: %v", ns.Definition.Name, delErr)
}
}
// Fallback: Also cleanup namespaces with e2e- prefix (for backwards compatibility)
allNamespaces, err := namespace.List(APIClient, metav1.ListOptions{})
if err != nil {
klog.V(90).Infof("Warning: failed to list all namespaces: %v", err)
}
for _, ns := range allNamespaces {
if strings.HasPrefix(ns.Definition.Name, "e2e-") {
klog.V(90).Infof("Removing leftover namespace %q (e2e- prefix)", ns.Definition.Name)
if delErr := ns.DeleteAndWait(tsparams.CleanupTimeout); delErr != nil {
klog.V(90).Infof("Warning: failed to delete namespace %q: %v", ns.Definition.Name, delErr)
}
}
}
// Remove all SR-IOV networks using existing function
if err := sriovoperator.RemoveAllSriovNetworks(APIClient, sriovOpNs, tsparams.CleanupTimeout); err != nil {
klog.V(90).Infof("Warning: failed to remove SR-IOV networks: %v", err)
}
// Remove all SR-IOV policies and wait for stability using existing function
if err := sriovoperator.RemoveAllPoliciesAndWaitForSriovAndMCPStable(
APIClient, "worker", sriovOpNs, tsparams.CleanupTimeout); err != nil {
klog.V(90).Infof("Warning: failed to remove SR-IOV policies: %v", err)
}
klog.V(90).Info("Cleanup completed")
return nil
}