ipset.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. /*
  2. Copyright 2017 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 ipvs
  14. import (
  15. "k8s.io/apimachinery/pkg/util/sets"
  16. utilversion "k8s.io/apimachinery/pkg/util/version"
  17. utilipset "k8s.io/kubernetes/pkg/util/ipset"
  18. "fmt"
  19. "strings"
  20. "k8s.io/klog"
  21. )
  22. const (
  23. // MinIPSetCheckVersion is the min ipset version we need. IPv6 is supported in ipset 6.x
  24. MinIPSetCheckVersion = "6.0"
  25. kubeLoopBackIPSetComment = "Kubernetes endpoints dst ip:port, source ip for solving hairpin purpose"
  26. kubeLoopBackIPSet = "KUBE-LOOP-BACK"
  27. kubeClusterIPSetComment = "Kubernetes service cluster ip + port for masquerade purpose"
  28. kubeClusterIPSet = "KUBE-CLUSTER-IP"
  29. kubeExternalIPSetComment = "Kubernetes service external ip + port for masquerade and filter purpose"
  30. kubeExternalIPSet = "KUBE-EXTERNAL-IP"
  31. kubeLoadBalancerSetComment = "Kubernetes service lb portal"
  32. kubeLoadBalancerSet = "KUBE-LOAD-BALANCER"
  33. kubeLoadBalancerLocalSetComment = "Kubernetes service load balancer ip + port with externalTrafficPolicy=local"
  34. kubeLoadBalancerLocalSet = "KUBE-LOAD-BALANCER-LOCAL"
  35. kubeLoadbalancerFWSetComment = "Kubernetes service load balancer ip + port for load balancer with sourceRange"
  36. kubeLoadbalancerFWSet = "KUBE-LOAD-BALANCER-FW"
  37. kubeLoadBalancerSourceIPSetComment = "Kubernetes service load balancer ip + port + source IP for packet filter purpose"
  38. kubeLoadBalancerSourceIPSet = "KUBE-LOAD-BALANCER-SOURCE-IP"
  39. kubeLoadBalancerSourceCIDRSetComment = "Kubernetes service load balancer ip + port + source cidr for packet filter purpose"
  40. kubeLoadBalancerSourceCIDRSet = "KUBE-LOAD-BALANCER-SOURCE-CIDR"
  41. kubeNodePortSetTCPComment = "Kubernetes nodeport TCP port for masquerade purpose"
  42. kubeNodePortSetTCP = "KUBE-NODE-PORT-TCP"
  43. kubeNodePortLocalSetTCPComment = "Kubernetes nodeport TCP port with externalTrafficPolicy=local"
  44. kubeNodePortLocalSetTCP = "KUBE-NODE-PORT-LOCAL-TCP"
  45. kubeNodePortSetUDPComment = "Kubernetes nodeport UDP port for masquerade purpose"
  46. kubeNodePortSetUDP = "KUBE-NODE-PORT-UDP"
  47. kubeNodePortLocalSetUDPComment = "Kubernetes nodeport UDP port with externalTrafficPolicy=local"
  48. kubeNodePortLocalSetUDP = "KUBE-NODE-PORT-LOCAL-UDP"
  49. kubeNodePortSetSCTPComment = "Kubernetes nodeport SCTP port for masquerade purpose with type 'hash ip:port'"
  50. kubeNodePortSetSCTP = "KUBE-NODE-PORT-SCTP-HASH"
  51. kubeNodePortLocalSetSCTPComment = "Kubernetes nodeport SCTP port with externalTrafficPolicy=local with type 'hash ip:port'"
  52. kubeNodePortLocalSetSCTP = "KUBE-NODE-PORT-LOCAL-SCTP-HASH"
  53. )
  54. // IPSetVersioner can query the current ipset version.
  55. type IPSetVersioner interface {
  56. // returns "X.Y"
  57. GetVersion() (string, error)
  58. }
  59. // IPSet wraps util/ipset which is used by IPVS proxier.
  60. type IPSet struct {
  61. utilipset.IPSet
  62. // activeEntries is the current active entries of the ipset.
  63. activeEntries sets.String
  64. // handle is the util ipset interface handle.
  65. handle utilipset.Interface
  66. }
  67. // NewIPSet initialize a new IPSet struct
  68. func NewIPSet(handle utilipset.Interface, name string, setType utilipset.Type, isIPv6 bool, comment string) *IPSet {
  69. hashFamily := utilipset.ProtocolFamilyIPV4
  70. if isIPv6 {
  71. hashFamily = utilipset.ProtocolFamilyIPV6
  72. // In dual-stack both ipv4 and ipv6 ipset's can co-exist. To
  73. // ensure unique names the prefix for ipv6 is changed from
  74. // "KUBE-" to "KUBE-6-". The "KUBE-" prefix is kept for
  75. // backward compatibility. The maximum name length of an ipset
  76. // is 31 characters which must be taken into account. The
  77. // ipv4 names are not altered to minimize the risk for
  78. // problems on upgrades.
  79. if strings.HasPrefix(name, "KUBE-") {
  80. name = strings.Replace(name, "KUBE-", "KUBE-6-", 1)
  81. if len(name) > 31 {
  82. klog.Warningf("ipset name truncated; [%s] -> [%s]", name, name[:31])
  83. name = name[:31]
  84. }
  85. }
  86. }
  87. set := &IPSet{
  88. IPSet: utilipset.IPSet{
  89. Name: name,
  90. SetType: setType,
  91. HashFamily: hashFamily,
  92. Comment: comment,
  93. },
  94. activeEntries: sets.NewString(),
  95. handle: handle,
  96. }
  97. return set
  98. }
  99. func (set *IPSet) validateEntry(entry *utilipset.Entry) bool {
  100. return entry.Validate(&set.IPSet)
  101. }
  102. func (set *IPSet) isEmpty() bool {
  103. return len(set.activeEntries.UnsortedList()) == 0
  104. }
  105. func (set *IPSet) getComment() string {
  106. return fmt.Sprintf("\"%s\"", set.Comment)
  107. }
  108. func (set *IPSet) resetEntries() {
  109. set.activeEntries = sets.NewString()
  110. }
  111. func (set *IPSet) syncIPSetEntries() {
  112. appliedEntries, err := set.handle.ListEntries(set.Name)
  113. if err != nil {
  114. klog.Errorf("Failed to list ip set entries, error: %v", err)
  115. return
  116. }
  117. // currentIPSetEntries represents Endpoints watched from API Server.
  118. currentIPSetEntries := sets.NewString()
  119. for _, appliedEntry := range appliedEntries {
  120. currentIPSetEntries.Insert(appliedEntry)
  121. }
  122. if !set.activeEntries.Equal(currentIPSetEntries) {
  123. // Clean legacy entries
  124. for _, entry := range currentIPSetEntries.Difference(set.activeEntries).List() {
  125. if err := set.handle.DelEntry(entry, set.Name); err != nil {
  126. if !utilipset.IsNotFoundError(err) {
  127. klog.Errorf("Failed to delete ip set entry: %s from ip set: %s, error: %v", entry, set.Name, err)
  128. }
  129. } else {
  130. klog.V(3).Infof("Successfully delete legacy ip set entry: %s from ip set: %s", entry, set.Name)
  131. }
  132. }
  133. // Create active entries
  134. for _, entry := range set.activeEntries.Difference(currentIPSetEntries).List() {
  135. if err := set.handle.AddEntry(entry, &set.IPSet, true); err != nil {
  136. klog.Errorf("Failed to add entry: %v to ip set: %s, error: %v", entry, set.Name, err)
  137. } else {
  138. klog.V(3).Infof("Successfully add entry: %v to ip set: %s", entry, set.Name)
  139. }
  140. }
  141. }
  142. }
  143. func ensureIPSet(set *IPSet) error {
  144. if err := set.handle.CreateSet(&set.IPSet, true); err != nil {
  145. klog.Errorf("Failed to make sure ip set: %v exist, error: %v", set, err)
  146. return err
  147. }
  148. return nil
  149. }
  150. // checkMinVersion checks if ipset current version satisfies required min version
  151. func checkMinVersion(vstring string) bool {
  152. version, err := utilversion.ParseGeneric(vstring)
  153. if err != nil {
  154. klog.Errorf("vstring (%s) is not a valid version string: %v", vstring, err)
  155. return false
  156. }
  157. minVersion, err := utilversion.ParseGeneric(MinIPSetCheckVersion)
  158. if err != nil {
  159. klog.Errorf("MinCheckVersion (%s) is not a valid version string: %v", MinIPSetCheckVersion, err)
  160. return false
  161. }
  162. return !version.LessThan(minVersion)
  163. }