cronjob.go 20 KB

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