controller.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 scheduledjob
  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 ScheduledJobs, we 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. "fmt"
  25. "time"
  26. "github.com/golang/glog"
  27. "k8s.io/kubernetes/pkg/api"
  28. "k8s.io/kubernetes/pkg/api/errors"
  29. "k8s.io/kubernetes/pkg/api/unversioned"
  30. "k8s.io/kubernetes/pkg/apis/batch"
  31. "k8s.io/kubernetes/pkg/client/record"
  32. client "k8s.io/kubernetes/pkg/client/unversioned"
  33. "k8s.io/kubernetes/pkg/controller/job"
  34. "k8s.io/kubernetes/pkg/runtime"
  35. utilerrors "k8s.io/kubernetes/pkg/util/errors"
  36. "k8s.io/kubernetes/pkg/util/metrics"
  37. utilruntime "k8s.io/kubernetes/pkg/util/runtime"
  38. "k8s.io/kubernetes/pkg/util/wait"
  39. )
  40. // Utilities for dealing with Jobs and ScheduledJobs and time.
  41. type ScheduledJobController struct {
  42. kubeClient *client.Client
  43. jobControl jobControlInterface
  44. sjControl sjControlInterface
  45. podControl podControlInterface
  46. recorder record.EventRecorder
  47. }
  48. func NewScheduledJobController(kubeClient *client.Client) *ScheduledJobController {
  49. eventBroadcaster := record.NewBroadcaster()
  50. eventBroadcaster.StartLogging(glog.Infof)
  51. // TODO: remove the wrapper when every clients have moved to use the clientset.
  52. eventBroadcaster.StartRecordingToSink(kubeClient.Events(""))
  53. if kubeClient != nil && kubeClient.GetRateLimiter() != nil {
  54. metrics.RegisterMetricAndTrackRateLimiterUsage("scheduledjob_controller", kubeClient.GetRateLimiter())
  55. }
  56. jm := &ScheduledJobController{
  57. kubeClient: kubeClient,
  58. jobControl: realJobControl{KubeClient: kubeClient},
  59. sjControl: &realSJControl{KubeClient: kubeClient},
  60. podControl: &realPodControl{KubeClient: kubeClient},
  61. recorder: eventBroadcaster.NewRecorder(api.EventSource{Component: "scheduled-job-controller"}),
  62. }
  63. return jm
  64. }
  65. func NewScheduledJobControllerFromClient(kubeClient *client.Client) *ScheduledJobController {
  66. jm := NewScheduledJobController(kubeClient)
  67. return jm
  68. }
  69. // Run the main goroutine responsible for watching and syncing jobs.
  70. func (jm *ScheduledJobController) Run(stopCh <-chan struct{}) {
  71. defer utilruntime.HandleCrash()
  72. glog.Infof("Starting ScheduledJob Manager")
  73. // Check things every 10 second.
  74. go wait.Until(jm.SyncAll, 10*time.Second, stopCh)
  75. <-stopCh
  76. glog.Infof("Shutting down ScheduledJob Manager")
  77. }
  78. // SyncAll lists all the ScheduledJobs and Jobs and reconciles them.
  79. func (jm *ScheduledJobController) SyncAll() {
  80. sjl, err := jm.kubeClient.Batch().ScheduledJobs(api.NamespaceAll).List(api.ListOptions{})
  81. if err != nil {
  82. glog.Errorf("Error listing scheduledjobs: %v", err)
  83. return
  84. }
  85. sjs := sjl.Items
  86. glog.Infof("Found %d scheduledjobs", len(sjs))
  87. jl, err := jm.kubeClient.Batch().Jobs(api.NamespaceAll).List(api.ListOptions{})
  88. if err != nil {
  89. glog.Errorf("Error listing jobs")
  90. return
  91. }
  92. js := jl.Items
  93. glog.Infof("Found %d jobs", len(js))
  94. jobsBySj := groupJobsByParent(sjs, js)
  95. glog.Infof("Found %d groups", len(jobsBySj))
  96. for _, sj := range sjs {
  97. SyncOne(sj, jobsBySj[sj.UID], time.Now(), jm.jobControl, jm.sjControl, jm.podControl, jm.recorder)
  98. }
  99. }
  100. // SyncOne reconciles a ScheduledJob with a list of any Jobs that it created.
  101. // All known jobs created by "sj" should be included in "js".
  102. // The current time is passed in to facilitate testing.
  103. // It has no receiver, to facilitate testing.
  104. func SyncOne(sj batch.ScheduledJob, js []batch.Job, now time.Time, jc jobControlInterface, sjc sjControlInterface, pc podControlInterface, recorder record.EventRecorder) {
  105. nameForLog := fmt.Sprintf("%s/%s", sj.Namespace, sj.Name)
  106. for i := range js {
  107. j := js[i]
  108. found := inActiveList(sj, j.ObjectMeta.UID)
  109. if !found && !job.IsJobFinished(&j) {
  110. recorder.Eventf(&sj, api.EventTypeWarning, "UnexpectedJob", "Saw a job that the controller did not create or forgot: %v", j.Name)
  111. // We found an unfinished job that has us as the parent, but it is not in our Active list.
  112. // This could happen if we crashed right after creating the Job and before updating the status,
  113. // or if our jobs list is newer than our sj status after a relist, or if someone intentionally created
  114. // a job that they wanted us to adopt.
  115. // TODO: maybe handle the adoption case? Concurrency/suspend rules will not apply in that case, obviously, since we can't
  116. // stop users from creating jobs if they have permission. It is assumed that if a
  117. // user has permission to create a job within a namespace, then they have permission to make any scheduledJob
  118. // in the same namespace "adopt" that job. ReplicaSets and their Pods work the same way.
  119. // TBS: how to update sj.Status.LastScheduleTime if the adopted job is newer than any we knew about?
  120. } else if found && job.IsJobFinished(&j) {
  121. deleteFromActiveList(&sj, j.ObjectMeta.UID)
  122. // TODO: event to call out failure vs success.
  123. recorder.Eventf(&sj, api.EventTypeNormal, "SawCompletedJob", "Saw completed job: %v", j.Name)
  124. }
  125. }
  126. updatedSJ, err := sjc.UpdateStatus(&sj)
  127. if err != nil {
  128. glog.Errorf("Unable to update status for %s (rv = %s): %v", nameForLog, sj.ResourceVersion, err)
  129. }
  130. sj = *updatedSJ
  131. if sj.Spec.Suspend != nil && *sj.Spec.Suspend {
  132. glog.V(4).Infof("Not starting job for %s because it is suspended", nameForLog)
  133. return
  134. }
  135. times, err := getRecentUnmetScheduleTimes(sj, now)
  136. if err != nil {
  137. glog.Errorf("Cannot determine if %s needs to be started: %v", nameForLog, err)
  138. }
  139. // TODO: handle multiple unmet start times, from oldest to newest, updating status as needed.
  140. if len(times) == 0 {
  141. glog.V(4).Infof("No unmet start times for %s", nameForLog)
  142. return
  143. }
  144. if len(times) > 1 {
  145. glog.Errorf("Multiple unmet start times for %s so only starting last one", nameForLog)
  146. }
  147. scheduledTime := times[len(times)-1]
  148. tooLate := false
  149. if sj.Spec.StartingDeadlineSeconds != nil {
  150. tooLate = scheduledTime.Add(time.Second * time.Duration(*sj.Spec.StartingDeadlineSeconds)).Before(now)
  151. }
  152. if tooLate {
  153. glog.Errorf("Missed starting window for %s", nameForLog)
  154. // TODO: generate an event for a miss. Use a warning level event because it indicates a
  155. // problem with the controller (restart or long queue), and is not expected by user either.
  156. // Since we don't set LastScheduleTime when not scheduling, we are going to keep noticing
  157. // the miss every cycle. In order to avoid sending multiple events, and to avoid processing
  158. // the sj again and again, we could set a Status.LastMissedTime when we notice a miss.
  159. // Then, when we call getRecentUnmetScheduleTimes, we can take max(creationTimestamp,
  160. // Status.LastScheduleTime, Status.LastMissedTime), and then so we won't generate
  161. // and event the next time we process it, and also so the user looking at the status
  162. // can see easily that there was a missed execution.
  163. return
  164. }
  165. if sj.Spec.ConcurrencyPolicy == batch.ForbidConcurrent && len(sj.Status.Active) > 0 {
  166. // Regardless which source of information we use for the set of active jobs,
  167. // there is some risk that we won't see an active job when there is one.
  168. // (because we haven't seen the status update to the SJ or the created pod).
  169. // So it is theoretically possible to have concurrency with Forbid.
  170. // As long the as the invokations are "far enough apart in time", this usually won't happen.
  171. //
  172. // TODO: for Forbid, we could use the same name for every execution, as a lock.
  173. // With replace, we could use a name that is deterministic per execution time.
  174. // But that would mean that you could not inspect prior successes or failures of Forbid jobs.
  175. glog.V(4).Infof("Not starting job for %s because of prior execution still running and concurrency policy is Forbid.", nameForLog)
  176. return
  177. }
  178. if sj.Spec.ConcurrencyPolicy == batch.ReplaceConcurrent {
  179. for _, j := range sj.Status.Active {
  180. // TODO: this should be replaced with server side job deletion
  181. // currently this mimics JobReaper from pkg/kubectl/stop.go
  182. glog.V(4).Infof("Deleting job %s of %s s that was still running at next scheduled start time", j.Name, nameForLog)
  183. job, err := jc.GetJob(j.Namespace, j.Name)
  184. if err != nil {
  185. recorder.Eventf(&sj, api.EventTypeWarning, "FailedGet", "Get job: %v", err)
  186. return
  187. }
  188. // scale job down to 0
  189. if *job.Spec.Parallelism != 0 {
  190. zero := int32(0)
  191. job.Spec.Parallelism = &zero
  192. job, err = jc.UpdateJob(job.Namespace, job)
  193. if err != nil {
  194. recorder.Eventf(&sj, api.EventTypeWarning, "FailedUpdate", "Update job: %v", err)
  195. return
  196. }
  197. }
  198. // remove all pods...
  199. selector, _ := unversioned.LabelSelectorAsSelector(job.Spec.Selector)
  200. options := api.ListOptions{LabelSelector: selector}
  201. podList, err := pc.ListPods(job.Namespace, options)
  202. if err != nil {
  203. recorder.Eventf(&sj, api.EventTypeWarning, "FailedList", "List job-pods: %v", err)
  204. }
  205. errList := []error{}
  206. for _, pod := range podList.Items {
  207. if err := pc.DeletePod(pod.Namespace, pod.Name); err != nil {
  208. // ignores the error when the pod isn't found
  209. if !errors.IsNotFound(err) {
  210. errList = append(errList, err)
  211. }
  212. }
  213. }
  214. if len(errList) != 0 {
  215. recorder.Eventf(&sj, api.EventTypeWarning, "FailedDelete", "Deleted job-pods: %v", utilerrors.NewAggregate(errList))
  216. return
  217. }
  218. // ... and the job itself
  219. if err := jc.DeleteJob(job.Namespace, job.Name); err != nil {
  220. recorder.Eventf(&sj, api.EventTypeWarning, "FailedDelete", "Deleted job: %v", err)
  221. return
  222. }
  223. recorder.Eventf(&sj, api.EventTypeNormal, "SuccessfulDelete", "Deleted job %v", j.Name)
  224. }
  225. }
  226. jobReq, err := getJobFromTemplate(&sj, scheduledTime)
  227. if err != nil {
  228. glog.Errorf("Unable to make Job from template in %s: %v", nameForLog, err)
  229. return
  230. }
  231. jobResp, err := jc.CreateJob(sj.Namespace, jobReq)
  232. if err != nil {
  233. recorder.Eventf(&sj, api.EventTypeWarning, "FailedCreate", "Error creating job: %v", err)
  234. return
  235. }
  236. recorder.Eventf(&sj, api.EventTypeNormal, "SuccessfulCreate", "Created job %v", jobResp.Name)
  237. // ------------------------------------------------------------------ //
  238. // If this process restarts at this point (after posting a job, but
  239. // before updating the status), then we might try to start the job on
  240. // the next time. Actually, if we relist the SJs and Jobs on the next
  241. // iteration of SyncAll, we might not see our own status update, and
  242. // then post one again. So, we need to use the job name as a lock to
  243. // prevent us from making the job twice (name the job with hash of its
  244. // scheduled time).
  245. // Add the just-started job to the status list.
  246. ref, err := getRef(jobResp)
  247. if err != nil {
  248. glog.V(2).Infof("Unable to make object reference for job for %s", nameForLog)
  249. } else {
  250. sj.Status.Active = append(sj.Status.Active, *ref)
  251. }
  252. sj.Status.LastScheduleTime = &unversioned.Time{Time: scheduledTime}
  253. if _, err := sjc.UpdateStatus(&sj); err != nil {
  254. glog.Infof("Unable to update status for %s (rv = %s): %v", nameForLog, sj.ResourceVersion, err)
  255. }
  256. return
  257. }
  258. func getRef(object runtime.Object) (*api.ObjectReference, error) {
  259. return api.GetReference(object)
  260. }