Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

改变现状

在Kubernetes API中,相对常见的变化是将一些以前是非结构化或以某种特殊字符串格式存储的数据,改变为结构化数据。我们的 schedule 字段恰好符合这一点 —— 目前在 v1 中,我们的计划看起来是这样的:

日程安排: "*/1 * * * *"

这是一个典型的特殊字符串格式示例(如果你不是一个 Unix 系统管理员,它也相当难以阅读)。

让它更结构化一些。根据 CronJob 代码,它支持「标准」Cron 格式。

在 Kubernetes 中,所有版本必须能安全地相互往返转换。这意味着若从版本 1 转到版本 2,再转回版本 1,不得丢失信息。因此,对 API 的任何变更都必须与 v1 所支持的内容兼容,并且要确保在 v2 添加的任何内容在 v1 中也受支持。有时这意味着需要向 v1 添加新字段,但本例不必,因为你没有添加新功能。

考虑到这些,让我们将上述示例稍微结构化一下:

日程安排:
  分钟: */1

现在,我们至少有了每个字段的标签,但我们仍然可以轻松支持每个字段的不同语法。

此变更需要新的 API 版本。称之为 v2:

kubebuilder create api --group batch --version v2 --kind CronJob

按 y 以继续\

现在,让我们复制我们现有的类型,并进行更改:

project/api/v2/cronjob_types.go
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.

由于我们位于 v2 包中,controller-gen 会自动假定这是针对 v2 版本。我们可以用 +versionName 标记 覆盖。

package v2
Imports
import (
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

// 请编辑本文件!这是供您拥有的脚手架代码!
// 注意:需要 json 标签。新增字段必须带有 json 标签才能被序列化。

我们将大体保持 spec 不变,只是把 schedule 字段改为新类型。

// CronJobSpec 定义 CronJob 的期望状态
type CronJobSpec struct {
	// Cron 格式的调度表达式,参见 https://en.wikipedia.org/wiki/Cron.
	// +required
	Schedule CronSchedule `json:"schedule"`
CronJobSpec Full Code
	// startingDeadlineSeconds 定义若错过计划时间则启动 Job 的秒数截止
	// time for any reason.  Missed jobs executions will be counted as failed ones.
	// +optional
	// +kubebuilder:validation:Minimum=0
	StartingDeadlineSeconds *int64 `json:"startingDeadlineSeconds,omitempty"`

	// concurrencyPolicy defines how to treat concurrent executions of a Job.
	// 有效值为:
	// - "Allow"(默认):允许 CronJob 并发运行;
	// - "Forbid":禁止并发,若上次运行未结束则跳过下次;
	// - "Replace":取消当前运行的 Job 并用新 Job 替换
	// +optional
	// +kubebuilder:default:=Allow
	ConcurrencyPolicy ConcurrencyPolicy `json:"concurrencyPolicy,omitempty"`

	// suspend 告诉控制器暂停后续执行,它
	// 不适用于已开始的执行。默认为 false。
	// +optional
	Suspend *bool `json:"suspend,omitempty"`

	// jobTemplate 定义执行 CronJob 时将创建的 Job。
	// +required
	JobTemplate batchv1.JobTemplateSpec `json:"jobTemplate"`

	// successfulJobsHistoryLimit 定义要保留的成功完成 Job 数量。
	// 使用指针以区分显式零值与未指定。
	// +optional
	// +kubebuilder:validation:Minimum=0
	SuccessfulJobsHistoryLimit *int32 `json:"successfulJobsHistoryLimit,omitempty"`

	// failedJobsHistoryLimit 定义要保留的失败完成 Job 数量。
	// 使用指针以区分显式零值与未指定。
	// +optional
	// +kubebuilder:validation:Minimum=0
	FailedJobsHistoryLimit *int32 `json:"failedJobsHistoryLimit,omitempty"`
}

接下来,我们需要定义一个类型来保存 schedule。根据上面提议的 YAML,它会为每个对应的 Cron「字段」提供一个字段。

// describes a Cron schedule.
type CronSchedule struct {
	// minute specifies the minutes during which the job executes.
	// +optional
	Minute *CronField `json:"minute,omitempty"`
	// hour specifies the hour during which the job executes.
	// +optional
	Hour *CronField `json:"hour,omitempty"`
	// dayOfMonth specifies the day of the month during which the job executes.
	// +optional
	DayOfMonth *CronField `json:"dayOfMonth,omitempty"`
	// month specifies the month during which the job executes.
	// +optional
	Month *CronField `json:"month,omitempty"`
	// dayOfWeek specifies the day of the week during which the job executes.
	// +optional
	DayOfWeek *CronField `json:"dayOfWeek,omitempty"`
}

最后,我们将定义一个包装类型来表示字段。我们可以为此字段附加额外校验,但目前仅用于文档目的。

// represents a Cron field specifier.
type CronField string
Other Types

所有其他类型将保持与之前相同。

// ConcurrencyPolicy 描述如何处理 Job。
// 下列并发策略只能指定其一。
// 若未指定下列任一策略,则默认
// 为 AllowConcurrent。
// +kubebuilder:validation:Enum=Allow;Forbid;Replace
type ConcurrencyPolicy string

const (
	// AllowConcurrent 允许 CronJob 并发运行。
	AllowConcurrent ConcurrencyPolicy = "Allow"

	// ForbidConcurrent 禁止并发运行;若上次
	// 尚未结束则跳过下次运行。
	ForbidConcurrent ConcurrencyPolicy = "Forbid"

	// ReplaceConcurrent 取消当前运行的 Job 并用新 Job 替换。
	ReplaceConcurrent ConcurrencyPolicy = "Replace"
)

// CronJobStatus 定义 CronJob 的观测状态.
type CronJobStatus struct {
	// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
	// Important: Run "make" to regenerate code after modifying this file
	// active 定义指向当前运行 Job 的指针列表。
	// +optional
	// +listType=atomic
	// +kubebuilder:validation:MinItems=1
	// +kubebuilder:validation:MaxItems=10
	Active []corev1.ObjectReference `json:"active,omitempty"`

	// lastScheduleTime defines the information when was the last time the job was successfully scheduled.
	// +optional
	LastScheduleTime *metav1.Time `json:"lastScheduleTime,omitempty"`

	// Kubernetes API 约定参见:
	// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties

	// conditions 表示 CronJob 资源的当前状态。
	// 每个 condition 有唯一类型,反映资源某一方面的状态。
	//
	// Standard condition types include:
	// - "Available": the resource is fully functional
	// - "Progressing": the resource is being created or updated
	// - "Degraded": the resource failed to reach or maintain its desired state
	//
	// The status of each condition is one of True, False, or Unknown.
	// +listType=map
	// +listMapKey=type
	// +optional
	Conditions []metav1.Condition `json:"conditions,omitempty"`
}

// +kubebuilder:object:root=true
// +kubebuilder:subresource:status
// +versionName=v2
// CronJob is the Schema for the cronjobs API
type CronJob struct {
	metav1.TypeMeta `json:",inline"`

	// metadata 是标准对象元数据
	// +optional
	metav1.ObjectMeta `json:"metadata,omitzero"`

	// spec 定义 CronJob 的期望状态
	// +required
	Spec CronJobSpec `json:"spec"`

	// status 定义 CronJob 的观测状态
	// +optional
	Status CronJobStatus `json:"status,omitzero"`
}

// +kubebuilder:object:root=true

// CronJobList 包含一个 CronJob 列表
type CronJobList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitzero"`
	Items           []CronJob `json:"items"`
}

