ref.go 2.4 KB

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