实现控制器
我们CronJob控制器的基本逻辑是这样的:
-
加载指定的 CronJob
-
列出所有有效的工作,并更新状态。
-
根据历史限制清理旧的工作记录。
-
检查是否已挂起(若已挂起则不做其他事)
-
获取下一个计划的运行时间
-
如果新工作在计划时间内、未超过截止日期且未被我们的并发策略阻止,则可以运行。
-
当我们看到一个正在运行的任务(自动完成)或是下一个定时运行的时间到时,请重新排队。
Apache License
Copyright 2026 The Kubernetes authors.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
从一些导入开始。下面会看到比脚手架更多的导入,用到时再说明。
package controller
import (
"context"
"fmt"
"maps"
"slices"
"time"
"github.com/robfig/cron"
kbatch "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
ref "k8s.io/client-go/tools/reference"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
batchv1 "tutorial.kubebuilder.io/project/api/v1"
)
接下来需要 Clock,以便在测试中伪造时间。
// CronJobReconciler 协调 CronJob 对象
type CronJobReconciler struct {
client.Client
Scheme *runtime.Scheme
Clock
}
Clock Code Implementation
我们会 mock 时钟以便测试中随意跳转时间;“真实”时钟只是调用 time.Now。
type realClock struct{}
func (_ realClock) Now() time.Time { return time.Now() } //nolint:staticcheck
// Clock 知道如何获取当前时间。
// 可用于在测试中伪造时间。
type Clock interface {
Now() time.Time
}
// 管理状态条件的定义
const (
// typeAvailableCronJob 表示 CronJob 协调的状态
typeAvailableCronJob = "Available"
// typeProgressingCronJob 表示 CronJob 正在协调时使用的状态
typeProgressingCronJob = "Progressing"
// typeDegradedCronJob 表示 CronJob 遇到错误时使用的状态
typeDegradedCronJob = "Degraded"
)
注意我们还需要更多 RBAC 权限——因为现在要创建和管理 Job,需要相应权限,这意味着再添加几条 标记。
// +kubebuilder:rbac:groups=batch.tutorial.kubebuilder.io,resources=cronjobs,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=batch.tutorial.kubebuilder.io,resources=cronjobs/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=batch.tutorial.kubebuilder.io,resources=cronjobs/finalizers,verbs=update
// +kubebuilder:rbac:groups=batch,resources=jobs,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=batch,resources=jobs/status,verbs=get
现在进入控制器核心——reconciler 逻辑。
var (
scheduledTimeAnnotation = "batch.tutorial.kubebuilder.io/scheduled-at"
)
// Reconcile 是主 kubernetes 协调循环的一部分,其目标是
// 使集群当前状态更接近期望状态。
// TODO(user): Modify the Reconcile function to compare the state specified by
// the CronJob object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// 更多细节参见 Reconcile 及其 Result:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.25.0/pkg/reconcile
// nolint:gocyclo
func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := logf.FromContext(ctx)
1:按名称加载 CronJob
我们用客户端获取 CronJob。所有客户端方法以 context(允许取消)为第一个参数,以相关对象为最后一个参数。Get 有些特殊,中间参数是 NamespacedName(如下文所见,多数方法没有中间参数)。
许多 client 方法末尾还接受可变参数选项。
var cronJob batchv1.CronJob
if err := r.Get(ctx, req.NamespacedName, &cronJob); err != nil {
if apierrors.IsNotFound(err) {
// 如果未找到自定义资源,通常意味着它已被删除或未创建
// 这样,我们将停止调整过程
log.Info("CronJob resource not found. Ignoring since object must be deleted")
return ctrl.Result{}, nil
}
// 读取对象时出错 - 重新排队请求。
log.Error(err, "Failed to get CronJob")
return ctrl.Result{}, err
}
// 若尚未存在则初始化 status conditions
if len(cronJob.Status.Conditions) == 0 {
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeProgressingCronJob,
Status: metav1.ConditionUnknown,
Reason: "Reconciling",
Message: "Starting reconciliation",
})
if err := r.Status().Update(ctx, &cronJob); err != nil {
log.Error(err, "Failed to update CronJob status")
return ctrl.Result{}, err
}
更新 status 后重新获取 CronJob,确保使用 API 服务器上的最新版本。
Kubernetes 使用乐观并发,意味着任何更新(包括 status 更新)都可能更改资源版本。若继续用过期副本协调,后续更新可能因冲突失败,例如:“the object has been modified; please apply your changes to the latest version and try again”。
在此重新获取可使协调逻辑与实际集群状态同步,避免不必要的冲突与重新入队。
if err := r.Get(ctx, req.NamespacedName, &cronJob); err != nil {
log.Error(err, "Failed to re-fetch CronJob")
return ctrl.Result{}, err
}
}
2:列出所有活动 Job,并更新 status
要完整更新 status,需要列出此命名空间中属于该 CronJob 的所有子 Job。与 Get 类似,可用 List 方法列出子 Job。注意我们用可变参数选项设置命名空间与字段匹配(实际是下面设置的索引查找)。
var childJobs kbatch.JobList
if err := r.List(ctx, &childJobs, client.InNamespace(req.Namespace), client.MatchingFields{jobOwnerKey: req.Name}); err != nil {
log.Error(err, "unable to list child Jobs")
更新前请确保拿到资源的最新状态,以避免冲突错误(例如 “the object has been modified”),否则会重新触发协调循环。
if fetchErr := r.Get(ctx, req.NamespacedName, &cronJob); fetchErr != nil {
log.Error(fetchErr, "Failed to re-fetch CronJob")
return ctrl.Result{}, fetchErr
}
// 更新 status condition 以反映错误
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeDegradedCronJob,
Status: metav1.ConditionTrue,
Reason: "ReconciliationError",
Message: fmt.Sprintf("Failed to list child jobs: %v", err),
})
if statusErr := r.Status().Update(ctx, &cronJob); statusErr != nil {
log.Error(statusErr, "Failed to update CronJob status")
}
return ctrl.Result{}, err
}
一旦拥有所有归我们所有的 Job,就把它们分成活动、成功与失败的 Job,并跟踪最近一次运行以便记入 status。请记住,status 应能从世界状态重建,因此通常不宜读取根对象的 status。相反,每次运行都应重建它。我们在这里就这样做。
我们可以使用 status 条件检查 Job 是否「已完成」以及成功还是失败。我们把该逻辑放在辅助函数中,使代码更清晰。
// 查找活动 Job 列表
var activeJobs []*kbatch.Job
var successfulJobs []*kbatch.Job
var failedJobs []*kbatch.Job
var mostRecentTime *time.Time // 查找上次运行以便更新 status
isJobFinished
若 Job 具有标记为 true 的 “Complete” 或 “Failed” 条件,我们视其为「已完成」。Status 条件允许向对象添加可扩展状态信息,供其他人或控制器检查完成度与健康状况等。
isJobFinished := func(job *kbatch.Job) (bool, kbatch.JobConditionType) {
for _, c := range job.Status.Conditions {
if (c.Type == kbatch.JobComplete || c.Type == kbatch.JobFailed) && c.Status == corev1.ConditionTrue {
return true, c.Type
}
}
return false, ""
}
getScheduledTimeForJob
用辅助函数从创建 Job 时添加的注解中提取计划时间。
getScheduledTimeForJob := func(job *kbatch.Job) (*time.Time, error) {
timeRaw := job.Annotations[scheduledTimeAnnotation]
if len(timeRaw) == 0 {
return nil, nil
}
timeParsed, err := time.Parse(time.RFC3339, timeRaw)
if err != nil {
return nil, err
}
return &timeParsed, nil
}
for i, job := range childJobs.Items {
_, finishedType := isJobFinished(&job)
switch finishedType {
case "": // 进行中
activeJobs = append(activeJobs, &childJobs.Items[i])
case kbatch.JobFailed:
failedJobs = append(failedJobs, &childJobs.Items[i])
case kbatch.JobComplete:
successfulJobs = append(successfulJobs, &childJobs.Items[i])
}
// 我们将启动时间存在注解中,以便从
// 活动 Job 自身重建。
scheduledTimeForJob, err := getScheduledTimeForJob(&job)
if err != nil {
log.Error(err, "unable to parse schedule time for child job", "job", &job)
continue
}
if scheduledTimeForJob != nil {
if mostRecentTime == nil || mostRecentTime.Before(*scheduledTimeForJob) {
mostRecentTime = scheduledTimeForJob
}
}
}
if mostRecentTime != nil {
cronJob.Status.LastScheduleTime = &metav1.Time{Time: *mostRecentTime}
} else {
cronJob.Status.LastScheduleTime = nil
}
cronJob.Status.Active = nil
for _, activeJob := range activeJobs {
jobRef, err := ref.GetReference(r.Scheme, activeJob)
if err != nil {
log.Error(err, "unable to make reference to active job", "job", activeJob)
continue
}
cronJob.Status.Active = append(cronJob.Status.Active, *jobRef)
}
这里我们以稍高的日志级别记录观察到的 Job 数量,便于调试。注意我们不用格式化字符串,而是用固定消息,并用键值对附加额外信息。这样更易过滤与查询日志行。
log.V(1).Info("job count", "active jobs", len(activeJobs), "successful jobs", len(successfulJobs), "failed jobs", len(failedJobs))
// 检查 CronJob 是否已挂起
isSuspended := cronJob.Spec.Suspend != nil && *cronJob.Spec.Suspend
// 根据当前状态更新 status conditions
if isSuspended {
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeAvailableCronJob,
Status: metav1.ConditionFalse,
Reason: "Suspended",
Message: "CronJob is suspended",
})
} else if len(failedJobs) > 0 {
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeDegradedCronJob,
Status: metav1.ConditionTrue,
Reason: "JobsFailed",
Message: fmt.Sprintf("%d job(s) have failed", len(failedJobs)),
})
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeAvailableCronJob,
Status: metav1.ConditionFalse,
Reason: "JobsFailed",
Message: fmt.Sprintf("%d job(s) have failed", len(failedJobs)),
})
} else if len(activeJobs) > 0 {
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeProgressingCronJob,
Status: metav1.ConditionTrue,
Reason: "JobsActive",
Message: fmt.Sprintf("%d job(s) are currently active", len(activeJobs)),
})
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeAvailableCronJob,
Status: metav1.ConditionTrue,
Reason: "JobsActive",
Message: fmt.Sprintf("CronJob is progressing with %d active job(s)", len(activeJobs)),
})
} else {
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeAvailableCronJob,
Status: metav1.ConditionTrue,
Reason: "AllJobsCompleted",
Message: "All jobs have completed successfully",
})
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeProgressingCronJob,
Status: metav1.ConditionFalse,
Reason: "NoJobsActive",
Message: "No jobs are currently active",
})
}
利用已收集的数据,我们将更新 CRD 的 status。与之前一样使用客户端。要专门更新 status 子资源,使用客户端的 Status 部分及其 Update 方法。
status 子资源忽略对 spec 的更改,因此更不易与其他更新冲突,并可有独立权限。
if err := r.Status().Update(ctx, &cronJob); err != nil {
log.Error(err, "unable to update CronJob status")
return ctrl.Result{}, err
}
更新 status 后,继续确保现实状态与 spec 中的期望一致。
3:按历史限制清理旧 Job
首先清理旧 Job,以免残留过多。
// 注意:删除为“尽力而为”——若某一个失败,
// 不会仅为完成删除而重新入队。
if cronJob.Spec.FailedJobsHistoryLimit != nil {
slices.SortStableFunc(failedJobs, func(a, b *kbatch.Job) int {
aStartTime := a.Status.StartTime
bStartTime := b.Status.StartTime
switch {
case aStartTime == nil && bStartTime == nil:
return 0
case aStartTime == nil:
return -1
case bStartTime == nil:
return 1
case aStartTime.Before(bStartTime):
return -1
case bStartTime.Before(aStartTime):
return 1
default:
return 0
}
})
for i, job := range failedJobs {
if int32(i) >= int32(len(failedJobs))-*cronJob.Spec.FailedJobsHistoryLimit {
break
}
if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); client.IgnoreNotFound(err) != nil {
log.Error(err, "unable to delete old failed job", "job", job)
} else {
log.V(1).Info("deleted old failed job", "job", job)
}
}
}
if cronJob.Spec.SuccessfulJobsHistoryLimit != nil {
slices.SortStableFunc(successfulJobs, func(a, b *kbatch.Job) int {
aStartTime := a.Status.StartTime
bStartTime := b.Status.StartTime
switch {
case aStartTime == nil && bStartTime == nil:
return 0
case aStartTime == nil:
return -1
case bStartTime == nil:
return 1
case aStartTime.Before(bStartTime):
return -1
case bStartTime.Before(aStartTime):
return 1
default:
return 0
}
})
for i, job := range successfulJobs {
if int32(i) >= int32(len(successfulJobs))-*cronJob.Spec.SuccessfulJobsHistoryLimit {
break
}
if err := r.Delete(ctx, job, client.PropagationPolicy(metav1.DeletePropagationBackground)); err != nil {
log.Error(err, "unable to delete old successful job", "job", job)
} else {
log.V(1).Info("deleted old successful job", "job", job)
}
}
}
4:检查是否已挂起
若此对象被挂起,我们不想运行任何 Job,因此到此停止。当正在运行的 Job 出了问题、想暂停运行以排查或调整集群而又不想删除对象时,这很有用。
if cronJob.Spec.Suspend != nil && *cronJob.Spec.Suspend {
log.V(1).Info("cronjob suspended, skipping")
return ctrl.Result{}, nil
}
5:获取下次计划运行
若未暂停,需计算下次计划运行,以及是否还有未处理的运行。
getNextSchedule
我们将使用方便的 cron 库计算下次计划时间。从上次运行开始计算合适时间;若找不到上次运行,则从 CronJob 创建时开始。
如果错过的运行太多且未设置任何截止时间,我们将退出,以免在控制器重启或卡住时引发问题。
否则返回错过的运行(只用最新一次)和下次运行,以便知道何时再次协调。
getNextSchedule := func(cronJob *batchv1.CronJob, now time.Time) (lastMissed time.Time, next time.Time, err error) {
sched, err := cron.ParseStandard(cronJob.Spec.Schedule)
if err != nil {
return time.Time{}, time.Time{}, fmt.Errorf("unparseable schedule %q: %w", cronJob.Spec.Schedule, err)
}
// 为优化,略取巧地从上次观测到的运行时间开始
// we could reconstitute this here, but there's not much point, since we've
// just updated it.
var earliestTime time.Time
if cronJob.Status.LastScheduleTime != nil {
earliestTime = cronJob.Status.LastScheduleTime.Time
} else {
earliestTime = cronJob.CreationTimestamp.Time
}
if cronJob.Spec.StartingDeadlineSeconds != nil {
// 控制器不会在此点之下调度任何内容
schedulingDeadline := now.Add(-time.Second * time.Duration(*cronJob.Spec.StartingDeadlineSeconds))
if schedulingDeadline.After(earliestTime) {
earliestTime = schedulingDeadline
}
}
if earliestTime.After(now) {
return time.Time{}, sched.Next(now), nil
}
starts := 0
for t := sched.Next(earliestTime); !t.After(now); t = sched.Next(t) {
lastMissed = t
// 对象可能错过多次启动。例如,若
// 控制器在周五下午 5:01 卡住,而大家都
// gone home, and someone comes in on Tuesday AM and discovers
// the problem and restarts the controller, then all the hourly
// jobs, more than 80 of them for one hourly scheduledJob, should
// all start running with no further intervention (if the scheduledJob
// allows concurrency and late starts).
//
// However, if there is a bug somewhere, or incorrect clock
// on controller's server or apiservers (for setting creationTimestamp)
// then there could be so many missed start times (it could be off
// by decades or more), that it would eat up all the CPU and memory
// of this controller. In that case, we want to not try to list
// all the missed start times.
starts++
if starts > 100 {
// 无法获取最近时间则返回空切片
return time.Time{}, time.Time{}, fmt.Errorf("Too many missed start times (> 100). Set or decrease .spec.startingDeadlineSeconds or check clock skew.") //nolint:staticcheck
}
}
return lastMissed, sched.Next(now), nil
}
// 算出下次需要创建的时间
// Job 的时间点(或任何错过的)。
missedRun, nextRun, err := getNextSchedule(&cronJob, r.Now())
if err != nil {
log.Error(err, "unable to figure out CronJob schedule")
if fetchErr := r.Get(ctx, req.NamespacedName, &cronJob); fetchErr != nil {
log.Error(fetchErr, "Failed to re-fetch CronJob")
return ctrl.Result{}, fetchErr
}
// 更新 status condition 以反映调度错误
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeDegradedCronJob,
Status: metav1.ConditionTrue,
Reason: "InvalidSchedule",
Message: fmt.Sprintf("Failed to parse schedule: %v", err),
})
if statusErr := r.Status().Update(ctx, &cronJob); statusErr != nil {
log.Error(statusErr, "Failed to update CronJob status")
}
// 在收到能修复调度的更新前不必重新入队
// 因此不返回错误
return ctrl.Result{}, nil
}
准备最终的重新入队请求直到下次 Job,再判断是否真正需要运行。
scheduledResult := ctrl.Result{RequeueAfter: nextRun.Sub(r.Now())} // 保存以便别处复用
log = log.WithValues("now", r.Now(), "next run", nextRun)
6:若已到点、未过截止且未被并发策略阻塞,则运行新 Job
若错过一次运行且仍在启动截止时间内,则需要运行 Job。
if missedRun.IsZero() {
log.V(1).Info("no upcoming scheduled times, sleeping until next")
return scheduledResult, nil
}
// 确保启动运行尚未过晚
log = log.WithValues("current run", missedRun)
tooLate := false
if cronJob.Spec.StartingDeadlineSeconds != nil {
tooLate = missedRun.Add(time.Duration(*cronJob.Spec.StartingDeadlineSeconds) * time.Second).Before(r.Now())
}
if tooLate {
log.V(1).Info("missed starting deadline for last run, sleeping till next")
if fetchErr := r.Get(ctx, req.NamespacedName, &cronJob); fetchErr != nil {
log.Error(fetchErr, "Failed to re-fetch CronJob")
return ctrl.Result{}, fetchErr
}
// 更新 status condition 以反映错过截止时间
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeDegradedCronJob,
Status: metav1.ConditionTrue,
Reason: "MissedSchedule",
Message: fmt.Sprintf("Missed starting deadline for run at %v", missedRun),
})
if statusErr := r.Status().Update(ctx, &cronJob); statusErr != nil {
log.Error(statusErr, "Failed to update CronJob status")
}
return scheduledResult, nil
}
若确实需要运行 Job,我们要么等待现有 Job 完成,要么替换现有 Job,要么直接添加新 Job。若因缓存延迟导致信息过时,在拿到最新信息时会重新入队。
// 确定如何运行此 Job——并发策略可能禁止我们
// 同时运行多个……
if cronJob.Spec.ConcurrencyPolicy == batchv1.ForbidConcurrent && len(activeJobs) > 0 {
log.V(1).Info("concurrency policy blocks concurrent runs, skipping", "num active", len(activeJobs))
return scheduledResult, nil
}
// ……或指示我们替换现有的……
if cronJob.Spec.ConcurrencyPolicy == batchv1.ReplaceConcurrent {
for _, activeJob := range activeJobs {
// 不关心 Job 是否已删除
if err := r.Delete(ctx, activeJob, client.PropagationPolicy(metav1.DeletePropagationBackground)); client.IgnoreNotFound(err) != nil {
log.Error(err, "unable to delete active job", "job", activeJob)
return ctrl.Result{}, err
}
}
}
确定如何处理现有 Job 后,实际创建期望的 Job
constructJobForCronJob
需根据 CronJob 模板构造 Job。复制模板中的 spec 与部分基本 object meta。
然后设置“计划时间”注解,以便每次协调重建 LastScheduleTime 字段。
最后,需要设置所有者引用。这允许 Kubernetes 垃圾回收器在删除 CronJob 时清理 Job,并让 controller-runtime 在给定 Job 变更(添加、删除、完成等)时确定需要协调哪个 CronJob。
constructJobForCronJob := func(cronJob *batchv1.CronJob, scheduledTime time.Time) (*kbatch.Job, error) {
// 希望给定名义启动时间的 Job 名称确定性,避免重复创建同一 Job
name := fmt.Sprintf("%s-%d", cronJob.Name, scheduledTime.Unix())
job := &kbatch.Job{
ObjectMeta: metav1.ObjectMeta{
Labels: make(map[string]string),
Annotations: make(map[string]string),
Name: name,
Namespace: cronJob.Namespace,
},
Spec: *cronJob.Spec.JobTemplate.Spec.DeepCopy(),
}
maps.Copy(job.Annotations, cronJob.Spec.JobTemplate.Annotations)
job.Annotations[scheduledTimeAnnotation] = scheduledTime.Format(time.RFC3339)
maps.Copy(job.Labels, cronJob.Spec.JobTemplate.Labels)
if err := ctrl.SetControllerReference(cronJob, job, r.Scheme); err != nil {
return nil, err
}
return job, nil
}
// 实际创建 Job……
job, err := constructJobForCronJob(&cronJob, missedRun)
if err != nil {
log.Error(err, "unable to construct job from template")
// 不要立即重试;失败发生在构造 Job 时。
// 将在下次计划运行时再次协调, and updates to the CronJob
// can also trigger reconciliation sooner
return scheduledResult, nil
}
// ...and create it on the cluster
if err := r.Create(ctx, job); err != nil {
log.Error(err, "unable to create Job for CronJob", "job", job)
if fetchErr := r.Get(ctx, req.NamespacedName, &cronJob); fetchErr != nil {
log.Error(fetchErr, "Failed to re-fetch CronJob")
return ctrl.Result{}, fetchErr
}
// 更新 status condition 以反映错误
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeDegradedCronJob,
Status: metav1.ConditionTrue,
Reason: "JobCreationFailed",
Message: fmt.Sprintf("Failed to create job: %v", err),
})
if statusErr := r.Status().Update(ctx, &cronJob); statusErr != nil {
log.Error(statusErr, "Failed to update CronJob status")
}
return ctrl.Result{}, err
}
log.V(1).Info("created Job for CronJob run", "job", job)
if fetchErr := r.Get(ctx, req.NamespacedName, &cronJob); fetchErr != nil {
log.Error(fetchErr, "Failed to re-fetch CronJob")
return ctrl.Result{}, fetchErr
}
// Update status condition to reflect successful job creation
meta.SetStatusCondition(&cronJob.Status.Conditions, metav1.Condition{
Type: typeProgressingCronJob,
Status: metav1.ConditionTrue,
Reason: "JobCreated",
Message: fmt.Sprintf("Created job %s", job.Name),
})
if statusErr := r.Status().Update(ctx, &cronJob); statusErr != nil {
log.Error(statusErr, "Failed to update CronJob status")
}
7:当我们看到正在运行的 Job,或到了下次计划运行时间时重新入队
最后,返回上面准备好的结果,表示希望在下次运行需要发生时重新入队。这视为最大截止时间——若其间发生其他变更,如 Job 开始或完成、我们被修改等,可能更早再次协调。
// we'll requeue once we see the running job, and update our status
return scheduledResult, nil
}
Setup
最后,更新我们的设置。为了让 reconciler 能按所有者快速查找 Job,需要索引。我们声明一个稍后可与客户端一起用作伪字段名的索引键,然后描述如何从 Job 对象提取索引值。索引器会自动处理命名空间,因此若 Job 有 CronJob 所有者,我们只需提取所有者名称。
此外,我们将告知 manager 此控制器拥有一些 Job,这样当 Job 变更、被删除等时,它会自动对底层 CronJob 调用 Reconcile。
var (
jobOwnerKey = ".metadata.controller"
apiGVStr = batchv1.GroupVersion.String()
)
// SetupWithManager 将控制器与管理器进行设置。
func (r *CronJobReconciler) SetupWithManager(mgr ctrl.Manager) error {
// set up a real clock, since we're not in a test
if r.Clock == nil {
r.Clock = realClock{}
}
if err := mgr.GetFieldIndexer().IndexField(context.Background(), &kbatch.Job{}, jobOwnerKey, func(rawObj client.Object) []string {
// grab the job object, extract the owner...
job := rawObj.(*kbatch.Job)
owner := metav1.GetControllerOf(job)
if owner == nil {
return nil
}
// ...make sure it's a CronJob...
if owner.APIVersion != apiGVStr || owner.Kind != "CronJob" {
return nil
}
// ...and if so, return it
return []string{owner.Name}
}); err != nil {
return err
}
return ctrl.NewControllerManagedBy(mgr).
For(&batchv1.CronJob{}).
Owns(&kbatch.Job{}).
Named("cronjob").
Complete(r)
}
那真是个难题,不过现在我们有了一个可用的控制器。接下来让我们对集群进行测试,如果没有问题,就可以部署了!