Welcome to my GitHub
Github.com/zq2599/blog…
Content: all original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;
Links to articles
- Kubebuilder: Preparation
- Kubebuilder For the first time
- Kubebuilder 3: Quick overview of basic knowledge
- Operator requirements specification and design
- Kubebuilder operator code
- Kubebuilder Six: Build deployment run
- Kubebuilder: Webhook
- Kubebuilder: How do you do
This paper gives an overview of
- As the third chapter of “KubeBuilder Combat” series, kubeBuilder should have entered the real operator development link, but suddenly found that KubeBuilder involves too many knowledge points and too scattered, if now to type the command to write code to combat, even if the completion of the operator development, However, the lack of a lot of information (such as how to order the operation, how to link the steps, etc.), not only kubeBuilder series lost reference value, after a few months, even I can not understand these content, therefore, put off the actual practice, let’s take a shorthand for the knowledge points in the development process of KubeBuilder. Then calmly start the development work;
- Special note: Webhook is an important function of operator, and its theory and practice both need a lot of space, so there will be special articles in this aspect later, this paper will not involve the knowledge of Webhook;
- Now, the lecture begins;
Knowledge reserves
- To understand the code of kubeBuilder official Demo, and to operate Kubernetes resources with client objects, the above two points are the most basic requirements for competent operator development, otherwise in the development process there will be a feeling of difficulty, to achieve these conditions require a small amount of knowledge. Now Xinchen has prepared it for you, I hope you can browse it briefly:
- Kubernetes Group, Version, Resource Learning tips
- Client-go: Preparation
- Client-go Combat ii :RESTClient
- “Client-go Combat: Clientset”
- Client-go: dynamicClient
- Client-go Combat 5: DiscoveryClient
Initialize related knowledge points
- The first step in creating an operator is to create the entire project using the KubeBuilder command line, which was tried in KubeBuilder for the first time with the following three lines:
mkdir -p $GOPATH/src/helloworld
cd $GOPATH/src/helloworld
kubebuilder init --domain com.bolingcavalry
Copy the code
- $GOPATH/ SRC = $GOPATH/ SRC = $GOPATH/ SRC
- Don’t have anywhere to create a new directory (path space) and Chinese, for example, / Users / / elasticweb zhaoqin/temp / 202102/15
- Create a project named ElasticWeb using the go mod init ElasticWeb command in the directory.
- Execute kubeBuilder init –domain com.bolingcavalry to create operator project;
infrastructure
- After the operator project is created, a number of files and directories will be added.
- The go.mod: module configuration file, which is already populated with several important dependencies;
- Makefile: a very important tool, as we have seen before, for compiling, building, deploying, and running;
- PROJECT: KubeBuilder PROJECT metadata, in the generation of various apis will use this information;
- Config /default: a configuration file made based on kustomize, which provides standard configuration for controller and can also be modified as required;
- Config /manager: manager-related details, such as resource limits for mirroring;
- Config /rbac: as the name suggests, if you want to restrict the operator’s permission in kubernetes, you need to use RBAC to do fine permission configuration, which is the details of permission configuration.
main.go
- Main. go is automatically generated by KubeBuilder. This is the startup code for operator.
- SetupLog is used to output logs. Needless to say, Scheme is also a common tool that provides mapping of data structures in Kind and Go code:
var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup"))Copy the code
- There are also Settings, such as monitoring metrics and managing Controllers and Webhooks, that run until they are terminated externally. Another thing to note about Manage is its parameters. The following are the default parameters. If you want the operator to operate within the specified namespace, you can also add the namespace parameter in the afternoon. If you want to specify multiple nanespace, Use the cache. MultiNamespacedCacheBuilder (namespaces) parameters:
- The content of Main. go does not need to be changed in most scenarios.
API related (Data core)
- The API is at the heart of operator, and when you decide to use operator, you should start to design the CRD from real requirements, which are reflected in the DATA structure of the CRD and the processing logic for real and expected values.
- We created the API in KubeBuilder, and the command was:
kubebuilder create api \
--group webapp \
--version v1 \
--kind Guestbook
Copy the code
-
- Kubebuilder automatically adds a lot of content, as shown below, for this CRD service:
-
- The most important new content is the CRD, the guestbook_types.go file that contains the Guestbook data structure. The most important data structure is as follows:
type Guestbook struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec GuestbookSpec `json:"spec,omitempty"`
Status GuestbookStatus `json:"status,omitempty"`
}
Copy the code
- Metav1. TypeMeta: saves the Group, Version, and Kind of the resource
- Metav1. ObjectMeta: Saves the name and namespace of the resource object
- Spec: Expected state, such as Deployment specifying three copies of pod at creation time
- Status: True state (e.g., deployment has only one copy after creation (the others have not been successfully created). Most resource objects have this field, except ConfigMap (think of configuration information as being exactly what it is).
- GuestbookList is a collection of individual resource objects.
- There are two more files in the guestbook_types.go directory: Groupversion_info. go defines the Group and Version, as well as the SchemeBuilder used when registering with Scheme and zz_generated.
Controller related (business core)
- Having talked about the data core, it is now time to discuss how to implement the business requirements. In operator development, although the business logic is different, there are two commonalities:
- Status(true Status) is a data structure whose fields are defined by the business and whose field values are calculated by custom logic executed by the business code;
- The core business goal is to ensure that Status is consistent with the Spec. For example, deployment specifies a number of pod copies to be 3. If there are no real pod copies, deployment’s controller code creates pod copies. The Controller code of deployment removes the POD;
- This is what our controller needs to do. Let’s look at the details of the code. Guestbook_controller. go created by KubeBuilder is the controller, our business code is written in this file. Check out what KubeBuilder has prepared for us:
- Data structure definition, as shown below, client.Client, logging tool, Kind and data structure relation Scheme, these are all ready for us, really nice:
type GuestbookReconciler struct {
client.Client
Log logr.Logger
Scheme *runtime.Scheme
}
Copy the code
- The SetupWithManager method, called in main.go, specifies that changes to the Guestbook resource will be monitored by the Manager, triggering the Reconcile method:
func (r *GuestbookReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&webappv1.Guestbook{}).
Complete(r)
}
Copy the code
- As shown in the Reconcile method, there are some + kubeBuilder: rBAC comments in front of the Reconcile method. These are used to make sure the Controller has access to the resource when it runs. For example, IN the red box, I added them myself so that the Controller has access to the POD resource object:
- Guestbook_controller. go is the core of operator business, and the core of Controller is its Reconcile method. In the future, most of our code will be written here, mainly to obtain status. Then get status and spec to agree;
- The state of the resource object should be recalculated every time. Taking deployment as an example, there are two ways to know how many PODS there are. The first way is to prepare a field record, which should be modified every time a pod is added or deleted. The second method is to use the client tool to query the number of pods in real time. Currently, the second method is clearly recommended by the official:
- So far, the basic knowledge series is completed, we in accordance with the order of the official information to the knowledge point again, next, is in accordance with the order of the official information to combat, let you wait for a long time, the next chapter, operator combat;
You are not alone, Xinchen original accompany all the way
- Java series
- Spring series
- The Docker series
- Kubernetes series
- Database + middleware series
- The conversation series
Welcome to pay attention to the public number: programmer Xin Chen
Wechat search “programmer Xin Chen”, I am Xin Chen, looking forward to enjoying the Java world with you…
Github.com/zq2599/blog…