如何在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 编程库的工作原理,就是在下一篇文章中主要内容。
参考:
k8s-controller-custom-resource
如何在Kubernetes 里添加自定义的 API 对象(一)的更多相关文章
- 如何在Kubernetes里创建一个Nginx service
Jerry之前的文章如何在Kubernetes里创建一个Nginx应用,已经使用kubectl命令行创建了Pod,但是在kubernetes中,Pod的IP地址会随着Pod的重启而变化,因此用Pod的 ...
- 如何在Kubernetes里给PostgreSQL创建secret
创建一个initdb.sql文件,输入如下内容: -- This is a postgres initialization script for the postgres container. -- ...
- 如何在Kubernetes里创建一个Nginx应用
使用命令行kubectl run --image=nginx nginx-app --port=80 创建一个名为nginx-app的应用 结果: deployment.apps/nginx-app ...
- kubernetes之常用核心资源对象
部门产品线本身是做DEVOPS平台,最近部署架构也在往K8S上靠了,不得不学一下K8S.自己搭建了K8S集群与harbor仓库来学习. 1.kubernetes之常用核心资源对象 1.1.K8s服务部 ...
- Kubernetes的核心技术概念和API对象
Kubernetes的核心技术概念和API对象 API对象是K8s集群中的管理操作单元.K8s集群系统每支持一项新功能,引入一项新技术,一定会新引入对应的API对象,支持对该功能的管理操作.例如副本集 ...
- 【Kubernetes】声明式API与Kubernetes编程范式
什么是声明式API呢? 答案是,kubectl apply命令. 举个栗子 在本地编写一个Deployment的YAML文件: apiVersion: apps/v1 kind: Deployment ...
- Chrome出了个小bug:论如何在Chrome下劫持原生只读对象
Chrome出了个小bug:论如何在Chrome下劫持原生只读对象 概述 众所周知,虽然JavaScript是个很灵活的语言,浏览器里很多原生的方法都可以随意覆盖或者重写,比如alert.但是为了保证 ...
- 在SharePoint 2010 母版页里添加自定义用户控件
在SharePoint 2010 母版页里添加自定义用户控件(译) 使用自定义用户控件的好处: 1.容易部署:2.易于控制显示或隐藏. (在使用的过程中)可能要面对的问题是:如何在用户控件里使用Sha ...
- [转]如何在 Git 里撤销(几乎)任何操作
任何版本控制系统的一个最有的用特性就是“撤销 (undo)”你的错误操作的能力.在 Git 里,“撤销” 蕴含了不少略有差别的功能. 当你进行一次新的提交的时候,Git 会保存你代码库在那个特定时间点 ...
随机推荐
- 字母 Letters
D. 字母 Letters 内存限制:256 MiB 时间限制:500 ms 标准输入输出 题目类型:传统 评测方式:文本比较 题目描述 给定两个长度相同且由大写英文字母组成的字符串 A 和 B,保证 ...
- 《Python核心编程第3版中文版》(高清).PDF,免费无需任何解压密码
链接:https://pan.baidu.com/s/18d3xinNX1oH5q8zpB10ABA 提取码:dx7h
- Flask_环境部署(十六)
flask自带的服务器,无法满足性能要求,我们这里采用Gunicorn做wsgi容器,来部署flask程序并使用 Nginx 做前端代理实现分流.转发.负载均衡,以及分担服务器的压力. Gunicor ...
- JSch Algorithm negotiation fail
https://stackoverflow.com/questions/30846076/jsch-algorithm-negotiation-fail As you can see, the ser ...
- nuxt中iview按需加载配置
在plugins/iview.js中修改 初始代码如下 import Vue from 'vue' import iView from 'iview' import locale from 'ivie ...
- layui 时间插件,change&&done,按照官网写法无效,解决方式!
摘抄自 hahei2020:https://blog.csdn.net/hahei2020/article/details/79285370 layui 时间插件, 当选择时间或时间发生改变后,按照官 ...
- SYCOJ246螺旋矩阵
题目-螺旋矩阵 (shiyancang.cn) noip201403螺旋矩阵[普及组]数学算法 - 大本营 - 博客园 (cnblogs.com) 以下为搬运代码.一个为算圈数,另外一个是数学方法 思 ...
- 使用Kubernetes两年来的7大经验教训
来源:分布式实验室译者:冯旭松在Ridecell公司管理基础设施团队几年后,我想在停下来休息时记录一些想法和经验教训. 1Kubernetes不仅仅是炒作 我在Kubernetes领域里活跃了很久,所 ...
- leetcode 509. 斐波那契数
问题描述 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列.该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和.也就是: F(0) = 0, F(1) = 1 F(N) ...
- 通过HTML+CSS+Javascript实现向下滚动滚动条出现导航栏并出现回到顶部按钮点击按钮回到顶部(一)
回到顶部实例一 效果:默认隐藏导航栏,当滚动条滚到超过300px后导航栏和按钮出现,点击回到顶部按钮回到顶部,并隐藏导航栏和按钮(导航栏和按钮都是固定定位) <!doctype html> ...