Kubernetes 新玩法:在 yaml 中编程

头图.png

作者 | 悟鹏

引子

性能测试在日常的开发工作中是常规需求,用来摸底服务的性能。

那么如何做性能测试?要么是通过编码的方式完成,写一堆脚本,用完即弃;要么是基于平台,在平台定义的流程中进行。对于后者,通常由于目标场景的复杂性,如部署特定的 workload、观测特定的性能项、网络访问问题等,往往导致性能测试平台要以高成本才能满足不断变化的开发场景的需求。

在云原生的背景下,是否可以更好解决这种问题?

先看两个 yaml 文件:

  • performance-test.yaml 描述了在 K8s 中的操作流程:

    1. 创建测试用的 Namespace
    2. 启动针对 Deployment 创建效率和创建成功率的监控
    3. 下述动作重复 N 次:① 使用 workload 模板创建 Deployment;② 等待 Deployment 变为 Ready
    4. 删除测试用的 Namespace
  • basic-1-pod-deployment.yaml 描述使用的 workload 模板

performance-test.yaml :

1apiVersion: aliyun.com/v1alpha1 2kind: Beidou 3metadata: 4 name: performance 5 namespace: beidou 6spec: 7 steps: 8 - name: "Create Namespace If Not Exits" 9 operations: 10 - name: "create namespace" 11 type: Task 12 op: CreateNamespace 13 args: 14 - name: NS 15 value: beidou 16 - name: "Monitor Deployment Creation Efficiency" 17 operations: 18 - name: "Begin To Monitor Deployment Creation Efficiency" 19 type: Task 20 op: DeploymentCreationEfficiency 21 args: 22 - name: NS 23 value: beidou 24 - name: "Repeat 1 Times" 25 type: Task 26 op: RepeatNTimes 27 args: 28 - name: TIMES 29 value: "1" 30 - name: ACTION 31 reference: 32 id: deployment-operation 33 - name: "Delete namespace" 34 operations: 35 - name: "delete namespace" 36 type: Task 37 op: DeleteNamespace 38 args: 39 - name: NS 40 value: beidou 41 - name: FORCE 42 value: "false" 43 references: 44 - id: deployment-operation 45 steps: 46 - name: "Prepare Deployment" 47 operations: 48 - name: "Prepare Deployment" 49 type: Task 50 op: PrepareBatchDeployments 51 args: 52 - name: NS 53 value: beidou 54 - name: NODE_TYPE 55 value: ebm 56 - name: BATCH_NUM 57 value: "1" 58 - name: TEMPLATE 59 value: "./templates/basic-1-pod-deployment.yaml" 60 - name: DEPLOYMENT_REPLICAS 61 value: "1" 62 - name: DEPLOYMENT_PREFIX 63 value: "ebm" 64 - name: "Wait For Deployments To Be Ready" 65 type: Task 66 op: WaitForBatchDeploymentsReady 67 args: 68 - name: NS 69 value: beidou 70 - name: TIMEOUT 71 value: "3m" 72 - name: CHECK_INTERVAL 73 value: "2s"

basic-1-pod-deployment.yaml:

1apiVersion: apps/v1 2kind: Deployment 3metadata: 4 labels: 5 app: basic-1-pod 6spec: 7 selector: 8 matchLabels: 9 app: basic-1-pod 10 template: 11 metadata: 12 labels: 13 app: basic-1-pod 14 spec: 15 containers: 16 - name: nginx 17 image: registry-vpc.cn-hangzhou.aliyuncs.com/xxx/nginx:1.17.9 18 imagePullPolicy: Always 19 resources: 20 limits: 21 cpu: 2 22 memory: 4Gi

然后通过一个命令行工具执行 performance-test.yaml:

$ beidou server -c ~/.kube/config services/performance-test.yaml

执行效果如下 (每个 Deployment 创建耗时,所有 Deployment 创建耗时的 TP95 值,每个 Deployment 是否创建成功):

1.png

