前言
前面几节介绍了 kubebuilder 帮我们初始化了工程脚手架、生成 api、controller 代码、生成 manifest 文件,但是对 k8s 的开发使用仍然存在不足, 引入 code-generator(另一个代码生成的框架)能帮我们做更多事情:快速的生成Informers,Clientset, listers,灵活自定义 workqueue消费k8s产生的事件。
安装
code-generator/...
需要下载 code-generator 包下的所有东西
go get -u -v k8s.io/code-generator/...
// go get -u -v k8s.io/code-generator 只会下载代码中依赖的
遇到下面错误
go get: github.com/googleapis/gnostic@v0.5.5 updating to
github.com/googleapis/gnostic@v0.5.7: parsing go.mod:
module declares its path as: github.com/google/gnostic
but was required as: github.com/googleapis/gnostic
解决办法
go.mod 文件新增下面一条 replace
replace (
github.com/googleapis/gnostic => github.com/google/gnostic v0.5.7
)
使用
$ vendor/k8s.io/code-generator/generate-groups.sh all \
gitee.com/kubeclub/pkg/client \ github.com/openshift-evangelist/crd-code-generation/pkg/apis \
example.com:v1
参数说明
Usage: $(basename "$0") <generators> <output> <apis> <groups> ...
<generators> the generators comma separated to run (deepcopy,defaulter,client,lister,informer) or "all".
<output> the output package name (e.g. github.com/example/project/pkg/generated).
<apis> the external types dir (e.g. github.com/example/api or github.com/example/project/pkg/apis).
<groups> the groups and their versions in the format "groupA:v1,v2 groupB:v1 groupC:v2", relative
to <api>.
... arbitrary flags passed to all generator binaries.
自动生成如下文件
参考文档
https://cloud.redhat.com/blog/kubernetes-deep-dive-code-generation-customresources
kubebuilder-webhook(三) https://www.kubeclub.cn/kubernetes/180.html