cronjob.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /*
  2. Copyright 2016 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 apps
  14. import (
  15. "context"
  16. "fmt"
  17. "time"
  18. "github.com/onsi/ginkgo"
  19. "github.com/onsi/gomega"
  20. batchv1 "k8s.io/api/batch/v1"
  21. batchv1beta1 "k8s.io/api/batch/v1beta1"
  22. v1 "k8s.io/api/core/v1"
  23. apierrors "k8s.io/apimachinery/pkg/api/errors"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/util/wait"
  26. clientset "k8s.io/client-go/kubernetes"
  27. "k8s.io/client-go/kubernetes/scheme"
  28. batchinternal "k8s.io/kubernetes/pkg/apis/batch"
  29. "k8s.io/kubernetes/pkg/controller/job"
  30. "k8s.io/kubernetes/test/e2e/framework"
  31. e2ejob "k8s.io/kubernetes/test/e2e/framework/job"
  32. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  33. imageutils "k8s.io/kubernetes/test/utils/image"
  34. )
  35. const (
  36. // How long to wait for a cronjob
  37. cronJobTimeout = 5 * time.Minute
  38. )
  39. var _ = SIGDescribe("CronJob", func() {
  40. f := framework.NewDefaultFramework("cronjob")
  41. sleepCommand := []string{"sleep", "300"}
  42. // Pod will complete instantly
  43. successCommand := []string{"/bin/true"}
  44. failureCommand := []string{"/bin/false"}
  45. ginkgo.BeforeEach(func() {
  46. e2eskipper.SkipIfMissingResource(f.DynamicClient, CronJobGroupVersionResourceBeta, f.Namespace.Name)
  47. })
  48. // multiple jobs running at once
  49. ginkgo.It("should schedule multiple jobs concurrently", func() {
  50. ginkgo.By("Creating a cronjob")
  51. cronJob := newTestCronJob("concurrent", "*/1 * * * ?", batchv1beta1.AllowConcurrent,
  52. sleepCommand, nil, nil)
  53. cronJob, err := createCronJob(f.ClientSet, f.Namespace.Name, cronJob)
  54. framework.ExpectNoError(err, "Failed to create CronJob in namespace %s", f.Namespace.Name)
  55. ginkgo.By("Ensuring more than one job is running at a time")
  56. err = waitForActiveJobs(f.ClientSet, f.Namespace.Name, cronJob.Name, 2)
  57. framework.ExpectNoError(err, "Failed to wait for active jobs in CronJob %s in namespace %s", cronJob.Name, f.Namespace.Name)
  58. ginkgo.By("Ensuring at least two running jobs exists by listing jobs explicitly")
  59. jobs, err := f.ClientSet.BatchV1().Jobs(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{})
  60. framework.ExpectNoError(err, "Failed to list the CronJobs in namespace %s", f.Namespace.Name)
  61. activeJobs, _ := filterActiveJobs(jobs)
  62. gomega.Expect(len(activeJobs)).To(gomega.BeNumerically(">=", 2))
  63. ginkgo.By("Removing cronjob")
  64. err = deleteCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  65. framework.ExpectNoError(err, "Failed to delete CronJob %s in namespace %s", cronJob.Name, f.Namespace.Name)
  66. })
  67. // suspended should not schedule jobs
  68. ginkgo.It("should not schedule jobs when suspended [Slow]", func() {
  69. ginkgo.By("Creating a suspended cronjob")
  70. cronJob := newTestCronJob("suspended", "*/1 * * * ?", batchv1beta1.AllowConcurrent,
  71. sleepCommand, nil, nil)
  72. t := true
  73. cronJob.Spec.Suspend = &t
  74. cronJob, err := createCronJob(f.ClientSet, f.Namespace.Name, cronJob)
  75. framework.ExpectNoError(err, "Failed to create CronJob in namespace %s", f.Namespace.Name)
  76. ginkgo.By("Ensuring no jobs are scheduled")
  77. err = waitForNoJobs(f.ClientSet, f.Namespace.Name, cronJob.Name, false)
  78. framework.ExpectError(err)
  79. ginkgo.By("Ensuring no job exists by listing jobs explicitly")
  80. jobs, err := f.ClientSet.BatchV1().Jobs(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{})
  81. framework.ExpectNoError(err, "Failed to list the CronJobs in namespace %s", f.Namespace.Name)
  82. gomega.Expect(jobs.Items).To(gomega.HaveLen(0))
  83. ginkgo.By("Removing cronjob")
  84. err = deleteCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  85. framework.ExpectNoError(err, "Failed to delete CronJob %s in namespace %s", cronJob.Name, f.Namespace.Name)
  86. })
  87. // only single active job is allowed for ForbidConcurrent
  88. ginkgo.It("should not schedule new jobs when ForbidConcurrent [Slow]", func() {
  89. ginkgo.By("Creating a ForbidConcurrent cronjob")
  90. cronJob := newTestCronJob("forbid", "*/1 * * * ?", batchv1beta1.ForbidConcurrent,
  91. sleepCommand, nil, nil)
  92. cronJob, err := createCronJob(f.ClientSet, f.Namespace.Name, cronJob)
  93. framework.ExpectNoError(err, "Failed to create CronJob in namespace %s", f.Namespace.Name)
  94. ginkgo.By("Ensuring a job is scheduled")
  95. err = waitForActiveJobs(f.ClientSet, f.Namespace.Name, cronJob.Name, 1)
  96. framework.ExpectNoError(err, "Failed to schedule CronJob %s", cronJob.Name)
  97. ginkgo.By("Ensuring exactly one is scheduled")
  98. cronJob, err = getCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  99. framework.ExpectNoError(err, "Failed to get CronJob %s", cronJob.Name)
  100. gomega.Expect(cronJob.Status.Active).Should(gomega.HaveLen(1))
  101. ginkgo.By("Ensuring exactly one running job exists by listing jobs explicitly")
  102. jobs, err := f.ClientSet.BatchV1().Jobs(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{})
  103. framework.ExpectNoError(err, "Failed to list the CronJobs in namespace %s", f.Namespace.Name)
  104. activeJobs, _ := filterActiveJobs(jobs)
  105. gomega.Expect(activeJobs).To(gomega.HaveLen(1))
  106. ginkgo.By("Ensuring no more jobs are scheduled")
  107. err = waitForActiveJobs(f.ClientSet, f.Namespace.Name, cronJob.Name, 2)
  108. framework.ExpectError(err)
  109. ginkgo.By("Removing cronjob")
  110. err = deleteCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  111. framework.ExpectNoError(err, "Failed to delete CronJob %s in namespace %s", cronJob.Name, f.Namespace.Name)
  112. })
  113. // only single active job is allowed for ReplaceConcurrent
  114. ginkgo.It("should replace jobs when ReplaceConcurrent", func() {
  115. ginkgo.By("Creating a ReplaceConcurrent cronjob")
  116. cronJob := newTestCronJob("replace", "*/1 * * * ?", batchv1beta1.ReplaceConcurrent,
  117. sleepCommand, nil, nil)
  118. cronJob, err := createCronJob(f.ClientSet, f.Namespace.Name, cronJob)
  119. framework.ExpectNoError(err, "Failed to create CronJob in namespace %s", f.Namespace.Name)
  120. ginkgo.By("Ensuring a job is scheduled")
  121. err = waitForActiveJobs(f.ClientSet, f.Namespace.Name, cronJob.Name, 1)
  122. framework.ExpectNoError(err, "Failed to schedule CronJob %s in namespace %s", cronJob.Name, f.Namespace.Name)
  123. ginkgo.By("Ensuring exactly one is scheduled")
  124. cronJob, err = getCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  125. framework.ExpectNoError(err, "Failed to get CronJob %s", cronJob.Name)
  126. gomega.Expect(cronJob.Status.Active).Should(gomega.HaveLen(1))
  127. ginkgo.By("Ensuring exactly one running job exists by listing jobs explicitly")
  128. jobs, err := f.ClientSet.BatchV1().Jobs(f.Namespace.Name).List(context.TODO(), metav1.ListOptions{})
  129. framework.ExpectNoError(err, "Failed to list the jobs in namespace %s", f.Namespace.Name)
  130. activeJobs, _ := filterActiveJobs(jobs)
  131. gomega.Expect(activeJobs).To(gomega.HaveLen(1))
  132. ginkgo.By("Ensuring the job is replaced with a new one")
  133. err = waitForJobReplaced(f.ClientSet, f.Namespace.Name, jobs.Items[0].Name)
  134. framework.ExpectNoError(err, "Failed to replace CronJob %s in namespace %s", jobs.Items[0].Name, f.Namespace.Name)
  135. ginkgo.By("Removing cronjob")
  136. err = deleteCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  137. framework.ExpectNoError(err, "Failed to delete CronJob %s in namespace %s", cronJob.Name, f.Namespace.Name)
  138. })
  139. // shouldn't give us unexpected warnings
  140. ginkgo.It("should not emit unexpected warnings", func() {
  141. ginkgo.By("Creating a cronjob")
  142. cronJob := newTestCronJob("concurrent", "*/1 * * * ?", batchv1beta1.AllowConcurrent,
  143. nil, nil, nil)
  144. cronJob, err := createCronJob(f.ClientSet, f.Namespace.Name, cronJob)
  145. framework.ExpectNoError(err, "Failed to create CronJob in namespace %s", f.Namespace.Name)
  146. ginkgo.By("Ensuring at least two jobs and at least one finished job exists by listing jobs explicitly")
  147. err = waitForJobsAtLeast(f.ClientSet, f.Namespace.Name, 2)
  148. framework.ExpectNoError(err, "Failed to ensure at least two job exists in namespace %s", f.Namespace.Name)
  149. err = waitForAnyFinishedJob(f.ClientSet, f.Namespace.Name)
  150. framework.ExpectNoError(err, "Failed to ensure at least on finished job exists in namespace %s", f.Namespace.Name)
  151. ginkgo.By("Ensuring no unexpected event has happened")
  152. err = waitForEventWithReason(f.ClientSet, f.Namespace.Name, cronJob.Name, []string{"MissingJob", "UnexpectedJob"})
  153. framework.ExpectError(err)
  154. ginkgo.By("Removing cronjob")
  155. err = deleteCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  156. framework.ExpectNoError(err, "Failed to delete CronJob %s in namespace %s", cronJob.Name, f.Namespace.Name)
  157. })
  158. // deleted jobs should be removed from the active list
  159. ginkgo.It("should remove from active list jobs that have been deleted", func() {
  160. ginkgo.By("Creating a ForbidConcurrent cronjob")
  161. cronJob := newTestCronJob("forbid", "*/1 * * * ?", batchv1beta1.ForbidConcurrent,
  162. sleepCommand, nil, nil)
  163. cronJob, err := createCronJob(f.ClientSet, f.Namespace.Name, cronJob)
  164. framework.ExpectNoError(err, "Failed to create CronJob in namespace %s", f.Namespace.Name)
  165. ginkgo.By("Ensuring a job is scheduled")
  166. err = waitForActiveJobs(f.ClientSet, f.Namespace.Name, cronJob.Name, 1)
  167. framework.ExpectNoError(err, "Failed to ensure a %s cronjob is scheduled in namespace %s", cronJob.Name, f.Namespace.Name)
  168. ginkgo.By("Ensuring exactly one is scheduled")
  169. cronJob, err = getCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  170. framework.ExpectNoError(err, "Failed to ensure exactly one %s cronjob is scheduled in namespace %s", cronJob.Name, f.Namespace.Name)
  171. gomega.Expect(cronJob.Status.Active).Should(gomega.HaveLen(1))
  172. ginkgo.By("Deleting the job")
  173. job := cronJob.Status.Active[0]
  174. framework.ExpectNoError(framework.DeleteResourceAndWaitForGC(f.ClientSet, batchinternal.Kind("Job"), f.Namespace.Name, job.Name))
  175. ginkgo.By("Ensuring job was deleted")
  176. _, err = e2ejob.GetJob(f.ClientSet, f.Namespace.Name, job.Name)
  177. framework.ExpectError(err)
  178. framework.ExpectEqual(apierrors.IsNotFound(err), true)
  179. ginkgo.By("Ensuring the job is not in the cronjob active list")
  180. err = waitForJobNotActive(f.ClientSet, f.Namespace.Name, cronJob.Name, job.Name)
  181. framework.ExpectNoError(err, "Failed to ensure the %s cronjob is not in active list in namespace %s", cronJob.Name, f.Namespace.Name)
  182. ginkgo.By("Ensuring MissingJob event has occurred")
  183. err = waitForEventWithReason(f.ClientSet, f.Namespace.Name, cronJob.Name, []string{"MissingJob"})
  184. framework.ExpectNoError(err, "Failed to ensure missing job event has occurred for %s cronjob in namespace %s", cronJob.Name, f.Namespace.Name)
  185. ginkgo.By("Removing cronjob")
  186. err = deleteCronJob(f.ClientSet, f.Namespace.Name, cronJob.Name)
  187. framework.ExpectNoError(err, "Failed to remove %s cronjob in namespace %s", cronJob.Name, f.Namespace.Name)
  188. })
  189. // cleanup of successful finished jobs, with limit of one successful job
  190. ginkgo.It("should delete successful finished jobs with limit of one successful job", func() {
  191. ginkgo.By("Creating an AllowConcurrent cronjob with custom history limit")
  192. successLimit := int32(1)
  193. failedLimit := int32(0)
  194. cronJob := newTestCronJob("successful-jobs-history-limit", "*/1 * * * ?", batchv1beta1.AllowConcurrent,
  195. successCommand, &successLimit, &failedLimit)
  196. ensureHistoryLimits(f.ClientSet, f.Namespace.Name, cronJob)
  197. })
  198. // cleanup of failed finished jobs, with limit of one failed job
  199. ginkgo.It("should delete failed finished jobs with limit of one job", func() {
  200. ginkgo.By("Creating an AllowConcurrent cronjob with custom history limit")
  201. successLimit := int32(0)
  202. failedLimit := int32(1)
  203. cronJob := newTestCronJob("failed-jobs-history-limit", "*/1 * * * ?", batchv1beta1.AllowConcurrent,
  204. failureCommand, &successLimit, &failedLimit)
  205. ensureHistoryLimits(f.ClientSet, f.Namespace.Name, cronJob)
  206. })
  207. })
  208. func ensureHistoryLimits(c clientset.Interface, ns string, cronJob *batchv1beta1.CronJob) {
  209. cronJob, err := createCronJob(c, ns, cronJob)
  210. framework.ExpectNoError(err, "Failed to create allowconcurrent cronjob with custom history limits in namespace %s", ns)
  211. // Job is going to complete instantly: do not check for an active job
  212. // as we are most likely to miss it
  213. ginkgo.By("Ensuring a finished job exists")
  214. err = waitForAnyFinishedJob(c, ns)
  215. framework.ExpectNoError(err, "Failed to ensure a finished cronjob exists in namespace %s", ns)
  216. ginkgo.By("Ensuring a finished job exists by listing jobs explicitly")
  217. jobs, err := c.BatchV1().Jobs(ns).List(context.TODO(), metav1.ListOptions{})
  218. framework.ExpectNoError(err, "Failed to ensure a finished cronjob exists by listing jobs explicitly in namespace %s", ns)
  219. activeJobs, finishedJobs := filterActiveJobs(jobs)
  220. if len(finishedJobs) != 1 {
  221. framework.Logf("Expected one finished job in namespace %s; activeJobs=%v; finishedJobs=%v", ns, activeJobs, finishedJobs)
  222. framework.ExpectEqual(len(finishedJobs), 1)
  223. }
  224. // Job should get deleted when the next job finishes the next minute
  225. ginkgo.By("Ensuring this job and its pods does not exist anymore")
  226. err = waitForJobToDisappear(c, ns, finishedJobs[0])
  227. framework.ExpectNoError(err, "Failed to ensure that job does not exists anymore in namespace %s", ns)
  228. err = waitForJobsPodToDisappear(c, ns, finishedJobs[0])
  229. framework.ExpectNoError(err, "Failed to ensure that pods for job does not exists anymore in namespace %s", ns)
  230. ginkgo.By("Ensuring there is 1 finished job by listing jobs explicitly")
  231. jobs, err = c.BatchV1().Jobs(ns).List(context.TODO(), metav1.ListOptions{})
  232. framework.ExpectNoError(err, "Failed to ensure there is one finished job by listing job explicitly in namespace %s", ns)
  233. activeJobs, finishedJobs = filterActiveJobs(jobs)
  234. if len(finishedJobs) != 1 {
  235. framework.Logf("Expected one finished job in namespace %s; activeJobs=%v; finishedJobs=%v", ns, activeJobs, finishedJobs)
  236. framework.ExpectEqual(len(finishedJobs), 1)
  237. }
  238. ginkgo.By("Removing cronjob")
  239. err = deleteCronJob(c, ns, cronJob.Name)
  240. framework.ExpectNoError(err, "Failed to remove the %s cronjob in namespace %s", cronJob.Name, ns)
  241. }
  242. // newTestCronJob returns a cronjob which does one of several testing behaviors.
  243. func newTestCronJob(name, schedule string, concurrencyPolicy batchv1beta1.ConcurrencyPolicy,
  244. command []string, successfulJobsHistoryLimit *int32, failedJobsHistoryLimit *int32) *batchv1beta1.CronJob {
  245. parallelism := int32(1)
  246. completions := int32(1)
  247. backofflimit := int32(1)
  248. sj := &batchv1beta1.CronJob{
  249. ObjectMeta: metav1.ObjectMeta{
  250. Name: name,
  251. },
  252. TypeMeta: metav1.TypeMeta{
  253. Kind: "CronJob",
  254. },
  255. Spec: batchv1beta1.CronJobSpec{
  256. Schedule: schedule,
  257. ConcurrencyPolicy: concurrencyPolicy,
  258. JobTemplate: batchv1beta1.JobTemplateSpec{
  259. Spec: batchv1.JobSpec{
  260. Parallelism: &parallelism,
  261. Completions: &completions,
  262. BackoffLimit: &backofflimit,
  263. Template: v1.PodTemplateSpec{
  264. Spec: v1.PodSpec{
  265. RestartPolicy: v1.RestartPolicyOnFailure,
  266. Volumes: []v1.Volume{
  267. {
  268. Name: "data",
  269. VolumeSource: v1.VolumeSource{
  270. EmptyDir: &v1.EmptyDirVolumeSource{},
  271. },
  272. },
  273. },
  274. Containers: []v1.Container{
  275. {
  276. Name: "c",
  277. Image: imageutils.GetE2EImage(imageutils.BusyBox),
  278. VolumeMounts: []v1.VolumeMount{
  279. {
  280. MountPath: "/data",
  281. Name: "data",
  282. },
  283. },
  284. },
  285. },
  286. },
  287. },
  288. },
  289. },
  290. },
  291. }
  292. sj.Spec.SuccessfulJobsHistoryLimit = successfulJobsHistoryLimit
  293. sj.Spec.FailedJobsHistoryLimit = failedJobsHistoryLimit
  294. if command != nil {
  295. sj.Spec.JobTemplate.Spec.Template.Spec.Containers[0].Command = command
  296. }
  297. return sj
  298. }
  299. func createCronJob(c clientset.Interface, ns string, cronJob *batchv1beta1.CronJob) (*batchv1beta1.CronJob, error) {
  300. return c.BatchV1beta1().CronJobs(ns).Create(context.TODO(), cronJob, metav1.CreateOptions{})
  301. }
  302. func getCronJob(c clientset.Interface, ns, name string) (*batchv1beta1.CronJob, error) {
  303. return c.BatchV1beta1().CronJobs(ns).Get(context.TODO(), name, metav1.GetOptions{})
  304. }
  305. func deleteCronJob(c clientset.Interface, ns, name string) error {
  306. propagationPolicy := metav1.DeletePropagationBackground // Also delete jobs and pods related to cronjob
  307. return c.BatchV1beta1().CronJobs(ns).Delete(context.TODO(), name, &metav1.DeleteOptions{PropagationPolicy: &propagationPolicy})
  308. }
  309. // Wait for at least given amount of active jobs.
  310. func waitForActiveJobs(c clientset.Interface, ns, cronJobName string, active int) error {
  311. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  312. curr, err := getCronJob(c, ns, cronJobName)
  313. if err != nil {
  314. return false, err
  315. }
  316. return len(curr.Status.Active) >= active, nil
  317. })
  318. }
  319. // Wait for jobs to appear in the active list of a cronjob or not.
  320. // When failIfNonEmpty is set, this fails if the active set of jobs is still non-empty after
  321. // the timeout. When failIfNonEmpty is not set, this fails if the active set of jobs is still
  322. // empty after the timeout.
  323. func waitForNoJobs(c clientset.Interface, ns, jobName string, failIfNonEmpty bool) error {
  324. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  325. curr, err := getCronJob(c, ns, jobName)
  326. if err != nil {
  327. return false, err
  328. }
  329. if failIfNonEmpty {
  330. return len(curr.Status.Active) == 0, nil
  331. }
  332. return len(curr.Status.Active) != 0, nil
  333. })
  334. }
  335. // Wait till a given job actually goes away from the Active list for a given cronjob
  336. func waitForJobNotActive(c clientset.Interface, ns, cronJobName, jobName string) error {
  337. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  338. curr, err := getCronJob(c, ns, cronJobName)
  339. if err != nil {
  340. return false, err
  341. }
  342. for _, j := range curr.Status.Active {
  343. if j.Name == jobName {
  344. return false, nil
  345. }
  346. }
  347. return true, nil
  348. })
  349. }
  350. // Wait for a job to disappear by listing them explicitly.
  351. func waitForJobToDisappear(c clientset.Interface, ns string, targetJob *batchv1.Job) error {
  352. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  353. jobs, err := c.BatchV1().Jobs(ns).List(context.TODO(), metav1.ListOptions{})
  354. if err != nil {
  355. return false, err
  356. }
  357. _, finishedJobs := filterActiveJobs(jobs)
  358. for _, job := range finishedJobs {
  359. if targetJob.Namespace == job.Namespace && targetJob.Name == job.Name {
  360. return false, nil
  361. }
  362. }
  363. return true, nil
  364. })
  365. }
  366. // Wait for a pod to disappear by listing them explicitly.
  367. func waitForJobsPodToDisappear(c clientset.Interface, ns string, targetJob *batchv1.Job) error {
  368. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  369. options := metav1.ListOptions{LabelSelector: fmt.Sprintf("controller-uid=%s", targetJob.UID)}
  370. pods, err := c.CoreV1().Pods(ns).List(context.TODO(), options)
  371. if err != nil {
  372. return false, err
  373. }
  374. return len(pods.Items) == 0, nil
  375. })
  376. }
  377. // Wait for a job to be replaced with a new one.
  378. func waitForJobReplaced(c clientset.Interface, ns, previousJobName string) error {
  379. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  380. jobs, err := c.BatchV1().Jobs(ns).List(context.TODO(), metav1.ListOptions{})
  381. if err != nil {
  382. return false, err
  383. }
  384. // Ignore Jobs pending deletion, since deletion of Jobs is now asynchronous.
  385. aliveJobs := filterNotDeletedJobs(jobs)
  386. if len(aliveJobs) > 1 {
  387. return false, fmt.Errorf("More than one job is running %+v", jobs.Items)
  388. } else if len(aliveJobs) == 0 {
  389. framework.Logf("Warning: Found 0 jobs in namespace %v", ns)
  390. return false, nil
  391. }
  392. return aliveJobs[0].Name != previousJobName, nil
  393. })
  394. }
  395. // waitForJobsAtLeast waits for at least a number of jobs to appear.
  396. func waitForJobsAtLeast(c clientset.Interface, ns string, atLeast int) error {
  397. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  398. jobs, err := c.BatchV1().Jobs(ns).List(context.TODO(), metav1.ListOptions{})
  399. if err != nil {
  400. return false, err
  401. }
  402. return len(jobs.Items) >= atLeast, nil
  403. })
  404. }
  405. // waitForAnyFinishedJob waits for any completed job to appear.
  406. func waitForAnyFinishedJob(c clientset.Interface, ns string) error {
  407. return wait.Poll(framework.Poll, cronJobTimeout, func() (bool, error) {
  408. jobs, err := c.BatchV1().Jobs(ns).List(context.TODO(), metav1.ListOptions{})
  409. if err != nil {
  410. return false, err
  411. }
  412. for i := range jobs.Items {
  413. if job.IsJobFinished(&jobs.Items[i]) {
  414. return true, nil
  415. }
  416. }
  417. return false, nil
  418. })
  419. }
  420. // waitForEventWithReason waits for events with a reason within a list has occurred
  421. func waitForEventWithReason(c clientset.Interface, ns, cronJobName string, reasons []string) error {
  422. return wait.Poll(framework.Poll, 30*time.Second, func() (bool, error) {
  423. sj, err := getCronJob(c, ns, cronJobName)
  424. if err != nil {
  425. return false, err
  426. }
  427. events, err := c.CoreV1().Events(ns).Search(scheme.Scheme, sj)
  428. if err != nil {
  429. return false, err
  430. }
  431. for _, e := range events.Items {
  432. for _, reason := range reasons {
  433. if e.Reason == reason {
  434. return true, nil
  435. }
  436. }
  437. }
  438. return false, nil
  439. })
  440. }
  441. // filterNotDeletedJobs returns the job list without any jobs that are pending
  442. // deletion.
  443. func filterNotDeletedJobs(jobs *batchv1.JobList) []*batchv1.Job {
  444. var alive []*batchv1.Job
  445. for i := range jobs.Items {
  446. job := &jobs.Items[i]
  447. if job.DeletionTimestamp == nil {
  448. alive = append(alive, job)
  449. }
  450. }
  451. return alive
  452. }
  453. func filterActiveJobs(jobs *batchv1.JobList) (active []*batchv1.Job, finished []*batchv1.Job) {
  454. for i := range jobs.Items {
  455. j := jobs.Items[i]
  456. if !job.IsJobFinished(&j) {
  457. active = append(active, &j)
  458. } else {
  459. finished = append(finished, &j)
  460. }
  461. }
  462. return
  463. }