util.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. Copyright 2016 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 service
  14. import (
  15. "fmt"
  16. "strings"
  17. "k8s.io/kubernetes/pkg/api"
  18. netsets "k8s.io/kubernetes/pkg/util/net/sets"
  19. )
  20. const (
  21. defaultLoadBalancerSourceRanges = "0.0.0.0/0"
  22. )
  23. // IsAllowAll checks whether the netsets.IPNet allows traffic from 0.0.0.0/0
  24. func IsAllowAll(ipnets netsets.IPNet) bool {
  25. for _, s := range ipnets.StringSlice() {
  26. if s == "0.0.0.0/0" {
  27. return true
  28. }
  29. }
  30. return false
  31. }
  32. // GetLoadBalancerSourceRanges first try to parse and verify LoadBalancerSourceRanges field from a service.
  33. // If the field is not specified, turn to parse and verify the AnnotationLoadBalancerSourceRangesKey annotation from a service,
  34. // extracting the source ranges to allow, and if not present returns a default (allow-all) value.
  35. func GetLoadBalancerSourceRanges(service *api.Service) (netsets.IPNet, error) {
  36. var ipnets netsets.IPNet
  37. var err error
  38. // if SourceRange field is specified, ignore sourceRange annotation
  39. if len(service.Spec.LoadBalancerSourceRanges) > 0 {
  40. specs := service.Spec.LoadBalancerSourceRanges
  41. ipnets, err = netsets.ParseIPNets(specs...)
  42. if err != nil {
  43. return nil, fmt.Errorf("service.Spec.LoadBalancerSourceRanges: %v is not valid. Expecting a list of IP ranges. For example, 10.0.0.0/24. Error msg: %v", specs, err)
  44. }
  45. } else {
  46. val := service.Annotations[AnnotationLoadBalancerSourceRangesKey]
  47. val = strings.TrimSpace(val)
  48. if val == "" {
  49. val = defaultLoadBalancerSourceRanges
  50. }
  51. specs := strings.Split(val, ",")
  52. ipnets, err = netsets.ParseIPNets(specs...)
  53. if err != nil {
  54. return nil, fmt.Errorf("%s: %s is not valid. Expecting a comma-separated list of source IP ranges. For example, 10.0.0.0/24,192.168.2.0/24", AnnotationLoadBalancerSourceRangesKey, val)
  55. }
  56. }
  57. return ipnets, nil
  58. }