当前位置:网站首页>Développer un opérateur basé sur kubebuilder (démarrer)
Développer un opérateur basé sur kubebuilder (démarrer)
2022-06-26 16:14:00 【Chenxy02】
Adresse originale:Utiliserkubebuilder Compris.k8s crd - Oui.
Compris.k8sDecrdIl faut d'abord comprendrek8sDecontrollerMode
- Par exemple,kube-controller-managerDansdeploymentController,Lors de l'initialisation, il passe à écouterDeployments、ReplicaSetEtpodLes troisinformerObjet
- Tout d'abord,listL'objet suivant est mis en cache localement,En même tempswatchChangement d'objet,égale mise à jour progressive
func startDeploymentController(ctx ControllerContext) (controller.Interface, bool, error) {
dc, err := deployment.NewDeploymentController(
ctx.InformerFactory.Apps().V1().Deployments(),
ctx.InformerFactory.Apps().V1().ReplicaSets(),
ctx.InformerFactory.Core().V1().Pods(),
ctx.ClientBuilder.ClientOrDie("deployment-controller"),
)
if err != nil {
return nil, true, fmt.Errorf("error creating Deployment controller: %v", err)
}
go dc.Run(int(ctx.ComponentConfig.DeploymentController.ConcurrentDeploymentSyncs), ctx.Stop)
return nil, true, nil
}
- Et l'intérieur le fera. syncEn fait, c'estReconcile loop, C'est - à - dire le cycle de réglage —— C'est un objet de comparaison. actualStateEtexpectStateDifférences, Effectuer les opérations d'ajout et de suppression correspondantes Par exemple,deployment Opération d'expansion et de réduction moyennes
- Calculer la différence, Que vous pouvez créer pod Nombre moins toutes les activités rs Somme des copies
- Si la différence est positive ,Description de l'expansion nécessaire,Et deReplicaSetsBySizeNewer Trier par l'expansion du nouveau à l'ancien
- Si la différence est négative , Description du rétrécissement requis ,Et deReplicaSetsBySizeOlder Trier par ancien à nouveau
La différence est calculée comme suit:
deploymentReplicasToAdd := allowedSize - allRSsReplicas
var scalingOperation string
switch {
case deploymentReplicasToAdd > 0:
sort.Sort(controller.ReplicaSetsBySizeNewer(allRSs))
scalingOperation = "up"
case deploymentReplicasToAdd < 0:
sort.Sort(controller.ReplicaSetsBySizeOlder(allRSs))
scalingOperation = "down"
}
Compris.k8sDecontrollerAprès le mode,crd C'est toi qui l'as écrit. controller
- Écouter et traiter vos propres ressources définies ,
- C'est une image.
Installation Kubebuilder
wget https://github.com/kubernetes-sigs/kubebuilder/releases/download/v3.1.0/kubebuilder_linux_amd64
mv kubebuilder_linux_amd64 /usr/local/bin/kubebuilder
Créer un projet d'échafaudage
- Créer un répertoire, Et spécifiez ce répertoire comme entrepôt de code
mkdir -p ~/projects/guestbook
cd ~/projects/guestbook
kubebuilder init --domain my.domain --repo my.domain/guestbook
- Voir les résultats des fichiers dans ce répertoire
[[email protected] guestbook]# tree
.
├── config
│ ├── default
│ │ ├── kustomization.yaml
│ │ ├── manager_auth_proxy_patch.yaml
│ │ └── manager_config_patch.yaml
│ ├── manager
│ │ ├── controller_manager_config.yaml
│ │ ├── kustomization.yaml
│ │ └── manager.yaml
│ ├── prometheus
│ │ ├── kustomization.yaml
│ │ └── monitor.yaml
│ └── rbac
│ ├── auth_proxy_client_clusterrole.yaml
│ ├── auth_proxy_role_binding.yaml
│ ├── auth_proxy_role.yaml
│ ├── auth_proxy_service.yaml
│ ├── kustomization.yaml
│ ├── leader_election_role_binding.yaml
│ ├── leader_election_role.yaml
│ ├── role_binding.yaml
│ └── service_account.yaml
├── Dockerfile
├── go.mod
├── go.sum
├── hack
│ └── boilerplate.go.txt
├── main.go
├── Makefile
└── PROJECT
6 directories, 24 files
Créationapi
- Créer un nom webapp/v1De API (group/version)
- Créer un nouveau type Guestbook
kubebuilder create api --group webapp --version v1 --kind Guestbook
- Suivi des résultats , J'ai trouvé beaucoup plus de fichiers. ,Parmi euxapi/v1/guestbook_types.goDéfinition de la représentationAPIOù? ,controllers/guestbook_controller.go Logique représentative de l'Accord
[[email protected] guestbook]# tree
.
├── api
│ └── v1
│ ├── groupversion_info.go
│ ├── guestbook_types.go
│ └── zz_generated.deepcopy.go
├── bin
│ └── controller-gen
├── config
│ ├── crd
│ │ ├── kustomization.yaml
│ │ ├── kustomizeconfig.yaml
│ │ └── patches
│ │ ├── cainjection_in_guestbooks.yaml
│ │ └── webhook_in_guestbooks.yaml
│ ├── default
│ │ ├── kustomization.yaml
│ │ ├── manager_auth_proxy_patch.yaml
│ │ └── manager_config_patch.yaml
│ ├── manager
│ │ ├── controller_manager_config.yaml
│ │ ├── kustomization.yaml
│ │ └── manager.yaml
│ ├── prometheus
│ │ ├── kustomization.yaml
│ │ └── monitor.yaml
│ ├── rbac
│ │ ├── auth_proxy_client_clusterrole.yaml
│ │ ├── auth_proxy_role_binding.yaml
│ │ ├── auth_proxy_role.yaml
│ │ ├── auth_proxy_service.yaml
│ │ ├── guestbook_editor_role.yaml
│ │ ├── guestbook_viewer_role.yaml
│ │ ├── kustomization.yaml
│ │ ├── leader_election_role_binding.yaml
│ │ ├── leader_election_role.yaml
│ │ ├── role_binding.yaml
│ │ └── service_account.yaml
│ └── samples
│ └── webapp_v1_guestbook.yaml
├── controllers
│ ├── guestbook_controller.go
│ └── suite_test.go
├── Dockerfile
├── go.mod
├── go.sum
├── hack
│ └── boilerplate.go.txt
├── main.go
├── Makefile
└── PROJECT
13 directories, 37 files
- Ajouter un journal d'impression à la fonction Tuning ,Situé à controller/guestbook_controller.go
func (r *GuestbookReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx)
// your logic here
log.FromContext(ctx).Info("print_req", "req", req.String())
return ctrl.Result{}, nil
}
Déploiement àk8sEn grappes
- Compiler l'image de frappe
make docker-build IMG=guestbook:v1.0 # Mise en œuvre effective docker build -t guestbook:v1.0 .
- En général, nous devons modifier les dockerfile,Voilà. go ParamètresproxyAgents,Voilà. go mod download Pas de temps mort.
- Le miroir doit ensuite être poussé manuellement dans l'entrepôt local ,Si la couche inférieureruntime- Oui.ctrEt si Besoindocker save Exporter et importer
docker save guestbook:v1.0 > a.tar
ctr --namespace k8s.io images import a.tar
- Parce que le projet utilise kube-rbac-proxy, Ce miroir peut également avoir des problèmes de téléchargement , Il faut s'en occuper manuellement. ,Comme suit:
- Déployez - vous maintenant.crd
make deploy IMG=guestbook:v1.0 #Mise en œuvre effective kustomize build config/default | kubectl apply -f -
- Vérifier àguestbook-system ns Objet du déploiement inférieur
- Vérifiezapi-resources
- Déploiementguestbook
kubectl apply -f config/samples/webapp_v1_guestbook.yaml
# guestbook.webapp.my.domain/guestbook-cxy created
- Voircrd Les journaux peuvent être vus dans la fonction Tuning pour imprimer
边栏推荐
- R language uses cor function to calculate the correlation matrix for correlation analysis, uses corrgram package to visualize the correlation matrix, reorders rows and columns using principal componen
- SAP OData 开发教程 - 从入门到提高(包含 SEGW, RAP 和 CDP)
- 100+数据科学面试问题和答案总结 - 基础知识和数据分析
- Everyone is a scientist free gas experience Mint love crash
- JS教程之使用 ElectronJS、VueJS、SQLite 和 Sequelize ORM 从 A 到 Z 创建多对多 CRUD 应用程序
- What is the process of switching C # read / write files from user mode to kernel mode?
- Simple use of tensor
- Transformation of zero knowledge QAP problem
- Svg rising Color Bubble animation
- Tsinghua's "magic potion" is published in nature: reversing stem cell differentiation, and the achievements of the Nobel Prize go further. Netizen: life can be created without sperm and eggs
猜你喜欢
Tsinghua's "magic potion" is published in nature: reversing stem cell differentiation, and the achievements of the Nobel Prize go further. Netizen: life can be created without sperm and eggs
STEPN 新手入门及进阶
长安链交易防重之布谷鸟过滤器
今年高考英语AI得分134,复旦武大校友这项研究有点意思
11 cnn简介
【力扣刷题】二分查找:4. 寻找两个正序数组的中位数
基于STM32+华为云IOT设计的云平台监控系统
Svg canvas canvas drag
C# 读写文件从用户态切到内核态,到底是个什么流程?
Supplement the short board - Open Source im project openim about initialization / login / friend interface document introduction
随机推荐
100+ data science interview questions and answers Summary - basic knowledge and data analysis
Exquisite makeup has become the "soft power" of camping, and the sales of vipshop outdoor beauty and skin care products have surged
How to create your own NFT (polygon) on opensea
【时间复杂度和空间复杂度】
R language uses cor function to calculate the correlation matrix for correlation analysis, uses corrgram package to visualize the correlation matrix, reorders rows and columns using principal componen
JVM notes
心情不好,我就这样写代码
C language reading data
【207】Apache崩溃的几个很可能的原因,apache崩溃几个
[Blue Bridge Cup training 100 questions] scratch distinguishing prime numbers and composite numbers Blue Bridge Cup scratch competition special prediction programming question intensive training simul
Tweenmax+svg switch color animation scene
Redis的ACID
补齐短板-开源IM项目OpenIM关于初始化/登录/好友接口文档介绍
NFT contract basic knowledge explanation
国内首款开源 MySQL HTAP 数据库即将发布,三大看点提前告知
TCP拥塞控制详解 | 1. 概述
Canvas three dot flashing animation
[time complexity and space complexity]
(1) Keras handwritten numeral recognition and recognition of self written numbers
牛客编程题--必刷101之动态规划(一文彻底了解动态规划)