util.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 pod
  14. import (
  15. "fmt"
  16. "k8s.io/kubernetes/pkg/api"
  17. "k8s.io/kubernetes/pkg/util/intstr"
  18. )
  19. const (
  20. // TODO: to be de!eted after v1.3 is released. PodSpec has a dedicated Hostname field.
  21. // The annotation value is a string specifying the hostname to be used for the pod e.g 'my-webserver-1'
  22. PodHostnameAnnotation = "pod.beta.kubernetes.io/hostname"
  23. // TODO: to be de!eted after v1.3 is released. PodSpec has a dedicated Subdomain field.
  24. // The annotation value is a string specifying the subdomain e.g. "my-web-service"
  25. // If specified, on the pod itself, "<hostname>.my-web-service.<namespace>.svc.<cluster domain>" would resolve to
  26. // the pod's IP.
  27. // If there is a headless service named "my-web-service" in the same namespace as the pod, then,
  28. // <hostname>.my-web-service.<namespace>.svc.<cluster domain>" would be resolved by the cluster DNS Server.
  29. PodSubdomainAnnotation = "pod.beta.kubernetes.io/subdomain"
  30. )
  31. // FindPort locates the container port for the given pod and portName. If the
  32. // targetPort is a number, use that. If the targetPort is a string, look that
  33. // string up in all named ports in all containers in the target pod. If no
  34. // match is found, fail.
  35. func FindPort(pod *api.Pod, svcPort *api.ServicePort) (int, error) {
  36. portName := svcPort.TargetPort
  37. switch portName.Type {
  38. case intstr.String:
  39. name := portName.StrVal
  40. for _, container := range pod.Spec.Containers {
  41. for _, port := range container.Ports {
  42. if port.Name == name && port.Protocol == svcPort.Protocol {
  43. return int(port.ContainerPort), nil
  44. }
  45. }
  46. }
  47. case intstr.Int:
  48. return portName.IntValue(), nil
  49. }
  50. return 0, fmt.Errorf("no suitable port for manifest: %s", pod.UID)
  51. }