如何在Kubernetes 里添加自定义的 API 对象(一)

环境:

golang 1.15 依赖包采用go module

实例:现在往 Kubernetes 添加一个名叫 Network 的 API 资源类型。它的作用是,一旦用户创建一个 Network 对象,那么 Kubernetes 就应该使用这个对象定义的网络参数,调用真实的网络插件,为用户创建一个真正的“网络”。这样,将来用户创建的 Pod,就可以声明使用这个“网络”了。

结构如下:

MacBook-Pro kubernetes % tree k8s-controller-custom-resource -L 5

├── go.mod
├── hack
│   ├── boilerplate.go.txt
│   ├── tools.go
│   └── update-codegen.sh
├── pkg
│   └── apis
│       └── samplecrd
│           ├── register.go
│           └── v1
│               ├── doc.go
│               ├── register.go
│               └── types.go

1、初始化项目

#创建目录
$ mkdir k8s-controller-custom-resource && cd k8s-controller-custom-resource
#初始化项目,生成go.mod文件
$ go mod init k8s-controller-custom-resource
# 获取依赖
$ go get k8s.io/apimachinery@v0.0.0-20190425132440-17f84483f500
$ go get k8s.io/client-go@v0.0.0-20190425172711-65184652c889
$ go get k8s.io/code-generator@v0.0.0-20190419212335-ff26e7842f9d

2、初始化crd资源类型

在初始化了项目后,需要建立好自己的crd struct,然后使用code-generator生成我们的代码.

mkdir -p pkg/apis/samplecrd/v1 && cd pkg/apis/samplecrd

其中,pkg/apis/samplecrd 就是 API 组的名字,v1 是版本。

然后,我在 pkg/apis/samplecrd 目录下创建了一个 register.go 文件,用来放置后面要用到的全局变量。这个文件的内容如下所示:


package samplecrd

const (
 GroupName = "samplecrd.k8s.io"
 Version   = "v1"
)

接着,我需要在 pkg/apis/samplecrd/v1 目录下添加一个 doc.go 文件(Golang 的文档源文件)。这个文件里的内容如下所示:


// +k8s:deepcopy-gen=package

// +groupName=samplecrd.k8s.io
package v1

在这个文件中,你会看到 +<tag_name>[=value]格式的注释,这就是 Kubernetes 进行代码生成要用的 Annotation 风格的注释。其中,+k8s:deepcopy-gen=package 意思是,请为整个 v1 包里的所有类型定义自动生成 DeepCopy 方法;而+groupName=samplecrd.k8s.io,则定义了这个包对应的 API 组的名字。可以看到,这些定义在 doc.go 文件的注释,起到的是全局的代码生成控制的作用,所以也被称为 Global Tags。 

接下来,我需要添加 types.go 文件。顾名思义,它的作用就是定义一个 Network 类型到底有哪些字段(比如,spec 字段里的内容)。这个文件的主要内容如下所示:

package v1