这些 metrics 是按照 Prometheus 标准输出,可以被 Prometheus server 收集走,再结合 Grafana 可以可视化展示性能测试数据。

通过在 yaml 中表达想法,编排对 K8s 资源的操作、监控,再也不用为性能测试的实现头疼了 :D

为什么要在 yaml 中编程?

性能测试、回归测试等对于服务质量保障有很大帮助,需要做,但常规的实现方法在初期需要投入较多的时间和精力,新增变更后维护成本比较高。

通常这个过程是以代码的方式实现原子操作,如创建 Deployment、检测 Pod 配置等,然后再组合原子操作来满足需求,如 创建 Deployment -> 等待 Deployment ready -> 检测 Pod 配置等。

有没有办法在实现的过程中既可以尽量低成本实现,又可以复用已有的经验?

可以将原子操作封装为原语,如 CreateDeployment、CheckPod,再通过 yaml 的结构表达流程,那么就可以通过 yaml 而非代码的方式描述想法,又可以复用他人已经写好的 yaml 文件来解决某类场景的需求。

即在 yaml 中编程,减少重复性代码工作,通过 声明式 的方式描述逻辑,并以 yaml 文件来满足场景级别的复用。

业界有很多种类型的 声明式操作 服务,如运维领域中的 AnsibleSaltStack,Kubernetes 中的Argo Workflowclusterloader2。它们的思想整体比较类似,将高频使用的操作封装为原语,使用者通过原语来表述操作逻辑。

通过声明式的方法,将面向 K8s 的操作抽象成 yaml 中的关键词,在 yaml 中提供串行、并行等控制逻辑,那么就可以通过 yaml 文件完整描述想要进行的工作。

这种思想和 Argo Workflow 比较像,但粒度比 Argo 更细,关注在操作函数上:

2.png

下面简单描述该服务的设计和实现。

设计和实现

1. 服务形态

  • 使用者在 yaml 中,通过 声明式 的方式描述操作逻辑;
  • 以 all-in-one 的二进制工具或 Operator 的方式交付;
  • 服务内置常见原语的实现,以关键字的方式在 yaml 中提供;
  • 支持配置原生 K8s 资源。

2. 设计

该方案的核心在于配置管理的设计,将操作流程配置化,自上而下有如下概念:

  • Service:Modules 或 Tasks 的编排;

  • Module:一种任务场景,是操作单元的集合(其中包含 templates/ 目录,表征模板文件的集合,可用来配置 K8s 原生资源);  

  • Task:操作单元,使用 plugin 及参数执行操作;  

  • Plugin:操作指令,类似开发语言中的函数。

抽象目标场景中的通用操作,这些通用操作即为可在 yaml 中使用的原语,对应上述 Plugin:

  • K8s 相关

    • CreateNamespace
    • DeleteNamespace
    • PrepareSecret
    • PrepareConfigMap
    • PrepareBatchDeployments
    • WaitForBatchDeploymentsReady
    • etc.
  • 观测性相关

    • DeploymentCreationEfficiency
    • PodCreationEfficiency
    • etc.
  • 检测项相关

    • CheckPodAnnotations
    • CheckPodObjectInfo
    • CheckPodInnerStates
    • etc.
  • 控制语句相关

    • RepeatNTimes
    • etc.

上述 4 个概念的关系如下:

3.png

示例可参见文章开头的 yaml 文件,对应形式二。

3. 核心实现

CRD 设计:

