util.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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 endpoints
  14. import (
  15. "bytes"
  16. "crypto/md5"
  17. "encoding/hex"
  18. "hash"
  19. "sort"
  20. "k8s.io/apimachinery/pkg/types"
  21. api "k8s.io/kubernetes/pkg/apis/core"
  22. hashutil "k8s.io/kubernetes/pkg/util/hash"
  23. )
  24. // RepackSubsets takes a slice of EndpointSubset objects, expands it to the full
  25. // representation, and then repacks that into the canonical layout. This
  26. // ensures that code which operates on these objects can rely on the common
  27. // form for things like comparison. The result is a newly allocated slice.
  28. func RepackSubsets(subsets []api.EndpointSubset) []api.EndpointSubset {
  29. // First map each unique port definition to the sets of hosts that
  30. // offer it.
  31. allAddrs := map[addressKey]*api.EndpointAddress{}
  32. portToAddrReadyMap := map[api.EndpointPort]addressSet{}
  33. for i := range subsets {
  34. if len(subsets[i].Ports) == 0 {
  35. // Don't discard endpoints with no ports defined, use a sentinel.
  36. mapAddressesByPort(&subsets[i], api.EndpointPort{Port: -1}, allAddrs, portToAddrReadyMap)
  37. } else {
  38. for _, port := range subsets[i].Ports {
  39. mapAddressesByPort(&subsets[i], port, allAddrs, portToAddrReadyMap)
  40. }
  41. }
  42. }
  43. // Next, map the sets of hosts to the sets of ports they offer.
  44. // Go does not allow maps or slices as keys to maps, so we have
  45. // to synthesize an artificial key and do a sort of 2-part
  46. // associative entity.
  47. type keyString string
  48. keyToAddrReadyMap := map[keyString]addressSet{}
  49. addrReadyMapKeyToPorts := map[keyString][]api.EndpointPort{}
  50. for port, addrs := range portToAddrReadyMap {
  51. key := keyString(hashAddresses(addrs))
  52. keyToAddrReadyMap[key] = addrs
  53. if port.Port > 0 { // avoid sentinels
  54. addrReadyMapKeyToPorts[key] = append(addrReadyMapKeyToPorts[key], port)
  55. } else {
  56. if _, found := addrReadyMapKeyToPorts[key]; !found {
  57. // Force it to be present in the map
  58. addrReadyMapKeyToPorts[key] = nil
  59. }
  60. }
  61. }
  62. // Next, build the N-to-M association the API wants.
  63. final := []api.EndpointSubset{}
  64. for key, ports := range addrReadyMapKeyToPorts {
  65. var readyAddrs, notReadyAddrs []api.EndpointAddress
  66. for addr, ready := range keyToAddrReadyMap[key] {
  67. if ready {
  68. readyAddrs = append(readyAddrs, *addr)
  69. } else {
  70. notReadyAddrs = append(notReadyAddrs, *addr)
  71. }
  72. }
  73. final = append(final, api.EndpointSubset{Addresses: readyAddrs, NotReadyAddresses: notReadyAddrs, Ports: ports})
  74. }
  75. // Finally, sort it.
  76. return SortSubsets(final)
  77. }
  78. // The sets of hosts must be de-duped, using IP+UID as the key.
  79. type addressKey struct {
  80. ip string
  81. uid types.UID
  82. }
  83. // mapAddressesByPort adds all ready and not-ready addresses into a map by a single port.
  84. func mapAddressesByPort(subset *api.EndpointSubset, port api.EndpointPort, allAddrs map[addressKey]*api.EndpointAddress, portToAddrReadyMap map[api.EndpointPort]addressSet) {
  85. for k := range subset.Addresses {
  86. mapAddressByPort(&subset.Addresses[k], port, true, allAddrs, portToAddrReadyMap)
  87. }
  88. for k := range subset.NotReadyAddresses {
  89. mapAddressByPort(&subset.NotReadyAddresses[k], port, false, allAddrs, portToAddrReadyMap)
  90. }
  91. }
  92. // mapAddressByPort adds one address into a map by port, registering the address with a unique pointer, and preserving
  93. // any existing ready state.
  94. func mapAddressByPort(addr *api.EndpointAddress, port api.EndpointPort, ready bool, allAddrs map[addressKey]*api.EndpointAddress, portToAddrReadyMap map[api.EndpointPort]addressSet) *api.EndpointAddress {
  95. // use addressKey to distinguish between two endpoints that are identical addresses
  96. // but may have come from different hosts, for attribution.
  97. key := addressKey{ip: addr.IP}
  98. if addr.TargetRef != nil {
  99. key.uid = addr.TargetRef.UID
  100. }
  101. // Accumulate the address. The full EndpointAddress structure is preserved for use when
  102. // we rebuild the subsets so that the final TargetRef has all of the necessary data.
  103. existingAddress := allAddrs[key]
  104. if existingAddress == nil {
  105. // Make a copy so we don't write to the
  106. // input args of this function.
  107. existingAddress = &api.EndpointAddress{}
  108. *existingAddress = *addr
  109. allAddrs[key] = existingAddress
  110. }
  111. // Remember that this port maps to this address.
  112. if _, found := portToAddrReadyMap[port]; !found {
  113. portToAddrReadyMap[port] = addressSet{}
  114. }
  115. // if we have not yet recorded this port for this address, or if the previous
  116. // state was ready, write the current ready state. not ready always trumps
  117. // ready.
  118. if wasReady, found := portToAddrReadyMap[port][existingAddress]; !found || wasReady {
  119. portToAddrReadyMap[port][existingAddress] = ready
  120. }
  121. return existingAddress
  122. }
  123. type addressSet map[*api.EndpointAddress]bool
  124. type addrReady struct {
  125. addr *api.EndpointAddress
  126. ready bool
  127. }
  128. func hashAddresses(addrs addressSet) string {
  129. // Flatten the list of addresses into a string so it can be used as a
  130. // map key. Unfortunately, DeepHashObject is implemented in terms of
  131. // spew, and spew does not handle non-primitive map keys well. So
  132. // first we collapse it into a slice, sort the slice, then hash that.
  133. slice := make([]addrReady, 0, len(addrs))
  134. for k, ready := range addrs {
  135. slice = append(slice, addrReady{k, ready})
  136. }
  137. sort.Sort(addrsReady(slice))
  138. hasher := md5.New()
  139. hashutil.DeepHashObject(hasher, slice)
  140. return hex.EncodeToString(hasher.Sum(nil)[0:])
  141. }
  142. func lessAddrReady(a, b addrReady) bool {
  143. // ready is not significant to hashing since we can't have duplicate addresses
  144. return LessEndpointAddress(a.addr, b.addr)
  145. }
  146. type addrsReady []addrReady
  147. func (sl addrsReady) Len() int { return len(sl) }
  148. func (sl addrsReady) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }
  149. func (sl addrsReady) Less(i, j int) bool {
  150. return lessAddrReady(sl[i], sl[j])
  151. }
  152. // LessEndpointAddress compares IP addresses lexicographically and returns true if first argument is lesser than second
  153. func LessEndpointAddress(a, b *api.EndpointAddress) bool {
  154. ipComparison := bytes.Compare([]byte(a.IP), []byte(b.IP))
  155. if ipComparison != 0 {
  156. return ipComparison < 0
  157. }
  158. if b.TargetRef == nil {
  159. return false
  160. }
  161. if a.TargetRef == nil {
  162. return true
  163. }
  164. return a.TargetRef.UID < b.TargetRef.UID
  165. }
  166. // SortSubsets sorts an array of EndpointSubset objects in place. For ease of
  167. // use it returns the input slice.
  168. func SortSubsets(subsets []api.EndpointSubset) []api.EndpointSubset {
  169. for i := range subsets {
  170. ss := &subsets[i]
  171. sort.Sort(addrsByIPAndUID(ss.Addresses))
  172. sort.Sort(addrsByIPAndUID(ss.NotReadyAddresses))
  173. sort.Sort(portsByHash(ss.Ports))
  174. }
  175. sort.Sort(subsetsByHash(subsets))
  176. return subsets
  177. }
  178. func hashObject(hasher hash.Hash, obj interface{}) []byte {
  179. hashutil.DeepHashObject(hasher, obj)
  180. return hasher.Sum(nil)
  181. }
  182. type subsetsByHash []api.EndpointSubset
  183. func (sl subsetsByHash) Len() int { return len(sl) }
  184. func (sl subsetsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }
  185. func (sl subsetsByHash) Less(i, j int) bool {
  186. hasher := md5.New()
  187. h1 := hashObject(hasher, sl[i])
  188. h2 := hashObject(hasher, sl[j])
  189. return bytes.Compare(h1, h2) < 0
  190. }
  191. type addrsByIPAndUID []api.EndpointAddress
  192. func (sl addrsByIPAndUID) Len() int { return len(sl) }
  193. func (sl addrsByIPAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }
  194. func (sl addrsByIPAndUID) Less(i, j int) bool {
  195. return LessEndpointAddress(&sl[i], &sl[j])
  196. }
  197. type portsByHash []api.EndpointPort
  198. func (sl portsByHash) Len() int { return len(sl) }
  199. func (sl portsByHash) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }
  200. func (sl portsByHash) Less(i, j int) bool {
  201. hasher := md5.New()
  202. h1 := hashObject(hasher, sl[i])
  203. h2 := hashObject(hasher, sl[j])
  204. return bytes.Compare(h1, h2) < 0
  205. }