Kubernetes Operators 是一种用于自动化运维的模式,它结合了 Kubernetes 自定义资源和控制器来管理应用程序和服务。Operators 扩展了 Kubernetes API,并利用控制循环来管理应用的生命周期,从而实现复杂的自动化运维任务。

 

什么是 Kubernetes Operators

Operators 是一个用于管理复杂应用程序的 Kubernetes 模式,它定义了以下内容:

Operators 利用这两部分,持续监控和维护应用程序的状态,确保其始终处于期望的状态。

 

Operators 的工作原理

Operators 的核心是控制器,它遵循控制循环模式:

  1. 观察(Observe):控制器通过 Kubernetes API 监控自定义资源对象的状态。
  2. 分析(Analyze):控制器比较当前状态和期望状态。
  3. 行动(Act):如果发现差异,控制器会执行相应的操作,使实际状态匹配期望状态。

     

创建一个简单的 Operator

以下是创建一个简单 Operator 的步骤:

 

1. 安装 Operator SDK

Operator SDK 提供了一些工具和库来帮助开发 Operators。

curl -LO https://github.com/operator-framework/operator-sdk/releases/download/v1.8.0/operator-sdk_linux_amd64
chmod +x operator-sdk_linux_amd64
mv operator-sdk_linux_amd64 /usr/local/bin/operator-sdk

 

2. 创建新项目

使用 Operator SDK 创建一个新的 Operator 项目:

operator-sdk init --domain=example.com --repo=github.com/example/memcached-operator

 

3. 创建 API 和控制器

生成自定义资源定义(CRD)和控制器代码:

operator-sdk create api --group cache --version v1alpha1 --kind Memcached --resource --controller

 

4. 定义自定义资源

编辑 api/v1alpha1/memcached_types.go 文件,定义自定义资源的 Spec 和 Status:

type MemcachedSpec struct {
	// Size is the size of the memcached deployment
	Size int32 `json:"size"`
}
type MemcachedStatus struct {
	// Nodes are the names of the memcached pods
	Nodes []string `json:"nodes"`
}

 

5. 实现控制器逻辑

在 controllers/memcached_controller.go 中,实现控制器逻辑:

func (r *MemcachedReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
	// Fetch the Memcached instance
	memcached := &cachev1alpha1.Memcached{}
	err := r.Get(ctx, req.NamespacedName, memcached)
	if err != nil {
		if errors.IsNotFound(err) {
			// Memcached resource not found. Ignore since object must be deleted.
			return ctrl.Result{}, nil
		}
		// Error reading the object - requeue the request.
		return ctrl.Result{}, err
	}
	// Define the desired Deployment
	dep := r.deploymentForMemcached(memcached)
	// Set Memcached instance as the owner and controller
	if err := ctrl.SetControllerReference(memcached, dep, r.Scheme); err != nil {
		return ctrl.Result{}, err
	}
	// Check if the Deployment already exists, if not create a new one
	found := &appsv1.Deployment{}
	err = r.Get(ctx, types.NamespacedName{Name: dep.Name, Namespace: dep.Namespace}, found)
	if err != nil && errors.IsNotFound(err) {
		log.Info("Creating a new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
		err = r.Create(ctx, dep)
		if err != nil {
			return ctrl.Result{}, err
		}
		// Deployment created successfully - return and requeue
		return ctrl.Result{Requeue: true}, nil
	} else if err != nil {
		return ctrl.Result{}, err
	}
	// Ensure the deployment size is the same as the spec
	size := memcached.Spec.Size
	if *found.Spec.Replicas != size {
		found.Spec.Replicas = &size
		err = r.Update(ctx, found)
		if err != nil {
			return ctrl.Result{}, err
		}
	}
	// Update the Memcached status with the pod names
	// List the pods for this memcached's deployment
	podList := &corev1.PodList{}
	listOpts := []client.ListOption{
		client.InNamespace(memcached.Namespace),
		client.MatchingLabels(labelsForMemcached(memcached.Name)),
	}
	if err = r.List(ctx, podList, listOpts...); err != nil {
		return ctrl.Result{}, err
	}
	podNames := getPodNames(podList.Items)
	// Update status.Nodes if needed
	if !reflect.DeepEqual(podNames, memcached.Status.Nodes) {
		memcached.Status.Nodes = podNames
		err = r.Status().Update(ctx, memcached)
		if err != nil {
			return ctrl.Result{}, err
		}
	}
	return ctrl.Result{}, nil
}

 

6. 部署 CRD 和 Operator

使用 Makefile 构建并部署 CRD 和 Operator:

make install
make run

 

7. 创建自定义资源实例

创建一个 Memcached 实例:

apiVersion: cache.example.com/v1alpha1
kind: Memcached
metadata:
  name: memcached-sample
spec:
  size: 3

 

应用此资源:

kubectl apply -f config/samples/cache_v1alpha1_memcached.yaml

 

高级功能

Operators 可以实现更复杂的功能,如:

  • 自动备份和恢复:管理数据库的备份和恢复任务。
  • 滚动升级:确保应用在升级过程中的可用性。
  • 自愈:检测并恢复故障状态的应用。
  • 扩展:根据负载自动扩展或缩减资源。

     

社区和现有 Operators

Kubernetes 社区提供了许多现成的 Operators,可以用于常见应用的管理。可以在 OperatorHub 上找到并部署这些 Operators。

 

总结

Operators 是 Kubernetes 中强大的自动化运维工具,能够通过自定义资源和控制器扩展 Kubernetes 的能力,管理复杂的应用生命周期。利用 Operators,可以实现高效、可靠的自动化运维,提升应用的稳定性和可维护性。