admission.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. "context"
  16. "fmt"
  17. "io"
  18. apiv1 "k8s.io/api/core/v1"
  19. schedulingv1 "k8s.io/api/scheduling/v1"
  20. "k8s.io/apimachinery/pkg/api/errors"
  21. "k8s.io/apimachinery/pkg/labels"
  22. "k8s.io/apiserver/pkg/admission"
  23. genericadmissioninitializers "k8s.io/apiserver/pkg/admission/initializer"
  24. "k8s.io/client-go/informers"
  25. "k8s.io/client-go/kubernetes"
  26. schedulingv1listers "k8s.io/client-go/listers/scheduling/v1"
  27. "k8s.io/component-base/featuregate"
  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. )
  33. const (
  34. // PluginName indicates name of admission plugin.
  35. PluginName = "Priority"
  36. )
  37. // Register registers a plugin
  38. func Register(plugins *admission.Plugins) {
  39. plugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {
  40. return NewPlugin(), nil
  41. })
  42. }
  43. // Plugin is an implementation of admission.Interface.
  44. type Plugin struct {
  45. *admission.Handler
  46. client kubernetes.Interface
  47. lister schedulingv1listers.PriorityClassLister
  48. nonPreemptingPriority bool
  49. }
  50. var _ admission.MutationInterface = &Plugin{}
  51. var _ admission.ValidationInterface = &Plugin{}
  52. var _ genericadmissioninitializers.WantsFeatures = &Plugin{}
  53. var _ = genericadmissioninitializers.WantsExternalKubeInformerFactory(&Plugin{})
  54. var _ = genericadmissioninitializers.WantsExternalKubeClientSet(&Plugin{})
  55. // NewPlugin creates a new priority admission plugin.
  56. func NewPlugin() *Plugin {
  57. return &Plugin{
  58. Handler: admission.NewHandler(admission.Create, admission.Update, admission.Delete),
  59. }
  60. }
  61. // ValidateInitialization implements the InitializationValidator interface.
  62. func (p *Plugin) ValidateInitialization() error {
  63. if p.client == nil {
  64. return fmt.Errorf("%s requires a client", PluginName)
  65. }
  66. if p.lister == nil {
  67. return fmt.Errorf("%s requires a lister", PluginName)
  68. }
  69. return nil
  70. }
  71. // InspectFeatureGates allows setting bools without taking a dep on a global variable
  72. func (p *Plugin) InspectFeatureGates(featureGates featuregate.FeatureGate) {
  73. p.nonPreemptingPriority = featureGates.Enabled(features.NonPreemptingPriority)
  74. }
  75. // SetExternalKubeClientSet implements the WantsInternalKubeClientSet interface.
  76. func (p *Plugin) SetExternalKubeClientSet(client kubernetes.Interface) {
  77. p.client = client
  78. }
  79. // SetExternalKubeInformerFactory implements the WantsInternalKubeInformerFactory interface.
  80. func (p *Plugin) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {
  81. priorityInformer := f.Scheduling().V1().PriorityClasses()
  82. p.lister = priorityInformer.Lister()
  83. p.SetReadyFunc(priorityInformer.Informer().HasSynced)
  84. }
  85. var (
  86. podResource = api.Resource("pods")
  87. priorityClassResource = scheduling.Resource("priorityclasses")
  88. )
  89. // Admit checks Pods and admits or rejects them. It also resolves the priority of pods based on their PriorityClass.
  90. // Note that pod validation mechanism prevents update of a pod priority.
  91. func (p *Plugin) Admit(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
  92. operation := a.GetOperation()
  93. // Ignore all calls to subresources
  94. if len(a.GetSubresource()) != 0 {
  95. return nil
  96. }
  97. switch a.GetResource().GroupResource() {
  98. case podResource:
  99. if operation == admission.Create || operation == admission.Update {
  100. return p.admitPod(a)
  101. }
  102. return nil
  103. default:
  104. return nil
  105. }
  106. }
  107. // Validate checks PriorityClasses and admits or rejects them.
  108. func (p *Plugin) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
  109. operation := a.GetOperation()
  110. // Ignore all calls to subresources
  111. if len(a.GetSubresource()) != 0 {
  112. return nil
  113. }
  114. switch a.GetResource().GroupResource() {
  115. case priorityClassResource:
  116. if operation == admission.Create || operation == admission.Update {
  117. return p.validatePriorityClass(a)
  118. }
  119. return nil
  120. default:
  121. return nil
  122. }
  123. }
  124. // 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.
  125. func (p *Plugin) admitPod(a admission.Attributes) error {
  126. operation := a.GetOperation()
  127. pod, ok := a.GetObject().(*api.Pod)
  128. if !ok {
  129. return errors.NewBadRequest("resource was marked with kind Pod but was unable to be converted")
  130. }
  131. if operation == admission.Update {
  132. oldPod, ok := a.GetOldObject().(*api.Pod)
  133. if !ok {
  134. return errors.NewBadRequest("resource was marked with kind Pod but was unable to be converted")
  135. }
  136. // This admission plugin set pod.Spec.Priority on create.
  137. // Ensure the existing priority is preserved on update.
  138. // API validation prevents mutations to Priority and PriorityClassName, so any other changes will fail update validation and not be persisted.
  139. if pod.Spec.Priority == nil && oldPod.Spec.Priority != nil {
  140. pod.Spec.Priority = oldPod.Spec.Priority
  141. }
  142. return nil
  143. }
  144. if operation == admission.Create {
  145. var priority int32
  146. var preemptionPolicy *apiv1.PreemptionPolicy
  147. if len(pod.Spec.PriorityClassName) == 0 {
  148. var err error
  149. var pcName string
  150. pcName, priority, preemptionPolicy, err = p.getDefaultPriority()
  151. if err != nil {
  152. return fmt.Errorf("failed to get default priority class: %v", err)
  153. }
  154. pod.Spec.PriorityClassName = pcName
  155. } else {
  156. // Try resolving the priority class name.
  157. pc, err := p.lister.Get(pod.Spec.PriorityClassName)
  158. if err != nil {
  159. if errors.IsNotFound(err) {
  160. return admission.NewForbidden(a, fmt.Errorf("no PriorityClass with name %v was found", pod.Spec.PriorityClassName))
  161. }
  162. return fmt.Errorf("failed to get PriorityClass with name %s: %v", pod.Spec.PriorityClassName, err)
  163. }
  164. priority = pc.Value
  165. preemptionPolicy = pc.PreemptionPolicy
  166. }
  167. // if the pod contained a priority that differs from the one computed from the priority class, error
  168. if pod.Spec.Priority != nil && *pod.Spec.Priority != priority {
  169. 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))
  170. }
  171. pod.Spec.Priority = &priority
  172. if p.nonPreemptingPriority {
  173. var corePolicy core.PreemptionPolicy
  174. if preemptionPolicy != nil {
  175. corePolicy = core.PreemptionPolicy(*preemptionPolicy)
  176. if pod.Spec.PreemptionPolicy != nil && *pod.Spec.PreemptionPolicy != corePolicy {
  177. 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))
  178. }
  179. pod.Spec.PreemptionPolicy = &corePolicy
  180. }
  181. }
  182. }
  183. return nil
  184. }
  185. // 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.
  186. func (p *Plugin) validatePriorityClass(a admission.Attributes) error {
  187. operation := a.GetOperation()
  188. pc, ok := a.GetObject().(*scheduling.PriorityClass)
  189. if !ok {
  190. return errors.NewBadRequest("resource was marked with kind PriorityClass but was unable to be converted")
  191. }
  192. // If the new PriorityClass tries to be the default priority, make sure that no other priority class is marked as default.
  193. if pc.GlobalDefault {
  194. dpc, err := p.getDefaultPriorityClass()
  195. if err != nil {
  196. return fmt.Errorf("failed to get default priority class: %v", err)
  197. }
  198. if dpc != nil {
  199. // 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.
  200. if operation == admission.Create || (operation == admission.Update && dpc.GetName() != pc.GetName()) {
  201. return admission.NewForbidden(a, fmt.Errorf("PriorityClass %v is already marked as default. Only one default can exist", dpc.GetName()))
  202. }
  203. }
  204. }
  205. return nil
  206. }
  207. func (p *Plugin) getDefaultPriorityClass() (*schedulingv1.PriorityClass, error) {
  208. list, err := p.lister.List(labels.Everything())
  209. if err != nil {
  210. return nil, err
  211. }
  212. // In case more than one global default priority class is added as a result of a race condition,
  213. // we pick the one with the lowest priority value.
  214. var defaultPC *schedulingv1.PriorityClass
  215. for _, pci := range list {
  216. if pci.GlobalDefault {
  217. if defaultPC == nil || defaultPC.Value > pci.Value {
  218. defaultPC = pci
  219. }
  220. }
  221. }
  222. return defaultPC, nil
  223. }
  224. func (p *Plugin) getDefaultPriority() (string, int32, *apiv1.PreemptionPolicy, error) {
  225. dpc, err := p.getDefaultPriorityClass()
  226. if err != nil {
  227. return "", 0, nil, err
  228. }
  229. if dpc != nil {
  230. return dpc.Name, dpc.Value, dpc.PreemptionPolicy, nil
  231. }
  232. preemptLowerPriority := apiv1.PreemptLowerPriority
  233. return "", int32(scheduling.DefaultPriorityWhenNoDefaultClassExists), &preemptLowerPriority, nil
  234. }