strategy_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. "reflect"
  16. "testing"
  17. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  18. "k8s.io/apimachinery/pkg/types"
  19. genericapirequest "k8s.io/apiserver/pkg/endpoints/request"
  20. "k8s.io/apiserver/pkg/registry/rest"
  21. utilfeature "k8s.io/apiserver/pkg/util/feature"
  22. featuregatetesting "k8s.io/component-base/featuregate/testing"
  23. apitesting "k8s.io/kubernetes/pkg/api/testing"
  24. "k8s.io/kubernetes/pkg/apis/batch"
  25. _ "k8s.io/kubernetes/pkg/apis/batch/install"
  26. api "k8s.io/kubernetes/pkg/apis/core"
  27. "k8s.io/kubernetes/pkg/features"
  28. )
  29. func newBool(a bool) *bool {
  30. return &a
  31. }
  32. func newInt32(i int32) *int32 {
  33. return &i
  34. }
  35. func TestJobStrategy(t *testing.T) {
  36. ttlEnabled := utilfeature.DefaultFeatureGate.Enabled(features.TTLAfterFinished)
  37. ctx := genericapirequest.NewDefaultContext()
  38. if !Strategy.NamespaceScoped() {
  39. t.Errorf("Job must be namespace scoped")
  40. }
  41. if Strategy.AllowCreateOnUpdate() {
  42. t.Errorf("Job should not allow create on update")
  43. }
  44. validSelector := &metav1.LabelSelector{
  45. MatchLabels: map[string]string{"a": "b"},
  46. }
  47. validPodTemplateSpec := api.PodTemplateSpec{
  48. ObjectMeta: metav1.ObjectMeta{
  49. Labels: validSelector.MatchLabels,
  50. },
  51. Spec: api.PodSpec{
  52. RestartPolicy: api.RestartPolicyOnFailure,
  53. DNSPolicy: api.DNSClusterFirst,
  54. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: api.TerminationMessageReadFile}},
  55. },
  56. }
  57. job := &batch.Job{
  58. ObjectMeta: metav1.ObjectMeta{
  59. Name: "myjob",
  60. Namespace: metav1.NamespaceDefault,
  61. },
  62. Spec: batch.JobSpec{
  63. Selector: validSelector,
  64. Template: validPodTemplateSpec,
  65. TTLSecondsAfterFinished: newInt32(0), // Set TTL
  66. ManualSelector: newBool(true),
  67. },
  68. Status: batch.JobStatus{
  69. Active: 11,
  70. },
  71. }
  72. Strategy.PrepareForCreate(ctx, job)
  73. if job.Status.Active != 0 {
  74. t.Errorf("Job does not allow setting status on create")
  75. }
  76. errs := Strategy.Validate(ctx, job)
  77. if len(errs) != 0 {
  78. t.Errorf("Unexpected error validating %v", errs)
  79. }
  80. if ttlEnabled && job.Spec.TTLSecondsAfterFinished == nil {
  81. // When the TTL feature is enabled, the TTL field can be set
  82. t.Errorf("Job should allow setting .spec.ttlSecondsAfterFinished when %v feature is enabled", features.TTLAfterFinished)
  83. }
  84. if !ttlEnabled && job.Spec.TTLSecondsAfterFinished != nil {
  85. // When the TTL feature is disabled, the TTL field cannot be set
  86. t.Errorf("Job should not allow setting .spec.ttlSecondsAfterFinished when %v feature is disabled", features.TTLAfterFinished)
  87. }
  88. parallelism := int32(10)
  89. updatedJob := &batch.Job{
  90. ObjectMeta: metav1.ObjectMeta{Name: "bar", ResourceVersion: "4"},
  91. Spec: batch.JobSpec{
  92. Parallelism: &parallelism,
  93. TTLSecondsAfterFinished: newInt32(1), // Update TTL
  94. },
  95. Status: batch.JobStatus{
  96. Active: 11,
  97. },
  98. }
  99. // ensure we do not change status
  100. job.Status.Active = 10
  101. Strategy.PrepareForUpdate(ctx, updatedJob, job)
  102. if updatedJob.Status.Active != 10 {
  103. t.Errorf("PrepareForUpdate should have preserved prior version status")
  104. }
  105. errs = Strategy.ValidateUpdate(ctx, updatedJob, job)
  106. if len(errs) == 0 {
  107. t.Errorf("Expected a validation error")
  108. }
  109. if ttlEnabled != (job.Spec.TTLSecondsAfterFinished != nil || updatedJob.Spec.TTLSecondsAfterFinished != nil) {
  110. t.Errorf("Job should only allow updating .spec.ttlSecondsAfterFinished when %v feature is enabled", features.TTLAfterFinished)
  111. }
  112. // set TTLSecondsAfterFinished on both old and new jobs
  113. job.Spec.TTLSecondsAfterFinished = newInt32(1)
  114. updatedJob.Spec.TTLSecondsAfterFinished = newInt32(2)
  115. // Existing TTLSecondsAfterFinished should be preserved when feature is on
  116. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.TTLAfterFinished, true)()
  117. Strategy.PrepareForUpdate(ctx, updatedJob, job)
  118. if job.Spec.TTLSecondsAfterFinished == nil || updatedJob.Spec.TTLSecondsAfterFinished == nil {
  119. t.Errorf("existing TTLSecondsAfterFinished should be preserved")
  120. }
  121. // Existing TTLSecondsAfterFinished should be preserved when feature is off
  122. defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.TTLAfterFinished, false)()
  123. Strategy.PrepareForUpdate(ctx, updatedJob, job)
  124. if job.Spec.TTLSecondsAfterFinished == nil || updatedJob.Spec.TTLSecondsAfterFinished == nil {
  125. t.Errorf("existing TTLSecondsAfterFinished should be preserved")
  126. }
  127. // Make sure we correctly implement the interface.
  128. // Otherwise a typo could silently change the default.
  129. var gcds rest.GarbageCollectionDeleteStrategy = Strategy
  130. if got, want := gcds.DefaultGarbageCollectionPolicy(genericapirequest.NewContext()), rest.DeleteDependents; got != want {
  131. t.Errorf("DefaultGarbageCollectionPolicy() = %#v, want %#v", got, want)
  132. }
  133. var (
  134. v1Ctx = genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{APIGroup: "batch", APIVersion: "v1", Resource: "jobs"})
  135. otherVersionCtx = genericapirequest.WithRequestInfo(genericapirequest.NewContext(), &genericapirequest.RequestInfo{APIGroup: "batch", APIVersion: "v100", Resource: "jobs"})
  136. )
  137. if got, want := gcds.DefaultGarbageCollectionPolicy(v1Ctx), rest.OrphanDependents; got != want {
  138. t.Errorf("DefaultGarbageCollectionPolicy() = %#v, want %#v", got, want)
  139. }
  140. if got, want := gcds.DefaultGarbageCollectionPolicy(otherVersionCtx), rest.DeleteDependents; got != want {
  141. t.Errorf("DefaultGarbageCollectionPolicy() = %#v, want %#v", got, want)
  142. }
  143. }
  144. func TestJobStrategyWithGeneration(t *testing.T) {
  145. ctx := genericapirequest.NewDefaultContext()
  146. theUID := types.UID("1a2b3c4d5e6f7g8h9i0k")
  147. validPodTemplateSpec := api.PodTemplateSpec{
  148. Spec: api.PodSpec{
  149. RestartPolicy: api.RestartPolicyOnFailure,
  150. DNSPolicy: api.DNSClusterFirst,
  151. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: api.TerminationMessageReadFile}},
  152. },
  153. }
  154. job := &batch.Job{
  155. ObjectMeta: metav1.ObjectMeta{
  156. Name: "myjob2",
  157. Namespace: metav1.NamespaceDefault,
  158. UID: theUID,
  159. },
  160. Spec: batch.JobSpec{
  161. Selector: nil,
  162. Template: validPodTemplateSpec,
  163. },
  164. }
  165. Strategy.PrepareForCreate(ctx, job)
  166. errs := Strategy.Validate(ctx, job)
  167. if len(errs) != 0 {
  168. t.Errorf("Unexpected error validating %v", errs)
  169. }
  170. // Validate the stuff that validation should have validated.
  171. if job.Spec.Selector == nil {
  172. t.Errorf("Selector not generated")
  173. }
  174. expectedLabels := make(map[string]string)
  175. expectedLabels["controller-uid"] = string(theUID)
  176. if !reflect.DeepEqual(job.Spec.Selector.MatchLabels, expectedLabels) {
  177. t.Errorf("Expected label selector not generated")
  178. }
  179. if job.Spec.Template.ObjectMeta.Labels == nil {
  180. t.Errorf("Expected template labels not generated")
  181. }
  182. if v, ok := job.Spec.Template.ObjectMeta.Labels["job-name"]; !ok || v != "myjob2" {
  183. t.Errorf("Expected template labels not present")
  184. }
  185. if v, ok := job.Spec.Template.ObjectMeta.Labels["controller-uid"]; !ok || v != string(theUID) {
  186. t.Errorf("Expected template labels not present: ok: %v, v: %v", ok, v)
  187. }
  188. }
  189. func TestJobStatusStrategy(t *testing.T) {
  190. ctx := genericapirequest.NewDefaultContext()
  191. if !StatusStrategy.NamespaceScoped() {
  192. t.Errorf("Job must be namespace scoped")
  193. }
  194. if StatusStrategy.AllowCreateOnUpdate() {
  195. t.Errorf("Job should not allow create on update")
  196. }
  197. validSelector := &metav1.LabelSelector{
  198. MatchLabels: map[string]string{"a": "b"},
  199. }
  200. validPodTemplateSpec := api.PodTemplateSpec{
  201. ObjectMeta: metav1.ObjectMeta{
  202. Labels: validSelector.MatchLabels,
  203. },
  204. Spec: api.PodSpec{
  205. RestartPolicy: api.RestartPolicyOnFailure,
  206. DNSPolicy: api.DNSClusterFirst,
  207. Containers: []api.Container{{Name: "abc", Image: "image", ImagePullPolicy: "IfNotPresent", TerminationMessagePolicy: api.TerminationMessageReadFile}},
  208. },
  209. }
  210. oldParallelism := int32(10)
  211. newParallelism := int32(11)
  212. oldJob := &batch.Job{
  213. ObjectMeta: metav1.ObjectMeta{
  214. Name: "myjob",
  215. Namespace: metav1.NamespaceDefault,
  216. ResourceVersion: "10",
  217. },
  218. Spec: batch.JobSpec{
  219. Selector: validSelector,
  220. Template: validPodTemplateSpec,
  221. Parallelism: &oldParallelism,
  222. },
  223. Status: batch.JobStatus{
  224. Active: 11,
  225. },
  226. }
  227. newJob := &batch.Job{
  228. ObjectMeta: metav1.ObjectMeta{
  229. Name: "myjob",
  230. Namespace: metav1.NamespaceDefault,
  231. ResourceVersion: "9",
  232. },
  233. Spec: batch.JobSpec{
  234. Selector: validSelector,
  235. Template: validPodTemplateSpec,
  236. Parallelism: &newParallelism,
  237. },
  238. Status: batch.JobStatus{
  239. Active: 12,
  240. },
  241. }
  242. StatusStrategy.PrepareForUpdate(ctx, newJob, oldJob)
  243. if newJob.Status.Active != 12 {
  244. t.Errorf("Job status updates must allow changes to job status")
  245. }
  246. if *newJob.Spec.Parallelism != 10 {
  247. t.Errorf("Job status updates must now allow changes to job spec")
  248. }
  249. errs := StatusStrategy.ValidateUpdate(ctx, newJob, oldJob)
  250. if len(errs) != 0 {
  251. t.Errorf("Unexpected error %v", errs)
  252. }
  253. if newJob.ResourceVersion != "9" {
  254. t.Errorf("Incoming resource version on update should not be mutated")
  255. }
  256. }
  257. func TestSelectableFieldLabelConversions(t *testing.T) {
  258. apitesting.TestSelectableFieldLabelConversionsOfKind(t,
  259. "batch/v1",
  260. "Job",
  261. JobToSelectableFields(&batch.Job{}),
  262. nil,
  263. )
  264. }