cronjob_controller.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 cronjob
  14. /*
  15. I did not use watch or expectations. Those add a lot of corner cases, and we aren't
  16. expecting a large volume of jobs or scheduledJobs. (We are favoring correctness
  17. over scalability. If we find a single controller thread is too slow because
  18. there are a lot of Jobs or CronJobs, we can parallelize by Namespace.
  19. If we find the load on the API server is too high, we can use a watch and
  20. UndeltaStore.)
  21. Just periodically list jobs and SJs, and then reconcile them.
  22. */
  23. import (
  24. "context"
  25. "fmt"
  26. "sort"
  27. "time"
  28. "k8s.io/klog"
  29. batchv1 "k8s.io/api/batch/v1"
  30. batchv1beta1 "k8s.io/api/batch/v1beta1"
  31. "k8s.io/api/core/v1"
  32. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  33. "k8s.io/apimachinery/pkg/runtime"
  34. "k8s.io/apimachinery/pkg/types"
  35. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  36. "k8s.io/apimachinery/pkg/util/wait"
  37. clientset "k8s.io/client-go/kubernetes"
  38. "k8s.io/client-go/kubernetes/scheme"
  39. v1core "k8s.io/client-go/kubernetes/typed/core/v1"
  40. "k8s.io/client-go/tools/pager"
  41. "k8s.io/client-go/tools/record"
  42. ref "k8s.io/client-go/tools/reference"
  43. "k8s.io/kubernetes/pkg/util/metrics"
  44. )
  45. // Utilities for dealing with Jobs and CronJobs and time.
  46. // controllerKind contains the schema.GroupVersionKind for this controller type.
  47. var controllerKind = batchv1beta1.SchemeGroupVersion.WithKind("CronJob")
  48. // Controller is a controller for CronJobs.
  49. type Controller struct {
  50. kubeClient clientset.Interface
  51. jobControl jobControlInterface
  52. sjControl sjControlInterface
  53. podControl podControlInterface
  54. recorder record.EventRecorder
  55. }
  56. // NewController creates and initializes a new Controller.
  57. func NewController(kubeClient clientset.Interface) (*Controller, error) {
  58. eventBroadcaster := record.NewBroadcaster()
  59. eventBroadcaster.StartLogging(klog.Infof)
  60. eventBroadcaster.StartRecordingToSink(&v1core.EventSinkImpl{Interface: kubeClient.CoreV1().Events("")})
  61. if kubeClient != nil && kubeClient.CoreV1().RESTClient().GetRateLimiter() != nil {
  62. if err := metrics.RegisterMetricAndTrackRateLimiterUsage("cronjob_controller", kubeClient.CoreV1().RESTClient().GetRateLimiter()); err != nil {
  63. return nil, err
  64. }
  65. }
  66. jm := &Controller{
  67. kubeClient: kubeClient,
  68. jobControl: realJobControl{KubeClient: kubeClient},
  69. sjControl: &realSJControl{KubeClient: kubeClient},
  70. podControl: &realPodControl{KubeClient: kubeClient},
  71. recorder: eventBroadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: "cronjob-controller"}),
  72. }
  73. return jm, nil
  74. }
  75. // Run starts the main goroutine responsible for watching and syncing jobs.
  76. func (jm *Controller) Run(stopCh <-chan struct{}) {
  77. defer utilruntime.HandleCrash()
  78. klog.Infof("Starting CronJob Manager")
  79. // Check things every 10 second.
  80. go wait.Until(jm.syncAll, 10*time.Second, stopCh)
  81. <-stopCh
  82. klog.Infof("Shutting down CronJob Manager")
  83. }
  84. // syncAll lists all the CronJobs and Jobs and reconciles them.
  85. func (jm *Controller) syncAll() {
  86. // List children (Jobs) before parents (CronJob).
  87. // This guarantees that if we see any Job that got orphaned by the GC orphan finalizer,
  88. // we must also see that the parent CronJob has non-nil DeletionTimestamp (see #42639).
  89. // Note that this only works because we are NOT using any caches here.
  90. jobListFunc := func(opts metav1.ListOptions) (runtime.Object, error) {
  91. return jm.kubeClient.BatchV1().Jobs(metav1.NamespaceAll).List(opts)
  92. }
  93. js := make([]batchv1.Job, 0)
  94. err := pager.New(pager.SimplePageFunc(jobListFunc)).EachListItem(context.Background(), metav1.ListOptions{}, func(object runtime.Object) error {
  95. jobTmp, ok := object.(*batchv1.Job)
  96. if !ok {
  97. return fmt.Errorf("expected type *batchv1.Job, got type %T", jobTmp)
  98. }
  99. js = append(js, *jobTmp)
  100. return nil
  101. })
  102. if err != nil {
  103. utilruntime.HandleError(fmt.Errorf("Failed to extract job list: %v", err))
  104. return
  105. }
  106. klog.V(4).Infof("Found %d jobs", len(js))
  107. cronJobListFunc := func(opts metav1.ListOptions) (runtime.Object, error) {
  108. return jm.kubeClient.BatchV1beta1().CronJobs(metav1.NamespaceAll).List(opts)
  109. }
  110. jobsBySj := groupJobsByParent(js)
  111. klog.V(4).Infof("Found %d groups", len(jobsBySj))
  112. err = pager.New(pager.SimplePageFunc(cronJobListFunc)).EachListItem(context.Background(), metav1.ListOptions{}, func(object runtime.Object) error {
  113. sj, ok := object.(*batchv1beta1.CronJob)
  114. if !ok {
  115. return fmt.Errorf("expected type *batchv1beta1.CronJob, got type %T", sj)
  116. }
  117. syncOne(sj, jobsBySj[sj.UID], time.Now(), jm.jobControl, jm.sjControl, jm.recorder)
  118. cleanupFinishedJobs(sj, jobsBySj[sj.UID], jm.jobControl, jm.sjControl, jm.recorder)
  119. return nil
  120. })
  121. if err != nil {
  122. utilruntime.HandleError(fmt.Errorf("Failed to extract cronJobs list: %v", err))
  123. return
  124. }
  125. }
  126. // cleanupFinishedJobs cleanups finished jobs created by a CronJob
  127. func cleanupFinishedJobs(sj *batchv1beta1.CronJob, js []batchv1.Job, jc jobControlInterface,
  128. sjc sjControlInterface, recorder record.EventRecorder) {
  129. // If neither limits are active, there is no need to do anything.
  130. if sj.Spec.FailedJobsHistoryLimit == nil && sj.Spec.SuccessfulJobsHistoryLimit == nil {
  131. return
  132. }
  133. failedJobs := []batchv1.Job{}
  134. succesfulJobs := []batchv1.Job{}
  135. for _, job := range js {
  136. isFinished, finishedStatus := getFinishedStatus(&job)
  137. if isFinished && finishedStatus == batchv1.JobComplete {
  138. succesfulJobs = append(succesfulJobs, job)
  139. } else if isFinished && finishedStatus == batchv1.JobFailed {
  140. failedJobs = append(failedJobs, job)
  141. }
  142. }
  143. if sj.Spec.SuccessfulJobsHistoryLimit != nil {
  144. removeOldestJobs(sj,
  145. succesfulJobs,
  146. jc,
  147. *sj.Spec.SuccessfulJobsHistoryLimit,
  148. recorder)
  149. }
  150. if sj.Spec.FailedJobsHistoryLimit != nil {
  151. removeOldestJobs(sj,
  152. failedJobs,
  153. jc,
  154. *sj.Spec.FailedJobsHistoryLimit,
  155. recorder)
  156. }
  157. // Update the CronJob, in case jobs were removed from the list.
  158. if _, err := sjc.UpdateStatus(sj); err != nil {
  159. nameForLog := fmt.Sprintf("%s/%s", sj.Namespace, sj.Name)
  160. klog.Infof("Unable to update status for %s (rv = %s): %v", nameForLog, sj.ResourceVersion, err)
  161. }
  162. }
  163. // removeOldestJobs removes the oldest jobs from a list of jobs
  164. func removeOldestJobs(sj *batchv1beta1.CronJob, js []batchv1.Job, jc jobControlInterface, maxJobs int32, recorder record.EventRecorder) {
  165. numToDelete := len(js) - int(maxJobs)
  166. if numToDelete <= 0 {
  167. return
  168. }
  169. nameForLog := fmt.Sprintf("%s/%s", sj.Namespace, sj.Name)
  170. klog.V(4).Infof("Cleaning up %d/%d jobs from %s", numToDelete, len(js), nameForLog)
  171. sort.Sort(byJobStartTime(js))
  172. for i := 0; i < numToDelete; i++ {
  173. klog.V(4).Infof("Removing job %s from %s", js[i].Name, nameForLog)
  174. deleteJob(sj, &js[i], jc, recorder)
  175. }
  176. }
  177. // syncOne reconciles a CronJob with a list of any Jobs that it created.
  178. // All known jobs created by "sj" should be included in "js".
  179. // The current time is passed in to facilitate testing.
  180. // It has no receiver, to facilitate testing.
  181. func syncOne(sj *batchv1beta1.CronJob, js []batchv1.Job, now time.Time, jc jobControlInterface, sjc sjControlInterface, recorder record.EventRecorder) {
  182. nameForLog := fmt.Sprintf("%s/%s", sj.Namespace, sj.Name)
  183. childrenJobs := make(map[types.UID]bool)
  184. for _, j := range js {
  185. childrenJobs[j.ObjectMeta.UID] = true
  186. found := inActiveList(*sj, j.ObjectMeta.UID)
  187. if !found && !IsJobFinished(&j) {
  188. recorder.Eventf(sj, v1.EventTypeWarning, "UnexpectedJob", "Saw a job that the controller did not create or forgot: %s", j.Name)
  189. // We found an unfinished job that has us as the parent, but it is not in our Active list.
  190. // This could happen if we crashed right after creating the Job and before updating the status,
  191. // or if our jobs list is newer than our sj status after a relist, or if someone intentionally created
  192. // a job that they wanted us to adopt.
  193. // TODO: maybe handle the adoption case? Concurrency/suspend rules will not apply in that case, obviously, since we can't
  194. // stop users from creating jobs if they have permission. It is assumed that if a
  195. // user has permission to create a job within a namespace, then they have permission to make any scheduledJob
  196. // in the same namespace "adopt" that job. ReplicaSets and their Pods work the same way.
  197. // TBS: how to update sj.Status.LastScheduleTime if the adopted job is newer than any we knew about?
  198. } else if found && IsJobFinished(&j) {
  199. _, status := getFinishedStatus(&j)
  200. deleteFromActiveList(sj, j.ObjectMeta.UID)
  201. recorder.Eventf(sj, v1.EventTypeNormal, "SawCompletedJob", "Saw completed job: %s, status: %v", j.Name, status)
  202. }
  203. }
  204. // Remove any job reference from the active list if the corresponding job does not exist any more.
  205. // Otherwise, the cronjob may be stuck in active mode forever even though there is no matching
  206. // job running.
  207. for _, j := range sj.Status.Active {
  208. if found := childrenJobs[j.UID]; !found {
  209. recorder.Eventf(sj, v1.EventTypeNormal, "MissingJob", "Active job went missing: %v", j.Name)
  210. deleteFromActiveList(sj, j.UID)
  211. }
  212. }
  213. updatedSJ, err := sjc.UpdateStatus(sj)
  214. if err != nil {
  215. klog.Errorf("Unable to update status for %s (rv = %s): %v", nameForLog, sj.ResourceVersion, err)
  216. return
  217. }
  218. *sj = *updatedSJ
  219. if sj.DeletionTimestamp != nil {
  220. // The CronJob is being deleted.
  221. // Don't do anything other than updating status.
  222. return
  223. }
  224. if sj.Spec.Suspend != nil && *sj.Spec.Suspend {
  225. klog.V(4).Infof("Not starting job for %s because it is suspended", nameForLog)
  226. return
  227. }
  228. times, err := getRecentUnmetScheduleTimes(*sj, now)
  229. if err != nil {
  230. recorder.Eventf(sj, v1.EventTypeWarning, "FailedNeedsStart", "Cannot determine if job needs to be started: %v", err)
  231. klog.Errorf("Cannot determine if %s needs to be started: %v", nameForLog, err)
  232. return
  233. }
  234. // TODO: handle multiple unmet start times, from oldest to newest, updating status as needed.
  235. if len(times) == 0 {
  236. klog.V(4).Infof("No unmet start times for %s", nameForLog)
  237. return
  238. }
  239. if len(times) > 1 {
  240. klog.V(4).Infof("Multiple unmet start times for %s so only starting last one", nameForLog)
  241. }
  242. scheduledTime := times[len(times)-1]
  243. tooLate := false
  244. if sj.Spec.StartingDeadlineSeconds != nil {
  245. tooLate = scheduledTime.Add(time.Second * time.Duration(*sj.Spec.StartingDeadlineSeconds)).Before(now)
  246. }
  247. if tooLate {
  248. klog.V(4).Infof("Missed starting window for %s", nameForLog)
  249. recorder.Eventf(sj, v1.EventTypeWarning, "MissSchedule", "Missed scheduled time to start a job: %s", scheduledTime.Format(time.RFC1123Z))
  250. // TODO: Since we don't set LastScheduleTime when not scheduling, we are going to keep noticing
  251. // the miss every cycle. In order to avoid sending multiple events, and to avoid processing
  252. // the sj again and again, we could set a Status.LastMissedTime when we notice a miss.
  253. // Then, when we call getRecentUnmetScheduleTimes, we can take max(creationTimestamp,
  254. // Status.LastScheduleTime, Status.LastMissedTime), and then so we won't generate
  255. // and event the next time we process it, and also so the user looking at the status
  256. // can see easily that there was a missed execution.
  257. return
  258. }
  259. if sj.Spec.ConcurrencyPolicy == batchv1beta1.ForbidConcurrent && len(sj.Status.Active) > 0 {
  260. // Regardless which source of information we use for the set of active jobs,
  261. // there is some risk that we won't see an active job when there is one.
  262. // (because we haven't seen the status update to the SJ or the created pod).
  263. // So it is theoretically possible to have concurrency with Forbid.
  264. // As long the as the invocations are "far enough apart in time", this usually won't happen.
  265. //
  266. // TODO: for Forbid, we could use the same name for every execution, as a lock.
  267. // With replace, we could use a name that is deterministic per execution time.
  268. // But that would mean that you could not inspect prior successes or failures of Forbid jobs.
  269. klog.V(4).Infof("Not starting job for %s because of prior execution still running and concurrency policy is Forbid", nameForLog)
  270. return
  271. }
  272. if sj.Spec.ConcurrencyPolicy == batchv1beta1.ReplaceConcurrent {
  273. for _, j := range sj.Status.Active {
  274. klog.V(4).Infof("Deleting job %s of %s that was still running at next scheduled start time", j.Name, nameForLog)
  275. job, err := jc.GetJob(j.Namespace, j.Name)
  276. if err != nil {
  277. recorder.Eventf(sj, v1.EventTypeWarning, "FailedGet", "Get job: %v", err)
  278. return
  279. }
  280. if !deleteJob(sj, job, jc, recorder) {
  281. return
  282. }
  283. }
  284. }
  285. jobReq, err := getJobFromTemplate(sj, scheduledTime)
  286. if err != nil {
  287. klog.Errorf("Unable to make Job from template in %s: %v", nameForLog, err)
  288. return
  289. }
  290. jobResp, err := jc.CreateJob(sj.Namespace, jobReq)
  291. if err != nil {
  292. recorder.Eventf(sj, v1.EventTypeWarning, "FailedCreate", "Error creating job: %v", err)
  293. return
  294. }
  295. klog.V(4).Infof("Created Job %s for %s", jobResp.Name, nameForLog)
  296. recorder.Eventf(sj, v1.EventTypeNormal, "SuccessfulCreate", "Created job %v", jobResp.Name)
  297. // ------------------------------------------------------------------ //
  298. // If this process restarts at this point (after posting a job, but
  299. // before updating the status), then we might try to start the job on
  300. // the next time. Actually, if we re-list the SJs and Jobs on the next
  301. // iteration of syncAll, we might not see our own status update, and
  302. // then post one again. So, we need to use the job name as a lock to
  303. // prevent us from making the job twice (name the job with hash of its
  304. // scheduled time).
  305. // Add the just-started job to the status list.
  306. ref, err := getRef(jobResp)
  307. if err != nil {
  308. klog.V(2).Infof("Unable to make object reference for job for %s", nameForLog)
  309. } else {
  310. sj.Status.Active = append(sj.Status.Active, *ref)
  311. }
  312. sj.Status.LastScheduleTime = &metav1.Time{Time: scheduledTime}
  313. if _, err := sjc.UpdateStatus(sj); err != nil {
  314. klog.Infof("Unable to update status for %s (rv = %s): %v", nameForLog, sj.ResourceVersion, err)
  315. }
  316. return
  317. }
  318. // deleteJob reaps a job, deleting the job, the pods and the reference in the active list
  319. func deleteJob(sj *batchv1beta1.CronJob, job *batchv1.Job, jc jobControlInterface, recorder record.EventRecorder) bool {
  320. nameForLog := fmt.Sprintf("%s/%s", sj.Namespace, sj.Name)
  321. // delete the job itself...
  322. if err := jc.DeleteJob(job.Namespace, job.Name); err != nil {
  323. recorder.Eventf(sj, v1.EventTypeWarning, "FailedDelete", "Deleted job: %v", err)
  324. klog.Errorf("Error deleting job %s from %s: %v", job.Name, nameForLog, err)
  325. return false
  326. }
  327. // ... and its reference from active list
  328. deleteFromActiveList(sj, job.ObjectMeta.UID)
  329. recorder.Eventf(sj, v1.EventTypeNormal, "SuccessfulDelete", "Deleted job %v", job.Name)
  330. return true
  331. }
  332. func getRef(object runtime.Object) (*v1.ObjectReference, error) {
  333. return ref.GetReference(scheme.Scheme, object)
  334. }