k8s之CRD--為自訂資源產生代碼

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

CRD簡介和使用姿勢

CustomResourceDefinition(CRD)是 v1.7 + 新增的無需改變代碼就可以擴充 Kubernetes API 的機制,用來管理自訂對象。它實際上是 ThirdPartyResources(TPR) 的升級版本,而 TPR 已經在 v1.8 中刪除。

一些使用情境:

  • 提供/管理外部資料儲存/資料庫(例如 CloudSQL/RDS 執行個體)
  • 對k8s基礎資源進行更高層次的抽象(比如定義一個etcd叢集)

其實crd在很多k8s周邊開源項目中有使用,比如ingress-controller和眾多的operator。

CRD 控制器

在使用 CRD 擴充 Kubernetes API 時,通常還需要實現一個建立資源的控制器,監聽改資源的變化情況,並作進一步的處理。官方提供的樣本項目sample-controller。
這個例子主要講述了以下幾個方面:

  • 如何使用自訂資源定義註冊Foo類型的新自訂資源(自訂資源類型)
  • 如何建立/擷取/列出新資源類型Foo執行個體
  • 如何在資源處理建立/更新/刪除事件上設定控制器

編寫crd controller之前,一定要使用k8s官方提供的代碼產生工具k8s.io/code-generator 去產生 client, informers, listers and deep-copy函數.不僅代碼風格符合k8s,而且減少出錯和減少工作量都是有很大的協助。

在項目中使用代碼產生器

下面展示了代碼產生工具是如何工作的以及如何使用最少的程式碼將它們應用到自己的項目中,從而為您產生 deepcopy 函數/typed clients/listers/informer,所有這些的產生僅需要一個 shell 指令碼調用和部分代碼注釋。
不要覺得代碼產生有多麼複雜,其實官方已經做了很多工作了,提供了 generator-group.sh。看過client-go的gopher應該都知道項目中有大量代碼工具產生的程式碼。
執行./hack/update-codegen.sh,即

#!/usr/bin/env bash# Copyright 2017 The Kubernetes Authors.## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You 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 under the License is 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 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 be able to run inside the vendor 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 be 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

update-codegen指令碼將自動產生下面的檔案和路徑

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

指令碼運行後大體會建立如下的包管理結構:

是不是很簡單?pkg/client 代碼是被完全產生的,就像包含我們的 CustomResource golang語言類型的 types.go 檔案下面的 zz_generated.deepcopy.go 檔案一樣,然後你就可以基於產生的程式碼寫自己的controller了。
不過並不是不需要自己寫一點代碼,畢竟機器沒有智能到你定義了什麼樣子的crd。所有以下幾個檔案需要自己來定義和實現,均是和你自己的商務邏輯相關。
pkg/apis以下的除zz_generated.deepcopy.go以外的所有檔案。
比如:
types.go

 /*Copyright 2017 The Kubernetes Authors.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at    http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is 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")// +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"`}// CanarySpec is the spec for a Foo resourcetype CanarySpec struct {    DeploymentName string `json:"deploymentName"`    Replicas       *int32 `json:"replicas"`}// CanaryStatus is the status for a Foo resourcetype CanaryStatus struct {    AvailableReplicas int32 `json:"availableReplicas"`}// +k8s:deepcopy-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 2017 The Kubernetes Authors.Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at    http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is 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/runtime/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 string) schema.GroupResource {    return SchemeGroupVersion.WithResource(resource).GroupResource()}var (    SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes)    AddToScheme   = SchemeBuilder.AddToScheme)// Adds the list of known types to Scheme.func addKnownTypes(scheme *runtime.Scheme) error {    scheme.AddKnownTypes(SchemeGroupVersion,        &Canary{},        &CanaryList{},    )    metav1.AddToGroupVersion(scheme, SchemeGroupVersion)    return nil}

更多相關細節

見 Kubernetes Deep Dive: Code Generation for CustomResources給出了具體的步驟和關於tag的標註。

總結

基於crd以及crd controller可以抽象很多業務情境。接下我司準備實現一個部署策略相關的項目。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.