1package v1alpha1 2 3import ( 4 corev1 "k8s.io/api/core/v1" 5 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 6) 7 8// BeidouType is the type related to Beidou execution. 9type BeidouType string 10 11const ( 12 // BeidouTask represents the Task execution type. 13 BeidouTask BeidouType = "Task" 14) 15 16// +genclient 17// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object 18 19// Beidou represents a crd used to describe serices. 20type Beidou struct { 21 metav1.TypeMeta `json:",inline"` 22 metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"` 23 24 Spec BeidouSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"` 25 Status BeidouStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"` 26} 27 28// BeidouSpec is the spec of a Beidou. 29type BeidouSpec struct { 30 Steps []BeidouStep `json:"steps" protobuf:"bytes,1,opt,name=steps"` 31 References []BeidouReference `json:"references" protobuf:"bytes,2,opt,name=references"` 32} 33 34// BeidouStep is the spec of step. 35type BeidouStep struct { 36 Name string `json:"name" protobuf:"bytes,1,opt,name=name"` 37 Operations []BeidouOperation `json:"operations" protobuf:"bytes,2,opt,name=operations"` 38} 39 40// BeidouOperation is the spec of operation. 41type BeidouOperation struct { 42 Name string `json:"name" protobuf:"bytes,1,opt,name=name"` 43 Type BeidouType `json:"type" protobuf:"bytes,2,opt,name=type"` 44 Op string `json:"op" protobuf:"bytes,3,opt,name=op"` 45 Args []BeidouArg `json:"args" protobuf:"bytes,4,opt,name=args"` 46} 47 48// BeidouArg is the spec of arg. 49type BeidouArg struct { 50 Name string `json:"name" protobuf:"bytes,1,opt,name=name"` 51 Value string `json:"value,omitempty" protobuf:"bytes,2,opt,name=value"` 52 Reference BeidouOperationReference `json:"reference,omitempty" protobuf:"bytes,3,opt,name=reference"` 53 Tolerations []corev1.Toleration `json:"tolerations,omitempty" protobuf:"bytes,4,opt,name=tolerations"` 54 Checking []string `json:"checking,omitempty" protobuf:"bytes,5,opt,name=checking"` 55} 56 57// BeidouOperationReference is the spec of operation reference. 58type BeidouOperationReference struct { 59 ID string `json:"id" protobuf:"bytes,1,opt,name=id"` 60} 61 62// BeidouReference is the spec of reference. 63type BeidouReference struct { 64 ID string `json:"id" protobuf:"bytes,1,opt,name=id"` 65 Steps []BeidouStep `json:"steps" protobuf:"bytes,2,opt,name=steps"` 66} 67 68// BeidouStatus represents the current state of a Beidou. 69type BeidouStatus struct { 70 Message string `json:"message" protobuf:"bytes,1,opt,name=message"` 71} 72 73// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object 74 75// BeidouList is a collection of Beidou. 76type BeidouList struct { 77 metav1.TypeMeta `json:",inline"` 78 metav1.ListMeta `json:"metadata" protobuf:"bytes,1,opt,name=metadata"` 79 80 Items []Beidou `json:"items" protobuf:"bytes,2,opt,name=items"` 81}

核心流程:

