strategy.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 job
  14. import (
  15. "context"
  16. "fmt"
  17. "strconv"
  18. batchv1 "k8s.io/api/batch/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/fields"
  21. "k8s.io/apimachinery/pkg/labels"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apimachinery/pkg/runtime/schema"
  24. "k8s.io/apimachinery/pkg/util/validation/field"
  25. genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
  26. "k8s.io/apiserver/pkg/registry/generic"
  27. "k8s.io/apiserver/pkg/registry/rest"
  28. "k8s.io/apiserver/pkg/storage"
  29. "k8s.io/apiserver/pkg/storage/names"
  30. utilfeature "k8s.io/apiserver/pkg/util/feature"
  31. "k8s.io/kubernetes/pkg/api/legacyscheme"
  32. "k8s.io/kubernetes/pkg/api/pod"
  33. "k8s.io/kubernetes/pkg/apis/batch"
  34. "k8s.io/kubernetes/pkg/apis/batch/validation"
  35. corevalidation "k8s.io/kubernetes/pkg/apis/core/validation"
  36. "k8s.io/kubernetes/pkg/features"
  37. )
  38. // jobStrategy implements verification logic for Replication Controllers.
  39. type jobStrategy struct {
  40. runtime.ObjectTyper
  41. names.NameGenerator
  42. }
  43. // Strategy is the default logic that applies when creating and updating Replication Controller objects.
  44. var Strategy = jobStrategy{legacyscheme.Scheme, names.SimpleNameGenerator}
  45. // DefaultGarbageCollectionPolicy returns OrphanDependents for batch/v1 for backwards compatibility,
  46. // and DeleteDependents for all other versions.
  47. func (jobStrategy) DefaultGarbageCollectionPolicy(ctx context.Context) rest.GarbageCollectionPolicy {
  48. var groupVersion schema.GroupVersion
  49. if requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {
  50. groupVersion = schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}
  51. }
  52. switch groupVersion {
  53. case batchv1.SchemeGroupVersion:
  54. // for back compatibility
  55. return rest.OrphanDependents
  56. default:
  57. return rest.DeleteDependents
  58. }
  59. }
  60. // NamespaceScoped returns true because all jobs need to be within a namespace.
  61. func (jobStrategy) NamespaceScoped() bool {
  62. return true
  63. }
  64. // PrepareForCreate clears the status of a job before creation.
  65. func (jobStrategy) PrepareForCreate(ctx context.Context, obj runtime.Object) {
  66. job := obj.(*batch.Job)
  67. job.Status = batch.JobStatus{}
  68. if !utilfeature.DefaultFeatureGate.Enabled(features.TTLAfterFinished) {
  69. job.Spec.TTLSecondsAfterFinished = nil
  70. }
  71. pod.DropDisabledTemplateFields(&job.Spec.Template, nil)
  72. }
  73. // PrepareForUpdate clears fields that are not allowed to be set by end users on update.
  74. func (jobStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
  75. newJob := obj.(*batch.Job)
  76. oldJob := old.(*batch.Job)
  77. newJob.Status = oldJob.Status
  78. if !utilfeature.DefaultFeatureGate.Enabled(features.TTLAfterFinished) && oldJob.Spec.TTLSecondsAfterFinished == nil {
  79. newJob.Spec.TTLSecondsAfterFinished = nil
  80. }
  81. pod.DropDisabledTemplateFields(&newJob.Spec.Template, &oldJob.Spec.Template)
  82. }
  83. // Validate validates a new job.
  84. func (jobStrategy) Validate(ctx context.Context, obj runtime.Object) field.ErrorList {
  85. job := obj.(*batch.Job)
  86. // TODO: move UID generation earlier and do this in defaulting logic?
  87. if job.Spec.ManualSelector == nil || *job.Spec.ManualSelector == false {
  88. generateSelector(job)
  89. }
  90. allErrs := validation.ValidateJob(job)
  91. allErrs = append(allErrs, corevalidation.ValidateConditionalPodTemplate(&job.Spec.Template, nil, field.NewPath("spec.template"))...)
  92. return allErrs
  93. }
  94. // generateSelector adds a selector to a job and labels to its template
  95. // which can be used to uniquely identify the pods created by that job,
  96. // if the user has requested this behavior.
  97. func generateSelector(obj *batch.Job) {
  98. if obj.Spec.Template.Labels == nil {
  99. obj.Spec.Template.Labels = make(map[string]string)
  100. }
  101. // The job-name label is unique except in cases that are expected to be
  102. // quite uncommon, and is more user friendly than uid. So, we add it as
  103. // a label.
  104. _, found := obj.Spec.Template.Labels["job-name"]
  105. if found {
  106. // User asked us to not automatically generate a selector and labels,
  107. // but set a possibly conflicting value. If there is a conflict,
  108. // we will reject in validation.
  109. } else {
  110. obj.Spec.Template.Labels["job-name"] = string(obj.ObjectMeta.Name)
  111. }
  112. // The controller-uid label makes the pods that belong to this job
  113. // only match this job.
  114. _, found = obj.Spec.Template.Labels["controller-uid"]
  115. if found {
  116. // User asked us to automatically generate a selector and labels,
  117. // but set a possibly conflicting value. If there is a conflict,
  118. // we will reject in validation.
  119. } else {
  120. obj.Spec.Template.Labels["controller-uid"] = string(obj.ObjectMeta.UID)
  121. }
  122. // Select the controller-uid label. This is sufficient for uniqueness.
  123. if obj.Spec.Selector == nil {
  124. obj.Spec.Selector = &metav1.LabelSelector{}
  125. }
  126. if obj.Spec.Selector.MatchLabels == nil {
  127. obj.Spec.Selector.MatchLabels = make(map[string]string)
  128. }
  129. if _, found := obj.Spec.Selector.MatchLabels["controller-uid"]; !found {
  130. obj.Spec.Selector.MatchLabels["controller-uid"] = string(obj.ObjectMeta.UID)
  131. }
  132. // If the user specified matchLabel controller-uid=$WRONGUID, then it should fail
  133. // in validation, either because the selector does not match the pod template
  134. // (controller-uid=$WRONGUID does not match controller-uid=$UID, which we applied
  135. // above, or we will reject in validation because the template has the wrong
  136. // labels.
  137. }
  138. // TODO: generalize generateSelector so it can work for other controller
  139. // objects such as ReplicaSet. Can use pkg/api/meta to generically get the
  140. // UID, but need some way to generically access the selector and pod labels
  141. // fields.
  142. // Canonicalize normalizes the object after validation.
  143. func (jobStrategy) Canonicalize(obj runtime.Object) {
  144. }
  145. func (jobStrategy) AllowUnconditionalUpdate() bool {
  146. return true
  147. }
  148. // AllowCreateOnUpdate is false for jobs; this means a POST is needed to create one.
  149. func (jobStrategy) AllowCreateOnUpdate() bool {
  150. return false
  151. }
  152. // ValidateUpdate is the default update validation for an end user.
  153. func (jobStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
  154. job := obj.(*batch.Job)
  155. oldJob := old.(*batch.Job)
  156. validationErrorList := validation.ValidateJob(job)
  157. updateErrorList := validation.ValidateJobUpdate(job, oldJob)
  158. updateErrorList = append(updateErrorList, corevalidation.ValidateConditionalPodTemplate(&job.Spec.Template, &oldJob.Spec.Template, field.NewPath("spec.template"))...)
  159. return append(validationErrorList, updateErrorList...)
  160. }
  161. type jobStatusStrategy struct {
  162. jobStrategy
  163. }
  164. var StatusStrategy = jobStatusStrategy{Strategy}
  165. func (jobStatusStrategy) PrepareForUpdate(ctx context.Context, obj, old runtime.Object) {
  166. newJob := obj.(*batch.Job)
  167. oldJob := old.(*batch.Job)
  168. newJob.Spec = oldJob.Spec
  169. }
  170. func (jobStatusStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
  171. return validation.ValidateJobUpdateStatus(obj.(*batch.Job), old.(*batch.Job))
  172. }
  173. // JobSelectableFields returns a field set that represents the object for matching purposes.
  174. func JobToSelectableFields(job *batch.Job) fields.Set {
  175. objectMetaFieldsSet := generic.ObjectMetaFieldsSet(&job.ObjectMeta, true)
  176. specificFieldsSet := fields.Set{
  177. "status.successful": strconv.Itoa(int(job.Status.Succeeded)),
  178. }
  179. return generic.MergeFieldsSets(objectMetaFieldsSet, specificFieldsSet)
  180. }
  181. // GetAttrs returns labels and fields of a given object for filtering purposes.
  182. func GetAttrs(obj runtime.Object) (labels.Set, fields.Set, error) {
  183. job, ok := obj.(*batch.Job)
  184. if !ok {
  185. return nil, nil, fmt.Errorf("given object is not a job.")
  186. }
  187. return labels.Set(job.ObjectMeta.Labels), JobToSelectableFields(job), nil
  188. }
  189. // MatchJob is the filter used by the generic etcd backend to route
  190. // watch events from etcd to clients of the apiserver only interested in specific
  191. // labels/fields.
  192. func MatchJob(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
  193. return storage.SelectionPredicate{
  194. Label: label,
  195. Field: field,
  196. GetAttrs: GetAttrs,
  197. }
  198. }