func init() {
	SchemeBuilder.Register(func(s *runtime.Scheme) error {
		s.AddKnownTypes(SchemeGroupVersion, &CronJob{}, &CronJobList{})
		return nil
	})
}

存储版本

project/api/v1/cronjob_types.go
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 v1
Imports
import (
	batchv1 "k8s.io/api/batch/v1"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

// 请编辑本文件!这是供您拥有的脚手架代码!
// 注意:需要 json 标签。新增字段必须带有 json 标签才能被序列化。
Remaining code from cronjob_types.go
// CronJobSpec 定义 CronJob 的期望状态
type CronJobSpec struct {
	// Cron 格式的调度表达式,参见 https://en.wikipedia.org/wiki/Cron.
	// +kubebuilder:validation:MinLength=0
	// +required
	Schedule string `json:"schedule"`

	// startingDeadlineSeconds 定义若错过计划时间则启动 Job 的秒数截止
	// time for any reason.  Missed jobs executions will be counted as failed ones.
	// +optional
	// +kubebuilder:validation:Minimum=0
	StartingDeadlineSeconds *int64 `json:"startingDeadlineSeconds,omitempty"`

	// concurrencyPolicy 指定如何处理 Job 的并发执行。
	// 有效值为:
	// - "Allow"(默认):允许 CronJob 并发运行;
	// - "Forbid":禁止并发,若上次运行未结束则跳过下次;
	// - "Replace":取消当前运行的 Job 并用新 Job 替换
	// +optional
	// +kubebuilder:default:=Allow
	ConcurrencyPolicy ConcurrencyPolicy `json:"concurrencyPolicy,omitempty"`

	// suspend 告诉控制器暂停后续执行,它
	// 不适用于已开始的执行。默认为 false。
	// +optional
	Suspend *bool `json:"suspend,omitempty"`

	// jobTemplate 定义执行 CronJob 时将创建的 Job。
	// +required
	JobTemplate batchv1.JobTemplateSpec `json:"jobTemplate"`

	// successfulJobsHistoryLimit 定义要保留的成功完成 Job 数量。
	// 使用指针以区分显式零值与未指定。
	// +optional
	// +kubebuilder:validation:Minimum=0
	SuccessfulJobsHistoryLimit *int32 `json:"successfulJobsHistoryLimit,omitempty"`

	// failedJobsHistoryLimit 定义要保留的失败完成 Job 数量。
	// 使用指针以区分显式零值与未指定。
	// +optional
	// +kubebuilder:validation:Minimum=0
	FailedJobsHistoryLimit *int32 `json:"failedJobsHistoryLimit,omitempty"`
}

// ConcurrencyPolicy 描述如何处理 Job。
// 下列并发策略只能指定其一。
// 若未指定下列任一策略,则默认
// 为 AllowConcurrent。
// +kubebuilder:validation:Enum=Allow;Forbid;Replace
type ConcurrencyPolicy string

const (
	// AllowConcurrent 允许 CronJob 并发运行。
	AllowConcurrent ConcurrencyPolicy = "Allow"

	// ForbidConcurrent 禁止并发运行;若上次
	// 尚未结束则跳过下次运行。
	ForbidConcurrent ConcurrencyPolicy = "Forbid"

	// ReplaceConcurrent 取消当前运行的 Job 并用新 Job 替换。
	ReplaceConcurrent ConcurrencyPolicy = "Replace"
)

// CronJobStatus 定义 CronJob 的观测状态.
type CronJobStatus struct {
	// 插入额外的状态字段 - 定义集群的观察状态
	// 重要:在修改此文件后,请运行 "make" 以重新生成代码

	// active 定义指向当前运行 Job 的指针列表。
	// +optional
	// +listType=atomic
	// +kubebuilder:validation:MinItems=1
	// +kubebuilder:validation:MaxItems=10
	Active []corev1.ObjectReference `json:"active,omitempty"`

	// lastScheduleTime 定义 Job 上次成功调度的时间。
	// +optional
	LastScheduleTime *metav1.Time `json:"lastScheduleTime,omitempty"`

	// Kubernetes API 约定参见:
	// https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md#typical-status-properties

	// conditions 表示 CronJob 资源的当前状态。
	// 每个 condition 有唯一类型,反映资源某一方面的状态。
	//
	// Standard condition types include:
	// - "Available": the resource is fully functional
	// - "Progressing": the resource is being created or updated
	// - "Degraded": the resource failed to reach or maintain its desired state
	//
	// The status of each condition is one of True, False, or Unknown.
	// +listType=map
	// +listMapKey=type
	// +optional
	Conditions []metav1.Condition `json:"conditions,omitempty"`
}

由于将有多个版本,我们需要标记一个存储版本。这是 Kubernetes API 服务器用来存储数据的版本。本项目选择 v1 版本。

我们将使用 +kubebuilder:storageversion 来完成此事。

注意:若对象在存储版本变更前已写入,存储中可能仍存在多个版本——更改存储版本仅影响变更之后创建/更新对象的方式。

// +kubebuilder:object:root=true
// +kubebuilder:storageversion
// +kubebuilder:subresource:status
// +versionName=v1
// +kubebuilder:storageversion
// CronJob is the Schema for the cronjobs API
type CronJob struct {
	metav1.TypeMeta `json:",inline"`

	// metadata 是标准对象元数据
	// +optional
	metav1.ObjectMeta `json:"metadata,omitzero"`

	// spec 定义 CronJob 的期望状态
	// +required
	Spec CronJobSpec `json:"spec"`

	// status 定义 CronJob 的观测状态
	// +optional
	Status CronJobStatus `json:"status,omitzero"`
}
Remaining code from cronjob_types.go
// +kubebuilder:object:root=true

// CronJobList 包含一个 CronJob 列表
type CronJobList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata,omitzero"`
	Items           []CronJob `json:"items"`
}

func init() {
	SchemeBuilder.Register(func(s *runtime.Scheme) error {
		s.AddKnownTypes(SchemeGroupVersion, &CronJob{}, &CronJobList{})
		return nil
	})
}

现在我们已经确定了类型,我们需要设置转换…