...
1
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
28 var ImplicitContainerPrefix = "implicitly required container "
29
30
31
32
33 func GenerateContainerRef(pod *v1.Pod, container *v1.Container) (*v1.ObjectReference, error) {
34 fieldPath, err := fieldPath(pod, container)
35 if err != nil {
36
37
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
48
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 }
79
View as plain text