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和任何操作器的核心。

控制器的职责是确保对于任何给定的对象,实际的世界状态(包括集群状态以及可能的外部状态,例如 Kubelet 的运行容器或云服务提供商的负载均衡器)与对象中的期望状态相匹配。每个控制器专注于一个_根_ Kind,但可能与其他 Kind 进行交互。

我们称这个过程为 调整。

在 controller-runtime 中,实现特定种类的对账逻辑的部分称为 Reconciler。一个 reconciler 接收一个对象的名称,并返回是否需要重新尝试(例如,在出现错误或周期性控制器的情况下,如水平 Pod 自动缩放器)。

emptycontroller.go
Apache License

Copyright 2022.

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.

先从标准导入开始。与之前一样,需要核心 controller-runtime 库、client 包,以及 API 类型包。

package controllers

import (
	"context"

	"k8s.io/apimachinery/pkg/runtime"
	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"
)

接下来,kubebuilder 已为我们脚手架生成基本的 reconciler 结构体。几乎每个 reconciler 都需要日志并能获取对象,因此这些已开箱即加。

// CronJobReconciler 协调 CronJob 对象
type CronJobReconciler struct {
	client.Client
	Scheme *runtime.Scheme
}

大多数控制器最终会在集群上运行,因此需要 RBAC 权限,我们用 controller-tools RBAC 标记 指定。这些是运行所需的最低权限。随着功能增加,我们需要再审视它们。

// +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

config/rbac/role.yaml 中的 ClusterRole 清单由上述标记经 controller-gen 用以下命令生成:

make manifests

注意:若收到错误,请运行错误中给出的命令,然后重新执行 make manifests。

Reconcile 实际对单个具名对象执行协调。我们的 Request 只有名称,但可用 client 从缓存获取该对象。

我们返回空结果且无错误,这向 controller-runtime 表明已成功协调该对象,在出现变更前无需重试。

多数控制器需要日志句柄与 context,因此在此设置。

context 用于允许取消请求,以及可能的追踪等。它是所有客户端方法的第一个参数。Background context 只是没有额外数据或时间限制的基本 context。

日志句柄让我们记录日志。controller-runtime 通过名为 logr 的库使用结构化日志。稍后会看到,日志通过向静态消息附加键值对工作。我们可以在 reconcile 方法顶部预分配一些键值对,使它们附加到此 reconciler 的所有日志行。

func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	_ = logf.FromContext(ctx)

	// 在此编写逻辑

	return ctrl.Result{}, nil
}

最后把该 reconciler 加入 manager,以便 manager 启动时一并启动。

目前只标明该 reconciler 操作 CronJob。稍后会用此标记我们也关心相关对象。

func (r *CronJobReconciler) SetupWithManager(mgr ctrl.Manager) error {
	return ctrl.NewControllerManagedBy(mgr).
		For(&batchv1.CronJob{}).
		Complete(r)
}

现在我们已经看到了 reconciler 的基本结构,让我们来完善 CronJob 的逻辑。