service_port.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. Copyright 2018 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 util
  14. import (
  15. "fmt"
  16. "k8s.io/api/core/v1"
  17. "k8s.io/apimachinery/pkg/util/intstr"
  18. )
  19. // LookupContainerPortNumberByServicePort implements
  20. // the handling of resolving container named port, as well as ignoring targetPort when clusterIP=None
  21. // It returns an error when a named port can't find a match (with -1 returned), or when the service does not
  22. // declare such port (with the input port number returned).
  23. func LookupContainerPortNumberByServicePort(svc v1.Service, pod v1.Pod, port int32) (int32, error) {
  24. for _, svcportspec := range svc.Spec.Ports {
  25. if svcportspec.Port != port {
  26. continue
  27. }
  28. if svc.Spec.ClusterIP == v1.ClusterIPNone {
  29. return port, nil
  30. }
  31. if svcportspec.TargetPort.Type == intstr.Int {
  32. if svcportspec.TargetPort.IntValue() == 0 {
  33. // targetPort is omitted, and the IntValue() would be zero
  34. return svcportspec.Port, nil
  35. }
  36. return int32(svcportspec.TargetPort.IntValue()), nil
  37. }
  38. return LookupContainerPortNumberByName(pod, svcportspec.TargetPort.String())
  39. }
  40. return port, fmt.Errorf("Service %s does not have a service port %d", svc.Name, port)
  41. }
  42. // LookupServicePortNumberByName find service port number by its named port name
  43. func LookupServicePortNumberByName(svc v1.Service, name string) (int32, error) {
  44. for _, svcportspec := range svc.Spec.Ports {
  45. if svcportspec.Name == name {
  46. return svcportspec.Port, nil
  47. }
  48. }
  49. return int32(-1), fmt.Errorf("Service '%s' does not have a named port '%s'", svc.Name, name)
  50. }