job_controller.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  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. "math"
  18. "reflect"
  19. "sort"
  20. "sync"
  21. "time"
  22. batch "k8s.io/api/batch/v1"
  23. "k8s.io/api/core/v1"
  24. "k8s.io/apimachinery/pkg/api/errors"
  25. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  26. "k8s.io/apimachinery/pkg/labels"
  27. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  28. "k8s.io/apimachinery/pkg/util/wait"
  29. batchinformers "k8s.io/client-go/informers/batch/v1"
  30. coreinformers "k8s.io/client-go/informers/core/v1"
  31. clientset "k8s.io/client-go/kubernetes"
  32. "k8s.io/client-go/kubernetes/scheme"
  33. v1core "k8s.io/client-go/kubernetes/typed/core/v1"
  34. batchv1listers "k8s.io/client-go/listers/batch/v1"
  35. corelisters "k8s.io/client-go/listers/core/v1"
  36. "k8s.io/client-go/tools/cache"
  37. "k8s.io/client-go/tools/record"
  38. "k8s.io/client-go/util/workqueue"
  39. "k8s.io/component-base/metrics/prometheus/ratelimiter"
  40. "k8s.io/kubernetes/pkg/controller"
  41. "k8s.io/utils/integer"
  42. "k8s.io/klog"
  43. )
  44. const statusUpdateRetries = 3
  45. // controllerKind contains the schema.GroupVersionKind for this controller type.
  46. var controllerKind = batch.SchemeGroupVersion.WithKind("Job")
  47. var (
  48. // DefaultJobBackOff is the max backoff period, exported for the e2e test
  49. DefaultJobBackOff = 10 * time.Second
  50. // MaxJobBackOff is the max backoff period, exported for the e2e test
  51. MaxJobBackOff = 360 * time.Second
  52. )
  53. type JobController struct {
  54. kubeClient clientset.Interface
  55. podControl controller.PodControlInterface
  56. // To allow injection of updateJobStatus for testing.
  57. updateHandler func(job *batch.Job) error
  58. syncHandler func(jobKey string) (bool, error)
  59. // podStoreSynced returns true if the pod store has been synced at least once.
  60. // Added as a member to the struct to allow injection for testing.
  61. podStoreSynced cache.InformerSynced
  62. // jobStoreSynced returns true if the job store has been synced at least once.
  63. // Added as a member to the struct to allow injection for testing.
  64. jobStoreSynced cache.InformerSynced
  65. // A TTLCache of pod creates/deletes each rc expects to see
  66. expectations controller.ControllerExpectationsInterface
  67. // A store of jobs
  68. jobLister batchv1listers.JobLister
  69. // A store of pods, populated by the podController
  70. podStore corelisters.PodLister
  71. // Jobs that need to be updated
  72. queue workqueue.RateLimitingInterface
  73. recorder record.EventRecorder
  74. }
  75. func NewJobController(podInformer coreinformers.PodInformer, jobInformer batchinformers.JobInformer, kubeClient clientset.Interface) *JobController {
  76. eventBroadcaster := record.NewBroadcaster()
  77. eventBroadcaster.StartLogging(klog.Infof)
  78. eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.CoreV1().Events("")})
  79. if kubeClient != nil && kubeClient.CoreV1().RESTClient().GetRateLimiter() != nil {
  80. ratelimiter.RegisterMetricAndTrackRateLimiterUsage("job_controller", kubeClient.CoreV1().RESTClient().GetRateLimiter())
  81. }
  82. jm := &JobController{
  83. kubeClient: kubeClient,
  84. podControl: controller.RealPodControl{
  85. KubeClient: kubeClient,
  86. Recorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "job-controller"}),
  87. },
  88. expectations: controller.NewControllerExpectations(),
  89. queue: workqueue.NewNamedRateLimitingQueue(workqueue.NewItemExponentialFailureRateLimiter(DefaultJobBackOff, MaxJobBackOff), "job"),
  90. recorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "job-controller"}),
  91. }
  92. jobInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
  93. AddFunc: func(obj interface{}) {
  94. jm.enqueueController(obj, true)
  95. },
  96. UpdateFunc: jm.updateJob,
  97. DeleteFunc: func(obj interface{}) {
  98. jm.enqueueController(obj, true)
  99. },
  100. })
  101. jm.jobLister = jobInformer.Lister()
  102. jm.jobStoreSynced = jobInformer.Informer().HasSynced
  103. podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
  104. AddFunc: jm.addPod,
  105. UpdateFunc: jm.updatePod,
  106. DeleteFunc: jm.deletePod,
  107. })
  108. jm.podStore = podInformer.Lister()
  109. jm.podStoreSynced = podInformer.Informer().HasSynced
  110. jm.updateHandler = jm.updateJobStatus
  111. jm.syncHandler = jm.syncJob
  112. return jm
  113. }
  114. // Run the main goroutine responsible for watching and syncing jobs.
  115. func (jm *JobController) Run(workers int, stopCh <-chan struct{}) {
  116. defer utilruntime.HandleCrash()
  117. defer jm.queue.ShutDown()
  118. klog.Infof("Starting job controller")
  119. defer klog.Infof("Shutting down job controller")
  120. if !cache.WaitForNamedCacheSync("job", stopCh, jm.podStoreSynced, jm.jobStoreSynced) {
  121. return
  122. }
  123. for i := 0; i < workers; i++ {
  124. go wait.Until(jm.worker, time.Second, stopCh)
  125. }
  126. <-stopCh
  127. }
  128. // getPodJobs returns a list of Jobs that potentially match a Pod.
  129. func (jm *JobController) getPodJobs(pod *v1.Pod) []*batch.Job {
  130. jobs, err := jm.jobLister.GetPodJobs(pod)
  131. if err != nil {
  132. return nil
  133. }
  134. if len(jobs) > 1 {
  135. // ControllerRef will ensure we don't do anything crazy, but more than one
  136. // item in this list nevertheless constitutes user error.
  137. utilruntime.HandleError(fmt.Errorf("user error! more than one job is selecting pods with labels: %+v", pod.Labels))
  138. }
  139. ret := make([]*batch.Job, 0, len(jobs))
  140. for i := range jobs {
  141. ret = append(ret, &jobs[i])
  142. }
  143. return ret
  144. }
  145. // resolveControllerRef returns the controller referenced by a ControllerRef,
  146. // or nil if the ControllerRef could not be resolved to a matching controller
  147. // of the correct Kind.
  148. func (jm *JobController) resolveControllerRef(namespace string, controllerRef *metav1.OwnerReference) *batch.Job {
  149. // We can't look up by UID, so look up by Name and then verify UID.
  150. // Don't even try to look up by Name if it's the wrong Kind.
  151. if controllerRef.Kind != controllerKind.Kind {
  152. return nil
  153. }
  154. job, err := jm.jobLister.Jobs(namespace).Get(controllerRef.Name)
  155. if err != nil {
  156. return nil
  157. }
  158. if job.UID != controllerRef.UID {
  159. // The controller we found with this Name is not the same one that the
  160. // ControllerRef points to.
  161. return nil
  162. }
  163. return job
  164. }
  165. // When a pod is created, enqueue the controller that manages it and update it's expectations.
  166. func (jm *JobController) addPod(obj interface{}) {
  167. pod := obj.(*v1.Pod)
  168. if pod.DeletionTimestamp != nil {
  169. // on a restart of the controller controller, it's possible a new pod shows up in a state that
  170. // is already pending deletion. Prevent the pod from being a creation observation.
  171. jm.deletePod(pod)
  172. return
  173. }
  174. // If it has a ControllerRef, that's all that matters.
  175. if controllerRef := metav1.GetControllerOf(pod); controllerRef != nil {
  176. job := jm.resolveControllerRef(pod.Namespace, controllerRef)
  177. if job == nil {
  178. return
  179. }
  180. jobKey, err := controller.KeyFunc(job)
  181. if err != nil {
  182. return
  183. }
  184. jm.expectations.CreationObserved(jobKey)
  185. jm.enqueueController(job, true)
  186. return
  187. }
  188. // Otherwise, it's an orphan. Get a list of all matching controllers and sync
  189. // them to see if anyone wants to adopt it.
  190. // DO NOT observe creation because no controller should be waiting for an
  191. // orphan.
  192. for _, job := range jm.getPodJobs(pod) {
  193. jm.enqueueController(job, true)
  194. }
  195. }
  196. // When a pod is updated, figure out what job/s manage it and wake them up.
  197. // If the labels of the pod have changed we need to awaken both the old
  198. // and new job. old and cur must be *v1.Pod types.
  199. func (jm *JobController) updatePod(old, cur interface{}) {
  200. curPod := cur.(*v1.Pod)
  201. oldPod := old.(*v1.Pod)
  202. if curPod.ResourceVersion == oldPod.ResourceVersion {
  203. // Periodic resync will send update events for all known pods.
  204. // Two different versions of the same pod will always have different RVs.
  205. return
  206. }
  207. if curPod.DeletionTimestamp != nil {
  208. // when a pod is deleted gracefully it's deletion timestamp is first modified to reflect a grace period,
  209. // and after such time has passed, the kubelet actually deletes it from the store. We receive an update
  210. // for modification of the deletion timestamp and expect an job to create more pods asap, not wait
  211. // until the kubelet actually deletes the pod.
  212. jm.deletePod(curPod)
  213. return
  214. }
  215. // the only time we want the backoff to kick-in, is when the pod failed
  216. immediate := curPod.Status.Phase != v1.PodFailed
  217. curControllerRef := metav1.GetControllerOf(curPod)
  218. oldControllerRef := metav1.GetControllerOf(oldPod)
  219. controllerRefChanged := !reflect.DeepEqual(curControllerRef, oldControllerRef)
  220. if controllerRefChanged && oldControllerRef != nil {
  221. // The ControllerRef was changed. Sync the old controller, if any.
  222. if job := jm.resolveControllerRef(oldPod.Namespace, oldControllerRef); job != nil {
  223. jm.enqueueController(job, immediate)
  224. }
  225. }
  226. // If it has a ControllerRef, that's all that matters.
  227. if curControllerRef != nil {
  228. job := jm.resolveControllerRef(curPod.Namespace, curControllerRef)
  229. if job == nil {
  230. return
  231. }
  232. jm.enqueueController(job, immediate)
  233. return
  234. }
  235. // Otherwise, it's an orphan. If anything changed, sync matching controllers
  236. // to see if anyone wants to adopt it now.
  237. labelChanged := !reflect.DeepEqual(curPod.Labels, oldPod.Labels)
  238. if labelChanged || controllerRefChanged {
  239. for _, job := range jm.getPodJobs(curPod) {
  240. jm.enqueueController(job, immediate)
  241. }
  242. }
  243. }
  244. // When a pod is deleted, enqueue the job that manages the pod and update its expectations.
  245. // obj could be an *v1.Pod, or a DeletionFinalStateUnknown marker item.
  246. func (jm *JobController) deletePod(obj interface{}) {
  247. pod, ok := obj.(*v1.Pod)
  248. // When a delete is dropped, the relist will notice a pod in the store not
  249. // in the list, leading to the insertion of a tombstone object which contains
  250. // the deleted key/value. Note that this value might be stale. If the pod
  251. // changed labels the new job will not be woken up till the periodic resync.
  252. if !ok {
  253. tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
  254. if !ok {
  255. utilruntime.HandleError(fmt.Errorf("couldn't get object from tombstone %+v", obj))
  256. return
  257. }
  258. pod, ok = tombstone.Obj.(*v1.Pod)
  259. if !ok {
  260. utilruntime.HandleError(fmt.Errorf("tombstone contained object that is not a pod %+v", obj))
  261. return
  262. }
  263. }
  264. controllerRef := metav1.GetControllerOf(pod)
  265. if controllerRef == nil {
  266. // No controller should care about orphans being deleted.
  267. return
  268. }
  269. job := jm.resolveControllerRef(pod.Namespace, controllerRef)
  270. if job == nil {
  271. return
  272. }
  273. jobKey, err := controller.KeyFunc(job)
  274. if err != nil {
  275. return
  276. }
  277. jm.expectations.DeletionObserved(jobKey)
  278. jm.enqueueController(job, true)
  279. }
  280. func (jm *JobController) updateJob(old, cur interface{}) {
  281. oldJob := old.(*batch.Job)
  282. curJob := cur.(*batch.Job)
  283. // never return error
  284. key, err := controller.KeyFunc(curJob)
  285. if err != nil {
  286. return
  287. }
  288. jm.enqueueController(curJob, true)
  289. // check if need to add a new rsync for ActiveDeadlineSeconds
  290. if curJob.Status.StartTime != nil {
  291. curADS := curJob.Spec.ActiveDeadlineSeconds
  292. if curADS == nil {
  293. return
  294. }
  295. oldADS := oldJob.Spec.ActiveDeadlineSeconds
  296. if oldADS == nil || *oldADS != *curADS {
  297. now := metav1.Now()
  298. start := curJob.Status.StartTime.Time
  299. passed := now.Time.Sub(start)
  300. total := time.Duration(*curADS) * time.Second
  301. // AddAfter will handle total < passed
  302. jm.queue.AddAfter(key, total-passed)
  303. klog.V(4).Infof("job ActiveDeadlineSeconds updated, will rsync after %d seconds", total-passed)
  304. }
  305. }
  306. }
  307. // obj could be an *batch.Job, or a DeletionFinalStateUnknown marker item,
  308. // immediate tells the controller to update the status right away, and should
  309. // happen ONLY when there was a successful pod run.
  310. func (jm *JobController) enqueueController(obj interface{}, immediate bool) {
  311. key, err := controller.KeyFunc(obj)
  312. if err != nil {
  313. utilruntime.HandleError(fmt.Errorf("Couldn't get key for object %+v: %v", obj, err))
  314. return
  315. }
  316. backoff := time.Duration(0)
  317. if !immediate {
  318. backoff = getBackoff(jm.queue, key)
  319. }
  320. // TODO: Handle overlapping controllers better. Either disallow them at admission time or
  321. // deterministically avoid syncing controllers that fight over pods. Currently, we only
  322. // ensure that the same controller is synced for a given pod. When we periodically relist
  323. // all controllers there will still be some replica instability. One way to handle this is
  324. // by querying the store for all controllers that this rc overlaps, as well as all
  325. // controllers that overlap this rc, and sorting them.
  326. jm.queue.AddAfter(key, backoff)
  327. }
  328. // worker runs a worker thread that just dequeues items, processes them, and marks them done.
  329. // It enforces that the syncHandler is never invoked concurrently with the same key.
  330. func (jm *JobController) worker() {
  331. for jm.processNextWorkItem() {
  332. }
  333. }
  334. func (jm *JobController) processNextWorkItem() bool {
  335. key, quit := jm.queue.Get()
  336. if quit {
  337. return false
  338. }
  339. defer jm.queue.Done(key)
  340. forget, err := jm.syncHandler(key.(string))
  341. if err == nil {
  342. if forget {
  343. jm.queue.Forget(key)
  344. }
  345. return true
  346. }
  347. utilruntime.HandleError(fmt.Errorf("Error syncing job: %v", err))
  348. jm.queue.AddRateLimited(key)
  349. return true
  350. }
  351. // getPodsForJob returns the set of pods that this Job should manage.
  352. // It also reconciles ControllerRef by adopting/orphaning.
  353. // Note that the returned Pods are pointers into the cache.
  354. func (jm *JobController) getPodsForJob(j *batch.Job) ([]*v1.Pod, error) {
  355. selector, err := metav1.LabelSelectorAsSelector(j.Spec.Selector)
  356. if err != nil {
  357. return nil, fmt.Errorf("couldn't convert Job selector: %v", err)
  358. }
  359. // List all pods to include those that don't match the selector anymore
  360. // but have a ControllerRef pointing to this controller.
  361. pods, err := jm.podStore.Pods(j.Namespace).List(labels.Everything())
  362. if err != nil {
  363. return nil, err
  364. }
  365. // If any adoptions are attempted, we should first recheck for deletion
  366. // with an uncached quorum read sometime after listing Pods (see #42639).
  367. canAdoptFunc := controller.RecheckDeletionTimestamp(func() (metav1.Object, error) {
  368. fresh, err := jm.kubeClient.BatchV1().Jobs(j.Namespace).Get(context.TODO(), j.Name, metav1.GetOptions{})
  369. if err != nil {
  370. return nil, err
  371. }
  372. if fresh.UID != j.UID {
  373. return nil, fmt.Errorf("original Job %v/%v is gone: got uid %v, wanted %v", j.Namespace, j.Name, fresh.UID, j.UID)
  374. }
  375. return fresh, nil
  376. })
  377. cm := controller.NewPodControllerRefManager(jm.podControl, j, selector, controllerKind, canAdoptFunc)
  378. return cm.ClaimPods(pods)
  379. }
  380. // syncJob will sync the job with the given key if it has had its expectations fulfilled, meaning
  381. // it did not expect to see any more of its pods created or deleted. This function is not meant to be invoked
  382. // concurrently with the same key.
  383. func (jm *JobController) syncJob(key string) (bool, error) {
  384. startTime := time.Now()
  385. defer func() {
  386. klog.V(4).Infof("Finished syncing job %q (%v)", key, time.Since(startTime))
  387. }()
  388. ns, name, err := cache.SplitMetaNamespaceKey(key)
  389. if err != nil {
  390. return false, err
  391. }
  392. if len(ns) == 0 || len(name) == 0 {
  393. return false, fmt.Errorf("invalid job key %q: either namespace or name is missing", key)
  394. }
  395. sharedJob, err := jm.jobLister.Jobs(ns).Get(name)
  396. if err != nil {
  397. if errors.IsNotFound(err) {
  398. klog.V(4).Infof("Job has been deleted: %v", key)
  399. jm.expectations.DeleteExpectations(key)
  400. return true, nil
  401. }
  402. return false, err
  403. }
  404. job := *sharedJob
  405. // if job was finished previously, we don't want to redo the termination
  406. if IsJobFinished(&job) {
  407. return true, nil
  408. }
  409. // retrieve the previous number of retry
  410. previousRetry := jm.queue.NumRequeues(key)
  411. // Check the expectations of the job before counting active pods, otherwise a new pod can sneak in
  412. // and update the expectations after we've retrieved active pods from the store. If a new pod enters
  413. // the store after we've checked the expectation, the job sync is just deferred till the next relist.
  414. jobNeedsSync := jm.expectations.SatisfiedExpectations(key)
  415. pods, err := jm.getPodsForJob(&job)
  416. if err != nil {
  417. return false, err
  418. }
  419. activePods := controller.FilterActivePods(pods)
  420. active := int32(len(activePods))
  421. succeeded, failed := getStatus(pods)
  422. conditions := len(job.Status.Conditions)
  423. // job first start
  424. if job.Status.StartTime == nil {
  425. now := metav1.Now()
  426. job.Status.StartTime = &now
  427. // enqueue a sync to check if job past ActiveDeadlineSeconds
  428. if job.Spec.ActiveDeadlineSeconds != nil {
  429. klog.V(4).Infof("Job %s has ActiveDeadlineSeconds will sync after %d seconds",
  430. key, *job.Spec.ActiveDeadlineSeconds)
  431. jm.queue.AddAfter(key, time.Duration(*job.Spec.ActiveDeadlineSeconds)*time.Second)
  432. }
  433. }
  434. var manageJobErr error
  435. jobFailed := false
  436. var failureReason string
  437. var failureMessage string
  438. jobHaveNewFailure := failed > job.Status.Failed
  439. // new failures happen when status does not reflect the failures and active
  440. // is different than parallelism, otherwise the previous controller loop
  441. // failed updating status so even if we pick up failure it is not a new one
  442. exceedsBackoffLimit := jobHaveNewFailure && (active != *job.Spec.Parallelism) &&
  443. (int32(previousRetry)+1 > *job.Spec.BackoffLimit)
  444. if exceedsBackoffLimit || pastBackoffLimitOnFailure(&job, pods) {
  445. // check if the number of pod restart exceeds backoff (for restart OnFailure only)
  446. // OR if the number of failed jobs increased since the last syncJob
  447. jobFailed = true
  448. failureReason = "BackoffLimitExceeded"
  449. failureMessage = "Job has reached the specified backoff limit"
  450. } else if pastActiveDeadline(&job) {
  451. jobFailed = true
  452. failureReason = "DeadlineExceeded"
  453. failureMessage = "Job was active longer than specified deadline"
  454. }
  455. if jobFailed {
  456. errCh := make(chan error, active)
  457. jm.deleteJobPods(&job, activePods, errCh)
  458. select {
  459. case manageJobErr = <-errCh:
  460. if manageJobErr != nil {
  461. break
  462. }
  463. default:
  464. }
  465. // update status values accordingly
  466. failed += active
  467. active = 0
  468. job.Status.Conditions = append(job.Status.Conditions, newCondition(batch.JobFailed, failureReason, failureMessage))
  469. jm.recorder.Event(&job, v1.EventTypeWarning, failureReason, failureMessage)
  470. } else {
  471. if jobNeedsSync && job.DeletionTimestamp == nil {
  472. active, manageJobErr = jm.manageJob(activePods, succeeded, &job)
  473. }
  474. completions := succeeded
  475. complete := false
  476. if job.Spec.Completions == nil {
  477. // This type of job is complete when any pod exits with success.
  478. // Each pod is capable of
  479. // determining whether or not the entire Job is done. Subsequent pods are
  480. // not expected to fail, but if they do, the failure is ignored. Once any
  481. // pod succeeds, the controller waits for remaining pods to finish, and
  482. // then the job is complete.
  483. if succeeded > 0 && active == 0 {
  484. complete = true
  485. }
  486. } else {
  487. // Job specifies a number of completions. This type of job signals
  488. // success by having that number of successes. Since we do not
  489. // start more pods than there are remaining completions, there should
  490. // not be any remaining active pods once this count is reached.
  491. if completions >= *job.Spec.Completions {
  492. complete = true
  493. if active > 0 {
  494. jm.recorder.Event(&job, v1.EventTypeWarning, "TooManyActivePods", "Too many active pods running after completion count reached")
  495. }
  496. if completions > *job.Spec.Completions {
  497. jm.recorder.Event(&job, v1.EventTypeWarning, "TooManySucceededPods", "Too many succeeded pods running after completion count reached")
  498. }
  499. }
  500. }
  501. if complete {
  502. job.Status.Conditions = append(job.Status.Conditions, newCondition(batch.JobComplete, "", ""))
  503. now := metav1.Now()
  504. job.Status.CompletionTime = &now
  505. jm.recorder.Event(&job, v1.EventTypeNormal, "Completed", "Job completed")
  506. }
  507. }
  508. forget := false
  509. // Check if the number of jobs succeeded increased since the last check. If yes "forget" should be true
  510. // This logic is linked to the issue: https://github.com/kubernetes/kubernetes/issues/56853 that aims to
  511. // improve the Job backoff policy when parallelism > 1 and few Jobs failed but others succeed.
  512. // In this case, we should clear the backoff delay.
  513. if job.Status.Succeeded < succeeded {
  514. forget = true
  515. }
  516. // no need to update the job if the status hasn't changed since last time
  517. if job.Status.Active != active || job.Status.Succeeded != succeeded || job.Status.Failed != failed || len(job.Status.Conditions) != conditions {
  518. job.Status.Active = active
  519. job.Status.Succeeded = succeeded
  520. job.Status.Failed = failed
  521. if err := jm.updateHandler(&job); err != nil {
  522. return forget, err
  523. }
  524. if jobHaveNewFailure && !IsJobFinished(&job) {
  525. // returning an error will re-enqueue Job after the backoff period
  526. return forget, fmt.Errorf("failed pod(s) detected for job key %q", key)
  527. }
  528. forget = true
  529. }
  530. return forget, manageJobErr
  531. }
  532. func (jm *JobController) deleteJobPods(job *batch.Job, pods []*v1.Pod, errCh chan<- error) {
  533. // TODO: below code should be replaced with pod termination resulting in
  534. // pod failures, rather than killing pods. Unfortunately none such solution
  535. // exists ATM. There's an open discussion in the topic in
  536. // https://github.com/kubernetes/kubernetes/issues/14602 which might give
  537. // some sort of solution to above problem.
  538. // kill remaining active pods
  539. wait := sync.WaitGroup{}
  540. nbPods := len(pods)
  541. wait.Add(nbPods)
  542. for i := int32(0); i < int32(nbPods); i++ {
  543. go func(ix int32) {
  544. defer wait.Done()
  545. if err := jm.podControl.DeletePod(job.Namespace, pods[ix].Name, job); err != nil {
  546. defer utilruntime.HandleError(err)
  547. klog.V(2).Infof("Failed to delete %v, job %q/%q deadline exceeded", pods[ix].Name, job.Namespace, job.Name)
  548. errCh <- err
  549. }
  550. }(i)
  551. }
  552. wait.Wait()
  553. }
  554. // pastBackoffLimitOnFailure checks if container restartCounts sum exceeds BackoffLimit
  555. // this method applies only to pods with restartPolicy == OnFailure
  556. func pastBackoffLimitOnFailure(job *batch.Job, pods []*v1.Pod) bool {
  557. if job.Spec.Template.Spec.RestartPolicy != v1.RestartPolicyOnFailure {
  558. return false
  559. }
  560. result := int32(0)
  561. for i := range pods {
  562. po := pods[i]
  563. if po.Status.Phase == v1.PodRunning || po.Status.Phase == v1.PodPending {
  564. for j := range po.Status.InitContainerStatuses {
  565. stat := po.Status.InitContainerStatuses[j]
  566. result += stat.RestartCount
  567. }
  568. for j := range po.Status.ContainerStatuses {
  569. stat := po.Status.ContainerStatuses[j]
  570. result += stat.RestartCount
  571. }
  572. }
  573. }
  574. if *job.Spec.BackoffLimit == 0 {
  575. return result > 0
  576. }
  577. return result >= *job.Spec.BackoffLimit
  578. }
  579. // pastActiveDeadline checks if job has ActiveDeadlineSeconds field set and if it is exceeded.
  580. func pastActiveDeadline(job *batch.Job) bool {
  581. if job.Spec.ActiveDeadlineSeconds == nil || job.Status.StartTime == nil {
  582. return false
  583. }
  584. now := metav1.Now()
  585. start := job.Status.StartTime.Time
  586. duration := now.Time.Sub(start)
  587. allowedDuration := time.Duration(*job.Spec.ActiveDeadlineSeconds) * time.Second
  588. return duration >= allowedDuration
  589. }
  590. func newCondition(conditionType batch.JobConditionType, reason, message string) batch.JobCondition {
  591. return batch.JobCondition{
  592. Type: conditionType,
  593. Status: v1.ConditionTrue,
  594. LastProbeTime: metav1.Now(),
  595. LastTransitionTime: metav1.Now(),
  596. Reason: reason,
  597. Message: message,
  598. }
  599. }
  600. // getStatus returns no of succeeded and failed pods running a job
  601. func getStatus(pods []*v1.Pod) (succeeded, failed int32) {
  602. succeeded = int32(filterPods(pods, v1.PodSucceeded))
  603. failed = int32(filterPods(pods, v1.PodFailed))
  604. return
  605. }
  606. // manageJob is the core method responsible for managing the number of running
  607. // pods according to what is specified in the job.Spec.
  608. // Does NOT modify <activePods>.
  609. func (jm *JobController) manageJob(activePods []*v1.Pod, succeeded int32, job *batch.Job) (int32, error) {
  610. var activeLock sync.Mutex
  611. active := int32(len(activePods))
  612. parallelism := *job.Spec.Parallelism
  613. jobKey, err := controller.KeyFunc(job)
  614. if err != nil {
  615. utilruntime.HandleError(fmt.Errorf("Couldn't get key for job %#v: %v", job, err))
  616. return 0, nil
  617. }
  618. var errCh chan error
  619. if active > parallelism {
  620. diff := active - parallelism
  621. errCh = make(chan error, diff)
  622. jm.expectations.ExpectDeletions(jobKey, int(diff))
  623. klog.V(4).Infof("Too many pods running job %q, need %d, deleting %d", jobKey, parallelism, diff)
  624. // Sort the pods in the order such that not-ready < ready, unscheduled
  625. // < scheduled, and pending < running. This ensures that we delete pods
  626. // in the earlier stages whenever possible.
  627. sort.Sort(controller.ActivePods(activePods))
  628. active -= diff
  629. wait := sync.WaitGroup{}
  630. wait.Add(int(diff))
  631. for i := int32(0); i < diff; i++ {
  632. go func(ix int32) {
  633. defer wait.Done()
  634. if err := jm.podControl.DeletePod(job.Namespace, activePods[ix].Name, job); err != nil {
  635. defer utilruntime.HandleError(err)
  636. // Decrement the expected number of deletes because the informer won't observe this deletion
  637. klog.V(2).Infof("Failed to delete %v, decrementing expectations for job %q/%q", activePods[ix].Name, job.Namespace, job.Name)
  638. jm.expectations.DeletionObserved(jobKey)
  639. activeLock.Lock()
  640. active++
  641. activeLock.Unlock()
  642. errCh <- err
  643. }
  644. }(i)
  645. }
  646. wait.Wait()
  647. } else if active < parallelism {
  648. wantActive := int32(0)
  649. if job.Spec.Completions == nil {
  650. // Job does not specify a number of completions. Therefore, number active
  651. // should be equal to parallelism, unless the job has seen at least
  652. // once success, in which leave whatever is running, running.
  653. if succeeded > 0 {
  654. wantActive = active
  655. } else {
  656. wantActive = parallelism
  657. }
  658. } else {
  659. // Job specifies a specific number of completions. Therefore, number
  660. // active should not ever exceed number of remaining completions.
  661. wantActive = *job.Spec.Completions - succeeded
  662. if wantActive > parallelism {
  663. wantActive = parallelism
  664. }
  665. }
  666. diff := wantActive - active
  667. if diff < 0 {
  668. utilruntime.HandleError(fmt.Errorf("More active than wanted: job %q, want %d, have %d", jobKey, wantActive, active))
  669. diff = 0
  670. }
  671. if diff == 0 {
  672. return active, nil
  673. }
  674. jm.expectations.ExpectCreations(jobKey, int(diff))
  675. errCh = make(chan error, diff)
  676. klog.V(4).Infof("Too few pods running job %q, need %d, creating %d", jobKey, wantActive, diff)
  677. active += diff
  678. wait := sync.WaitGroup{}
  679. // Batch the pod creates. Batch sizes start at SlowStartInitialBatchSize
  680. // and double with each successful iteration in a kind of "slow start".
  681. // This handles attempts to start large numbers of pods that would
  682. // likely all fail with the same error. For example a project with a
  683. // low quota that attempts to create a large number of pods will be
  684. // prevented from spamming the API service with the pod create requests
  685. // after one of its pods fails. Conveniently, this also prevents the
  686. // event spam that those failures would generate.
  687. for batchSize := int32(integer.IntMin(int(diff), controller.SlowStartInitialBatchSize)); diff > 0; batchSize = integer.Int32Min(2*batchSize, diff) {
  688. errorCount := len(errCh)
  689. wait.Add(int(batchSize))
  690. for i := int32(0); i < batchSize; i++ {
  691. go func() {
  692. defer wait.Done()
  693. err := jm.podControl.CreatePodsWithControllerRef(job.Namespace, &job.Spec.Template, job, metav1.NewControllerRef(job, controllerKind))
  694. if err != nil {
  695. if errors.HasStatusCause(err, v1.NamespaceTerminatingCause) {
  696. // If the namespace is being torn down, we can safely ignore
  697. // this error since all subsequent creations will fail.
  698. return
  699. }
  700. }
  701. if err != nil {
  702. defer utilruntime.HandleError(err)
  703. // Decrement the expected number of creates because the informer won't observe this pod
  704. klog.V(2).Infof("Failed creation, decrementing expectations for job %q/%q", job.Namespace, job.Name)
  705. jm.expectations.CreationObserved(jobKey)
  706. activeLock.Lock()
  707. active--
  708. activeLock.Unlock()
  709. errCh <- err
  710. }
  711. }()
  712. }
  713. wait.Wait()
  714. // any skipped pods that we never attempted to start shouldn't be expected.
  715. skippedPods := diff - batchSize
  716. if errorCount < len(errCh) && skippedPods > 0 {
  717. klog.V(2).Infof("Slow-start failure. Skipping creation of %d pods, decrementing expectations for job %q/%q", skippedPods, job.Namespace, job.Name)
  718. active -= skippedPods
  719. for i := int32(0); i < skippedPods; i++ {
  720. // Decrement the expected number of creates because the informer won't observe this pod
  721. jm.expectations.CreationObserved(jobKey)
  722. }
  723. // The skipped pods will be retried later. The next controller resync will
  724. // retry the slow start process.
  725. break
  726. }
  727. diff -= batchSize
  728. }
  729. }
  730. select {
  731. case err := <-errCh:
  732. // all errors have been reported before, we only need to inform the controller that there was an error and it should re-try this job once more next time.
  733. if err != nil {
  734. return active, err
  735. }
  736. default:
  737. }
  738. return active, nil
  739. }
  740. func (jm *JobController) updateJobStatus(job *batch.Job) error {
  741. jobClient := jm.kubeClient.BatchV1().Jobs(job.Namespace)
  742. var err error
  743. for i := 0; i <= statusUpdateRetries; i = i + 1 {
  744. var newJob *batch.Job
  745. newJob, err = jobClient.Get(context.TODO(), job.Name, metav1.GetOptions{})
  746. if err != nil {
  747. break
  748. }
  749. newJob.Status = job.Status
  750. if _, err = jobClient.UpdateStatus(context.TODO(), newJob, metav1.UpdateOptions{}); err == nil {
  751. break
  752. }
  753. }
  754. return err
  755. }
  756. func getBackoff(queue workqueue.RateLimitingInterface, key interface{}) time.Duration {
  757. exp := queue.NumRequeues(key)
  758. if exp <= 0 {
  759. return time.Duration(0)
  760. }
  761. // The backoff is capped such that 'calculated' value never overflows.
  762. backoff := float64(DefaultJobBackOff.Nanoseconds()) * math.Pow(2, float64(exp-1))
  763. if backoff > math.MaxInt64 {
  764. return MaxJobBackOff
  765. }
  766. calculated := time.Duration(backoff)
  767. if calculated > MaxJobBackOff {
  768. return MaxJobBackOff
  769. }
  770. return calculated
  771. }
  772. // filterPods returns pods based on their phase.
  773. func filterPods(pods []*v1.Pod, phase v1.PodPhase) int {
  774. result := 0
  775. for i := range pods {
  776. if phase == pods[i].Status.Phase {
  777. result++
  778. }
  779. }
  780. return result
  781. }