admission.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. Copyright 2017 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 priority
  14. import (
  15. "fmt"
  16. "io"
  17. apiv1 "k8s.io/api/core/v1"
  18. schedulingv1 "k8s.io/api/scheduling/v1"
  19. "k8s.io/apimachinery/pkg/api/errors"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/labels"
  22. "k8s.io/apiserver/pkg/admission"
  23. genericadmissioninitializers "k8s.io/apiserver/pkg/admission/initializer"
  24. utilfeature "k8s.io/apiserver/pkg/util/feature"
  25. "k8s.io/client-go/informers"
  26. "k8s.io/client-go/kubernetes"
  27. schedulingv1listers "k8s.io/client-go/listers/scheduling/v1"
  28. "k8s.io/kubernetes/pkg/apis/core"
  29. api "k8s.io/kubernetes/pkg/apis/core"
  30. "k8s.io/kubernetes/pkg/apis/scheduling"
  31. "k8s.io/kubernetes/pkg/features"
  32. kubelettypes "k8s.io/kubernetes/pkg/kubelet/types"
  33. )
  34. const (
  35. // PluginName indicates name of admission plugin.
  36. PluginName = "Priority"
  37. )
  38. // Register registers a plugin
  39. func Register(plugins *admission.Plugins) {
  40. plugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {
  41. return newPlugin(), nil
  42. })
  43. }
  44. // priorityPlugin is an implementation of admission.Interface.
  45. type priorityPlugin struct {
  46. *admission.Handler
  47. client kubernetes.Interface
  48. lister schedulingv1listers.PriorityClassLister
  49. }
  50. var _ admission.MutationInterface = &priorityPlugin{}
  51. var _ admission.ValidationInterface = &priorityPlugin{}
  52. var _ = genericadmissioninitializers.WantsExternalKubeInformerFactory(&priorityPlugin{})
  53. var _ = genericadmissioninitializers.WantsExternalKubeClientSet(&priorityPlugin{})
  54. // NewPlugin creates a new priority admission plugin.
  55. func newPlugin() *priorityPlugin {
  56. return &priorityPlugin{
  57. Handler: admission.NewHandler(admission.Create, admission.Update, admission.Delete),
  58. }
  59. }
  60. // ValidateInitialization implements the InitializationValidator interface.
  61. func (p *priorityPlugin) ValidateInitialization() error {
  62. if p.client == nil {
  63. return fmt.Errorf("%s requires a client", PluginName)
  64. }
  65. if p.lister == nil {
  66. return fmt.Errorf("%s requires a lister", PluginName)
  67. }
  68. return nil
  69. }
  70. // SetInternalKubeClientSet implements the WantsInternalKubeClientSet interface.
  71. func (p *priorityPlugin) SetExternalKubeClientSet(client kubernetes.Interface) {
  72. p.client = client
  73. }
  74. // SetInternalKubeInformerFactory implements the WantsInternalKubeInformerFactory interface.
  75. func (p *priorityPlugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {
  76. priorityInformer := f.Scheduling().V1().PriorityClasses()
  77. p.lister = priorityInformer.Lister()
  78. p.SetReadyFunc(priorityInformer.Informer().HasSynced)
  79. }
  80. var (
  81. podResource = api.Resource("pods")
  82. priorityClassResource = scheduling.Resource("priorityclasses")
  83. )
  84. // Admit checks Pods and admits or rejects them. It also resolves the priority of pods based on their PriorityClass.
  85. // Note that pod validation mechanism prevents update of a pod priority.
  86. func (p *priorityPlugin) Admit(a admission.Attributes, o admission.ObjectInterfaces) error {
  87. if !utilfeature.DefaultFeatureGate.Enabled(features.PodPriority) {
  88. return nil
  89. }
  90. operation := a.GetOperation()
  91. // Ignore all calls to subresources
  92. if len(a.GetSubresource()) != 0 {
  93. return nil
  94. }
  95. switch a.GetResource().GroupResource() {
  96. case podResource:
  97. if operation == admission.Create || operation == admission.Update {
  98. return p.admitPod(a)
  99. }
  100. return nil
  101. default:
  102. return nil
  103. }
  104. }
  105. // Validate checks PriorityClasses and admits or rejects them.
  106. func (p *priorityPlugin) Validate(a admission.Attributes, o admission.ObjectInterfaces) error {
  107. operation := a.GetOperation()
  108. // Ignore all calls to subresources
  109. if len(a.GetSubresource()) != 0 {
  110. return nil
  111. }
  112. switch a.GetResource().GroupResource() {
  113. case priorityClassResource:
  114. if operation == admission.Create || operation == admission.Update {
  115. return p.validatePriorityClass(a)
  116. }
  117. return nil
  118. default:
  119. return nil
  120. }
  121. }
  122. // priorityClassPermittedInNamespace returns true if we allow the given priority class name in the
  123. // given namespace. It currently checks that system priorities are created only in the system namespace.
  124. func priorityClassPermittedInNamespace(priorityClassName string, namespace string) bool {
  125. // Only allow system priorities in the system namespace. This is to prevent abuse or incorrect
  126. // usage of these priorities. Pods created at these priorities could preempt system critical
  127. // components.
  128. for _, spc := range scheduling.SystemPriorityClasses() {
  129. if spc.Name == priorityClassName && namespace != metav1.NamespaceSystem {
  130. return false
  131. }
  132. }
  133. return true
  134. }
  135. // admitPod makes sure a new pod does not set spec.Priority field. It also makes sure that the PriorityClassName exists if it is provided and resolves the pod priority from the PriorityClassName.
  136. func (p *priorityPlugin) admitPod(a admission.Attributes) error {
  137. operation := a.GetOperation()
  138. pod, ok := a.GetObject().(*api.Pod)
  139. if !ok {
  140. return errors.NewBadRequest("resource was marked with kind Pod but was unable to be converted")
  141. }
  142. if operation == admission.Update {
  143. oldPod, ok := a.GetOldObject().(*api.Pod)
  144. if !ok {
  145. return errors.NewBadRequest("resource was marked with kind Pod but was unable to be converted")
  146. }
  147. // This admission plugin set pod.Spec.Priority on create.
  148. // Ensure the existing priority is preserved on update.
  149. // API validation prevents mutations to Priority and PriorityClassName, so any other changes will fail update validation and not be persisted.
  150. if pod.Spec.Priority == nil && oldPod.Spec.Priority != nil {
  151. pod.Spec.Priority = oldPod.Spec.Priority
  152. }
  153. return nil
  154. }
  155. if operation == admission.Create {
  156. var priority int32
  157. var preemptionPolicy *apiv1.PreemptionPolicy
  158. // TODO: @ravig - This is for backwards compatibility to ensure that critical pods with annotations just work fine.
  159. // Remove when no longer needed.
  160. if len(pod.Spec.PriorityClassName) == 0 &&
  161. utilfeature.DefaultFeatureGate.Enabled(features.ExperimentalCriticalPodAnnotation) &&
  162. kubelettypes.IsCritical(a.GetNamespace(), pod.Annotations) {
  163. pod.Spec.PriorityClassName = scheduling.SystemClusterCritical
  164. }
  165. if len(pod.Spec.PriorityClassName) == 0 {
  166. var err error
  167. var pcName string
  168. pcName, priority, preemptionPolicy, err = p.getDefaultPriority()
  169. if err != nil {
  170. return fmt.Errorf("failed to get default priority class: %v", err)
  171. }
  172. pod.Spec.PriorityClassName = pcName
  173. } else {
  174. pcName := pod.Spec.PriorityClassName
  175. if !priorityClassPermittedInNamespace(pcName, a.GetNamespace()) {
  176. return admission.NewForbidden(a, fmt.Errorf("pods with %v priorityClass is not permitted in %v namespace", pcName, a.GetNamespace()))
  177. }
  178. // Try resolving the priority class name.
  179. pc, err := p.lister.Get(pod.Spec.PriorityClassName)
  180. if err != nil {
  181. if errors.IsNotFound(err) {
  182. return admission.NewForbidden(a, fmt.Errorf("no PriorityClass with name %v was found", pod.Spec.PriorityClassName))
  183. }
  184. return fmt.Errorf("failed to get PriorityClass with name %s: %v", pod.Spec.PriorityClassName, err)
  185. }
  186. priority = pc.Value
  187. preemptionPolicy = pc.PreemptionPolicy
  188. }
  189. // if the pod contained a priority that differs from the one computed from the priority class, error
  190. if pod.Spec.Priority != nil && *pod.Spec.Priority != priority {
  191. return admission.NewForbidden(a, fmt.Errorf("the integer value of priority (%d) must not be provided in pod spec; priority admission controller computed %d from the given PriorityClass name", *pod.Spec.Priority, priority))
  192. }
  193. pod.Spec.Priority = &priority
  194. if utilfeature.DefaultFeatureGate.Enabled(features.NonPreemptingPriority) {
  195. var corePolicy core.PreemptionPolicy
  196. if preemptionPolicy != nil {
  197. corePolicy = core.PreemptionPolicy(*preemptionPolicy)
  198. if pod.Spec.PreemptionPolicy != nil && *pod.Spec.PreemptionPolicy != corePolicy {
  199. return admission.NewForbidden(a, fmt.Errorf("the string value of PreemptionPolicy (%s) must not be provided in pod spec; priority admission controller computed %s from the given PriorityClass name", *pod.Spec.PreemptionPolicy, corePolicy))
  200. }
  201. pod.Spec.PreemptionPolicy = &corePolicy
  202. }
  203. }
  204. }
  205. return nil
  206. }
  207. // validatePriorityClass ensures that the value field is not larger than the highest user definable priority. If the GlobalDefault is set, it ensures that there is no other PriorityClass whose GlobalDefault is set.
  208. func (p *priorityPlugin) validatePriorityClass(a admission.Attributes) error {
  209. operation := a.GetOperation()
  210. pc, ok := a.GetObject().(*scheduling.PriorityClass)
  211. if !ok {
  212. return errors.NewBadRequest("resource was marked with kind PriorityClass but was unable to be converted")
  213. }
  214. // If the new PriorityClass tries to be the default priority, make sure that no other priority class is marked as default.
  215. if pc.GlobalDefault {
  216. dpc, err := p.getDefaultPriorityClass()
  217. if err != nil {
  218. return fmt.Errorf("failed to get default priority class: %v", err)
  219. }
  220. if dpc != nil {
  221. // Throw an error if a second default priority class is being created, or an existing priority class is being marked as default, while another default already exists.
  222. if operation == admission.Create || (operation == admission.Update && dpc.GetName() != pc.GetName()) {
  223. return admission.NewForbidden(a, fmt.Errorf("PriorityClass %v is already marked as default. Only one default can exist", dpc.GetName()))
  224. }
  225. }
  226. }
  227. return nil
  228. }
  229. func (p *priorityPlugin) getDefaultPriorityClass() (*schedulingv1.PriorityClass, error) {
  230. list, err := p.lister.List(labels.Everything())
  231. if err != nil {
  232. return nil, err
  233. }
  234. // In case more than one global default priority class is added as a result of a race condition,
  235. // we pick the one with the lowest priority value.
  236. var defaultPC *schedulingv1.PriorityClass
  237. for _, pci := range list {
  238. if pci.GlobalDefault {
  239. if defaultPC == nil || defaultPC.Value > pci.Value {
  240. defaultPC = pci
  241. }
  242. }
  243. }
  244. return defaultPC, nil
  245. }
  246. func (p *priorityPlugin) getDefaultPriority() (string, int32, *apiv1.PreemptionPolicy, error) {
  247. dpc, err := p.getDefaultPriorityClass()
  248. if err != nil {
  249. return "", 0, nil, err
  250. }
  251. if dpc != nil {
  252. return dpc.Name, dpc.Value, dpc.PreemptionPolicy, nil
  253. }
  254. preemptLowerPriority := apiv1.PreemptLowerPriority
  255. return "", int32(scheduling.DefaultPriorityWhenNoDefaultClassExists), &preemptLowerPriority, nil
  256. }