1// ExecSteps executes steps. 2func ExecSteps(ctx context.Context, steps []v1alpha1.BeidouStep, references []v1alpha1.BeidouReference) error { 3 logger, _ := ctx.Value(CtxLogger).(*log.Entry) 4 5 var hasMonitored bool 6 for i, step := range steps { 7 for j, op := range step.Operations { 8 switch op.Op { 9 case "DeploymentCreationEfficiency": 10 if !hasMonitored { 11 defer func() { 12 err := monitor.Output() 13 if err != nil { 14 logger.Errorf("Failed to output: %s", err) 15 } 16 }() 17 } 18 hasMonitored = true 19 } 20 21 err := ExecOperation(ctx, op, references) 22 if err != nil { 23 return fmt.Errorf("failed to run operation %s: %s", op.Name, err) 24 } 25 } 26 } 27 28 return nil 29} 30 31// ExecOperation executes operation. 32func ExecOperation(ctx context.Context, op v1alpha1.BeidouOperation, references []v1alpha1.BeidouReference) error { 33 switch op.Type { 34 case v1alpha1.BeidouTask: 35 if !tasks.IsRegistered(op.Op) { 36 return ErrNotRegistered 37 } 38 39 if !tasks.DoesSupportReference(op.Op) { 40 return ExecTask(ctx, op.Op, op.Args) 41 } 42 43 return ExecTaskWithRefer(ctx, op.Op, op.Args, references) 44 } 45 46 return nil 47} 48 49// ExecTask executes a task. 50func ExecTask(ctx context.Context, opname string, args []v1alpha1.BeidouArg) error { 51 switch opname { 52 case tasks.CreateNamespace: 53 var ns string 54 for _, arg := range args { 55 switch arg.Name { 56 case "NS": 57 ns = arg.Value 58 } 59 } 60 61 return op.CreateNamespace(ctx, ns) 62 // ... 63 } 64 // ... 65} 66 67// ExecTaskWithRefer executes a task with reference. 68func ExecTaskWithRefer(ctx context.Context, opname string, args []v1alpha1.BeidouArg, references []v1alpha1.BeidouReference) error { 69 switch opname { 70 case tasks.RepeatNTimes: 71 var times int 72 var steps []v1alpha1.BeidouStep 73 var err error 74 for _, arg := range args { 75 switch arg.Name { 76 case "TIMES": 77 times, err = strconv.Atoi(arg.Value) 78 if err != nil { 79 return ErrParseArgs 80 } 81 case "ACTION": 82 for _, refer := range references { 83 if refer.ID == arg.Reference.ID { 84 steps = refer.Steps 85 break 86 } 87 } 88 } 89 } 90 91 return RepeatNTimes(ctx, times, steps) 92 } 93 94 return ErrNotImplemented 95}

操作原语的实现示例:

1// PodAnnotations is an operation used to check whether annotations of Pod are expected. 2func PodAnnotations(ctx context.Context, data PodAnnotationsData) error { 3 kclient, ok := ctx.Value(tasks.KubernetesClient).(kubernetes.Interface) 4 if !ok { 5 return tasks.ErrNoKubernetesClient 6 } 7 8 pods, err := kclient.CoreV1().Pods(data.Namespace).List(metav1.ListOptions{}) 9 if err != nil { 10 return fmt.Errorf("failed to list pods in ns %s: %s", data.Namespace, err) 11 } 12 13 for _, pod := range pods.Items { 14 if pod.Annotations == nil { 15 return fmt.Errorf("pod %s in ns %s has no annotations", pod.Name, data.Namespace) 16 } 17 18 for _, annotation := range data.Exists { 19 if _, exists := pod.Annotations[annotation]; !exists { 20 return fmt.Errorf("annotation %s does not exist in pod %s in ns %s", annotation, pod.Name, data.Namespace) 21 } 22 } 23 24 for k, v := range data.Equal { 25 if pod.Annotations[k] != v { 26 return fmt.Errorf("value of annotation %s is not %s in pod %s in ns %s", k, v, pod.Name, data.Namespace) 27 } 28 } 29 } 30 31 return nil 32}

后续

目前阿里云容器服务团队内部已经实现了初版,已用于部分云产品的内部性能测试以及常规的回归测试,很大程度上提升了我们的工作效率。

在 yaml 中编程,是对云原生场景下声明式操作的体现,也是对声明式服务的一种实践。对于常规工作场景中重复编码或重复操作,可考虑类似的方式进行满足。

欢迎大家对这样的服务形态和项目进行讨论,探索这种模式的价值。

阿里云容器服务持续招聘,欢迎加入我们,一起在 K8s、边缘计算、Serverless 等领域开拓,让当前变得更美好,也为未来带来可能性!联系邮箱:flyer.zyf@alibaba-inc.com

Spring Cloud Alibaba 七天训练营

七天时间了解微服务各模块的实现原理,手把手教学如何独立开发一个微服务应用,助力小白开发者从 0 到 1 建立系统化的知识体系。点击链接即可报名体验:https://developer.aliyun.com/learning/trainingcamp/spring/1

阿里巴巴云原生关注微服务、Serverless、容器、Service Mesh 等技术领域、聚焦云原生流行技术趋势、云原生大规模的落地实践,做最懂云原生开发者的公众号。”

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )