Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to customize the sharp weapon kubebuilder of K8S CDR

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

Custom K8S CDR sharp weapon kubebuilder how to use, in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

Overview

SDK for quickly building and publishing Kubernetes API in Go builds on the canonical techniques used to build the core Kubernetes API to provide simplified abstractions to reduce development effort.

Project:

Chaos-mesh: a chaos project developed by Pingcap based on kubebuilder, with a small amount of code & relatively concise, and the tool is also very practical [portal]

Kube-service: the work of a classmate Ali (looks like a small toy, I don't know if it's practical), it's a good learning example for CRD [portal]

Function

Class using a project that includes a basic structure

Get package dependencies in the specification version.

Main program entry point

Makefile for formatting, building, testing, and building

Dockerfile used to build a container image

Scaffolding API

Resource (model) definition

Controller realization

Integration testing of resources and controllers

CRD definition

A simple abstraction for implementing API

Controllers

Resource Schema Validation

Validating Webhooks

Artifacts used to publish API for installation into the cluster

Namespace

CRDs

RBAC Roles and RoleBindings

Controller StatefulSet + Service

API reference documentation and samples

Running process

An example of workQueue given by client-go

Divide the code into general Common part and Special Part

The former is the basic process of client-go.

The latter part is the logic part of controller itself.

Install and use installation

Source code installation

Git clone https://github.com/kubernetes-sigs/kubebuildercd kubebuildermake buildcp bin/kubebuilder $GOPATH/bin

Binary installation

Os=$ (go env GOOS) arch=$ (go env GOARCH) # download kubebuilder and extract it to tmpcurl-sL https://go.kubebuilder.io/dl/2.0.0-beta.0/${os}/${arch} | tar-xz-C / tmp/# extract the archivesudo mv / tmp/kubebuilder_2.0.0-beta.0_$ {os} _ ${arch} / usr/local/kubebuilder# update your PATH to include / usr/local/kubebuilder/binexport PATH=$PATH:/usr/local/kubebuilder/bin

Auxiliary tool kustomize

Go install sigs.k8s.io/kustomize uses to create a new API

First switch directories, kubebuilder is not good, do not automatically create a dedicated directory

Mkdir-p $GOPATH/src/github.com/crdAPIDemo/cd $GOPATH/src/github.com/crdAPIDemo/

Initialize the project directory

Export GO111MODULE= "on" export GOPROXY= https://goproxy.cnkubebuilder init-domain k8s.io-license apache2-owner "The Kubernetes Authors"

API creation

Create a new API named Sloop

Kubebuilder create api-group ships-version v1beta1-kind Sloop

Running

Make install & make run

Start an instance

Sample configurations are available under config/samples

Kubectl apply-f config/samples/ships_v1beta1_sloop.yaml can view the content of execution through kubectl get crd

Yaml content

ApiVersion: ships.k8s.io/v1beta1kind: Sloopmetadata: name: sloop-samplespec: # Add fields here foo: bar

Nothing is done when only yaml is saved in etcd controller to listen to the event

Deploy controller

The execution of make docker-build docker-push IMG=fanux/ships-controller / / always fails, indicating that git can not pull make deploy / / but ignore the failure of the previous step. This operation can perform development.

Define Spec objects (api/v1beta1/sloop_types.go) to add configuration items

Type SloopSpec struct {/ / INSERT ADDITIONAL SPEC FIELDS-desired state of cluster / / Important: Run "make" to regenerate code after modifying this file / / Foo is an example field of Sloop. Edit Sloop_types.go to remove/update Foo string `json: "foo,omitempty" `/ / add a new field here. Cpu string `json: "cpu,omitempty" `Memory string `json: "memory,omitempty" `}

Edit the contents of the original yaml file (config/samples/ships_v1beta1_sloop.yaml) to a Spec object and provide a specific configuration value

ApiVersion: ships.k8s.io/v1beta1kind: Sloopmetadata: name: sloop-samplespec: # Add fields here foo: bar cpu: "1" / / add content memory: "500m" / / add content

