Skip to content

Commit 54bd8d4

Browse files
committed
use slices methods to deal with sidecars
Signed-off-by: Benedikt Bongartz <[email protected]>
1 parent 60e8a8e commit 54bd8d4

File tree

2 files changed

+18
-24
lines changed

2 files changed

+18
-24
lines changed

pkg/sidecar/pod.go

+16-24
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package sidecar
1717

1818
import (
1919
"fmt"
20+
"slices"
2021

2122
"github.com/go-logr/logr"
2223
corev1 "k8s.io/api/core/v1"
@@ -75,37 +76,28 @@ func remove(pod corev1.Pod) corev1.Pod {
7576
return pod
7677
}
7778

78-
var containers []corev1.Container
79-
for _, container := range pod.Spec.Containers {
80-
if container.Name != naming.Container() {
81-
containers = append(containers, container)
82-
}
83-
}
84-
pod.Spec.Containers = containers
85-
86-
// NOTE: we also remove init containers (native sidecars) since k8s 1.28.
87-
// This should have no side effects.
88-
var initContainers []corev1.Container
89-
for _, initContainer := range pod.Spec.InitContainers {
90-
if initContainer.Name != naming.Container() {
91-
initContainers = append(initContainers, initContainer)
92-
}
79+
fn := func(c corev1.Container) bool { return c.Name == naming.Container() }
80+
pod.Spec.Containers = slices.DeleteFunc(pod.Spec.Containers, fn)
81+
82+
if featuregate.EnableNativeSidecarContainers.IsEnabled() {
83+
// NOTE: we also remove init containers (native sidecars) since k8s 1.28.
84+
// This should have no side effects.
85+
pod.Spec.InitContainers = slices.DeleteFunc(pod.Spec.InitContainers, fn)
9386
}
94-
pod.Spec.InitContainers = initContainers
9587
return pod
9688
}
9789

9890
// existsIn checks whether a sidecar container exists in the given pod.
9991
func existsIn(pod corev1.Pod) bool {
100-
for _, container := range pod.Spec.Containers {
101-
if container.Name == naming.Container() {
102-
return true
103-
}
92+
fn := func(c corev1.Container) bool { return c.Name == naming.Container() }
93+
if slices.ContainsFunc(pod.Spec.Containers, fn) {
94+
return true
10495
}
105-
// NOTE: we also check init containers (native sidecars) since k8s 1.28.
106-
// This should have no side effects.
107-
for _, container := range pod.Spec.InitContainers {
108-
if container.Name == naming.Container() {
96+
97+
if featuregate.EnableNativeSidecarContainers.IsEnabled() {
98+
// NOTE: we also check init containers (native sidecars) since k8s 1.28.
99+
// This should have no side effects.
100+
if slices.ContainsFunc(pod.Spec.InitContainers, fn) {
109101
return true
110102
}
111103
}

pkg/sidecar/pod_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,8 @@ func TestRemoveNonExistingSidecar(t *testing.T) {
269269
}
270270

271271
func TestExistsIn(t *testing.T) {
272+
sidecarFeatureGate(t)
273+
272274
for _, tt := range []struct {
273275
desc string
274276
pod corev1.Pod

0 commit comments

Comments
 (0)