util.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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/kubernetes/pkg/api"
  21. "k8s.io/kubernetes/pkg/types"
  22. hashutil "k8s.io/kubernetes/pkg/util/hash"
  23. )
  24. const (
  25. // TODO: to be deleted after v1.3 is released
  26. // Its value is the json representation of map[string(IP)][HostRecord]
  27. // example: '{"10.245.1.6":{"HostName":"my-webserver"}}'
  28. PodHostnamesAnnotation = "endpoints.beta.kubernetes.io/hostnames-map"
  29. )
  30. // TODO: to be deleted after v1.3 is released
  31. type HostRecord struct {
  32. HostName string
  33. }
  34. // RepackSubsets takes a slice of EndpointSubset objects, expands it to the full
  35. // representation, and then repacks that into the canonical layout. This
  36. // ensures that code which operates on these objects can rely on the common
  37. // form for things like comparison. The result is a newly allocated slice.
  38. func RepackSubsets(subsets []api.EndpointSubset) []api.EndpointSubset {
  39. // First map each unique port definition to the sets of hosts that
  40. // offer it.
  41. allAddrs := map[addressKey]*api.EndpointAddress{}
  42. portToAddrReadyMap := map[api.EndpointPort]addressSet{}
  43. for i := range subsets {
  44. for _, port := range subsets[i].Ports {
  45. for k := range subsets[i].Addresses {
  46. mapAddressByPort(&subsets[i].Addresses[k], port, true, allAddrs, portToAddrReadyMap)
  47. }
  48. for k := range subsets[i].NotReadyAddresses {
  49. mapAddressByPort(&subsets[i].NotReadyAddresses[k], port, false, allAddrs, portToAddrReadyMap)
  50. }
  51. }
  52. }
  53. // Next, map the sets of hosts to the sets of ports they offer.
  54. // Go does not allow maps or slices as keys to maps, so we have
  55. // to synthesize an artificial key and do a sort of 2-part
  56. // associative entity.
  57. type keyString string
  58. keyToAddrReadyMap := map[keyString]addressSet{}
  59. addrReadyMapKeyToPorts := map[keyString][]api.EndpointPort{}
  60. for port, addrs := range portToAddrReadyMap {
  61. key := keyString(hashAddresses(addrs))
  62. keyToAddrReadyMap[key] = addrs
  63. addrReadyMapKeyToPorts[key] = append(addrReadyMapKeyToPorts[key], port)
  64. }
  65. // Next, build the N-to-M association the API wants.
  66. final := []api.EndpointSubset{}
  67. for key, ports := range addrReadyMapKeyToPorts {
  68. var readyAddrs, notReadyAddrs []api.EndpointAddress
  69. for addr, ready := range keyToAddrReadyMap[key] {
  70. if ready {
  71. readyAddrs = append(readyAddrs, *addr)
  72. } else {
  73. notReadyAddrs = append(notReadyAddrs, *addr)
  74. }
  75. }
  76. final = append(final, api.EndpointSubset{Addresses: readyAddrs, NotReadyAddresses: notReadyAddrs, Ports: ports})
  77. }
  78. // Finally, sort it.
  79. return SortSubsets(final)
  80. }
  81. // The sets of hosts must be de-duped, using IP+UID as the key.
  82. type addressKey struct {
  83. ip string
  84. uid types.UID
  85. }
  86. // mapAddressByPort adds an address into a map by its ports, registering the address with a unique pointer, and preserving
  87. // any existing ready state.
  88. func mapAddressByPort(addr *api.EndpointAddress, port api.EndpointPort, ready bool, allAddrs map[addressKey]*api.EndpointAddress, portToAddrReadyMap map[api.EndpointPort]addressSet) *api.EndpointAddress {
  89. // use addressKey to distinguish between two endpoints that are identical addresses
  90. // but may have come from different hosts, for attribution. For instance, Mesos
  91. // assigns pods the node IP, but the pods are distinct.
  92. key := addressKey{ip: addr.IP}
  93. if addr.TargetRef != nil {
  94. key.uid = addr.TargetRef.UID
  95. }
  96. // Accumulate the address. The full EndpointAddress structure is preserved for use when
  97. // we rebuild the subsets so that the final TargetRef has all of the necessary data.
  98. existingAddress := allAddrs[key]
  99. if existingAddress == nil {
  100. // Make a copy so we don't write to the
  101. // input args of this function.
  102. existingAddress = &api.EndpointAddress{}
  103. *existingAddress = *addr
  104. allAddrs[key] = existingAddress
  105. }
  106. // Remember that this port maps to this address.
  107. if _, found := portToAddrReadyMap[port]; !found {
  108. portToAddrReadyMap[port] = addressSet{}
  109. }
  110. // if we have not yet recorded this port for this address, or if the previous
  111. // state was ready, write the current ready state. not ready always trumps
  112. // ready.
  113. if wasReady, found := portToAddrReadyMap[port][existingAddress]; !found || wasReady {
  114. portToAddrReadyMap[port][existingAddress] = ready
  115. }
  116. return existingAddress
  117. }
  118. type addressSet map[*api.EndpointAddress]bool
  119. type addrReady struct {
  120. addr *api.EndpointAddress
  121. ready bool
  122. }
  123. func hashAddresses(addrs addressSet) string {
  124. // Flatten the list of addresses into a string so it can be used as a
  125. // map key. Unfortunately, DeepHashObject is implemented in terms of
  126. // spew, and spew does not handle non-primitive map keys well. So
  127. // first we collapse it into a slice, sort the slice, then hash that.
  128. slice := make([]addrReady, 0, len(addrs))
  129. for k, ready := range addrs {
  130. slice = append(slice, addrReady{k, ready})
  131. }
  132. sort.Sort(addrsReady(slice))
  133. hasher := md5.New()
  134. hashutil.DeepHashObject(hasher, slice)
  135. return hex.EncodeToString(hasher.Sum(nil)[0:])
  136. }
  137. func lessAddrReady(a, b addrReady) bool {
  138. // ready is not significant to hashing since we can't have duplicate addresses
  139. return LessEndpointAddress(a.addr, b.addr)
  140. }
  141. type addrsReady []addrReady
  142. func (sl addrsReady) Len() int { return len(sl) }
  143. func (sl addrsReady) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }
  144. func (sl addrsReady) Less(i, j int) bool {
  145. return lessAddrReady(sl[i], sl[j])
  146. }
  147. func LessEndpointAddress(a, b *api.EndpointAddress) bool {
  148. ipComparison := bytes.Compare([]byte(a.IP), []byte(b.IP))
  149. if ipComparison != 0 {
  150. return ipComparison < 0
  151. }
  152. if b.TargetRef == nil {
  153. return false
  154. }
  155. if a.TargetRef == nil {
  156. return true
  157. }
  158. return a.TargetRef.UID < b.TargetRef.UID
  159. }
  160. type addrPtrsByIpAndUID []*api.EndpointAddress
  161. func (sl addrPtrsByIpAndUID) Len() int { return len(sl) }
  162. func (sl addrPtrsByIpAndUID) Swap(i, j int) { sl[i], sl[j] = sl[j], sl[i] }
  163. func (sl addrPtrsByIpAndUID) Less(i, j int) bool {
  164. return LessEndpointAddress(sl[i], sl[j])
  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. }