Skip to content

Commit 509f5b3

Browse files
committed
Fix another set of lint errors
1 parent 7a55689 commit 509f5b3

13 files changed

Lines changed: 142 additions & 133 deletions

File tree

pkg/plugin/common/common_windows.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@
55
package common
66

77
import (
8+
"errors"
9+
"fmt"
10+
811
"golang.org/x/sys/windows/registry"
912
)
1013

@@ -22,19 +25,19 @@ const (
2225
func IsCiliumOnWindowsEnabled() (bool, error) {
2326
k, err := registry.OpenKey(registry.LOCAL_MACHINE, KeyPath, registry.QUERY_VALUE)
2427
if err != nil {
25-
if err == registry.ErrNotExist {
28+
if errors.Is(err, registry.ErrNotExist) {
2629
return false, nil
2730
}
28-
return false, err
31+
return false, fmt.Errorf("opening registry key: %w", err)
2932
}
3033
defer k.Close()
3134

3235
val, _, err := k.GetIntegerValue(ValueName)
3336
if err != nil {
34-
if err == registry.ErrNotExist {
37+
if errors.Is(err, registry.ErrNotExist) {
3538
return false, nil
3639
}
37-
return false, err
40+
return false, fmt.Errorf("reading registry value: %w", err)
3841
}
3942
return val == 1, nil
4043
}

pkg/plugin/ebpfwindows/datapath_drop_windows.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ func (n *DropNotify) decodeDropNotify(data []byte) error {
170170
n.DstID = byteorder.Native.Uint32(data[24:28])
171171
n.Line = byteorder.Native.Uint16(data[28:30])
172172
n.File = data[30]
173-
n.ExtError = int8(data[31])
173+
n.ExtError = int8(data[31]) //nolint:gosec // data[31] is a bounded error code field that fits in int8
174174
n.Ifindex = byteorder.Native.Uint32(data[32:36])
175175

176176
return nil

pkg/plugin/ebpfwindows/ebpf_windows.go

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,9 @@ func (p *Plugin) Start(ctx context.Context) error {
8585
p.l.Info("Start ebpfWindows plugin...")
8686

8787
ciliumEnabled, err := isCiliumOnWindowsEnabled()
88-
8988
if err != nil {
9089
p.l.Error("Error while checking if Cilium is enabled on Windows", zap.Error(err))
91-
return fmt.Errorf("Failed to check if Cilium is enabled on Windows: %w", err)
90+
return fmt.Errorf("failed to check if Cilium is enabled on Windows: %w", err)
9291
}
9392

9493
if !ciliumEnabled {
@@ -131,24 +130,26 @@ func (p *Plugin) metricsMapIterateCallback(key *MetricsKey, value *MetricsValue)
131130
}
132131
if key.IsDrop() {
133132
p.l.Debug("MetricsMapIterateCallback Drop", zap.String("key", key.String()))
134-
if key.IsEgress() {
133+
switch {
134+
case key.IsEgress():
135135
metrics.DropBytesGauge.WithLabelValues(key.DropForwardReason(), egressLabel).Set(float64(value.Bytes))
136136
metrics.DropPacketsGauge.WithLabelValues(key.DropForwardReason(), egressLabel).Set(float64(value.Count))
137-
} else if key.IsIngress() {
137+
case key.IsIngress():
138138
metrics.DropBytesGauge.WithLabelValues(key.DropForwardReason(), ingressLabel).Set(float64(value.Bytes))
139139
metrics.DropPacketsGauge.WithLabelValues(key.DropForwardReason(), ingressLabel).Set(float64(value.Count))
140-
} else {
140+
default:
141141
p.l.Error("MetricsMapIterateCallback drop key is neither ingress nor egress", zap.String("key", key.String()))
142142
}
143143
} else {
144144
p.l.Debug("MetricsMapIterateCallback Forward", zap.String("key", key.String()))
145-
if key.IsEgress() {
145+
switch {
146+
case key.IsEgress():
146147
metrics.ForwardPacketsGauge.WithLabelValues(egressLabel).Set(float64(value.Count))
147148
metrics.ForwardBytesGauge.WithLabelValues(egressLabel).Set(float64(value.Bytes))
148-
} else if key.IsIngress() {
149+
case key.IsIngress():
149150
metrics.ForwardPacketsGauge.WithLabelValues(ingressLabel).Set(float64(value.Count))
150151
metrics.ForwardBytesGauge.WithLabelValues(ingressLabel).Set(float64(value.Bytes))
151-
} else {
152+
default:
152153
p.l.Error("MetricsMapIterateCallback forward key is neither ingress nor egress", zap.String("key", key.String()))
153154
}
154155
}
@@ -216,16 +217,13 @@ func (p *Plugin) pullMetricsAndEvents(ctx context.Context) {
216217
}
217218

218219
lostEventsCount, err := GetLostEventsCount()
219-
220220
if err != nil {
221221
p.l.Error("Error getting lost events count", zap.Error(err))
222-
} else {
222+
} else if lostEventsCount > prevLostEventsCount {
223223
// The lost events count is cumulative, so we need to calculate the difference
224-
if lostEventsCount > prevLostEventsCount {
225-
counterToAdd := lostEventsCount - prevLostEventsCount
226-
metrics.LostEventsCounter.WithLabelValues(utils.Kernel, name).Add(float64(counterToAdd))
227-
prevLostEventsCount = lostEventsCount
228-
}
224+
counterToAdd := lostEventsCount - prevLostEventsCount
225+
metrics.LostEventsCounter.WithLabelValues(utils.Kernel, name).Add(float64(counterToAdd))
226+
prevLostEventsCount = lostEventsCount
229227
}
230228

231229
case <-ctx.Done():

pkg/plugin/ebpfwindows/ebpf_windows_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ const (
3434
)
3535

3636
var errTestFailure = errors.New("test failure")
37+
var errModuleNotFound = errors.New("module not found")
3738

3839
func makeMockEthernetIPv4TCPPacket() []byte {
3940
eth := &layers.Ethernet{
@@ -762,7 +763,7 @@ func TestStart_GracefullySkipsWhenRetinaEbpfAPIMissing(t *testing.T) {
762763
return true, nil
763764
}
764765
loadRetinaEbpfAPI = func() error {
765-
return fmt.Errorf("module not found")
766+
return errModuleNotFound
766767
}
767768
defer func() {
768769
isCiliumOnWindowsEnabled = origIsCiliumOnWindowsEnabled

pkg/plugin/ebpfwindows/metricsmap_windows.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package ebpfwindows
22

33
import (
4+
"errors"
45
"fmt"
56
"syscall"
67
"unsafe"
@@ -70,7 +71,7 @@ var enumCallBack enumMetricsCallback
7071
// This function will be passed to the Windows API
7172
func enumMetricsSysCallCallback(key, value unsafe.Pointer) uintptr {
7273
if enumCallBack != nil {
73-
return uintptr(enumCallBack(key, value))
74+
return uintptr(enumCallBack(key, value)) //nolint:gosec // callback return is a bounded status code
7475
}
7576

7677
return 0
@@ -87,7 +88,7 @@ var callEnumMetricsMap = func(callback uintptr) (uintptr, uintptr, error) {
8788

8889
var loadRetinaEbpfAPI = func() error {
8990
if err := retinaEbpfAPI.Load(); err != nil {
90-
return err
91+
return fmt.Errorf("loading retinaEbpfAPI: %w", err)
9192
}
9293

9394
for _, proc := range []*windows.LazyProc{
@@ -97,7 +98,7 @@ var loadRetinaEbpfAPI = func() error {
9798
unregisterEventsMapCallback,
9899
} {
99100
if err := proc.Find(); err != nil {
100-
return err
101+
return fmt.Errorf("finding proc %s: %w", proc.Name, err)
101102
}
102103
}
103104

@@ -195,7 +196,7 @@ func (k *MetricsKey) IsEgress() bool {
195196

196197
func GetLostEventsCount() (uint64, error) {
197198
ret, _, err := lostEventCount.Call()
198-
if err != nil && err != syscall.Errno(0) {
199+
if err != nil && !errors.Is(err, syscall.Errno(0)) {
199200
return 0, fmt.Errorf("RetinaGetLostEventsCount call failed: %w", err)
200201
}
201202
return uint64(ret), nil

pkg/plugin/ebpfwindows/parser_windows.go

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@ import (
2424
"google.golang.org/protobuf/types/known/wrapperspb"
2525
)
2626

27-
const MaxInt = int(^uint(0) >> 1)
28-
const MessageTypePktmonDrop = 100
27+
const (
28+
MaxInt = int(^uint(0) >> 1)
29+
MessageTypePktmonDrop = 100
30+
)
2931

3032
type PktmonPacketType uint8
3133

@@ -53,9 +55,11 @@ type Parser struct {
5355
}
5456

5557
var (
56-
errDataOffsetTooLarge = errorTypes.New("data offset too large")
57-
errNotEnoughBytes = errorTypes.New("not enough bytes to decode")
58-
errDropReasonOverflow = errorTypes.New("drop reason exceeds int32 range")
58+
errDataOffsetTooLarge = errorTypes.New("data offset too large")
59+
errNotEnoughBytes = errorTypes.New("not enough bytes to decode")
60+
errDropReasonOverflow = errorTypes.New("drop reason exceeds int32 range")
61+
errUnsupportedIPPacketType = errorTypes.New("decode layers failed for unsupported IP packet type")
62+
errUnsupportedPktmonPacketType = errorTypes.New("decode layers failed for unsupported packet type")
5963
)
6064

6165
// re-usable packet to avoid reallocating gopacket datastructures
@@ -151,7 +155,7 @@ func (p *Parser) Decode(monitorEvent *observerTypes.MonitorEvent) (*v1.Event, er
151155
}
152156

153157
// Decode decodes the data from 'data' into 'decoded'
154-
func (p *Parser) decode(data []byte, decoded *pb.Flow) error {
158+
func (p *Parser) decode(data []byte, decoded *pb.Flow) error { //nolint:gocyclo // complexity is inherent to protocol decoding logic
155159
if len(data) == 0 {
156160
return errors.ErrEmptyData
157161
}
@@ -244,10 +248,10 @@ func (p *Parser) decode(data []byte, decoded *pb.Flow) error {
244248
case 0x6:
245249
err = p.packet.decLayerL3Dev.IPv6.DecodeLayers(data[packetOffset:], &p.packet.Layers)
246250
default:
247-
return fmt.Errorf("decode layers failed for unsupported IP packet type starting with %d, data: %v", data[packetOffset], data[packetOffset:])
251+
return fmt.Errorf("%w: starting with %d, data: %v", errUnsupportedIPPacketType, data[packetOffset], data[packetOffset:])
248252
}
249253
default:
250-
return fmt.Errorf("decode layers failed for unsupported packet type %d, data: %v", pdn.PktmonHeader.Metadata.PacketType, data[packetOffset:])
254+
return fmt.Errorf("%w: %d, data: %v", errUnsupportedPktmonPacketType, pdn.PktmonHeader.Metadata.PacketType, data[packetOffset:])
251255
}
252256
} else {
253257
var isL3Device, isIPv6 bool
@@ -536,7 +540,7 @@ func decodeIsReply(tn *TraceNotify) *wrapperspb.BoolValue {
536540
func decodeCiliumEventType(eventType uint8, eventSubType uint32) *pb.CiliumEventType {
537541
return &pb.CiliumEventType{
538542
Type: int32(eventType),
539-
SubType: int32(eventSubType),
543+
SubType: int32(eventSubType), //nolint:gosec // eventSubType is a bounded event code that fits in int32
540544
}
541545
}
542546

pkg/plugin/hnsstats/hnsstats_windows.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -216,10 +216,9 @@ func (h *hnsstats) Start(ctx context.Context) error {
216216
h.state = start
217217

218218
ciliumEnabled, err := plugincommon.IsCiliumOnWindowsEnabled()
219-
220219
if err != nil {
221220
h.l.Error("Error while checking if Cilium is enabled on Windows", zap.Error(err))
222-
return fmt.Errorf("Failed to check if Cilium is enabled on Windows: %w", err)
221+
return fmt.Errorf("failed to check if Cilium is enabled on Windows: %w", err)
223222
}
224223

225224
if ciliumEnabled {

test/e2e/framework/kubernetes/apply-yaml-config.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@ func (a *ApplyYamlConfig) Run() error {
6060
reader := bytes.NewReader(yamlFile)
6161
decoder := yaml.NewYAMLOrJSONDecoder(reader, 100)
6262
var rawObj unstructured.Unstructured
63-
if err := decoder.Decode(&rawObj); err != nil {
64-
return fmt.Errorf("error decoding YAML file: %w", err)
63+
if decodeErr := decoder.Decode(&rawObj); decodeErr != nil {
64+
return fmt.Errorf("error decoding YAML file: %w", decodeErr)
6565
}
6666

6767
// Get GroupVersionResource to invoke the dynamic client
@@ -74,7 +74,7 @@ func (a *ApplyYamlConfig) Run() error {
7474

7575
// Apply the YAML document
7676
namespace := rawObj.GetNamespace()
77-
if len(namespace) == 0 {
77+
if namespace == "" {
7878
namespace = "default"
7979
}
8080
applyOpts := metav1.ApplyOptions{FieldManager: "kube-apply"}

test/e2e/framework/kubernetes/load-winbpf.go

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package kubernetes
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
67
"strings"
78
"time"
@@ -14,14 +15,19 @@ import (
1415
"k8s.io/client-go/tools/clientcmd"
1516
)
1617

18+
var (
19+
ErrNoWindowsPodFound = errors.New("no Windows Pod found in label")
20+
ErrNoCommandOutput = errors.New("no output from command")
21+
ErrLoadPinBPFFailed = errors.New("error in loading and pinning BPF maps and program")
22+
)
23+
1724
type LoadAndPinWinBPF struct {
1825
KubeConfigFilePath string
1926
LoadAndPinWinBPFDeamonSetNamespace string
2027
LoadAndPinWinBPFDeamonSetName string
2128
}
2229

2330
func WaitForPodReadyWithTimeOut(ctx context.Context, kubeConfigFilePath, namespace, labelSelector string, timeout time.Duration) error {
24-
2531
config, _ := clientcmd.BuildConfigFromFlags("", kubeConfigFilePath)
2632
clientset, _ := kubernetes.NewForConfig(config)
2733

@@ -31,12 +37,12 @@ func WaitForPodReadyWithTimeOut(ctx context.Context, kubeConfigFilePath, namespa
3137
return WaitForPodReady(timeoutCtx, clientset, namespace, labelSelector)
3238
}
3339

34-
func ExecCommandInWinPod(KubeConfigFilePath string, cmd string, Namespace string, LabelSelector string, expecNonEmptyOutput bool) (string, error) {
40+
func ExecCommandInWinPod(kubeConfigFilePath, cmd, namespace, labelSelector string, expecNonEmptyOutput bool) (string, error) {
3541
defaultRetrier = retry.Retrier{Attempts: 15, Delay: 5 * time.Second}
3642
// Create a context with a timeout (e.g., 120 seconds)
3743
ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second)
3844
defer cancel()
39-
config, err := clientcmd.BuildConfigFromFlags("", KubeConfigFilePath)
45+
config, err := clientcmd.BuildConfigFromFlags("", kubeConfigFilePath)
4046
if err != nil {
4147
return "", fmt.Errorf("error building kubeconfig: %w", err)
4248
}
@@ -46,8 +52,8 @@ func ExecCommandInWinPod(KubeConfigFilePath string, cmd string, Namespace string
4652
return "", fmt.Errorf("error creating Kubernetes client: %w", err)
4753
}
4854

49-
pods, err := clientset.CoreV1().Pods(Namespace).List(ctx, metav1.ListOptions{
50-
LabelSelector: LabelSelector,
55+
pods, err := clientset.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{
56+
LabelSelector: labelSelector,
5157
})
5258
if err != nil {
5359
return "", fmt.Errorf("error listing pods: %w", err)
@@ -65,7 +71,7 @@ func ExecCommandInWinPod(KubeConfigFilePath string, cmd string, Namespace string
6571
}
6672

6773
if windowsPod == nil {
68-
return "", fmt.Errorf("no Windows Pod found in label %s", LabelSelector)
74+
return "", fmt.Errorf("%w: %s", ErrNoWindowsPodFound, labelSelector)
6975
}
7076

7177
var outputBytes []byte
@@ -77,12 +83,11 @@ func ExecCommandInWinPod(KubeConfigFilePath string, cmd string, Namespace string
7783
}
7884

7985
if len(outputBytes) == 0 && expecNonEmptyOutput {
80-
return fmt.Errorf("no output from command")
86+
return ErrNoCommandOutput
8187
}
8288

8389
return nil
8490
})
85-
8691
if err != nil {
8792
return "", err
8893
}
@@ -92,7 +97,7 @@ func ExecCommandInWinPod(KubeConfigFilePath string, cmd string, Namespace string
9297

9398
func (a *LoadAndPinWinBPF) Run() error {
9499
// Copy Event Writer into Node
95-
LoadAndPinWinBPFDLabelSelector := fmt.Sprintf("name=%s", a.LoadAndPinWinBPFDeamonSetName)
100+
LoadAndPinWinBPFDLabelSelector := "name=" + a.LoadAndPinWinBPFDeamonSetName
96101
_, err := ExecCommandInWinPod(a.KubeConfigFilePath, "copy /Y .\\event-writer-helper.bat C:\\event-writer-helper.bat", a.LoadAndPinWinBPFDeamonSetNamespace, LoadAndPinWinBPFDLabelSelector, true)
97102
if err != nil {
98103
return err
@@ -111,7 +116,7 @@ func (a *LoadAndPinWinBPF) Run() error {
111116

112117
fmt.Println(output)
113118
if strings.Contains(output, "error") || strings.Contains(output, "failed") || strings.Contains(output, "existing") {
114-
return fmt.Errorf("error in loading and pinning BPF maps and program: %s", output)
119+
return fmt.Errorf("%w: %s", ErrLoadPinBPFFailed, output)
115120
}
116121
return nil
117122
}

test/e2e/framework/kubernetes/unload-winbpf.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ type UnLoadAndPinWinBPF struct {
1212
}
1313

1414
func (a *UnLoadAndPinWinBPF) Run() error {
15-
UnLoadAndPinWinBPFDLabelSelector := fmt.Sprintf("name=%s", a.UnLoadAndPinWinBPFDeamonSetName)
15+
UnLoadAndPinWinBPFDLabelSelector := "name=" + a.UnLoadAndPinWinBPFDeamonSetName
1616
output, err := ExecCommandInWinPod(a.KubeConfigFilePath, "C:\\event-writer-helper.bat EventWriter-UnPinPrgAndMaps", a.UnLoadAndPinWinBPFDeamonSetNamespace, UnLoadAndPinWinBPFDLabelSelector, false)
1717
if err != nil {
1818
return err

0 commit comments

Comments
 (0)