k8s crd--generate code for custom resources

Source: Internet
Author: User
Tags k8s
This is a creation in Article, where the information may have evolved or changed.

Introduction to CRD and usage posture

Customresourcedefinition (CRD) is the v1.7 + new mechanism to extend the Kubernetes API without changing the code to manage custom objects. It is actually an upgraded version of Thirdpartyresources (TPR), and TPR has been removed in v1.8.

Some usage scenarios:

    • Provide/manage external data stores/databases (e.g. Cloudsql/rds instances)
    • Higher-level abstraction of k8s base resources (e.g. defining a ETCD cluster)

In fact, CRD is used in many open source projects around k8s, such as Ingress-controller and numerous operator.

CRD Controller

When using CRD to extend the Kubernetes API, it is often necessary to implement a new controller to monitor the change of resources and to do further processing. The sample project Sample-controller is officially provided.
This example mainly covers the following aspects:

    • How to use a custom resource definition to register a new custom resource of type Foo (custom resource type)
    • How to create/get/List new resource type Foo instances
    • How to set up a controller on resource handling Create/update/delete events

Before writing the CRD controller, be sure to use K8s's official code generation tool K8s.io/code-generator to generate the client, Informers, Listers, and deep-copy function. Not only does the code style conform to k8s, but it also helps to reduce errors and reduce workload.

Using the code generator in your project

Here's how the code generation tools work and how you can use the fewest lines of code to apply them to your project, generating the Deepcopy function/typed Clients/listers/informer for you, all of which require only one shell Script calls and partial code comments.
Do not feel how complex code generation, in fact, the official has done a lot of work, provided the generator-group.sh. Gopher, who has seen client-go, should know that there are a number of code tools generated in the project.
Execute./hack/update-codegen.sh, i.e.

#!/usr/bin/env bash# Copyright The Kubernetes authors.## Licensed under the Apache License, Version 2.0 (the "License "); # you are not to use this file except in compliance with the license.# your 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 u NDEr the License is distributed on a "as is" basis,# without warranties OR CONDITIONS of any KIND, either express or Impl  ied.# See the License for the specific language governing permissions and# limitations under the License.set-o Errexitset -O nounsetset-o pipefailscript_root=$ (dirname ${bash_source})/. codegen_pkg=${codegen_pkg:-$ (CD ${script_root}; ls-d-1./vendor/k8s.io/code-generator 2>/dev/null | | echo. /code-generator)}# generate the code with:#--output-base because this script should also is able to run inside the Ven Dor 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 dropped.${codegen_pkg}/generate-groups.sh "Deepcopy,client,informer,lister" \ k8s.io/ Canary-controller/pkg/client k8s.io/canary-controller/pkg/apis \ CANARYCONTROLLER:V1ALPHA1 \--output-base "$ ( DirName ${bash_source})/.. /..  /: "\--go-header-file ${script_root}/hack/boilerplate.go.txt# to use your own boilerplate text use:#--go-header-file ${script_root}/hack/custom-boilerplate.go.txt

The Update-codegen script will automatically generate the following files and paths

    • Pkg/apis/canarycontroller/v1alpha1/zz_generated.deepcopy.go
    • pkg/client/

After the script runs, it is a great experience to build the following package management structure:

Isn't it simple? The Pkg/client code is fully generated, just like the Zz_generated.deepcopy.go file under the Types.go file containing our Customresource Golang language type, Then you can write your own controller based on the generated code.
However, it is not necessary to write a bit of code, after all, the machine is not intelligent to what you define the way the CRD. All of the following files need to be defined and implemented by themselves and are related to your own business logic.
All files except Zz_generated.deepcopy.go are Pkg/apis below.
Like what:
Types.go

 /*copyright the Kubernetes authors.licensed under the Apache License, Version 2.0 (the "License"); is file except in compliance with the license.you could obtain a copy of the License at Http://www.apache.org/licenses/LI Cense-2.0unless required by applicable law or agreed to writing, softwaredistributed under the License is distributed O n an ' as is ' basis,without warranties or CONDITIONS of any KIND, either express or implied. See the License for the specific language governing permissions andlimitations under the License.*/package v1alpha1import (metav1 "K8S.IO/APIMACHINERY/PKG/APIS/META/V1")//+genclient//+k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/ Pkg/runtime. object//Canary is a specification for a Foo resourcetype Canary struct {metav1. Typemeta ' JSON: ', ' inline ' ' metav1. Objectmeta ' JSON: "Metadata,omitempty" ' Spec Canaryspec ' JSON: "Spec" ' Status Canarystatus ' JSON: "status" '}//Cana Ryspec is the spec for a Foo resourcetype Canaryspec struct {deploymentname string ' JSON: ' deploymentname ' ' Replicas *int32 ' json: ' Replicas ' '}//canarystatus i s the status for a Foo resourcetype canarystatus struct {availablereplicas int32 ' json: ' Availablereplicas ' '}//+k8s:de Epcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime. object//Canarylist is a list of Foo resourcestype canarylist struct {metav1. Typemeta ' JSON: ', ' inline ' ' metav1. Listmeta ' JSON: ' Metadata ' items []canary ' JSON: ' Items '}

Registry.go

/*copyright the Kubernetes authors.licensed under the Apache License, Version 2.0 (the "License"); s file except in compliance with the license.you could obtain a copy of the License at Http://www.apache.org/licenses/LIC  Ense-2.0unless required by applicable law or agreed to writing, softwaredistributed under the License are 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 andlimitations under the License.*/package v1alpha1import (metav1 "K8s.io/apimachinery/pkg/apis/meta/v1" "K8s.io/apimachinery/pkg/runtime" "K8s.io/apimachinery/pkg/runtim E/schema "Canarycontroller" K8s.io/canary-controller/pkg/apis/canarycontroller ")//Schemegroupversion is group Version used to register these Objectsvar schemegroupversion = schema. Groupversion{group:canarycontroller. GroupName, Version: "V1alpha1"}//Kind takes an unqualified Kind and returns BACK a Group qualified groupkindfunc Kind (Kind string) schema. Groupkind {return Schemegroupversion.withkind (kind). Groupkind ()}//Resource takes an unqualified Resource and returns a Group qualified Groupresourcefunc Resource (Resource St Ring) schema. Groupresource {return Schemegroupversion.withresource (Resource). Groupresource ()}var (Schemebuilder = runtime. Newschemebuilder (addknowntypes) addtoscheme = schemebuilder.addtoscheme)//Adds The list of known types to Scheme.fun C addknowntypes (Scheme *runtime. Scheme) error {scheme. Addknowntypes (Schemegroupversion, &canary{}, &canarylist{},) metav1. Addtogroupversion (scheme, schemegroupversion) return nil}

More about the details

See Kubernetes deep Dive:code Generation for customresources gives specific steps and labeling on tags.

Summarize

CRD-based and CRD controllers can abstract many business scenarios. Then we are ready to implement a deployment strategy related projects.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.