index.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. /*
  2. Copyright 2014 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 persistentvolume
  14. import (
  15. "fmt"
  16. "sort"
  17. "k8s.io/kubernetes/pkg/api"
  18. "k8s.io/kubernetes/pkg/api/unversioned"
  19. "k8s.io/kubernetes/pkg/client/cache"
  20. "k8s.io/kubernetes/pkg/labels"
  21. )
  22. // persistentVolumeOrderedIndex is a cache.Store that keeps persistent volumes
  23. // indexed by AccessModes and ordered by storage capacity.
  24. type persistentVolumeOrderedIndex struct {
  25. store cache.Indexer
  26. }
  27. func newPersistentVolumeOrderedIndex() persistentVolumeOrderedIndex {
  28. return persistentVolumeOrderedIndex{cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{"accessmodes": accessModesIndexFunc})}
  29. }
  30. // accessModesIndexFunc is an indexing function that returns a persistent
  31. // volume's AccessModes as a string
  32. func accessModesIndexFunc(obj interface{}) ([]string, error) {
  33. if pv, ok := obj.(*api.PersistentVolume); ok {
  34. modes := api.GetAccessModesAsString(pv.Spec.AccessModes)
  35. return []string{modes}, nil
  36. }
  37. return []string{""}, fmt.Errorf("object is not a persistent volume: %v", obj)
  38. }
  39. // listByAccessModes returns all volumes with the given set of
  40. // AccessModeTypes. The list is unsorted!
  41. func (pvIndex *persistentVolumeOrderedIndex) listByAccessModes(modes []api.PersistentVolumeAccessMode) ([]*api.PersistentVolume, error) {
  42. pv := &api.PersistentVolume{
  43. Spec: api.PersistentVolumeSpec{
  44. AccessModes: modes,
  45. },
  46. }
  47. objs, err := pvIndex.store.Index("accessmodes", pv)
  48. if err != nil {
  49. return nil, err
  50. }
  51. volumes := make([]*api.PersistentVolume, len(objs))
  52. for i, obj := range objs {
  53. volumes[i] = obj.(*api.PersistentVolume)
  54. }
  55. return volumes, nil
  56. }
  57. // matchPredicate is a function that indicates that a persistent volume matches another
  58. type matchPredicate func(compareThis, toThis *api.PersistentVolume) bool
  59. // find returns the nearest PV from the ordered list or nil if a match is not found
  60. func (pvIndex *persistentVolumeOrderedIndex) findByClaim(claim *api.PersistentVolumeClaim, matchPredicate matchPredicate) (*api.PersistentVolume, error) {
  61. // PVs are indexed by their access modes to allow easier searching. Each
  62. // index is the string representation of a set of access modes. There is a
  63. // finite number of possible sets and PVs will only be indexed in one of
  64. // them (whichever index matches the PV's modes).
  65. //
  66. // A request for resources will always specify its desired access modes.
  67. // Any matching PV must have at least that number of access modes, but it
  68. // can have more. For example, a user asks for ReadWriteOnce but a GCEPD
  69. // is available, which is ReadWriteOnce+ReadOnlyMany.
  70. //
  71. // Searches are performed against a set of access modes, so we can attempt
  72. // not only the exact matching modes but also potential matches (the GCEPD
  73. // example above).
  74. allPossibleModes := pvIndex.allPossibleMatchingAccessModes(claim.Spec.AccessModes)
  75. var smallestVolume *api.PersistentVolume
  76. var smallestVolumeSize int64
  77. requestedQty := claim.Spec.Resources.Requests[api.ResourceName(api.ResourceStorage)]
  78. requestedSize := requestedQty.Value()
  79. requestedClass := getClaimClass(claim)
  80. var selector labels.Selector
  81. if claim.Spec.Selector != nil {
  82. internalSelector, err := unversioned.LabelSelectorAsSelector(claim.Spec.Selector)
  83. if err != nil {
  84. // should be unreachable code due to validation
  85. return nil, fmt.Errorf("error creating internal label selector for claim: %v: %v", claimToClaimKey(claim), err)
  86. }
  87. selector = internalSelector
  88. }
  89. for _, modes := range allPossibleModes {
  90. volumes, err := pvIndex.listByAccessModes(modes)
  91. if err != nil {
  92. return nil, err
  93. }
  94. // Go through all available volumes with two goals:
  95. // - find a volume that is either pre-bound by user or dynamically
  96. // provisioned for this claim. Because of this we need to loop through
  97. // all volumes.
  98. // - find the smallest matching one if there is no volume pre-bound to
  99. // the claim.
  100. for _, volume := range volumes {
  101. if isVolumeBoundToClaim(volume, claim) {
  102. // this claim and volume are pre-bound; return
  103. // the volume if the size request is satisfied,
  104. // otherwise continue searching for a match
  105. volumeQty := volume.Spec.Capacity[api.ResourceStorage]
  106. volumeSize := volumeQty.Value()
  107. if volumeSize < requestedSize {
  108. continue
  109. }
  110. return volume, nil
  111. }
  112. // In Alpha dynamic provisioning, we do now want not match claims
  113. // with existing PVs, findByClaim must find only PVs that are
  114. // pre-bound to the claim (by dynamic provisioning). TODO: remove in
  115. // 1.5
  116. if hasAnnotation(claim.ObjectMeta, annAlphaClass) {
  117. continue
  118. }
  119. // filter out:
  120. // - volumes bound to another claim
  121. // - volumes whose labels don't match the claim's selector, if specified
  122. // - volumes in Class that is not requested
  123. if volume.Spec.ClaimRef != nil {
  124. continue
  125. } else if selector != nil && !selector.Matches(labels.Set(volume.Labels)) {
  126. continue
  127. }
  128. if getVolumeClass(volume) != requestedClass {
  129. continue
  130. }
  131. volumeQty := volume.Spec.Capacity[api.ResourceStorage]
  132. volumeSize := volumeQty.Value()
  133. if volumeSize >= requestedSize {
  134. if smallestVolume == nil || smallestVolumeSize > volumeSize {
  135. smallestVolume = volume
  136. smallestVolumeSize = volumeSize
  137. }
  138. }
  139. }
  140. if smallestVolume != nil {
  141. // Found a matching volume
  142. return smallestVolume, nil
  143. }
  144. }
  145. return nil, nil
  146. }
  147. // findBestMatchForClaim is a convenience method that finds a volume by the claim's AccessModes and requests for Storage
  148. func (pvIndex *persistentVolumeOrderedIndex) findBestMatchForClaim(claim *api.PersistentVolumeClaim) (*api.PersistentVolume, error) {
  149. return pvIndex.findByClaim(claim, matchStorageCapacity)
  150. }
  151. // matchStorageCapacity is a matchPredicate used to sort and find volumes
  152. func matchStorageCapacity(pvA, pvB *api.PersistentVolume) bool {
  153. aQty := pvA.Spec.Capacity[api.ResourceStorage]
  154. bQty := pvB.Spec.Capacity[api.ResourceStorage]
  155. aSize := aQty.Value()
  156. bSize := bQty.Value()
  157. return aSize <= bSize
  158. }
  159. // allPossibleMatchingAccessModes returns an array of AccessMode arrays that
  160. // can satisfy a user's requested modes.
  161. //
  162. // see comments in the Find func above regarding indexing.
  163. //
  164. // allPossibleMatchingAccessModes gets all stringified accessmodes from the
  165. // index and returns all those that contain at least all of the requested
  166. // mode.
  167. //
  168. // For example, assume the index contains 2 types of PVs where the stringified
  169. // accessmodes are:
  170. //
  171. // "RWO,ROX" -- some number of GCEPDs
  172. // "RWO,ROX,RWX" -- some number of NFS volumes
  173. //
  174. // A request for RWO could be satisfied by both sets of indexed volumes, so
  175. // allPossibleMatchingAccessModes returns:
  176. //
  177. // [][]api.PersistentVolumeAccessMode {
  178. // []api.PersistentVolumeAccessMode {
  179. // api.ReadWriteOnce, api.ReadOnlyMany,
  180. // },
  181. // []api.PersistentVolumeAccessMode {
  182. // api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany,
  183. // },
  184. // }
  185. //
  186. // A request for RWX can be satisfied by only one set of indexed volumes, so
  187. // the return is:
  188. //
  189. // [][]api.PersistentVolumeAccessMode {
  190. // []api.PersistentVolumeAccessMode {
  191. // api.ReadWriteOnce, api.ReadOnlyMany, api.ReadWriteMany,
  192. // },
  193. // }
  194. //
  195. // This func returns modes with ascending levels of modes to give the user
  196. // what is closest to what they actually asked for.
  197. func (pvIndex *persistentVolumeOrderedIndex) allPossibleMatchingAccessModes(requestedModes []api.PersistentVolumeAccessMode) [][]api.PersistentVolumeAccessMode {
  198. matchedModes := [][]api.PersistentVolumeAccessMode{}
  199. keys := pvIndex.store.ListIndexFuncValues("accessmodes")
  200. for _, key := range keys {
  201. indexedModes := api.GetAccessModesFromString(key)
  202. if containedInAll(indexedModes, requestedModes) {
  203. matchedModes = append(matchedModes, indexedModes)
  204. }
  205. }
  206. // sort by the number of modes in each array with the fewest number of
  207. // modes coming first. this allows searching for volumes by the minimum
  208. // number of modes required of the possible matches.
  209. sort.Sort(byAccessModes{matchedModes})
  210. return matchedModes
  211. }
  212. func contains(modes []api.PersistentVolumeAccessMode, mode api.PersistentVolumeAccessMode) bool {
  213. for _, m := range modes {
  214. if m == mode {
  215. return true
  216. }
  217. }
  218. return false
  219. }
  220. func containedInAll(indexedModes []api.PersistentVolumeAccessMode, requestedModes []api.PersistentVolumeAccessMode) bool {
  221. for _, mode := range requestedModes {
  222. if !contains(indexedModes, mode) {
  223. return false
  224. }
  225. }
  226. return true
  227. }
  228. // byAccessModes is used to order access modes by size, with the fewest modes first
  229. type byAccessModes struct {
  230. modes [][]api.PersistentVolumeAccessMode
  231. }
  232. func (c byAccessModes) Less(i, j int) bool {
  233. return len(c.modes[i]) < len(c.modes[j])
  234. }
  235. func (c byAccessModes) Swap(i, j int) {
  236. c.modes[i], c.modes[j] = c.modes[j], c.modes[i]
  237. }
  238. func (c byAccessModes) Len() int {
  239. return len(c.modes)
  240. }
  241. func claimToClaimKey(claim *api.PersistentVolumeClaim) string {
  242. return fmt.Sprintf("%s/%s", claim.Namespace, claim.Name)
  243. }
  244. func claimrefToClaimKey(claimref *api.ObjectReference) string {
  245. return fmt.Sprintf("%s/%s", claimref.Namespace, claimref.Name)
  246. }