util.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  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 pod
  14. import (
  15. "strings"
  16. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  17. utilfeature "k8s.io/apiserver/pkg/util/feature"
  18. api "k8s.io/kubernetes/pkg/apis/core"
  19. "k8s.io/kubernetes/pkg/features"
  20. "k8s.io/kubernetes/pkg/security/apparmor"
  21. )
  22. // ContainerVisitor is called with each container spec, and returns true
  23. // if visiting should continue.
  24. type ContainerVisitor func(container *api.Container) (shouldContinue bool)
  25. // VisitContainers invokes the visitor function with a pointer to the container
  26. // spec of every container in the given pod spec. If visitor returns false,
  27. // visiting is short-circuited. VisitContainers returns true if visiting completes,
  28. // false if visiting was short-circuited.
  29. func VisitContainers(podSpec *api.PodSpec, visitor ContainerVisitor) bool {
  30. for i := range podSpec.InitContainers {
  31. if !visitor(&podSpec.InitContainers[i]) {
  32. return false
  33. }
  34. }
  35. for i := range podSpec.Containers {
  36. if !visitor(&podSpec.Containers[i]) {
  37. return false
  38. }
  39. }
  40. if utilfeature.DefaultFeatureGate.Enabled(features.EphemeralContainers) {
  41. for i := range podSpec.EphemeralContainers {
  42. if !visitor((*api.Container)(&podSpec.EphemeralContainers[i].EphemeralContainerCommon)) {
  43. return false
  44. }
  45. }
  46. }
  47. return true
  48. }
  49. // Visitor is called with each object name, and returns true if visiting should continue
  50. type Visitor func(name string) (shouldContinue bool)
  51. // VisitPodSecretNames invokes the visitor function with the name of every secret
  52. // referenced by the pod spec. If visitor returns false, visiting is short-circuited.
  53. // Transitive references (e.g. pod -> pvc -> pv -> secret) are not visited.
  54. // Returns true if visiting completed, false if visiting was short-circuited.
  55. func VisitPodSecretNames(pod *api.Pod, visitor Visitor) bool {
  56. for _, reference := range pod.Spec.ImagePullSecrets {
  57. if !visitor(reference.Name) {
  58. return false
  59. }
  60. }
  61. VisitContainers(&pod.Spec, func(c *api.Container) bool {
  62. return visitContainerSecretNames(c, visitor)
  63. })
  64. var source *api.VolumeSource
  65. for i := range pod.Spec.Volumes {
  66. source = &pod.Spec.Volumes[i].VolumeSource
  67. switch {
  68. case source.AzureFile != nil:
  69. if len(source.AzureFile.SecretName) > 0 && !visitor(source.AzureFile.SecretName) {
  70. return false
  71. }
  72. case source.CephFS != nil:
  73. if source.CephFS.SecretRef != nil && !visitor(source.CephFS.SecretRef.Name) {
  74. return false
  75. }
  76. case source.Cinder != nil:
  77. if source.Cinder.SecretRef != nil && !visitor(source.Cinder.SecretRef.Name) {
  78. return false
  79. }
  80. case source.FlexVolume != nil:
  81. if source.FlexVolume.SecretRef != nil && !visitor(source.FlexVolume.SecretRef.Name) {
  82. return false
  83. }
  84. case source.Projected != nil:
  85. for j := range source.Projected.Sources {
  86. if source.Projected.Sources[j].Secret != nil {
  87. if !visitor(source.Projected.Sources[j].Secret.Name) {
  88. return false
  89. }
  90. }
  91. }
  92. case source.RBD != nil:
  93. if source.RBD.SecretRef != nil && !visitor(source.RBD.SecretRef.Name) {
  94. return false
  95. }
  96. case source.Secret != nil:
  97. if !visitor(source.Secret.SecretName) {
  98. return false
  99. }
  100. case source.ScaleIO != nil:
  101. if source.ScaleIO.SecretRef != nil && !visitor(source.ScaleIO.SecretRef.Name) {
  102. return false
  103. }
  104. case source.ISCSI != nil:
  105. if source.ISCSI.SecretRef != nil && !visitor(source.ISCSI.SecretRef.Name) {
  106. return false
  107. }
  108. case source.StorageOS != nil:
  109. if source.StorageOS.SecretRef != nil && !visitor(source.StorageOS.SecretRef.Name) {
  110. return false
  111. }
  112. case source.CSI != nil:
  113. if source.CSI.NodePublishSecretRef != nil && !visitor(source.CSI.NodePublishSecretRef.Name) {
  114. return false
  115. }
  116. }
  117. }
  118. return true
  119. }
  120. func visitContainerSecretNames(container *api.Container, visitor Visitor) bool {
  121. for _, env := range container.EnvFrom {
  122. if env.SecretRef != nil {
  123. if !visitor(env.SecretRef.Name) {
  124. return false
  125. }
  126. }
  127. }
  128. for _, envVar := range container.Env {
  129. if envVar.ValueFrom != nil && envVar.ValueFrom.SecretKeyRef != nil {
  130. if !visitor(envVar.ValueFrom.SecretKeyRef.Name) {
  131. return false
  132. }
  133. }
  134. }
  135. return true
  136. }
  137. // VisitPodConfigmapNames invokes the visitor function with the name of every configmap
  138. // referenced by the pod spec. If visitor returns false, visiting is short-circuited.
  139. // Transitive references (e.g. pod -> pvc -> pv -> secret) are not visited.
  140. // Returns true if visiting completed, false if visiting was short-circuited.
  141. func VisitPodConfigmapNames(pod *api.Pod, visitor Visitor) bool {
  142. VisitContainers(&pod.Spec, func(c *api.Container) bool {
  143. return visitContainerConfigmapNames(c, visitor)
  144. })
  145. var source *api.VolumeSource
  146. for i := range pod.Spec.Volumes {
  147. source = &pod.Spec.Volumes[i].VolumeSource
  148. switch {
  149. case source.Projected != nil:
  150. for j := range source.Projected.Sources {
  151. if source.Projected.Sources[j].ConfigMap != nil {
  152. if !visitor(source.Projected.Sources[j].ConfigMap.Name) {
  153. return false
  154. }
  155. }
  156. }
  157. case source.ConfigMap != nil:
  158. if !visitor(source.ConfigMap.Name) {
  159. return false
  160. }
  161. }
  162. }
  163. return true
  164. }
  165. func visitContainerConfigmapNames(container *api.Container, visitor Visitor) bool {
  166. for _, env := range container.EnvFrom {
  167. if env.ConfigMapRef != nil {
  168. if !visitor(env.ConfigMapRef.Name) {
  169. return false
  170. }
  171. }
  172. }
  173. for _, envVar := range container.Env {
  174. if envVar.ValueFrom != nil && envVar.ValueFrom.ConfigMapKeyRef != nil {
  175. if !visitor(envVar.ValueFrom.ConfigMapKeyRef.Name) {
  176. return false
  177. }
  178. }
  179. }
  180. return true
  181. }
  182. // IsPodReady returns true if a pod is ready; false otherwise.
  183. func IsPodReady(pod *api.Pod) bool {
  184. return IsPodReadyConditionTrue(pod.Status)
  185. }
  186. // IsPodReadyConditionTrue returns true if a pod is ready; false otherwise.
  187. func IsPodReadyConditionTrue(status api.PodStatus) bool {
  188. condition := GetPodReadyCondition(status)
  189. return condition != nil && condition.Status == api.ConditionTrue
  190. }
  191. // GetPodReadyCondition extracts the pod ready condition from the given status and returns that.
  192. // Returns nil if the condition is not present.
  193. func GetPodReadyCondition(status api.PodStatus) *api.PodCondition {
  194. _, condition := GetPodCondition(&status, api.PodReady)
  195. return condition
  196. }
  197. // GetPodCondition extracts the provided condition from the given status and returns that.
  198. // Returns nil and -1 if the condition is not present, and the index of the located condition.
  199. func GetPodCondition(status *api.PodStatus, conditionType api.PodConditionType) (int, *api.PodCondition) {
  200. if status == nil {
  201. return -1, nil
  202. }
  203. for i := range status.Conditions {
  204. if status.Conditions[i].Type == conditionType {
  205. return i, &status.Conditions[i]
  206. }
  207. }
  208. return -1, nil
  209. }
  210. // UpdatePodCondition updates existing pod condition or creates a new one. Sets LastTransitionTime to now if the
  211. // status has changed.
  212. // Returns true if pod condition has changed or has been added.
  213. func UpdatePodCondition(status *api.PodStatus, condition *api.PodCondition) bool {
  214. condition.LastTransitionTime = metav1.Now()
  215. // Try to find this pod condition.
  216. conditionIndex, oldCondition := GetPodCondition(status, condition.Type)
  217. if oldCondition == nil {
  218. // We are adding new pod condition.
  219. status.Conditions = append(status.Conditions, *condition)
  220. return true
  221. }
  222. // We are updating an existing condition, so we need to check if it has changed.
  223. if condition.Status == oldCondition.Status {
  224. condition.LastTransitionTime = oldCondition.LastTransitionTime
  225. }
  226. isEqual := condition.Status == oldCondition.Status &&
  227. condition.Reason == oldCondition.Reason &&
  228. condition.Message == oldCondition.Message &&
  229. condition.LastProbeTime.Equal(&oldCondition.LastProbeTime) &&
  230. condition.LastTransitionTime.Equal(&oldCondition.LastTransitionTime)
  231. status.Conditions[conditionIndex] = *condition
  232. // Return true if one of the fields have changed.
  233. return !isEqual
  234. }
  235. // DropDisabledTemplateFields removes disabled fields from the pod template metadata and spec.
  236. // This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a PodTemplateSpec
  237. func DropDisabledTemplateFields(podTemplate, oldPodTemplate *api.PodTemplateSpec) {
  238. var (
  239. podSpec *api.PodSpec
  240. podAnnotations map[string]string
  241. oldPodSpec *api.PodSpec
  242. oldPodAnnotations map[string]string
  243. )
  244. if podTemplate != nil {
  245. podSpec = &podTemplate.Spec
  246. podAnnotations = podTemplate.Annotations
  247. }
  248. if oldPodTemplate != nil {
  249. oldPodSpec = &oldPodTemplate.Spec
  250. oldPodAnnotations = oldPodTemplate.Annotations
  251. }
  252. dropDisabledFields(podSpec, podAnnotations, oldPodSpec, oldPodAnnotations)
  253. }
  254. // DropDisabledPodFields removes disabled fields from the pod metadata and spec.
  255. // This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a Pod
  256. func DropDisabledPodFields(pod, oldPod *api.Pod) {
  257. var (
  258. podSpec *api.PodSpec
  259. podAnnotations map[string]string
  260. oldPodSpec *api.PodSpec
  261. oldPodAnnotations map[string]string
  262. podStatus *api.PodStatus
  263. oldPodStatus *api.PodStatus
  264. )
  265. if pod != nil {
  266. podSpec = &pod.Spec
  267. podAnnotations = pod.Annotations
  268. podStatus = &pod.Status
  269. }
  270. if oldPod != nil {
  271. oldPodSpec = &oldPod.Spec
  272. oldPodAnnotations = oldPod.Annotations
  273. oldPodStatus = &oldPod.Status
  274. }
  275. dropDisabledFields(podSpec, podAnnotations, oldPodSpec, oldPodAnnotations)
  276. dropPodStatusDisabledFields(podStatus, oldPodStatus)
  277. }
  278. // dropPodStatusDisabledFields removes disabled fields from the pod status
  279. func dropPodStatusDisabledFields(podStatus *api.PodStatus, oldPodStatus *api.PodStatus) {
  280. // trim PodIPs down to only one entry (non dual stack).
  281. if !utilfeature.DefaultFeatureGate.Enabled(features.IPv6DualStack) &&
  282. !multiplePodIPsInUse(oldPodStatus) {
  283. if len(podStatus.PodIPs) != 0 {
  284. podStatus.PodIPs = podStatus.PodIPs[0:1]
  285. }
  286. }
  287. }
  288. // dropDisabledFields removes disabled fields from the pod metadata and spec.
  289. func dropDisabledFields(
  290. podSpec *api.PodSpec, podAnnotations map[string]string,
  291. oldPodSpec *api.PodSpec, oldPodAnnotations map[string]string,
  292. ) {
  293. // the new spec must always be non-nil
  294. if podSpec == nil {
  295. podSpec = &api.PodSpec{}
  296. }
  297. if !utilfeature.DefaultFeatureGate.Enabled(features.TokenRequestProjection) &&
  298. !tokenRequestProjectionInUse(oldPodSpec) {
  299. for i := range podSpec.Volumes {
  300. if podSpec.Volumes[i].Projected != nil {
  301. for j := range podSpec.Volumes[i].Projected.Sources {
  302. podSpec.Volumes[i].Projected.Sources[j].ServiceAccountToken = nil
  303. }
  304. }
  305. }
  306. }
  307. if !utilfeature.DefaultFeatureGate.Enabled(features.AppArmor) && !appArmorInUse(oldPodAnnotations) {
  308. for k := range podAnnotations {
  309. if strings.HasPrefix(k, apparmor.ContainerAnnotationKeyPrefix) {
  310. delete(podAnnotations, k)
  311. }
  312. }
  313. }
  314. if !utilfeature.DefaultFeatureGate.Enabled(features.Sysctls) && !sysctlsInUse(oldPodSpec) {
  315. if podSpec.SecurityContext != nil {
  316. podSpec.SecurityContext.Sysctls = nil
  317. }
  318. }
  319. if !utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) && !emptyDirSizeLimitInUse(oldPodSpec) {
  320. for i := range podSpec.Volumes {
  321. if podSpec.Volumes[i].EmptyDir != nil {
  322. podSpec.Volumes[i].EmptyDir.SizeLimit = nil
  323. }
  324. }
  325. }
  326. if !utilfeature.DefaultFeatureGate.Enabled(features.VolumeSubpath) && !subpathInUse(oldPodSpec) {
  327. // drop subpath from the pod if the feature is disabled and the old spec did not specify subpaths
  328. VisitContainers(podSpec, func(c *api.Container) bool {
  329. for i := range c.VolumeMounts {
  330. c.VolumeMounts[i].SubPath = ""
  331. }
  332. return true
  333. })
  334. }
  335. if !utilfeature.DefaultFeatureGate.Enabled(features.EphemeralContainers) && !ephemeralContainersInUse(oldPodSpec) {
  336. podSpec.EphemeralContainers = nil
  337. }
  338. if (!utilfeature.DefaultFeatureGate.Enabled(features.VolumeSubpath) || !utilfeature.DefaultFeatureGate.Enabled(features.VolumeSubpathEnvExpansion)) && !subpathExprInUse(oldPodSpec) {
  339. // drop subpath env expansion from the pod if either of the subpath features is disabled and the old spec did not specify subpath env expansion
  340. VisitContainers(podSpec, func(c *api.Container) bool {
  341. for i := range c.VolumeMounts {
  342. c.VolumeMounts[i].SubPathExpr = ""
  343. }
  344. return true
  345. })
  346. }
  347. if !utilfeature.DefaultFeatureGate.Enabled(features.StartupProbe) && !startupProbeInUse(oldPodSpec) {
  348. // drop startupProbe from all containers if the feature is disabled
  349. VisitContainers(podSpec, func(c *api.Container) bool {
  350. c.StartupProbe = nil
  351. return true
  352. })
  353. }
  354. dropDisabledVolumeDevicesFields(podSpec, oldPodSpec)
  355. dropDisabledRunAsGroupField(podSpec, oldPodSpec)
  356. dropDisabledGMSAFields(podSpec, oldPodSpec)
  357. dropDisabledRunAsUserNameFields(podSpec, oldPodSpec)
  358. if !utilfeature.DefaultFeatureGate.Enabled(features.RuntimeClass) && !runtimeClassInUse(oldPodSpec) {
  359. // Set RuntimeClassName to nil only if feature is disabled and it is not used
  360. podSpec.RuntimeClassName = nil
  361. }
  362. if !utilfeature.DefaultFeatureGate.Enabled(features.PodOverhead) && !overheadInUse(oldPodSpec) {
  363. // Set Overhead to nil only if the feature is disabled and it is not used
  364. podSpec.Overhead = nil
  365. }
  366. dropDisabledProcMountField(podSpec, oldPodSpec)
  367. dropDisabledCSIVolumeSourceAlphaFields(podSpec, oldPodSpec)
  368. if !utilfeature.DefaultFeatureGate.Enabled(features.NonPreemptingPriority) &&
  369. !podPriorityInUse(oldPodSpec) {
  370. // Set to nil pod's PreemptionPolicy fields if the feature is disabled and the old pod
  371. // does not specify any values for these fields.
  372. podSpec.PreemptionPolicy = nil
  373. }
  374. if !utilfeature.DefaultFeatureGate.Enabled(features.EvenPodsSpread) && !topologySpreadConstraintsInUse(oldPodSpec) {
  375. // Set TopologySpreadConstraints to nil only if feature is disabled and it is not used
  376. podSpec.TopologySpreadConstraints = nil
  377. }
  378. }
  379. // dropDisabledRunAsGroupField removes disabled fields from PodSpec related
  380. // to RunAsGroup
  381. func dropDisabledRunAsGroupField(podSpec, oldPodSpec *api.PodSpec) {
  382. if !utilfeature.DefaultFeatureGate.Enabled(features.RunAsGroup) && !runAsGroupInUse(oldPodSpec) {
  383. if podSpec.SecurityContext != nil {
  384. podSpec.SecurityContext.RunAsGroup = nil
  385. }
  386. VisitContainers(podSpec, func(c *api.Container) bool {
  387. if c.SecurityContext != nil {
  388. c.SecurityContext.RunAsGroup = nil
  389. }
  390. return true
  391. })
  392. }
  393. }
  394. // dropDisabledGMSAFields removes disabled fields related to Windows GMSA
  395. // from the given PodSpec.
  396. func dropDisabledGMSAFields(podSpec, oldPodSpec *api.PodSpec) {
  397. if utilfeature.DefaultFeatureGate.Enabled(features.WindowsGMSA) ||
  398. gMSAFieldsInUse(oldPodSpec) {
  399. return
  400. }
  401. if podSpec.SecurityContext != nil {
  402. dropDisabledGMSAFieldsFromWindowsSecurityOptions(podSpec.SecurityContext.WindowsOptions)
  403. }
  404. dropDisabledGMSAFieldsFromContainers(podSpec.Containers)
  405. dropDisabledGMSAFieldsFromContainers(podSpec.InitContainers)
  406. }
  407. // dropDisabledGMSAFieldsFromWindowsSecurityOptions removes disabled fields
  408. // related to Windows GMSA from the given WindowsSecurityContextOptions.
  409. func dropDisabledGMSAFieldsFromWindowsSecurityOptions(windowsOptions *api.WindowsSecurityContextOptions) {
  410. if windowsOptions != nil {
  411. windowsOptions.GMSACredentialSpecName = nil
  412. windowsOptions.GMSACredentialSpec = nil
  413. }
  414. }
  415. // dropDisabledGMSAFieldsFromContainers removes disabled fields
  416. func dropDisabledGMSAFieldsFromContainers(containers []api.Container) {
  417. for i := range containers {
  418. if containers[i].SecurityContext != nil {
  419. dropDisabledGMSAFieldsFromWindowsSecurityOptions(containers[i].SecurityContext.WindowsOptions)
  420. }
  421. }
  422. }
  423. // dropDisabledRunAsUserNameFields removes disabled fields related to WindowsOptions.RunAsUserName
  424. // from the given PodSpec.
  425. func dropDisabledRunAsUserNameFields(podSpec, oldPodSpec *api.PodSpec) {
  426. if utilfeature.DefaultFeatureGate.Enabled(features.WindowsRunAsUserName) ||
  427. runAsUserNameFieldsInUse(oldPodSpec) {
  428. return
  429. }
  430. if podSpec.SecurityContext != nil {
  431. dropDisabledRunAsUserNameFieldsFromWindowsSecurityOptions(podSpec.SecurityContext.WindowsOptions)
  432. }
  433. dropDisabledRunAsUserNameFieldsFromContainers(podSpec.Containers)
  434. dropDisabledRunAsUserNameFieldsFromContainers(podSpec.InitContainers)
  435. }
  436. // dropDisabledRunAsUserNameFieldsFromWindowsSecurityOptions removes disabled fields
  437. // related to RunAsUserName from the given WindowsSecurityContextOptions.
  438. func dropDisabledRunAsUserNameFieldsFromWindowsSecurityOptions(windowsOptions *api.WindowsSecurityContextOptions) {
  439. if windowsOptions != nil {
  440. windowsOptions.RunAsUserName = nil
  441. }
  442. }
  443. // dropDisabledRunAsUserNameFieldsFromContainers removes disabled fields
  444. func dropDisabledRunAsUserNameFieldsFromContainers(containers []api.Container) {
  445. for i := range containers {
  446. if containers[i].SecurityContext != nil {
  447. dropDisabledRunAsUserNameFieldsFromWindowsSecurityOptions(containers[i].SecurityContext.WindowsOptions)
  448. }
  449. }
  450. }
  451. // dropDisabledProcMountField removes disabled fields from PodSpec related
  452. // to ProcMount only if it is not already used by the old spec
  453. func dropDisabledProcMountField(podSpec, oldPodSpec *api.PodSpec) {
  454. if !utilfeature.DefaultFeatureGate.Enabled(features.ProcMountType) && !procMountInUse(oldPodSpec) {
  455. defaultProcMount := api.DefaultProcMount
  456. VisitContainers(podSpec, func(c *api.Container) bool {
  457. if c.SecurityContext != nil && c.SecurityContext.ProcMount != nil {
  458. // The ProcMount field was improperly forced to non-nil in 1.12.
  459. // If the feature is disabled, and the existing object is not using any non-default values, and the ProcMount field is present in the incoming object, force to the default value.
  460. // Note: we cannot force the field to nil when the feature is disabled because it causes a diff against previously persisted data.
  461. c.SecurityContext.ProcMount = &defaultProcMount
  462. }
  463. return true
  464. })
  465. }
  466. }
  467. // dropDisabledVolumeDevicesFields removes disabled fields from []VolumeDevice if it has not been already populated.
  468. // This should be called from PrepareForCreate/PrepareForUpdate for all resources containing a VolumeDevice
  469. func dropDisabledVolumeDevicesFields(podSpec, oldPodSpec *api.PodSpec) {
  470. if !utilfeature.DefaultFeatureGate.Enabled(features.BlockVolume) && !volumeDevicesInUse(oldPodSpec) {
  471. VisitContainers(podSpec, func(c *api.Container) bool {
  472. c.VolumeDevices = nil
  473. return true
  474. })
  475. }
  476. }
  477. // dropDisabledCSIVolumeSourceAlphaFields removes disabled alpha fields from []CSIVolumeSource.
  478. // This should be called from PrepareForCreate/PrepareForUpdate for all pod specs resources containing a CSIVolumeSource
  479. func dropDisabledCSIVolumeSourceAlphaFields(podSpec, oldPodSpec *api.PodSpec) {
  480. if !utilfeature.DefaultFeatureGate.Enabled(features.CSIInlineVolume) && !csiInUse(oldPodSpec) {
  481. for i := range podSpec.Volumes {
  482. podSpec.Volumes[i].CSI = nil
  483. }
  484. }
  485. }
  486. func ephemeralContainersInUse(podSpec *api.PodSpec) bool {
  487. if podSpec == nil {
  488. return false
  489. }
  490. return len(podSpec.EphemeralContainers) > 0
  491. }
  492. // subpathInUse returns true if the pod spec is non-nil and has a volume mount that makes use of the subPath feature
  493. func subpathInUse(podSpec *api.PodSpec) bool {
  494. if podSpec == nil {
  495. return false
  496. }
  497. var inUse bool
  498. VisitContainers(podSpec, func(c *api.Container) bool {
  499. for i := range c.VolumeMounts {
  500. if len(c.VolumeMounts[i].SubPath) > 0 {
  501. inUse = true
  502. return false
  503. }
  504. }
  505. return true
  506. })
  507. return inUse
  508. }
  509. // runtimeClassInUse returns true if the pod spec is non-nil and has a RuntimeClassName set
  510. func runtimeClassInUse(podSpec *api.PodSpec) bool {
  511. if podSpec == nil {
  512. return false
  513. }
  514. if podSpec.RuntimeClassName != nil {
  515. return true
  516. }
  517. return false
  518. }
  519. // overheadInUse returns true if the pod spec is non-nil and has Overhead set
  520. func overheadInUse(podSpec *api.PodSpec) bool {
  521. if podSpec == nil {
  522. return false
  523. }
  524. if podSpec.Overhead != nil {
  525. return true
  526. }
  527. return false
  528. }
  529. // topologySpreadConstraintsInUse returns true if the pod spec is non-nil and has a TopologySpreadConstraints slice
  530. func topologySpreadConstraintsInUse(podSpec *api.PodSpec) bool {
  531. if podSpec == nil {
  532. return false
  533. }
  534. return len(podSpec.TopologySpreadConstraints) > 0
  535. }
  536. // procMountInUse returns true if the pod spec is non-nil and has a SecurityContext's ProcMount field set to a non-default value
  537. func procMountInUse(podSpec *api.PodSpec) bool {
  538. if podSpec == nil {
  539. return false
  540. }
  541. var inUse bool
  542. VisitContainers(podSpec, func(c *api.Container) bool {
  543. if c.SecurityContext == nil || c.SecurityContext.ProcMount == nil {
  544. return true
  545. }
  546. if *c.SecurityContext.ProcMount != api.DefaultProcMount {
  547. inUse = true
  548. return false
  549. }
  550. return true
  551. })
  552. return inUse
  553. }
  554. // appArmorInUse returns true if the pod has apparmor related information
  555. func appArmorInUse(podAnnotations map[string]string) bool {
  556. for k := range podAnnotations {
  557. if strings.HasPrefix(k, apparmor.ContainerAnnotationKeyPrefix) {
  558. return true
  559. }
  560. }
  561. return false
  562. }
  563. func tokenRequestProjectionInUse(podSpec *api.PodSpec) bool {
  564. if podSpec == nil {
  565. return false
  566. }
  567. for _, v := range podSpec.Volumes {
  568. if v.Projected == nil {
  569. continue
  570. }
  571. for _, s := range v.Projected.Sources {
  572. if s.ServiceAccountToken != nil {
  573. return true
  574. }
  575. }
  576. }
  577. return false
  578. }
  579. // podPriorityInUse returns true if the pod spec is non-nil and has Priority or PriorityClassName set.
  580. func podPriorityInUse(podSpec *api.PodSpec) bool {
  581. if podSpec == nil {
  582. return false
  583. }
  584. if podSpec.Priority != nil || podSpec.PriorityClassName != "" {
  585. return true
  586. }
  587. return false
  588. }
  589. func sysctlsInUse(podSpec *api.PodSpec) bool {
  590. if podSpec == nil {
  591. return false
  592. }
  593. if podSpec.SecurityContext != nil && podSpec.SecurityContext.Sysctls != nil {
  594. return true
  595. }
  596. return false
  597. }
  598. // emptyDirSizeLimitInUse returns true if any pod's EmptyDir volumes use SizeLimit.
  599. func emptyDirSizeLimitInUse(podSpec *api.PodSpec) bool {
  600. if podSpec == nil {
  601. return false
  602. }
  603. for i := range podSpec.Volumes {
  604. if podSpec.Volumes[i].EmptyDir != nil {
  605. if podSpec.Volumes[i].EmptyDir.SizeLimit != nil {
  606. return true
  607. }
  608. }
  609. }
  610. return false
  611. }
  612. // volumeDevicesInUse returns true if the pod spec is non-nil and has VolumeDevices set.
  613. func volumeDevicesInUse(podSpec *api.PodSpec) bool {
  614. if podSpec == nil {
  615. return false
  616. }
  617. var inUse bool
  618. VisitContainers(podSpec, func(c *api.Container) bool {
  619. if c.VolumeDevices != nil {
  620. inUse = true
  621. return false
  622. }
  623. return true
  624. })
  625. return inUse
  626. }
  627. // runAsGroupInUse returns true if the pod spec is non-nil and has a SecurityContext's RunAsGroup field set
  628. func runAsGroupInUse(podSpec *api.PodSpec) bool {
  629. if podSpec == nil {
  630. return false
  631. }
  632. if podSpec.SecurityContext != nil && podSpec.SecurityContext.RunAsGroup != nil {
  633. return true
  634. }
  635. var inUse bool
  636. VisitContainers(podSpec, func(c *api.Container) bool {
  637. if c.SecurityContext != nil && c.SecurityContext.RunAsGroup != nil {
  638. inUse = true
  639. return false
  640. }
  641. return true
  642. })
  643. return inUse
  644. }
  645. // gMSAFieldsInUse returns true if the pod spec is non-nil and has one of any
  646. // SecurityContext's GMSACredentialSpecName or GMSACredentialSpec fields set.
  647. func gMSAFieldsInUse(podSpec *api.PodSpec) bool {
  648. if podSpec == nil {
  649. return false
  650. }
  651. if podSpec.SecurityContext != nil && gMSAFieldsInUseInWindowsSecurityOptions(podSpec.SecurityContext.WindowsOptions) {
  652. return true
  653. }
  654. return gMSAFieldsInUseInAnyContainer(podSpec.Containers) ||
  655. gMSAFieldsInUseInAnyContainer(podSpec.InitContainers)
  656. }
  657. // gMSAFieldsInUseInWindowsSecurityOptions returns true if the given WindowsSecurityContextOptions is
  658. // non-nil and one of its GMSACredentialSpecName or GMSACredentialSpec fields is set.
  659. func gMSAFieldsInUseInWindowsSecurityOptions(windowsOptions *api.WindowsSecurityContextOptions) bool {
  660. if windowsOptions == nil {
  661. return false
  662. }
  663. return windowsOptions.GMSACredentialSpecName != nil ||
  664. windowsOptions.GMSACredentialSpec != nil
  665. }
  666. // gMSAFieldsInUseInAnyContainer returns true if any of the given Containers has its
  667. // SecurityContext's GMSACredentialSpecName or GMSACredentialSpec fields set.
  668. func gMSAFieldsInUseInAnyContainer(containers []api.Container) bool {
  669. for _, container := range containers {
  670. if container.SecurityContext != nil && gMSAFieldsInUseInWindowsSecurityOptions(container.SecurityContext.WindowsOptions) {
  671. return true
  672. }
  673. }
  674. return false
  675. }
  676. // runAsUserNameFieldsInUse returns true if the pod spec is non-nil and has the RunAsUserName
  677. // field set in the PodSecurityContext or any container's SecurityContext.
  678. func runAsUserNameFieldsInUse(podSpec *api.PodSpec) bool {
  679. if podSpec == nil {
  680. return false
  681. }
  682. if podSpec.SecurityContext != nil && runAsUserNameFieldsInUseInWindowsSecurityOptions(podSpec.SecurityContext.WindowsOptions) {
  683. return true
  684. }
  685. return runAsUserNameFieldsInUseInAnyContainer(podSpec.Containers) ||
  686. runAsUserNameFieldsInUseInAnyContainer(podSpec.InitContainers)
  687. }
  688. // runAsUserNameFieldsInUseInWindowsSecurityOptions returns true if the given WindowsSecurityContextOptions is
  689. // non-nil and its RunAsUserName field is set.
  690. func runAsUserNameFieldsInUseInWindowsSecurityOptions(windowsOptions *api.WindowsSecurityContextOptions) bool {
  691. return windowsOptions != nil && windowsOptions.RunAsUserName != nil
  692. }
  693. // runAsUserNameFieldsInUseInAnyContainer returns true if any of the given Containers has its
  694. // SecurityContext's RunAsUserName field set.
  695. func runAsUserNameFieldsInUseInAnyContainer(containers []api.Container) bool {
  696. for _, container := range containers {
  697. if container.SecurityContext != nil && runAsUserNameFieldsInUseInWindowsSecurityOptions(container.SecurityContext.WindowsOptions) {
  698. return true
  699. }
  700. }
  701. return false
  702. }
  703. // subpathExprInUse returns true if the pod spec is non-nil and has a volume mount that makes use of the subPathExpr feature
  704. func subpathExprInUse(podSpec *api.PodSpec) bool {
  705. if podSpec == nil {
  706. return false
  707. }
  708. var inUse bool
  709. VisitContainers(podSpec, func(c *api.Container) bool {
  710. for i := range c.VolumeMounts {
  711. if len(c.VolumeMounts[i].SubPathExpr) > 0 {
  712. inUse = true
  713. return false
  714. }
  715. }
  716. return true
  717. })
  718. return inUse
  719. }
  720. // startupProbeInUse returns true if the pod spec is non-nil and has a container that has a startupProbe defined
  721. func startupProbeInUse(podSpec *api.PodSpec) bool {
  722. if podSpec == nil {
  723. return false
  724. }
  725. var inUse bool
  726. VisitContainers(podSpec, func(c *api.Container) bool {
  727. if c.StartupProbe != nil {
  728. inUse = true
  729. return false
  730. }
  731. return true
  732. })
  733. return inUse
  734. }
  735. // csiInUse returns true if any pod's spec include inline CSI volumes.
  736. func csiInUse(podSpec *api.PodSpec) bool {
  737. if podSpec == nil {
  738. return false
  739. }
  740. for i := range podSpec.Volumes {
  741. if podSpec.Volumes[i].CSI != nil {
  742. return true
  743. }
  744. }
  745. return false
  746. }
  747. // podPriorityInUse returns true if status is not nil and number of PodIPs is greater than one
  748. func multiplePodIPsInUse(podStatus *api.PodStatus) bool {
  749. if podStatus == nil {
  750. return false
  751. }
  752. if len(podStatus.PodIPs) > 1 {
  753. return true
  754. }
  755. return false
  756. }