k8s.io/kubernetes@v1.29.3/pkg/kubelet/container/ref.go (about) 1 /* 2 Copyright 2015 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package container 18 19 import ( 20 "fmt" 21 22 v1 "k8s.io/api/core/v1" 23 ref "k8s.io/client-go/tools/reference" 24 "k8s.io/kubernetes/pkg/api/legacyscheme" 25 ) 26 27 // ImplicitContainerPrefix is a container name prefix that will indicate that container was started implicitly (like the pod infra container). 28 var ImplicitContainerPrefix = "implicitly required container " 29 30 // GenerateContainerRef returns an *v1.ObjectReference which references the given container 31 // within the given pod. Returns an error if the reference can't be constructed or the 32 // container doesn't actually belong to the pod. 33 func GenerateContainerRef(pod *v1.Pod, container *v1.Container) (*v1.ObjectReference, error) { 34 fieldPath, err := fieldPath(pod, container) 35 if err != nil { 36 // TODO: figure out intelligent way to refer to containers that we implicitly 37 // start (like the pod infra container). This is not a good way, ugh. 38 fieldPath = ImplicitContainerPrefix + container.Name 39 } 40 ref, err := ref.GetPartialReference(legacyscheme.Scheme, pod, fieldPath) 41 if err != nil { 42 return nil, err 43 } 44 return ref, nil 45 } 46 47 // fieldPath returns a fieldPath locating container within pod. 48 // Returns an error if the container isn't part of the pod. 49 func fieldPath(pod *v1.Pod, container *v1.Container) (string, error) { 50 for i := range pod.Spec.Containers { 51 here := &pod.Spec.Containers[i] 52 if here.Name == container.Name { 53 if here.Name == "" { 54 return fmt.Sprintf("spec.containers[%d]", i), nil 55 } 56 return fmt.Sprintf("spec.containers{%s}", here.Name), nil 57 } 58 } 59 for i := range pod.Spec.InitContainers { 60 here := &pod.Spec.InitContainers[i] 61 if here.Name == container.Name { 62 if here.Name == "" { 63 return fmt.Sprintf("spec.initContainers[%d]", i), nil 64 } 65 return fmt.Sprintf("spec.initContainers{%s}", here.Name), nil 66 } 67 } 68 for i := range pod.Spec.EphemeralContainers { 69 here := &pod.Spec.EphemeralContainers[i] 70 if here.Name == container.Name { 71 if here.Name == "" { 72 return fmt.Sprintf("spec.ephemeralContainers[%d]", i), nil 73 } 74 return fmt.Sprintf("spec.ephemeralContainers{%s}", here.Name), nil 75 } 76 } 77 return "", fmt.Errorf("container %q not found in pod %s/%s", container.Name, pod.Namespace, pod.Name) 78 }