utils.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. import (
  15. "fmt"
  16. "time"
  17. "github.com/robfig/cron"
  18. "k8s.io/klog"
  19. batchv1 "k8s.io/api/batch/v1"
  20. batchv1beta1 "k8s.io/api/batch/v1beta1"
  21. "k8s.io/api/core/v1"
  22. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  23. "k8s.io/apimachinery/pkg/types"
  24. )
  25. // Utilities for dealing with Jobs and CronJobs and time.
  26. func inActiveList(sj batchv1beta1.CronJob, uid types.UID) bool {
  27. for _, j := range sj.Status.Active {
  28. if j.UID == uid {
  29. return true
  30. }
  31. }
  32. return false
  33. }
  34. func deleteFromActiveList(sj *batchv1beta1.CronJob, uid types.UID) {
  35. if sj == nil {
  36. return
  37. }
  38. newActive := []v1.ObjectReference{}
  39. for _, j := range sj.Status.Active {
  40. if j.UID != uid {
  41. newActive = append(newActive, j)
  42. }
  43. }
  44. sj.Status.Active = newActive
  45. }
  46. // getParentUIDFromJob extracts UID of job's parent and whether it was found
  47. func getParentUIDFromJob(j batchv1.Job) (types.UID, bool) {
  48. controllerRef := metav1.GetControllerOf(&j)
  49. if controllerRef == nil {
  50. return types.UID(""), false
  51. }
  52. if controllerRef.Kind != "CronJob" {
  53. klog.V(4).Infof("Job with non-CronJob parent, name %s namespace %s", j.Name, j.Namespace)
  54. return types.UID(""), false
  55. }
  56. return controllerRef.UID, true
  57. }
  58. // groupJobsByParent groups jobs into a map keyed by the job parent UID (e.g. scheduledJob).
  59. // It has no receiver, to facilitate testing.
  60. func groupJobsByParent(js []batchv1.Job) map[types.UID][]batchv1.Job {
  61. jobsBySj := make(map[types.UID][]batchv1.Job)
  62. for _, job := range js {
  63. parentUID, found := getParentUIDFromJob(job)
  64. if !found {
  65. klog.V(4).Infof("Unable to get parent uid from job %s in namespace %s", job.Name, job.Namespace)
  66. continue
  67. }
  68. jobsBySj[parentUID] = append(jobsBySj[parentUID], job)
  69. }
  70. return jobsBySj
  71. }
  72. // getRecentUnmetScheduleTimes gets a slice of times (from oldest to latest) that have passed when a Job should have started but did not.
  73. //
  74. // If there are too many (>100) unstarted times, just give up and return an empty slice.
  75. // If there were missed times prior to the last known start time, then those are not returned.
  76. func getRecentUnmetScheduleTimes(sj batchv1beta1.CronJob, now time.Time) ([]time.Time, error) {
  77. starts := []time.Time{}
  78. sched, err := cron.ParseStandard(sj.Spec.Schedule)
  79. if err != nil {
  80. return starts, fmt.Errorf("unparseable schedule: %s : %s", sj.Spec.Schedule, err)
  81. }
  82. var earliestTime time.Time
  83. if sj.Status.LastScheduleTime != nil {
  84. earliestTime = sj.Status.LastScheduleTime.Time
  85. } else {
  86. // If none found, then this is either a recently created scheduledJob,
  87. // or the active/completed info was somehow lost (contract for status
  88. // in kubernetes says it may need to be recreated), or that we have
  89. // started a job, but have not noticed it yet (distributed systems can
  90. // have arbitrary delays). In any case, use the creation time of the
  91. // CronJob as last known start time.
  92. earliestTime = sj.ObjectMeta.CreationTimestamp.Time
  93. }
  94. if sj.Spec.StartingDeadlineSeconds != nil {
  95. // Controller is not going to schedule anything below this point
  96. schedulingDeadline := now.Add(-time.Second * time.Duration(*sj.Spec.StartingDeadlineSeconds))
  97. if schedulingDeadline.After(earliestTime) {
  98. earliestTime = schedulingDeadline
  99. }
  100. }
  101. if earliestTime.After(now) {
  102. return []time.Time{}, nil
  103. }
  104. for t := sched.Next(earliestTime); !t.After(now); t = sched.Next(t) {
  105. starts = append(starts, t)
  106. // An object might miss several starts. For example, if
  107. // controller gets wedged on friday at 5:01pm when everyone has
  108. // gone home, and someone comes in on tuesday AM and discovers
  109. // the problem and restarts the controller, then all the hourly
  110. // jobs, more than 80 of them for one hourly scheduledJob, should
  111. // all start running with no further intervention (if the scheduledJob
  112. // allows concurrency and late starts).
  113. //
  114. // However, if there is a bug somewhere, or incorrect clock
  115. // on controller's server or apiservers (for setting creationTimestamp)
  116. // then there could be so many missed start times (it could be off
  117. // by decades or more), that it would eat up all the CPU and memory
  118. // of this controller. In that case, we want to not try to list
  119. // all the missed start times.
  120. //
  121. // I've somewhat arbitrarily picked 100, as more than 80,
  122. // but less than "lots".
  123. if len(starts) > 100 {
  124. // We can't get the most recent times so just return an empty slice
  125. return []time.Time{}, fmt.Errorf("too many missed start time (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew")
  126. }
  127. }
  128. return starts, nil
  129. }
  130. // getJobFromTemplate makes a Job from a CronJob
  131. func getJobFromTemplate(sj *batchv1beta1.CronJob, scheduledTime time.Time) (*batchv1.Job, error) {
  132. labels := copyLabels(&sj.Spec.JobTemplate)
  133. annotations := copyAnnotations(&sj.Spec.JobTemplate)
  134. // We want job names for a given nominal start time to have a deterministic name to avoid the same job being created twice
  135. name := fmt.Sprintf("%s-%d", sj.Name, getTimeHash(scheduledTime))
  136. job := &batchv1.Job{
  137. ObjectMeta: metav1.ObjectMeta{
  138. Labels: labels,
  139. Annotations: annotations,
  140. Name: name,
  141. OwnerReferences: []metav1.OwnerReference{*metav1.NewControllerRef(sj, controllerKind)},
  142. },
  143. }
  144. sj.Spec.JobTemplate.Spec.DeepCopyInto(&job.Spec)
  145. return job, nil
  146. }
  147. // getTimeHash returns Unix Epoch Time
  148. func getTimeHash(scheduledTime time.Time) int64 {
  149. return scheduledTime.Unix()
  150. }
  151. func getFinishedStatus(j *batchv1.Job) (bool, batchv1.JobConditionType) {
  152. for _, c := range j.Status.Conditions {
  153. if (c.Type == batchv1.JobComplete || c.Type == batchv1.JobFailed) && c.Status == v1.ConditionTrue {
  154. return true, c.Type
  155. }
  156. }
  157. return false, ""
  158. }
  159. // IsJobFinished returns whether or not a job has completed successfully or failed.
  160. func IsJobFinished(j *batchv1.Job) bool {
  161. isFinished, _ := getFinishedStatus(j)
  162. return isFinished
  163. }
  164. // byJobStartTime sorts a list of jobs by start timestamp, using their names as a tie breaker.
  165. type byJobStartTime []batchv1.Job
  166. func (o byJobStartTime) Len() int { return len(o) }
  167. func (o byJobStartTime) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
  168. func (o byJobStartTime) Less(i, j int) bool {
  169. if o[i].Status.StartTime == nil && o[j].Status.StartTime != nil {
  170. return false
  171. }
  172. if o[i].Status.StartTime != nil && o[j].Status.StartTime == nil {
  173. return true
  174. }
  175. if o[i].Status.StartTime.Equal(o[j].Status.StartTime) {
  176. return o[i].Name < o[j].Name
  177. }
  178. return o[i].Status.StartTime.Before(o[j].Status.StartTime)
  179. }