service.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 proxy
  14. import (
  15. "fmt"
  16. "net"
  17. "reflect"
  18. "strings"
  19. "sync"
  20. "k8s.io/klog"
  21. "k8s.io/api/core/v1"
  22. "k8s.io/apimachinery/pkg/types"
  23. "k8s.io/apimachinery/pkg/util/sets"
  24. "k8s.io/client-go/tools/record"
  25. apiservice "k8s.io/kubernetes/pkg/api/v1/service"
  26. "k8s.io/kubernetes/pkg/proxy/metrics"
  27. utilproxy "k8s.io/kubernetes/pkg/proxy/util"
  28. utilnet "k8s.io/utils/net"
  29. )
  30. // BaseServiceInfo contains base information that defines a service.
  31. // This could be used directly by proxier while processing services,
  32. // or can be used for constructing a more specific ServiceInfo struct
  33. // defined by the proxier if needed.
  34. type BaseServiceInfo struct {
  35. ClusterIP net.IP
  36. Port int
  37. Protocol v1.Protocol
  38. NodePort int
  39. LoadBalancerStatus v1.LoadBalancerStatus
  40. SessionAffinityType v1.ServiceAffinity
  41. StickyMaxAgeSeconds int
  42. ExternalIPs []string
  43. LoadBalancerSourceRanges []string
  44. HealthCheckNodePort int
  45. OnlyNodeLocalEndpoints bool
  46. }
  47. var _ ServicePort = &BaseServiceInfo{}
  48. // String is part of ServicePort interface.
  49. func (info *BaseServiceInfo) String() string {
  50. return fmt.Sprintf("%s:%d/%s", info.ClusterIP, info.Port, info.Protocol)
  51. }
  52. // ClusterIPString is part of ServicePort interface.
  53. func (info *BaseServiceInfo) ClusterIPString() string {
  54. return info.ClusterIP.String()
  55. }
  56. // GetProtocol is part of ServicePort interface.
  57. func (info *BaseServiceInfo) GetProtocol() v1.Protocol {
  58. return info.Protocol
  59. }
  60. // GetHealthCheckNodePort is part of ServicePort interface.
  61. func (info *BaseServiceInfo) GetHealthCheckNodePort() int {
  62. return info.HealthCheckNodePort
  63. }
  64. // GetNodePort is part of the ServicePort interface.
  65. func (info *BaseServiceInfo) GetNodePort() int {
  66. return info.NodePort
  67. }
  68. // ExternalIPStrings is part of ServicePort interface.
  69. func (info *BaseServiceInfo) ExternalIPStrings() []string {
  70. return info.ExternalIPs
  71. }
  72. // LoadBalancerIPStrings is part of ServicePort interface.
  73. func (info *BaseServiceInfo) LoadBalancerIPStrings() []string {
  74. var ips []string
  75. for _, ing := range info.LoadBalancerStatus.Ingress {
  76. ips = append(ips, ing.IP)
  77. }
  78. return ips
  79. }
  80. func (sct *ServiceChangeTracker) newBaseServiceInfo(port *v1.ServicePort, service *v1.Service) *BaseServiceInfo {
  81. onlyNodeLocalEndpoints := false
  82. if apiservice.RequestsOnlyLocalTraffic(service) {
  83. onlyNodeLocalEndpoints = true
  84. }
  85. var stickyMaxAgeSeconds int
  86. if service.Spec.SessionAffinity == v1.ServiceAffinityClientIP {
  87. // Kube-apiserver side guarantees SessionAffinityConfig won't be nil when session affinity type is ClientIP
  88. stickyMaxAgeSeconds = int(*service.Spec.SessionAffinityConfig.ClientIP.TimeoutSeconds)
  89. }
  90. info := &BaseServiceInfo{
  91. ClusterIP: net.ParseIP(service.Spec.ClusterIP),
  92. Port: int(port.Port),
  93. Protocol: port.Protocol,
  94. NodePort: int(port.NodePort),
  95. // Deep-copy in case the service instance changes
  96. LoadBalancerStatus: *service.Status.LoadBalancer.DeepCopy(),
  97. SessionAffinityType: service.Spec.SessionAffinity,
  98. StickyMaxAgeSeconds: stickyMaxAgeSeconds,
  99. OnlyNodeLocalEndpoints: onlyNodeLocalEndpoints,
  100. }
  101. if sct.isIPv6Mode == nil {
  102. info.ExternalIPs = make([]string, len(service.Spec.ExternalIPs))
  103. info.LoadBalancerSourceRanges = make([]string, len(service.Spec.LoadBalancerSourceRanges))
  104. copy(info.LoadBalancerSourceRanges, service.Spec.LoadBalancerSourceRanges)
  105. copy(info.ExternalIPs, service.Spec.ExternalIPs)
  106. } else {
  107. // Filter out the incorrect IP version case.
  108. // If ExternalIPs and LoadBalancerSourceRanges on service contains incorrect IP versions,
  109. // only filter out the incorrect ones.
  110. var incorrectIPs []string
  111. info.ExternalIPs, incorrectIPs = utilproxy.FilterIncorrectIPVersion(service.Spec.ExternalIPs, *sct.isIPv6Mode)
  112. if len(incorrectIPs) > 0 {
  113. utilproxy.LogAndEmitIncorrectIPVersionEvent(sct.recorder, "externalIPs", strings.Join(incorrectIPs, ","), service.Namespace, service.Name, service.UID)
  114. }
  115. info.LoadBalancerSourceRanges, incorrectIPs = utilproxy.FilterIncorrectCIDRVersion(service.Spec.LoadBalancerSourceRanges, *sct.isIPv6Mode)
  116. if len(incorrectIPs) > 0 {
  117. utilproxy.LogAndEmitIncorrectIPVersionEvent(sct.recorder, "loadBalancerSourceRanges", strings.Join(incorrectIPs, ","), service.Namespace, service.Name, service.UID)
  118. }
  119. }
  120. if apiservice.NeedsHealthCheck(service) {
  121. p := service.Spec.HealthCheckNodePort
  122. if p == 0 {
  123. klog.Errorf("Service %s/%s has no healthcheck nodeport", service.Namespace, service.Name)
  124. } else {
  125. info.HealthCheckNodePort = int(p)
  126. }
  127. }
  128. return info
  129. }
  130. type makeServicePortFunc func(*v1.ServicePort, *v1.Service, *BaseServiceInfo) ServicePort
  131. // serviceChange contains all changes to services that happened since proxy rules were synced. For a single object,
  132. // changes are accumulated, i.e. previous is state from before applying the changes,
  133. // current is state after applying all of the changes.
  134. type serviceChange struct {
  135. previous ServiceMap
  136. current ServiceMap
  137. }
  138. // ServiceChangeTracker carries state about uncommitted changes to an arbitrary number of
  139. // Services, keyed by their namespace and name.
  140. type ServiceChangeTracker struct {
  141. // lock protects items.
  142. lock sync.Mutex
  143. // items maps a service to its serviceChange.
  144. items map[types.NamespacedName]*serviceChange
  145. // makeServiceInfo allows proxier to inject customized information when processing service.
  146. makeServiceInfo makeServicePortFunc
  147. // isIPv6Mode indicates if change tracker is under IPv6/IPv4 mode. Nil means not applicable.
  148. isIPv6Mode *bool
  149. recorder record.EventRecorder
  150. }
  151. // NewServiceChangeTracker initializes a ServiceChangeTracker
  152. func NewServiceChangeTracker(makeServiceInfo makeServicePortFunc, isIPv6Mode *bool, recorder record.EventRecorder) *ServiceChangeTracker {
  153. return &ServiceChangeTracker{
  154. items: make(map[types.NamespacedName]*serviceChange),
  155. makeServiceInfo: makeServiceInfo,
  156. isIPv6Mode: isIPv6Mode,
  157. recorder: recorder,
  158. }
  159. }
  160. // Update updates given service's change map based on the <previous, current> service pair. It returns true if items changed,
  161. // otherwise return false. Update can be used to add/update/delete items of ServiceChangeMap. For example,
  162. // Add item
  163. // - pass <nil, service> as the <previous, current> pair.
  164. // Update item
  165. // - pass <oldService, service> as the <previous, current> pair.
  166. // Delete item
  167. // - pass <service, nil> as the <previous, current> pair.
  168. func (sct *ServiceChangeTracker) Update(previous, current *v1.Service) bool {
  169. svc := current
  170. if svc == nil {
  171. svc = previous
  172. }
  173. // previous == nil && current == nil is unexpected, we should return false directly.
  174. if svc == nil {
  175. return false
  176. }
  177. metrics.ServiceChangesTotal.Inc()
  178. namespacedName := types.NamespacedName{Namespace: svc.Namespace, Name: svc.Name}
  179. sct.lock.Lock()
  180. defer sct.lock.Unlock()
  181. change, exists := sct.items[namespacedName]
  182. if !exists {
  183. change = &serviceChange{}
  184. change.previous = sct.serviceToServiceMap(previous)
  185. sct.items[namespacedName] = change
  186. }
  187. change.current = sct.serviceToServiceMap(current)
  188. // if change.previous equal to change.current, it means no change
  189. if reflect.DeepEqual(change.previous, change.current) {
  190. delete(sct.items, namespacedName)
  191. }
  192. metrics.ServiceChangesPending.Set(float64(len(sct.items)))
  193. return len(sct.items) > 0
  194. }
  195. // UpdateServiceMapResult is the updated results after applying service changes.
  196. type UpdateServiceMapResult struct {
  197. // HCServiceNodePorts is a map of Service names to node port numbers which indicate the health of that Service on this Node.
  198. // The value(uint16) of HCServices map is the service health check node port.
  199. HCServiceNodePorts map[types.NamespacedName]uint16
  200. // UDPStaleClusterIP holds stale (no longer assigned to a Service) Service IPs that had UDP ports.
  201. // Callers can use this to abort timeout-waits or clear connection-tracking information.
  202. UDPStaleClusterIP sets.String
  203. }
  204. // UpdateServiceMap updates ServiceMap based on the given changes.
  205. func UpdateServiceMap(serviceMap ServiceMap, changes *ServiceChangeTracker) (result UpdateServiceMapResult) {
  206. result.UDPStaleClusterIP = sets.NewString()
  207. serviceMap.apply(changes, result.UDPStaleClusterIP)
  208. // TODO: If this will appear to be computationally expensive, consider
  209. // computing this incrementally similarly to serviceMap.
  210. result.HCServiceNodePorts = make(map[types.NamespacedName]uint16)
  211. for svcPortName, info := range serviceMap {
  212. if info.GetHealthCheckNodePort() != 0 {
  213. result.HCServiceNodePorts[svcPortName.NamespacedName] = uint16(info.GetHealthCheckNodePort())
  214. }
  215. }
  216. return result
  217. }
  218. // ServiceMap maps a service to its ServicePort.
  219. type ServiceMap map[ServicePortName]ServicePort
  220. // serviceToServiceMap translates a single Service object to a ServiceMap.
  221. //
  222. // NOTE: service object should NOT be modified.
  223. func (sct *ServiceChangeTracker) serviceToServiceMap(service *v1.Service) ServiceMap {
  224. if service == nil {
  225. return nil
  226. }
  227. svcName := types.NamespacedName{Namespace: service.Namespace, Name: service.Name}
  228. if utilproxy.ShouldSkipService(svcName, service) {
  229. return nil
  230. }
  231. if len(service.Spec.ClusterIP) != 0 {
  232. // Filter out the incorrect IP version case.
  233. // If ClusterIP on service has incorrect IP version, service itself will be ignored.
  234. if sct.isIPv6Mode != nil && utilnet.IsIPv6String(service.Spec.ClusterIP) != *sct.isIPv6Mode {
  235. utilproxy.LogAndEmitIncorrectIPVersionEvent(sct.recorder, "clusterIP", service.Spec.ClusterIP, service.Namespace, service.Name, service.UID)
  236. return nil
  237. }
  238. }
  239. serviceMap := make(ServiceMap)
  240. for i := range service.Spec.Ports {
  241. servicePort := &service.Spec.Ports[i]
  242. svcPortName := ServicePortName{NamespacedName: svcName, Port: servicePort.Name}
  243. baseSvcInfo := sct.newBaseServiceInfo(servicePort, service)
  244. if sct.makeServiceInfo != nil {
  245. serviceMap[svcPortName] = sct.makeServiceInfo(servicePort, service, baseSvcInfo)
  246. } else {
  247. serviceMap[svcPortName] = baseSvcInfo
  248. }
  249. }
  250. return serviceMap
  251. }
  252. // apply the changes to ServiceMap and update the stale udp cluster IP set. The UDPStaleClusterIP argument is passed in to store the
  253. // udp protocol service cluster ip when service is deleted from the ServiceMap.
  254. func (sm *ServiceMap) apply(changes *ServiceChangeTracker, UDPStaleClusterIP sets.String) {
  255. changes.lock.Lock()
  256. defer changes.lock.Unlock()
  257. for _, change := range changes.items {
  258. sm.merge(change.current)
  259. // filter out the Update event of current changes from previous changes before calling unmerge() so that can
  260. // skip deleting the Update events.
  261. change.previous.filter(change.current)
  262. sm.unmerge(change.previous, UDPStaleClusterIP)
  263. }
  264. // clear changes after applying them to ServiceMap.
  265. changes.items = make(map[types.NamespacedName]*serviceChange)
  266. metrics.ServiceChangesPending.Set(0)
  267. return
  268. }
  269. // merge adds other ServiceMap's elements to current ServiceMap.
  270. // If collision, other ALWAYS win. Otherwise add the other to current.
  271. // In other words, if some elements in current collisions with other, update the current by other.
  272. // It returns a string type set which stores all the newly merged services' identifier, ServicePortName.String(), to help users
  273. // tell if a service is deleted or updated.
  274. // The returned value is one of the arguments of ServiceMap.unmerge().
  275. // ServiceMap A Merge ServiceMap B will do following 2 things:
  276. // * update ServiceMap A.
  277. // * produce a string set which stores all other ServiceMap's ServicePortName.String().
  278. // For example,
  279. // - A{}
  280. // - B{{"ns", "cluster-ip", "http"}: {"172.16.55.10", 1234, "TCP"}}
  281. // - A updated to be {{"ns", "cluster-ip", "http"}: {"172.16.55.10", 1234, "TCP"}}
  282. // - produce string set {"ns/cluster-ip:http"}
  283. // - A{{"ns", "cluster-ip", "http"}: {"172.16.55.10", 345, "UDP"}}
  284. // - B{{"ns", "cluster-ip", "http"}: {"172.16.55.10", 1234, "TCP"}}
  285. // - A updated to be {{"ns", "cluster-ip", "http"}: {"172.16.55.10", 1234, "TCP"}}
  286. // - produce string set {"ns/cluster-ip:http"}
  287. func (sm *ServiceMap) merge(other ServiceMap) sets.String {
  288. // existingPorts is going to store all identifiers of all services in `other` ServiceMap.
  289. existingPorts := sets.NewString()
  290. for svcPortName, info := range other {
  291. // Take ServicePortName.String() as the newly merged service's identifier and put it into existingPorts.
  292. existingPorts.Insert(svcPortName.String())
  293. _, exists := (*sm)[svcPortName]
  294. if !exists {
  295. klog.V(1).Infof("Adding new service port %q at %s", svcPortName, info.String())
  296. } else {
  297. klog.V(1).Infof("Updating existing service port %q at %s", svcPortName, info.String())
  298. }
  299. (*sm)[svcPortName] = info
  300. }
  301. return existingPorts
  302. }
  303. // filter filters out elements from ServiceMap base on given ports string sets.
  304. func (sm *ServiceMap) filter(other ServiceMap) {
  305. for svcPortName := range *sm {
  306. // skip the delete for Update event.
  307. if _, ok := other[svcPortName]; ok {
  308. delete(*sm, svcPortName)
  309. }
  310. }
  311. }
  312. // unmerge deletes all other ServiceMap's elements from current ServiceMap. We pass in the UDPStaleClusterIP strings sets
  313. // for storing the stale udp service cluster IPs. We will clear stale udp connection base on UDPStaleClusterIP later
  314. func (sm *ServiceMap) unmerge(other ServiceMap, UDPStaleClusterIP sets.String) {
  315. for svcPortName := range other {
  316. info, exists := (*sm)[svcPortName]
  317. if exists {
  318. klog.V(1).Infof("Removing service port %q", svcPortName)
  319. if info.GetProtocol() == v1.ProtocolUDP {
  320. UDPStaleClusterIP.Insert(info.ClusterIPString())
  321. }
  322. delete(*sm, svcPortName)
  323. } else {
  324. klog.Errorf("Service port %q doesn't exists", svcPortName)
  325. }
  326. }
  327. }