import (
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

// +genclient
// +genclient:noStatus
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// Network describes a Network resource
type Network struct {
	// TypeMeta is the metadata for the resource, like kind and apiversion
	metav1.TypeMeta `json:",inline"`
	// ObjectMeta contains the metadata for the particular object, including
	// things like...
	//  - name
	//  - namespace
	//  - self link
	//  - labels
	//  - ... etc ...
	metav1.ObjectMeta `json:"metadata,omitempty"`

	// Spec is the custom resource spec
	Spec NetworkSpec `json:"spec"`
}

// NetworkSpec is the spec for a Network resource
type NetworkSpec struct {
	// Cidr and Gateway are example custom spec fields
	//
	// this is where you would put your custom resource data
	Cidr    string `json:"cidr"`
	Gateway string `json:"gateway"`
}

// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object

// NetworkList is a list of Network resources
type NetworkList struct {
	metav1.TypeMeta `json:",inline"`
	metav1.ListMeta `json:"metadata"`

	Items []Network `json:"items"`
}

最后,我需要再编写一个 pkg/apis/samplecrd/v1/register.go 文件。

package v1

import (
	"k8s-controller-custom-resource/pkg/apis/samplecrd"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"

	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/runtime/schema"
)

// GroupVersion is the identifier for the API which includes
// the name of the group and the version of the API
var SchemeGroupVersion = schema.GroupVersion{
	Group:   samplecrd.GroupName,
	Version: samplecrd.Version,
}

// addKnownTypes adds our types to the API scheme by registering
// Network and NetworkList
func addKnownTypes(scheme *runtime.Scheme) error {
	scheme.AddKnownTypes(
		SchemeGroupVersion,
		&Network{},
		&NetworkList{},
	)

	// register the type in the scheme
	metav1.AddToGroupVersion(scheme, SchemeGroupVersion)
	return nil
}

这样,Network 对象的定义工作就全部完成了。可以看到,它其实定义了两部分内容:

第一部分是,自定义资源类型的 API 描述,包括:组(Group)、版本(Version)、资源类型(Resource)等。

第二部分是,自定义资源类型的对象描述,包括:Spec、Status 等。 

3、使用 Kubernetes 提供的代码生成工具,为上面定义的 Network 资源类型自动生成 clientset、informer 和 lister。

生成代码主要为下一章的controller使用。其中,clientset 就是操作 Network 对象所需要使用的客户端,而 informer 和 lister 这两个包的主要功能,我会在下一篇文章中重点讲解。这个代码生成工具名叫k8s.io/code-generator,使用方法如下所示:

  • 在项目跟路径创建目录
mkdir hack && cd hack
  • 建立tools.go来依赖code-generator,因为在没有代码使用code-generator时,go module 默认不会为我们依赖此包
// +build tools

/*
Copyright 2019 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.
*/

// This package imports things required by build scripts, to force `go mod` to see them as dependencies
package tools

import _ "k8s.io/code-generator"
  • 编写构建脚本:update-codegen.sh
#!/usr/bin/env bash

# Copyright 2017 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.

set -o errexit
set -o nounset
set -o pipefail

# generate the code with:
# --output-base    because this script should also be able to run inside the vendor dir of
#                  k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir
#                  instead of the $GOPATH directly. For normal projects this can be dropped.
../vendor/k8s.io/code-generator/generate-groups.sh \
  "deepcopy,client,informer,lister" \
  k8s-controller-custom-resource/pkg/client \
  k8s-controller-custom-resource/pkg/apis \
  samplecrd:v1 \
  --go-header-file $(pwd)/boilerplate.go.txt \
  --output-base $(pwd)/../../ 

  • 在构建api时,我们还提供了文件头,所以我们在此也创建文件头:boilerplate.go.txt
/*
Copyright 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.
*/
  • 生成代码
# 生成vendor文件夹
$ go mod vendor
# 进入项目根目录,为vendor中的code-generator赋予权限
$ chmod -R 777 vendor
# 调用脚本生成代码
MacBook-Pro hack % ./update-codegen.sh
Generating deepcopy funcs
Generating clientset for samplecrd:v1 at k8s-controller-custom-resource/pkg/client/clientset
Generating listers for samplecrd:v1 at k8s-controller-custom-resource/pkg/client/listers
Generating informers for samplecrd:v1 at k8s-controller-custom-resource/pkg/client/informers

代码生成工作完成之后,我们再查看一下这个项目的目录结构:

├── go.mod
├── go.sum
├── hack
│   ├── boilerplate.go.txt
│   ├── tools.go
│   └── update-codegen.sh
├── pkg
│   ├── apis
│   │   └── samplecrd
│   │       ├── register.go
│   │       └── v1
│   │           ├── doc.go
│   │           ├── register.go
│   │           ├── types.go
│   │           └── zz_generated.deepcopy.go
│   └── client
│       ├── clientset
│       ├── informers
│       └── listers

 其中,pkg/apis/samplecrd/v1 下面的 zz_generated.deepcopy.go 文件,就是自动生成的 DeepCopy 代码文件。而整个 client 目录,以及下面的三个包(clientset、informers、 listers),都是 Kubernetes 为 Network 类型生成的客户端库,这些库会在后面编写自定义控制器的时候用到。

4、在 Kubernetes 集群里创建一个 Network 类型的 API 对象

  • 创建CRD yaml文件:network.yaml

apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
  name: networks.samplecrd.k8s.io
spec:
  group: samplecrd.k8s.io
  version: v1
  names:
    kind: Network
    plural: networks
  scope: Namespaced

然后在k8s中创建crd,这个操作,就告诉了 Kubernetes,我现在要添加一个自定义的 API 对象。而这个对象的 API 信息,正是 network.yaml 里定义的内容。我们可以通过 kubectl get 命令,查看这个 CRD:

MacBook-Pro k8s-controller-custom-resource % k8sdev apply -f crd/network.yaml
customresourcedefinition.apiextensions.k8s.io/networks.samplecrd.k8s.io created

MacBook-Pro k8s-controller-custom-resource % k8sdev get crd
NAME                                  CREATED AT
networks.samplecrd.k8s.io             2022-02-14T08:50:46Z
  • 创建Network 对象的 YAML 文件,名叫 example-network.yaml

apiVersion: samplecrd.k8s.io/v1
kind: Network
metadata:
  name: example-network
spec:
  cidr: "192.168.0.0/16"
  gateway: "192.168.0.1"

在k8s中创建 Network 对象

MacBook-Pro k8s-controller-custom-resource % k8sdev apply -f example/example-network.yaml
network.samplecrd.k8s.io/example-network created

通过这个操作,就在 Kubernetes 集群里创建了一个 Network 对象。它的 API 资源路径是samplecrd.k8s.io/v1/networks。

这时候,你就可以通过 kubectl get 命令,查看到新创建的 Network 对象:

MacBook-Pro k8s-controller-custom-resource % k8sdev get network
NAME              AGE
example-network   69s

你还可以通过 kubectl describe 命令,看到这个 Network 对象的细节:

MacBook-Pro k8s-controller-custom-resource % k8sdev describe network  example-network
Name:         example-network
Namespace:    default
Labels:       <none>
Annotations:  <none>
API Version:  samplecrd.k8s.io/v1
Kind:         Network
Metadata:
  Creation Timestamp:  2022-02-14T08:57:58Z
  Generation:          1
  Resource Version:    34001215910
  Self Link:           /apis/samplecrd.k8s.io/v1/namespaces/default/networks/example-network
  UID:                 d2a3b4d8-4000-473d-976e-cf6acb050942
Spec:
  Cidr:     192.168.0.0/16
  Gateway:  192.168.0.1
Events:     <none>

 

5、总结

在今天这篇文章中,为 Kubernetes 添加一个名叫 Network 的 API 资源类型。从而达到了通过标准的 kubectl create 和 get 操作,来管理自定义 API 对象的目的。不过,创建出这样一个自定义 API 对象,我们只是完成了 Kubernetes 声明式 API 的一半工作。

接下来的另一半工作是:为这个 API 对象编写一个自定义控制器(Custom Controller)。这样, Kubernetes 才能根据 Network API 对象的“增、删、改”操作,在真实环境中做出相应的响应。比如,“创建、删除、修改”真正的 Neutron 网络。而这,正是 Network 这个 API 对象所关注的“业务逻辑”。这个业务逻辑的实现过程,以及它所使用的 Kubernetes API 编程库的工作原理,就是在下一篇文章中主要内容。

 

 

参考:

code-generator使用

k8s-controller-custom-resource

 

posted @ 2022-02-14 17:02  茁壮的小草  阅读(850)  评论(0编辑  收藏  举报