Take effect

Kubectl apply-f config/samples/

View

Kubectl get Sloop.ships.k8s.io-o yaml// output: new CRD definition content apiVersion: v1itemsapiVersion-apiVersion: ships.k8s.io/v1beta1 kind: Sloop metadata: annotations: kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion": "ships.k8s.io/v1beta1", "kind": "Sloop", "metadata": {"annotations": {}, "name": "sloop-sample", "namespace": "default"} "spec": {"cpu": "1", "foo": "bar", "memory": "500m"} creationTimestamp: "2020-01-19T09:07:41Z" generation: 2 name: sloop-sample namespace: default resourceVersion: "150773" selfLink: / apis/ships.k8s.io/v1beta1/namespaces/default/sloops/sloop-sample uid: 6a715921-86af-4dae-b25d-be193d64c4b2 spec: cpu: "1" / / change content Effective foo: bar memory: 500m / / change content, effective kind: Listmetadata: resourceVersion: "" selfLink: "Reconcile the only API function to be implemented

CRD only defines resources, and controller is the implementation

Controller encapsulates rotation training and event monitoring in this interface. You don't need to care about how the incident is monitored.

Controller internal

CURD and other logic are distributed by Reconcile ()

Code example

(controllers/sloop_controller.go)

Original content

Package controllersimport ("context"github.com/go-logr/logr"k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime"sigs.k8s.io/controller-runtime/pkg/client" shipsv1beta1 "github.com/crdAPIDemo/api/v1beta1") / / SloopReconciler reconciles a Sloop objecttype SloopReconciler struct {client.Client Log logr.Logger Scheme * runtime.Scheme} / / + kubebuilder:rbac:groups=ships.k8s.io Resources=sloops,verbs=get List;watch;create;update;patch;delete// + kubebuilder:rbac:groups=ships.k8s.io,resources=sloops/status,verbs=get;update;patchfunc (r * SloopReconciler) Reconcile (req ctrl.Request) (ctrl.Result, error) {_ = context.Background () _ = r.Log.WithValues ("sloop", req.NamespacedName) return ctrl.Result {}, nil} func (r * SloopReconciler) SetupWithManager (mgr ctrl.Manager) error {return ctrl.NewControllerManagedBy (mgr). For (& shipsv1beta1.Sloop {}). Complete (r)}

Modify to

Package controllersimport ("context"fmt"github.com/go-logr/logr", "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime"sigs.k8s.io/controller-runtime/pkg/client" shipsv1beta1 "github.com/crdAPIDemo/api/v1beta1") / / SloopReconciler reconciles a Sloop objecttype SloopReconciler struct {client.Client Log Logr.Logger Scheme * runtime.Scheme} / / + kubebuilder:rbac:groups=ships.k8s.io Resources=sloops,verbs=get List;watch;create;update;patch;delete// + kubebuilder:rbac:groups=ships.k8s.io,resources=sloops/status,verbs=get;update;patchfunc (r * SloopReconciler) Reconcile (req ctrl.Request) (ctrl.Result, error) {ctx: = context.Background () log: = r.Log.WithValues ("sloop", req.NamespacedName) / / your logic here vm: = & shipsv1beta1.Sloop {} if err: = r.Get (ctx, req.NamespacedName, vm) Err! = nil {log.Info ("unable to fetch vm:% v", err)} else {fmt.Println ("INFO:", vm.Spec.CPU, vm.Spec.Memory)} return ctrl.Result {}, nil} func (r * SloopReconciler) SetupWithManager (mgr ctrl.Manager) error {return ctrl.NewControllerManagedBy (mgr). For (& shipsv1beta1.Sloop {}). Complete (r)}

Compiling and using

Make; make install; make runkubectl apply-f config/samples / / will print out a log about how to customize K8S CDR's sharp weapon kubebuilder. This is the answer to the question. I hope the above content can be of some help to everyone. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report