non_csi.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. Copyright 2019 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 nodevolumelimits
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. "regexp"
  19. "strconv"
  20. v1 "k8s.io/api/core/v1"
  21. storage "k8s.io/api/storage/v1"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apimachinery/pkg/util/rand"
  24. utilfeature "k8s.io/apiserver/pkg/util/feature"
  25. "k8s.io/client-go/informers"
  26. corelisters "k8s.io/client-go/listers/core/v1"
  27. storagelisters "k8s.io/client-go/listers/storage/v1"
  28. csilibplugins "k8s.io/csi-translation-lib/plugins"
  29. "k8s.io/klog"
  30. "k8s.io/kubernetes/pkg/features"
  31. kubefeatures "k8s.io/kubernetes/pkg/features"
  32. framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
  33. "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  34. volumeutil "k8s.io/kubernetes/pkg/volume/util"
  35. )
  36. const (
  37. // defaultMaxGCEPDVolumes defines the maximum number of PD Volumes for GCE.
  38. // GCE instances can have up to 16 PD volumes attached.
  39. defaultMaxGCEPDVolumes = 16
  40. // defaultMaxAzureDiskVolumes defines the maximum number of PD Volumes for Azure.
  41. // Larger Azure VMs can actually have much more disks attached.
  42. // TODO We should determine the max based on VM size
  43. defaultMaxAzureDiskVolumes = 16
  44. // ebsVolumeFilterType defines the filter name for ebsVolumeFilter.
  45. ebsVolumeFilterType = "EBS"
  46. // gcePDVolumeFilterType defines the filter name for gcePDVolumeFilter.
  47. gcePDVolumeFilterType = "GCE"
  48. // azureDiskVolumeFilterType defines the filter name for azureDiskVolumeFilter.
  49. azureDiskVolumeFilterType = "AzureDisk"
  50. // cinderVolumeFilterType defines the filter name for cinderVolumeFilter.
  51. cinderVolumeFilterType = "Cinder"
  52. // ErrReasonMaxVolumeCountExceeded is used for MaxVolumeCount predicate error.
  53. ErrReasonMaxVolumeCountExceeded = "node(s) exceed max volume count"
  54. // KubeMaxPDVols defines the maximum number of PD Volumes per kubelet.
  55. KubeMaxPDVols = "KUBE_MAX_PD_VOLS"
  56. )
  57. // AzureDiskName is the name of the plugin used in the plugin registry and configurations.
  58. const AzureDiskName = "AzureDiskLimits"
  59. // NewAzureDisk returns function that initializes a new plugin and returns it.
  60. func NewAzureDisk(_ *runtime.Unknown, handle framework.FrameworkHandle) (framework.Plugin, error) {
  61. informerFactory := handle.SharedInformerFactory()
  62. return newNonCSILimitsWithInformerFactory(azureDiskVolumeFilterType, informerFactory), nil
  63. }
  64. // CinderName is the name of the plugin used in the plugin registry and configurations.
  65. const CinderName = "CinderLimits"
  66. // NewCinder returns function that initializes a new plugin and returns it.
  67. func NewCinder(_ *runtime.Unknown, handle framework.FrameworkHandle) (framework.Plugin, error) {
  68. informerFactory := handle.SharedInformerFactory()
  69. return newNonCSILimitsWithInformerFactory(cinderVolumeFilterType, informerFactory), nil
  70. }
  71. // EBSName is the name of the plugin used in the plugin registry and configurations.
  72. const EBSName = "EBSLimits"
  73. // NewEBS returns function that initializes a new plugin and returns it.
  74. func NewEBS(_ *runtime.Unknown, handle framework.FrameworkHandle) (framework.Plugin, error) {
  75. informerFactory := handle.SharedInformerFactory()
  76. return newNonCSILimitsWithInformerFactory(ebsVolumeFilterType, informerFactory), nil
  77. }
  78. // GCEPDName is the name of the plugin used in the plugin registry and configurations.
  79. const GCEPDName = "GCEPDLimits"
  80. // NewGCEPD returns function that initializes a new plugin and returns it.
  81. func NewGCEPD(_ *runtime.Unknown, handle framework.FrameworkHandle) (framework.Plugin, error) {
  82. informerFactory := handle.SharedInformerFactory()
  83. return newNonCSILimitsWithInformerFactory(gcePDVolumeFilterType, informerFactory), nil
  84. }
  85. // nonCSILimits contains information to check the max number of volumes for a plugin.
  86. type nonCSILimits struct {
  87. name string
  88. filter VolumeFilter
  89. volumeLimitKey v1.ResourceName
  90. maxVolumeFunc func(node *v1.Node) int
  91. csiNodeLister storagelisters.CSINodeLister
  92. pvLister corelisters.PersistentVolumeLister
  93. pvcLister corelisters.PersistentVolumeClaimLister
  94. scLister storagelisters.StorageClassLister
  95. // The string below is generated randomly during the struct's initialization.
  96. // It is used to prefix volumeID generated inside the predicate() method to
  97. // avoid conflicts with any real volume.
  98. randomVolumeIDPrefix string
  99. }
  100. var _ framework.FilterPlugin = &nonCSILimits{}
  101. // newNonCSILimitsWithInformerFactory returns a plugin with filter name and informer factory.
  102. func newNonCSILimitsWithInformerFactory(
  103. filterName string,
  104. informerFactory informers.SharedInformerFactory,
  105. ) framework.Plugin {
  106. pvLister := informerFactory.Core().V1().PersistentVolumes().Lister()
  107. pvcLister := informerFactory.Core().V1().PersistentVolumeClaims().Lister()
  108. scLister := informerFactory.Storage().V1().StorageClasses().Lister()
  109. return newNonCSILimits(filterName, getCSINodeListerIfEnabled(informerFactory), scLister, pvLister, pvcLister)
  110. }
  111. // newNonCSILimits creates a plugin which evaluates whether a pod can fit based on the
  112. // number of volumes which match a filter that it requests, and those that are already present.
  113. //
  114. // DEPRECATED
  115. // All cloudprovider specific predicates defined here are deprecated in favour of CSI volume limit
  116. // predicate - MaxCSIVolumeCountPred.
  117. //
  118. // The predicate looks for both volumes used directly, as well as PVC volumes that are backed by relevant volume
  119. // types, counts the number of unique volumes, and rejects the new pod if it would place the total count over
  120. // the maximum.
  121. func newNonCSILimits(
  122. filterName string,
  123. csiNodeLister storagelisters.CSINodeLister,
  124. scLister storagelisters.StorageClassLister,
  125. pvLister corelisters.PersistentVolumeLister,
  126. pvcLister corelisters.PersistentVolumeClaimLister,
  127. ) framework.Plugin {
  128. var filter VolumeFilter
  129. var volumeLimitKey v1.ResourceName
  130. var name string
  131. switch filterName {
  132. case ebsVolumeFilterType:
  133. name = EBSName
  134. filter = ebsVolumeFilter
  135. volumeLimitKey = v1.ResourceName(volumeutil.EBSVolumeLimitKey)
  136. case gcePDVolumeFilterType:
  137. name = GCEPDName
  138. filter = gcePDVolumeFilter
  139. volumeLimitKey = v1.ResourceName(volumeutil.GCEVolumeLimitKey)
  140. case azureDiskVolumeFilterType:
  141. name = AzureDiskName
  142. filter = azureDiskVolumeFilter
  143. volumeLimitKey = v1.ResourceName(volumeutil.AzureVolumeLimitKey)
  144. case cinderVolumeFilterType:
  145. name = CinderName
  146. filter = cinderVolumeFilter
  147. volumeLimitKey = v1.ResourceName(volumeutil.CinderVolumeLimitKey)
  148. default:
  149. klog.Fatalf("Wrong filterName, Only Support %v %v %v %v", ebsVolumeFilterType,
  150. gcePDVolumeFilterType, azureDiskVolumeFilterType, cinderVolumeFilterType)
  151. return nil
  152. }
  153. pl := &nonCSILimits{
  154. name: name,
  155. filter: filter,
  156. volumeLimitKey: volumeLimitKey,
  157. maxVolumeFunc: getMaxVolumeFunc(filterName),
  158. csiNodeLister: csiNodeLister,
  159. pvLister: pvLister,
  160. pvcLister: pvcLister,
  161. scLister: scLister,
  162. randomVolumeIDPrefix: rand.String(32),
  163. }
  164. return pl
  165. }
  166. // Name returns name of the plugin. It is used in logs, etc.
  167. func (pl *nonCSILimits) Name() string {
  168. return pl.name
  169. }
  170. // Filter invoked at the filter extension point.
  171. func (pl *nonCSILimits) Filter(ctx context.Context, _ *framework.CycleState, pod *v1.Pod, nodeInfo *nodeinfo.NodeInfo) *framework.Status {
  172. // If a pod doesn't have any volume attached to it, the predicate will always be true.
  173. // Thus we make a fast path for it, to avoid unnecessary computations in this case.
  174. if len(pod.Spec.Volumes) == 0 {
  175. return nil
  176. }
  177. newVolumes := make(map[string]bool)
  178. if err := pl.filterVolumes(pod.Spec.Volumes, pod.Namespace, newVolumes); err != nil {
  179. return framework.NewStatus(framework.Error, err.Error())
  180. }
  181. // quick return
  182. if len(newVolumes) == 0 {
  183. return nil
  184. }
  185. node := nodeInfo.Node()
  186. if node == nil {
  187. return framework.NewStatus(framework.Error, fmt.Sprintf("node not found"))
  188. }
  189. var csiNode *storage.CSINode
  190. var err error
  191. if pl.csiNodeLister != nil {
  192. csiNode, err = pl.csiNodeLister.Get(node.Name)
  193. if err != nil {
  194. // we don't fail here because the CSINode object is only necessary
  195. // for determining whether the migration is enabled or not
  196. klog.V(5).Infof("Could not get a CSINode object for the node: %v", err)
  197. }
  198. }
  199. // if a plugin has been migrated to a CSI driver, defer to the CSI predicate
  200. if pl.filter.IsMigrated(csiNode) {
  201. return nil
  202. }
  203. // count unique volumes
  204. existingVolumes := make(map[string]bool)
  205. for _, existingPod := range nodeInfo.Pods() {
  206. if err := pl.filterVolumes(existingPod.Spec.Volumes, existingPod.Namespace, existingVolumes); err != nil {
  207. return framework.NewStatus(framework.Error, err.Error())
  208. }
  209. }
  210. numExistingVolumes := len(existingVolumes)
  211. // filter out already-mounted volumes
  212. for k := range existingVolumes {
  213. if _, ok := newVolumes[k]; ok {
  214. delete(newVolumes, k)
  215. }
  216. }
  217. numNewVolumes := len(newVolumes)
  218. maxAttachLimit := pl.maxVolumeFunc(node)
  219. volumeLimits := nodeInfo.VolumeLimits()
  220. if maxAttachLimitFromAllocatable, ok := volumeLimits[pl.volumeLimitKey]; ok {
  221. maxAttachLimit = int(maxAttachLimitFromAllocatable)
  222. }
  223. if numExistingVolumes+numNewVolumes > maxAttachLimit {
  224. // violates MaxEBSVolumeCount or MaxGCEPDVolumeCount
  225. return framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded)
  226. }
  227. if nodeInfo != nil && nodeInfo.TransientInfo != nil && utilfeature.DefaultFeatureGate.Enabled(features.BalanceAttachedNodeVolumes) {
  228. nodeInfo.TransientInfo.TransientLock.Lock()
  229. defer nodeInfo.TransientInfo.TransientLock.Unlock()
  230. nodeInfo.TransientInfo.TransNodeInfo.AllocatableVolumesCount = maxAttachLimit - numExistingVolumes
  231. nodeInfo.TransientInfo.TransNodeInfo.RequestedVolumes = numNewVolumes
  232. }
  233. return nil
  234. }
  235. func (pl *nonCSILimits) filterVolumes(volumes []v1.Volume, namespace string, filteredVolumes map[string]bool) error {
  236. for i := range volumes {
  237. vol := &volumes[i]
  238. if id, ok := pl.filter.FilterVolume(vol); ok {
  239. filteredVolumes[id] = true
  240. } else if vol.PersistentVolumeClaim != nil {
  241. pvcName := vol.PersistentVolumeClaim.ClaimName
  242. if pvcName == "" {
  243. return fmt.Errorf("PersistentVolumeClaim had no name")
  244. }
  245. // Until we know real ID of the volume use namespace/pvcName as substitute
  246. // with a random prefix (calculated and stored inside 'c' during initialization)
  247. // to avoid conflicts with existing volume IDs.
  248. pvID := fmt.Sprintf("%s-%s/%s", pl.randomVolumeIDPrefix, namespace, pvcName)
  249. pvc, err := pl.pvcLister.PersistentVolumeClaims(namespace).Get(pvcName)
  250. if err != nil || pvc == nil {
  251. // If the PVC is invalid, we don't count the volume because
  252. // there's no guarantee that it belongs to the running predicate.
  253. klog.V(4).Infof("Unable to look up PVC info for %s/%s, assuming PVC doesn't match predicate when counting limits: %v", namespace, pvcName, err)
  254. continue
  255. }
  256. pvName := pvc.Spec.VolumeName
  257. if pvName == "" {
  258. // PVC is not bound. It was either deleted and created again or
  259. // it was forcefully unbound by admin. The pod can still use the
  260. // original PV where it was bound to, so we count the volume if
  261. // it belongs to the running predicate.
  262. if pl.matchProvisioner(pvc) {
  263. klog.V(4).Infof("PVC %s/%s is not bound, assuming PVC matches predicate when counting limits", namespace, pvcName)
  264. filteredVolumes[pvID] = true
  265. }
  266. continue
  267. }
  268. pv, err := pl.pvLister.Get(pvName)
  269. if err != nil || pv == nil {
  270. // If the PV is invalid and PVC belongs to the running predicate,
  271. // log the error and count the PV towards the PV limit.
  272. if pl.matchProvisioner(pvc) {
  273. klog.V(4).Infof("Unable to look up PV info for %s/%s/%s, assuming PV matches predicate when counting limits: %v", namespace, pvcName, pvName, err)
  274. filteredVolumes[pvID] = true
  275. }
  276. continue
  277. }
  278. if id, ok := pl.filter.FilterPersistentVolume(pv); ok {
  279. filteredVolumes[id] = true
  280. }
  281. }
  282. }
  283. return nil
  284. }
  285. // matchProvisioner helps identify if the given PVC belongs to the running predicate.
  286. func (pl *nonCSILimits) matchProvisioner(pvc *v1.PersistentVolumeClaim) bool {
  287. if pvc.Spec.StorageClassName == nil {
  288. return false
  289. }
  290. storageClass, err := pl.scLister.Get(*pvc.Spec.StorageClassName)
  291. if err != nil || storageClass == nil {
  292. return false
  293. }
  294. return pl.filter.MatchProvisioner(storageClass)
  295. }
  296. // getMaxVolLimitFromEnv checks the max PD volumes environment variable, otherwise returning a default value.
  297. func getMaxVolLimitFromEnv() int {
  298. if rawMaxVols := os.Getenv(KubeMaxPDVols); rawMaxVols != "" {
  299. if parsedMaxVols, err := strconv.Atoi(rawMaxVols); err != nil {
  300. klog.Errorf("Unable to parse maximum PD volumes value, using default: %v", err)
  301. } else if parsedMaxVols <= 0 {
  302. klog.Errorf("Maximum PD volumes must be a positive value, using default")
  303. } else {
  304. return parsedMaxVols
  305. }
  306. }
  307. return -1
  308. }
  309. // VolumeFilter contains information on how to filter PD Volumes when checking PD Volume caps.
  310. type VolumeFilter struct {
  311. // Filter normal volumes
  312. FilterVolume func(vol *v1.Volume) (id string, relevant bool)
  313. FilterPersistentVolume func(pv *v1.PersistentVolume) (id string, relevant bool)
  314. // MatchProvisioner evaluates if the StorageClass provisioner matches the running predicate
  315. MatchProvisioner func(sc *storage.StorageClass) (relevant bool)
  316. // IsMigrated returns a boolean specifying whether the plugin is migrated to a CSI driver
  317. IsMigrated func(csiNode *storage.CSINode) bool
  318. }
  319. // ebsVolumeFilter is a VolumeFilter for filtering AWS ElasticBlockStore Volumes.
  320. var ebsVolumeFilter = VolumeFilter{
  321. FilterVolume: func(vol *v1.Volume) (string, bool) {
  322. if vol.AWSElasticBlockStore != nil {
  323. return vol.AWSElasticBlockStore.VolumeID, true
  324. }
  325. return "", false
  326. },
  327. FilterPersistentVolume: func(pv *v1.PersistentVolume) (string, bool) {
  328. if pv.Spec.AWSElasticBlockStore != nil {
  329. return pv.Spec.AWSElasticBlockStore.VolumeID, true
  330. }
  331. return "", false
  332. },
  333. MatchProvisioner: func(sc *storage.StorageClass) (relevant bool) {
  334. if sc.Provisioner == csilibplugins.AWSEBSInTreePluginName {
  335. return true
  336. }
  337. return false
  338. },
  339. IsMigrated: func(csiNode *storage.CSINode) bool {
  340. return isCSIMigrationOn(csiNode, csilibplugins.AWSEBSInTreePluginName)
  341. },
  342. }
  343. // gcePDVolumeFilter is a VolumeFilter for filtering gce PersistentDisk Volumes.
  344. var gcePDVolumeFilter = VolumeFilter{
  345. FilterVolume: func(vol *v1.Volume) (string, bool) {
  346. if vol.GCEPersistentDisk != nil {
  347. return vol.GCEPersistentDisk.PDName, true
  348. }
  349. return "", false
  350. },
  351. FilterPersistentVolume: func(pv *v1.PersistentVolume) (string, bool) {
  352. if pv.Spec.GCEPersistentDisk != nil {
  353. return pv.Spec.GCEPersistentDisk.PDName, true
  354. }
  355. return "", false
  356. },
  357. MatchProvisioner: func(sc *storage.StorageClass) (relevant bool) {
  358. if sc.Provisioner == csilibplugins.GCEPDInTreePluginName {
  359. return true
  360. }
  361. return false
  362. },
  363. IsMigrated: func(csiNode *storage.CSINode) bool {
  364. return isCSIMigrationOn(csiNode, csilibplugins.GCEPDInTreePluginName)
  365. },
  366. }
  367. // azureDiskVolumeFilter is a VolumeFilter for filtering azure Disk Volumes.
  368. var azureDiskVolumeFilter = VolumeFilter{
  369. FilterVolume: func(vol *v1.Volume) (string, bool) {
  370. if vol.AzureDisk != nil {
  371. return vol.AzureDisk.DiskName, true
  372. }
  373. return "", false
  374. },
  375. FilterPersistentVolume: func(pv *v1.PersistentVolume) (string, bool) {
  376. if pv.Spec.AzureDisk != nil {
  377. return pv.Spec.AzureDisk.DiskName, true
  378. }
  379. return "", false
  380. },
  381. MatchProvisioner: func(sc *storage.StorageClass) (relevant bool) {
  382. if sc.Provisioner == csilibplugins.AzureDiskInTreePluginName {
  383. return true
  384. }
  385. return false
  386. },
  387. IsMigrated: func(csiNode *storage.CSINode) bool {
  388. return isCSIMigrationOn(csiNode, csilibplugins.AzureDiskInTreePluginName)
  389. },
  390. }
  391. // cinderVolumeFilter is a VolumeFilter for filtering cinder Volumes.
  392. // It will be deprecated once Openstack cloudprovider has been removed from in-tree.
  393. var cinderVolumeFilter = VolumeFilter{
  394. FilterVolume: func(vol *v1.Volume) (string, bool) {
  395. if vol.Cinder != nil {
  396. return vol.Cinder.VolumeID, true
  397. }
  398. return "", false
  399. },
  400. FilterPersistentVolume: func(pv *v1.PersistentVolume) (string, bool) {
  401. if pv.Spec.Cinder != nil {
  402. return pv.Spec.Cinder.VolumeID, true
  403. }
  404. return "", false
  405. },
  406. MatchProvisioner: func(sc *storage.StorageClass) (relevant bool) {
  407. if sc.Provisioner == csilibplugins.CinderInTreePluginName {
  408. return true
  409. }
  410. return false
  411. },
  412. IsMigrated: func(csiNode *storage.CSINode) bool {
  413. return isCSIMigrationOn(csiNode, csilibplugins.CinderInTreePluginName)
  414. },
  415. }
  416. func getMaxVolumeFunc(filterName string) func(node *v1.Node) int {
  417. return func(node *v1.Node) int {
  418. maxVolumesFromEnv := getMaxVolLimitFromEnv()
  419. if maxVolumesFromEnv > 0 {
  420. return maxVolumesFromEnv
  421. }
  422. var nodeInstanceType string
  423. for k, v := range node.ObjectMeta.Labels {
  424. if k == v1.LabelInstanceType || k == v1.LabelInstanceTypeStable {
  425. nodeInstanceType = v
  426. break
  427. }
  428. }
  429. switch filterName {
  430. case ebsVolumeFilterType:
  431. return getMaxEBSVolume(nodeInstanceType)
  432. case gcePDVolumeFilterType:
  433. return defaultMaxGCEPDVolumes
  434. case azureDiskVolumeFilterType:
  435. return defaultMaxAzureDiskVolumes
  436. case cinderVolumeFilterType:
  437. return volumeutil.DefaultMaxCinderVolumes
  438. default:
  439. return -1
  440. }
  441. }
  442. }
  443. func getMaxEBSVolume(nodeInstanceType string) int {
  444. if ok, _ := regexp.MatchString(volumeutil.EBSNitroLimitRegex, nodeInstanceType); ok {
  445. return volumeutil.DefaultMaxEBSNitroVolumeLimit
  446. }
  447. return volumeutil.DefaultMaxEBSVolumes
  448. }
  449. // getCSINodeListerIfEnabled returns the CSINode lister or nil if the feature is disabled
  450. func getCSINodeListerIfEnabled(factory informers.SharedInformerFactory) storagelisters.CSINodeLister {
  451. if !utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CSINodeInfo) {
  452. return nil
  453. }
  454. return factory.Storage().V1().CSINodes().Lister()
  455. }