基本项目中有什么?

在创建新项目时,Kubebuilder 为我们提供了一些基本的模板。

基础设施模板

首先,会创建一些用于构建项目的 basic infrastructure:

go.mod: 一个与项目匹配,包含最基本依赖关系的 go module 文件
module tutorial.kubebuilder.io/project

go 1.13

require (
	github.com/go-logr/logr v0.1.0
	github.com/robfig/cron v1.2.0
	k8s.io/api v0.17.2
	k8s.io/apimachinery v0.17.2
	k8s.io/client-go v0.17.2
	sigs.k8s.io/controller-runtime v0.5.0
)
Makefile: 用于构建和部署 controller

# Image URL to use all building/pushing image targets
IMG ?= controller:latest
# Produce CRDs that work back to Kubernetes 1.11 (no version conversion)
CRD_OPTIONS ?= "crd:trivialVersions=true"

all: manager

# Run tests
test: generate fmt vet manifests
	go test ./api/... ./controllers/... -coverprofile cover.out

# Build manager binary
manager: generate fmt vet
	go build -o bin/manager main.go

# Run against the configured Kubernetes cluster in ~/.kube/config
run: generate fmt vet
	go run ./main.go

# Install CRDs into a cluster
install: manifests
	kubectl apply -f config/crd/bases

# Deploy controller in the configured Kubernetes cluster in ~/.kube/config
deploy: manifests
	kubectl apply -f config/crd/bases
	kustomize build config/default | kubectl apply -f -

# Generate manifests e.g. CRD, RBAC etc.
manifests: controller-gen
	$(CONTROLLER_GEN) $(CRD_OPTIONS) rbac:roleName=manager-role webhook paths="./api/...;./controllers/..." output:crd:artifacts:config=config/crd/bases

# Run go fmt against code
fmt:
	go fmt ./...

# Run go vet against code
vet:
	go vet ./...

# Generate code
generate: controller-gen
	$(CONTROLLER_GEN) object:headerFile=./hack/boilerplate.go.txt paths=./api/...

# Build the docker image
docker-build: test
	docker build . -t ${IMG}
	@echo "updating kustomize image patch file for manager resource"
	sed -i'' -e 's@image: .*@image: '"${IMG}"'@' ./config/default/manager_image_patch.yaml

# Push the docker image
docker-push:
	docker push ${IMG}

# find or download controller-gen
# download controller-gen if necessary
controller-gen:
ifeq (, $(shell which controller-gen))
	go get sigs.k8s.io/controller-tools/cmd/controller-gen@v0.2.0-rc.0
CONTROLLER_GEN=$(shell go env GOPATH)/bin/controller-gen
else
CONTROLLER_GEN=$(shell which controller-gen)
endif
PROJECT: 用于创建新组件的 Kubebuilder 元数据
version: "2"
domain: tutorial.kubebuilder.io
repo: tutorial.kubebuilder.io/project

启动配置项模板

我们能在 config/ 目录下找到运行 operator 所需的所有配置文件,现在它只包含运行 controller 所需要的 Kustomize YAML 配置文件,后续我们编写 operator 时,这个目录还会包含 CustomResourceDefinitions(CRD)、RBAC 和 Webhook 等相关的配置文件

config/default 包含 Kustomize base 文件,用于以标准配置启动 controller。

config/目录下每个目录都包含不同的配置:

  • config/manager: 包含在 k8s 集群中以 pod 形式运行 controller 的 YAML 配置文件

  • config/rbac: 包含运行 controller 所需最小权限的配置文件

程序入口

最后,但同样重要的是,Kubebuilder 创建了我们项目的程序入口:main.go。下面让我们看看这个文件...