Restore early return for podSpecHasContainer

This commit is contained in:
Ted Yu
2019-06-26 14:17:11 +08:00
committed by Ted Yu
parent e8738d665b
commit cf7c164ae3
6 changed files with 28 additions and 12 deletions

View File

@@ -24,20 +24,28 @@ import (
"k8s.io/kubernetes/pkg/fieldpath"
)
// ContainerVisitorWithPath is called with each container and the field.Path to that container
type ContainerVisitorWithPath func(container *api.Container, path *field.Path)
// ContainerVisitorWithPath is called with each container and the field.Path to that container,
// and returns true if visiting should continue.
type ContainerVisitorWithPath func(container *api.Container, path *field.Path) bool
// VisitContainersWithPath invokes the visitor function with a pointer to the spec
// of every container in the given pod spec and the field.Path to that container.
func VisitContainersWithPath(podSpec *api.PodSpec, visitor ContainerVisitorWithPath) {
// If visitor returns false, visiting is short-circuited. VisitContainersWithPath returns true if visiting completes,
// false if visiting was short-circuited.
func VisitContainersWithPath(podSpec *api.PodSpec, visitor ContainerVisitorWithPath) bool {
path := field.NewPath("spec", "initContainers")
for i := range podSpec.InitContainers {
visitor(&podSpec.InitContainers[i], path.Index(i))
if !visitor(&podSpec.InitContainers[i], path.Index(i)) {
return false
}
}
path = field.NewPath("spec", "containers")
for i := range podSpec.Containers {
visitor(&podSpec.Containers[i], path.Index(i))
if !visitor(&podSpec.Containers[i], path.Index(i)) {
return false
}
}
return true
}
// ConvertDownwardAPIFieldLabel converts the specified downward API field label

View File

@@ -73,8 +73,9 @@ func TestVisitContainersWithPath(t *testing.T) {
for _, tc := range testCases {
gotNames := []string{}
VisitContainersWithPath(tc.haveSpec, func(c *api.Container, p *field.Path) {
VisitContainersWithPath(tc.haveSpec, func(c *api.Container, p *field.Path) bool {
gotNames = append(gotNames, p.String())
return true
})
if !reflect.DeepEqual(gotNames, tc.wantNames) {
t.Errorf("VisitContainersWithPath() for test case %q visited containers %q, wanted to visit %q", tc.description, gotNames, tc.wantNames)

View File

@@ -3435,10 +3435,12 @@ func ValidateAppArmorPodAnnotations(annotations map[string]string, spec *core.Po
func podSpecHasContainer(spec *core.PodSpec, containerName string) bool {
var hasContainer bool
podshelper.VisitContainersWithPath(spec, func(c *core.Container, _ *field.Path) {
podshelper.VisitContainersWithPath(spec, func(c *core.Container, _ *field.Path) bool {
if c.Name == containerName {
hasContainer = true
return false
}
return true
})
return hasContainer
}