深入 kubernetes API 的源碼實現


很多同學應該像我一樣,第一次打開 Github 上面 kubernetes 項目源碼的時候就被各種倉庫搞暈了,kuberentes 組織下有很多個倉庫,包括 kubernetes、client-go、api、apimachinery 等,該從哪兒倉庫看起?kubernetes 倉庫應該是 kubernetes 項目的核心倉庫,它包含 kubernetes 控制平面核心組件的源碼;client-go 從名字也不難看出是操作 kubernetes API 的 go 語言客戶端;api 與 apimachinery 應該是與 kubernetes API 相關的倉庫,但它們倆爲啥要分成兩個不同的倉庫?這些代碼倉庫之間如何交互?apimachinery 倉庫中還有 api、apis 兩個包,裏面定義了各種複雜的接口與實現,清楚這些複雜接口對於擴展 kubernetes API 大有裨益。所以,這篇文章就重點關注 api 與 apimachinery 這兩個倉庫。

api

我們知道 kubernetes 官方提供了多種多樣的的 API 資源類型,它們被定義在 k8s.io/api 這個倉庫中,作爲 kubernetes API 定義的規範地址。實際上,最開始這個倉庫只是 kubernetes 核心倉庫的一部分,後來 kubernetes API 定義規範被越來越多的其他倉庫使用,例如 k8s.io/client-go、k8s.io/apimachinery、k8s.io/apiserver 等,爲了避免交叉依賴,所以才把 api 拿出來作爲單獨的倉庫。k8s.io/api 倉庫是隻讀倉庫,所有代碼都同步自 https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/api 核心倉庫。

在 k8s.io/api 倉庫定義的 kubernetes API 規範中,Pod 作爲最基礎的資源類型,一個典型的 YAML 形式的序列化 pod 對象如下所示:

apiVersion: v1
kind: Pod
metadata:
  name: webserver
  labels:
    app: webserver
spec:
  containers:
  - name: webserver
    image: nginx
    ports:
    - containerPort: 80

從編程的角度來看,序列化的 pod 對象最終會被髮送到 API-Server 並解碼爲 Pod 類型的 Go 結構體,同時 YAML 中的各個字段會被賦值給該 Go 結構體。那麼,Pod 類型在 Go 語言結構體中是怎麼定義的呢?

// source code from https://github.com/kubernetes/api/blob/master/core/v1/types.go
type Pod struct {
    // 從TypeMeta字段名可以看出該字段定義Pod類型的元信息,類似於面向對象編程裏面
    // Class本身的元信息,類似於Pod類型的API分組、API版本等
    metav1.TypeMeta `json:",inline"`
    // ObjectMeta字段定義單個Pod對象的元信息。每個kubernetes資源對象都有自己的元信息,
    // 例如名字、命名空間、標籤、註釋等等,kuberentes把這些公共的屬性提取出來就是
    // metav1.ObjectMeta,成爲了API對象類型的父類
    metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    // PodSpec表示Pod類型的對象定義規範,最爲代表性的就是CPU、內存的資源使用。
    // 這個字段和YAML中spec字段對應
    Spec PodSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
    // PodStatus表示Pod的狀態,比如是運行還是掛起、Pod的IP等等。Kubernetes會根據pod在
    // 集羣中的實際狀態來更新PodStatus字段
    Status PodStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
}

從上面 Pod 定義的結構體可以看出,它繼承了 metav1.TypeMeta 和 metav1.ObjectMeta 兩個類型,metav1.TypeMeta 對應 YAML 中的 kind 與 apiVersion 段,而 metav1.ObjectMeta 則對應 metadata 字段。這其實也可以從 Go 結構體的字段 json 標籤看得出來。除了 metav1.TypeMeta 和 metav1.ObjectMeta 字段,Pod 結構體同時還定義了 Spec 和 Status 兩個成員變量。如果去查看 k8s.io/api 倉庫中其他 API 資源結構體的定義就會發現 kubernetes 絕大部分 API 資源類型都是這樣的結構,這也就是說 kubernetes API 資源類型都繼承 metav1.TypeMeta 和 metav1.ObjectMeta,前者用於定義資源類型的屬性,後者用於定義資源對象的公共屬性;Spec 用於定義 API 資源類型的私有屬性,也是不同 API 資源類型之間的區別所在;Status 則是用於描述每個資源對象的狀態,這和每個資源類型緊密相關的。

關於 metav1.TypeMeta 和 metav1.ObjectMeta 字段從語義上也很好理解,這兩個類型作爲所有 kubernetes API 資源對象的基類,每個 API 資源對象需要 metav1.TypeMeta 字段用於描述自己是什麼類型,這樣才能構造相應類型的對象,所以相同類型的所有資源對象的 metav1.TypeMeta 字段都是相同的,但是 metav1.ObjectMeta 則不同,它是定義資源對象實例的屬性,即所有資源對象都應該具備的屬性。這部分就是和對象本身相關,和類型無關,所以相同類型的資源對象的 metav1.ObjectMeta 可能是不同的。

在 kubernetes 的 API 資源對象中除了單體對象外,還有對象列表類型,用於描述一組相同類型的對象列表。對象列表的典型應用場景就是列舉,對象列表就可以表達一組資源對象。可能有些讀者會問爲什麼不用對象的 slice,例如[]Pod,伴隨着筆者對對象列表的解釋讀者就會理解,此處以 PodList 爲例進行分析:

// source code from https://github.com/kubernetes/api/blob/master/core/v1/types.go
type PodList struct {
    // PodList也需要繼承metav1.TypeMeta,畢竟對象列表也好、單體對象也好都需要類型屬性。
    // PodList比[]Pod類型在yaml或者json表達上多了類型描述,當需要根據YAML構建對象列表的時候,
    // 就可以根據類型描述反序列成爲PodList。而[]Pod則不可以,必須確保YAML就是[]Pod序列化的
    // 結果,否則就會報錯。這就無法實現一個通用的對象序列化/反序列化。
    metav1.TypeMeta `json:",inline"`
    // 與Pod不同,PodList繼承了metav1.ListMeta,metav1.ListMeta是所有資源對象列表類型的父類,
    // ListMeta定義了所有對象列表類型實例的公共屬性。
    metav1.ListMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
    // Items字段則是PodList定義的本質,表示Pod資源對象的列表,所以說PodList就是[]Pod基礎上加了一些
    // 跟類型和對象列表相關的元信息
    Items []Pod `json:"items" protobuf:"bytes,2,rep,name=items"`

在開始下一節的內容之前,我們先做個小結:

  1. metav1.TypeMeta 和 metav1.ObjectMeta 是所有 API 單體資源對象的父類;
  2. metav1.TypeMeta 和 metav1.ListMeta 是所有 API 資源對象列表的父類;
  3. metav1.TypeMeta 是所有 API 資源對象的父類,因爲所有的資源對象都要說明表示是什麼類型;

metav1

這裏的 metav1 是包 k8s.io/apimachinery/pkg/apis/meta/v1 的別名,本文其他部分的將用 metav1 指代。

metav1.TypeMeta

metav1.TypeMeta 用來描述 kubernetes API 資源對象類型的元信息,包括資源類型的名字以及對應 API 的 schema。這裏的 schema 指的是資源類型 API 分組以及版本。

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/types.go
//
// TypeMeta describes an individual object in an API response or request
// with strings representing the type of the object and its API schema version.
// Structures that are versioned or persisted should inline TypeMeta.
type TypeMeta struct {
 // Kind is a string value representing the REST resource this object represents.
 // Servers may infer this from the endpoint the client submits requests to.
 // Cannot be updated.
 Kind string `json:"kind,omitempty" protobuf:"bytes,1,opt,name=kind"`

 // APIVersion defines the versioned schema of this representation of an object.
 // Servers should convert recognized schemas to the latest internal value, and
 // may reject unrecognized values.
 APIVersion string `json:"apiVersion,omitempty" protobuf:"bytes,2,opt,name=apiVersion"`
}

細心的同學還會發現 metav1.TypeMeta 實現了 schema.ObjectKind 接口,schema.ObjectKind 接口了所有序列化對象怎麼解碼與編碼資源類型信息的方法,它的完整定義如下:

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/runtime/schema/interfaces.go
//
// All objects that are serialized from a Scheme encode their type information. This interface is used
// by serialization to set type information from the Scheme onto the serialized version of an object.
// For objects that cannot be serialized or have unique requirements, this interface may be a no-op.
type ObjectKind interface {
 // SetGroupVersionKind sets or clears the intended serialized kind of an object. Passing kind nil
 // should clear the current setting.
 SetGroupVersionKind(kind GroupVersionKind)
 // GroupVersionKind returns the stored group, version, and kind of an object, or an empty struct
 // if the object does not expose or provide these fields.
 GroupVersionKind() GroupVersionKind
}

從 metav1.TypeMeta 對象的實例(也就是任何 kubernetes API 資源對象)都可以通過 GetObjectKind() 方法獲取到 schema.ObjectKind 類型對象,而 TypeMeta 對象的實例本身也實現了 schema.ObjectKind 接口:

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/types.go

func (obj *TypeMeta) GetObjectKind() schema.ObjectKind { return obj }

// SetGroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta
func (obj *TypeMeta) SetGroupVersionKind(gvk schema.GroupVersionKind) {
 obj.APIVersion, obj.Kind = gvk.ToAPIVersionAndKind()
}

// GroupVersionKind satisfies the ObjectKind interface for all objects that embed TypeMeta
func (obj *TypeMeta) GroupVersionKind() schema.GroupVersionKind {
 return schema.FromAPIVersionAndKind(obj.APIVersion, obj.Kind)
}

metav1.ObjectMeta

metav1.ObjectMeta 則用來定義資源對象實例的屬性,即所有資源對象都應該具備的屬性。這部分就是和對象本身相關,和類型無關,所以相同類型的資源對象的 metav1.ObjectMeta 可能是不同的。

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/types.go
//
// ObjectMeta is metadata that all persisted resources must have, which includes all objects
// users must create.
type ObjectMeta struct {
 // Name must be unique within a namespace. Is required when creating resources, although
 // some resources may allow a client to request the generation of an appropriate name
 // automatically. Name is primarily intended for creation idempotence and configuration
 // definition.
 Name string `json:"name,omitempty" protobuf:"bytes,1,opt,name=name"`

 // GenerateName is an optional prefix, used by the server, to generate a unique
    // name ONLY IF the Name field has not been provided.
    // Populated by the system. Read-only.
 GenerateName string `json:"generateName,omitempty" protobuf:"bytes,2,opt,name=generateName"`

 // Namespace defines the space within which each name must be unique. An empty namespace is
 // equivalent to the "default" namespace, but "default" is the canonical representation.
 // Not all objects are required to be scoped to a namespace - the value of this field for
 // those objects will be empty.
 Namespace string `json:"namespace,omitempty" protobuf:"bytes,3,opt,name=namespace"`

    // SelfLink is a URL representing this object.
    // Populated by the system. Read-only.
 SelfLink string `json:"selfLink,omitempty" protobuf:"bytes,4,opt,name=selfLink"`

 // UID is the unique in time and space value for this object. It is typically generated by
 // the server on successful creation of a resource and is not allowed to change on PUT
    // operations.
    // Populated by the system. Read-only.
 UID types.UID `json:"uid,omitempty" protobuf:"bytes,5,opt,name=uid,casttype=k8s.io/kubernetes/pkg/types.UID"`

 // An opaque value that represents the internal version of this object that can
 // be used by clients to determine when objects have changed. May be used for optimistic
 // concurrency, change detection, and the watch operation on a resource or set of resources.
 // Clients must treat these values as opaque and passed unmodified back to the server.
    // They may only be valid for a particular resource or set of resources.
    // Populated by the system. Read-only.
 ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,6,opt,name=resourceVersion"`

 // A sequence number representing a specific generation of the desired state.
 // Populated by the system. Read-only.
 Generation int64 `json:"generation,omitempty" protobuf:"varint,7,opt,name=generation"`

 // CreationTimestamp is a timestamp representing the server time when this object was
 // created. It is not guaranteed to be set in happens-before order across separate operations.
 // Clients may not set this value. It is represented in RFC3339 form and is in UTC.
    // Populated by the system. Read-only.
 CreationTimestamp Time `json:"creationTimestamp,omitempty" protobuf:"bytes,8,opt,name=creationTimestamp"`

 // DeletionTimestamp is RFC 3339 date and time at which this resource will be deleted. This
 // field is set by the server when a graceful deletion is requested by the user, and is not
 // directly settable by a client. The resource is expected to be deleted (no longer visible
 // from resource lists, and not reachable by name) after the time in this field, once the
 // finalizers list is empty. As long as the finalizers list contains items, deletion is blocked.
 // Once the deletionTimestamp is set, this value may not be unset or be set further into the
 // future, although it may be shortened or the resource may be deleted prior to this time.
 // For example, a user may request that a pod is deleted in 30 seconds. The Kubelet will react
 // by sending a graceful termination signal to the containers in the pod. After that 30 seconds,
 // the Kubelet will send a hard termination signal (SIGKILL) to the container and after cleanup,
 // remove the pod from the API. In the presence of network partitions, this object may still
 // exist after this timestamp, until an administrator or automated process can determine the
 // resource is fully terminated.
 // If not set, graceful deletion of the object has not been requested.
 //
 // Populated by the system when a graceful deletion is requested.
 // Read-only.
 DeletionTimestamp *Time `json:"deletionTimestamp,omitempty" protobuf:"bytes,9,opt,name=deletionTimestamp"`

 // Number of seconds allowed for this object to gracefully terminate before
 // it will be removed from the system. Only set when deletionTimestamp is also set.
 // May only be shortened.
 // Read-only.
 DeletionGracePeriodSeconds *int64 `json:"deletionGracePeriodSeconds,omitempty" protobuf:"varint,10,opt,name=deletionGracePeriodSeconds"`

 // Map of string keys and values that can be used to organize and categorize
 // (scope and select) objects. May match selectors of replication controllers
 // and services.
 Labels map[string]string `json:"labels,omitempty" protobuf:"bytes,11,rep,name=labels"`

 // Annotations is an unstructured key value map stored with a resource that may be
 // set by external tools to store and retrieve arbitrary metadata. They are not
 // queryable and should be preserved when modifying objects.
 Annotations map[string]string `json:"annotations,omitempty" protobuf:"bytes,12,rep,name=annotations"`

 // List of objects depended by this object. If ALL objects in the list have
 // been deleted, this object will be garbage collected. If this object is managed by a controller,
 // then an entry in this list will point to this controller, with the controller field set to true.
 OwnerReferences []OwnerReference `json:"ownerReferences,omitempty" patchStrategy:"merge" patchMergeKey:"uid" protobuf:"bytes,13,rep,name=ownerReferences"`

 // Must be empty before the object is deleted from the registry. Each entry
 // is an identifier for the responsible component that will remove the entry
 // from the list. If the deletionTimestamp of the object is non-nil, entries
 // in this list can only be removed.
 // Finalizers may be processed and removed in any order.  Order is NOT enforced
 // because it introduces significant risk of stuck finalizers.
 // finalizers is a shared field, any actor with permission can reorder it.
 // If the finalizer list is processed in order, then this can lead to a situation
 // in which the component responsible for the first finalizer in the list is
 // waiting for a signal (field value, external system, or other) produced by a
 // component responsible for a finalizer later in the list, resulting in a deadlock.
 // Without enforced ordering finalizers are free to order amongst themselves and
 // are not vulnerable to ordering changes in the list.
 Finalizers []string `json:"finalizers,omitempty" patchStrategy:"merge" protobuf:"bytes,14,rep,name=finalizers"`

 // The name of the cluster which the object belongs to.
 // This is used to distinguish resources with same name and namespace in different clusters.
 // This field is not set anywhere right now and apiserver is going to ignore it if set in create or update request.
 ClusterName string `json:"clusterName,omitempty" protobuf:"bytes,15,opt,name=clusterName"`

 // ManagedFields maps workflow-id and version to the set of fields
 // that are managed by that workflow. This is mostly for internal
 // housekeeping, and users typically shouldn't need to set or
 // understand this field. A workflow can be the user's name, a
 // controller's name, or the name of a specific apply path like
 // "ci-cd". The set of fields is always in the version that the
 // workflow used when modifying the object.
 ManagedFields []ManagedFieldsEntry `json:"managedFields,omitempty" protobuf:"bytes,17,rep,name=managedFields"`
}

metav1.ObjectMeta 還實現了 metav1.Object 與 metav1.MetaAccessor 這兩個接口,其中 metav1.Object 接口定義了獲取單個資源對象各種元信息的 Get 與 Set 方法:

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/meta.go
//
// Object lets you work with object metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field (Name, UID, Namespace on lists) will be a no-op and return
// a default value.
type Object interface {
 GetNamespace() string
 SetNamespace(namespace string)
 GetName() string
 SetName(name string)
 GetGenerateName() string
 SetGenerateName(name string)
 GetUID() types.UID
 SetUID(uid types.UID)
 GetResourceVersion() string
 SetResourceVersion(version string)
 GetGeneration() int64
 SetGeneration(generation int64)
 GetSelfLink() string
 SetSelfLink(selfLink string)
 GetCreationTimestamp() Time
 SetCreationTimestamp(timestamp Time)
 GetDeletionTimestamp() *Time
 SetDeletionTimestamp(timestamp *Time)
 GetDeletionGracePeriodSeconds() *int64
 SetDeletionGracePeriodSeconds(*int64)
 GetLabels() map[string]string
 SetLabels(labels map[string]string)
 GetAnnotations() map[string]string
 SetAnnotations(annotations map[string]string)
 GetFinalizers() []string
 SetFinalizers(finalizers []string)
 GetOwnerReferences() []OwnerReference
 SetOwnerReferences([]OwnerReference)
 GetClusterName() string
 SetClusterName(clusterName string)
 GetManagedFields() []ManagedFieldsEntry
 SetManagedFields(managedFields []ManagedFieldsEntry)
}

metav1.MetaAccessor 接口則定義了獲取資源對象存取器的方法:

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/meta.go
//
type ObjectMetaAccessor interface {
 GetObjectMeta() Object
}

因爲 kubernetes 所有單體資源對象都繼承了 metav1.ObjectMeta,那麼所有的 API 資源對象就都實現了 metav1.Object 和 metav1.MetaAccessor 接口。kubernetes 中有很多地方訪問 API 資源對象的元信息並且不區分對象類型,只要是 metav1.Object 接口類型的對象都可以訪問。

metav1.ListMeta

metav1.ListMeta 定義了所有對象列表類型實例的公共屬性。

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/types.go
//
// ListMeta describes metadata that synthetic resources must have, including lists and
// various status objects. A resource may have only one of {ObjectMeta, ListMeta}.
type ListMeta struct {
 // selfLink is a URL representing this object.
 // Populated by the system.
 // Read-only.
 SelfLink string `json:"selfLink,omitempty" protobuf:"bytes,1,opt,name=selfLink"`

 // String that identifies the server's internal version of this object that
 // can be used by clients to determine when objects have changed.
 // Value must be treated as opaque by clients and passed unmodified back to the server.
 // Populated by the system.
 // Read-only.
 ResourceVersion string `json:"resourceVersion,omitempty" protobuf:"bytes,2,opt,name=resourceVersion"`

 // continue may be set if the user set a limit on the number of items returned, and indicates that
 // the server has more data available. The value is opaque and may be used to issue another request
 // to the endpoint that served this list to retrieve the next set of available objects. Continuing a
 // consistent list may not be possible if the server configuration has changed or more than a few
 // minutes have passed. The resourceVersion field returned when using this continue value will be
 // identical to the value in the first response, unless you have received this token from an error
 // message.
 Continue string `json:"continue,omitempty" protobuf:"bytes,3,opt,name=continue"`

 // remainingItemCount is the number of subsequent items in the list which are not included in this
 // list response. If the list request contained label or field selectors, then the number of
 // remaining items is unknown and the field will be left unset and omitted during serialization.
 // If the list is complete (either because it is not chunking or because this is the last chunk),
 // then there are no more remaining items and this field will be left unset and omitted during
 // serialization.
 // Servers older than v1.15 do not set this field.
 // The intended use of the remainingItemCount is *estimating* the size of a collection. Clients
 // should not rely on the remainingItemCount to be set or to be exact.
 RemainingItemCount *int64 `json:"remainingItemCount,omitempty" protobuf:"bytes,4,opt,name=remainingItemCount"`
}

類似於與 metav1.ObjectMeta 結構體,metav1.ListMeta 還實現了 metav1.ListInterface 與 metav1.ListMetaAccessor 這兩個接口,其中 metav1.ListInterface 接口定義了獲取資源對象列表各種元信息的 Get 與 Set 方法:

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/meta.go
//
// ListInterface lets you work with list metadata from any of the versioned or
// internal API objects. Attempting to set or retrieve a field on an object that does
// not support that field will be a no-op and return a default value.
type ListInterface interface {
 GetResourceVersion() string
 SetResourceVersion(version string)
 GetSelfLink() string
 SetSelfLink(selfLink string)
 GetContinue() string
 SetContinue(c string)
 GetRemainingItemCount() *int64
 SetRemainingItemCount(c *int64)
}

metav1.ListMetaAccessor 接口則定義了獲取資源對象列表存取器的方法:

// source code from https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/meta.go
//
// ListMetaAccessor retrieves the list interface from an object
type ListMetaAccessor interface {
 GetListMeta() ListInterface
}

runtime.Object

前面在介紹 metav1.TypeMeta 與 metav1.ObjectMeta 的時候我們發現 schema.ObjecKind 是所有 API 資源類型的抽象,metav1.Object 是所有 API 單體資源對象屬性的抽象,那麼同時實現這兩個接口的類型對象不就可以訪問任何 API 對象的公共屬性了嗎?是的,對於每一個特定的類型,如 Pod、Deployment 等,它們確實可以獲取當前 API 對象的公共屬性。有沒有一種所有特定類型的統一父類,同時擁有 schema.ObjecKind 和 metav1.Object 兩個接口,這樣就可以表示任何特定類型的對象。這就是本節要討論 runtime.Object 接口。

先來看看 runtime.Object 接口定義:

// source code from: https://github.com/kubernetes/apimachinery/blob/master/pkg/runtime/interfaces.go
//
// Object interface must be supported by all API types registered with Scheme. Since objects in a scheme are
// expected to be serialized to the wire, the interface an Object must provide to the Scheme allows
// serializers to set the kind, version, and group the object is represented as. An Object may choose
// to return a no-op ObjectKindAccessor in cases where it is not expected to be serialized.
type Object interface {
    // used to access type metadata(GVK)
    GetObjectKind() schema.ObjectKind
    // DeepCopyObject needed to implemented by each kubernetes API type definition,
    // usually by automatically generated code.
 DeepCopyObject() Object
}

爲什麼 runtime.Object 接口只有這兩個方法,不應該有 GetObjectMeta() 方法來獲取 metav1.ObjectMeta 對象嗎?仔細往下看的話會發現,這裏使用了不一樣的實現方式:

// source code from: https://github.com/kubernetes/apimachinery/blob/master/pkg/api/meta/meta.go
//
// Accessor takes an arbitrary object pointer and returns meta.Interface.
// obj must be a pointer to an API type. An error is returned if the minimum
// required fields are missing. Fields that are not required return the default
// value and are a no-op if set.
func Accessor(obj interface{}) (metav1.Object, error) {
 switch t := obj.(type) {
 case metav1.Object:
  return t, nil
 case metav1.ObjectMetaAccessor:
  if m := t.GetObjectMeta(); m != nil {
   return m, nil
  }
  return nil, errNotObject
 default:
  return nil, errNotObject
 }
}

Accessor 方法可以講任何的類型 metav1.Object 或者返回錯誤信息,這樣就避免了每個 API 資源類型都需要實現 GetObjectMeta() 方法了。

還有個問題是爲什麼沒有看到 API 資源類型實現 runtime.Object.DeepCopyObject() 方法?那是因爲深拷貝方法是具體 API 資源類型需要重載實現的,存在類型依賴,作爲 API 資源類型的父類不能統一實現。一般來說,深拷貝方法是由工具自動生成的,定義在 zz_generated.deepcopy.go 文件中,以 configMap 爲例:

// source code from https://github.com/kubernetes/api/blob/master/core/v1/zz_generated.deepcopy.go
//
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ConfigMap) DeepCopyObject() runtime.Object {
 if c := in.DeepCopy(); c != nil {
  return c
 }
 return nil
}

metav1.Unstructured

metav1.Unstructured 與具體實現 rutime.Object 接口的類型(如 Pod、Deployment、Service 等等)不同,如果說,各個實現 rutime.Object 接口的類型主要用於 client-go[1] 類型化的靜態客戶端,那麼 metav1.Unstructured 則用於動態客戶端。

在看 metav1.Unstructured 源碼實現之前,我們先了解一下什麼是結構化數據與非結構化數據。結構化數據,顧名思義,就是數據中的字段名與字段值都是固定的,例如一個 JSON 格式的字符串表示一個學生的信息:

{

 "id"101,
 "name""Tom"
}

定義這個學生的數據格式中的字段名與字段值都是固定的,我們很容易使用 Go 語言寫出一個 struct 結構來表示這個學生的信息,各個字段意義明確:

type Student struct {

 ID int
 Name String
}

實際的情況是,一個格式化的字符串裏面可能會包含很多編譯時未知的信息,這些信息只有在運行時才能獲取到。例如,上面的學生的數據中還包括第三個字段,該字段的類型和內容代碼編譯時未知,到運行時纔可以獲取具體的值。如何處理這種情況呢?熟悉反射的同學很快就應該想到,Go 語言可以依賴於反射機制在運行時動態獲取各個字段,在編譯階段,我們將這些未知的類型統一爲 interface{}。正是基於此,metav1.Unstructured 的數據結構定義很簡單:

// soure code from: https://github.com/kubernetes/apimachinery/blob/master/pkg/apis/meta/v1/unstructured/unstructured.go
//
type Unstructured struct {

 // Object is a JSON compatible map with string, float, int, bool, []interface{}, or
 // map[string]interface{} children.
 Object map[string]interface{}
}

事實上,metav1.Unstructured 是 apimachinery 中 runtime.Unstructured 接口的具體實現,runtime.Unstructured 接口定義了非結構化數據的操作接口方法列表,它提供程序來處理資源的通用屬性,例如 metadata.namespace 等。

// soure code from: https://github.com/kubernetes/apimachinery/blob/master/pkg/runtime/interfaces.go
//
// Unstructured objects store values as map[string]interface{}, with only values that can be serialized
// to JSON allowed.
type Unstructured interface {
 Object
 // NewEmptyInstance returns a new instance of the concrete type containing only kind/apiVersion and no other data.
 // This should be called instead of reflect.New() for unstructured types because the go type alone does not preserve kind/apiVersion info.
 NewEmptyInstance() Unstructured
 // UnstructuredContent returns a non-nil map with this object's contents. Values may be
 // []interface{}, map[string]interface{}, or any primitive type. Contents are typically serialized to
 // and from JSON. SetUnstructuredContent should be used to mutate the contents.
 UnstructuredContent() map[string]interface{}
 // SetUnstructuredContent updates the object content to match the provided map.
 SetUnstructuredContent(map[string]interface{})
 // IsList returns true if this type is a list or matches the list convention - has an array called "items".
 IsList() bool
 // EachListItem should pass a single item out of the list as an Object to the provided function. Any
 // error should terminate the iteration. If IsList() returns false, this method should return an error
 // instead of calling the provided function.
 EachListItem(func(Object) errorerror
}

只有 metav1.Unstructured 的定義並不能發揮什麼作用,真正重要的是其實現的方法,藉助這些方法可以靈活的處理非結構化數據。metav1.Unstructured 實現了存取類型元信息與對象元信息的方法,除此之外,它也實現了 runtime.Unstructured 接口中的所有方法。

基於這些方法,我們可以構建操作 kubernetes 資源的動態客戶端,不需要使用 k8s.io/api 中定義的 Go 類型,使用 metav1.Unstructured 非結構化直接解碼是 YAML/JSON 對象表示形式;非結構化數據編碼時生成的 JSON/YAML 外也不會添加額外的字段。

以下示例演示瞭如何將 YAML 清單讀爲非結構化,非結構化並將其編碼回 JSON:

import (
    "encoding/json"
    "fmt"
    "os"

    "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
    "k8s.io/apimachinery/pkg/runtime/serializer/yaml"
)

const dsManifest = `
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: example
  namespace: default
spec:
  selector:
    matchLabels:
      name: nginx-ds
  template:
    metadata:
      labels:
        name: nginx-ds
    spec:
      containers:
      - name: nginx
        image: nginx:latest
`


func main() {
    obj := &unstructured.Unstructured{}

    // decode YAML into unstructured.Unstructured
    dec := yaml.NewDecodingSerializer(unstructured.UnstructuredJSONScheme)
    _, gvk, err := dec.Decode([]byte(dsManifest), nil, obj)

    // Get the common metadata, and show GVK
    fmt.Println(obj.GetName(), gvk.String())

    // encode back to JSON
    enc := json.NewEncoder(os.Stdout)
    enc.SetIndent("""    ")
    enc.Encode(obj)
}

程序的輸出如下:

example apps/v1, Kind=DaemonSet
{
    "apiVersion""apps/v1",
    "kind""DaemonSet",
    "metadata": {
        "name""example",
        "namespace""default"
    },
    "spec": {
        "selector": {
            "matchLabels": {
                "name""nginx-ds"
            }
        },
        "template": {
            "metadata": {
                "labels": {
                    "name""nginx-ds"
                }
            },
            "spec": {
                "containers": [
                    {
                        "image""nginx:latest",
                        "name""nginx"
                    }
                ]
            }
        }
    }
}

此外,通過 Go 語言的反射機制可以實現 metav1.Unstructured 對象與具體資源對象的相互轉換,runtime.unstructuredConverter 接口定義了 metav1.Unstructured 對象與具體資源對象的相互轉換方法,並且內置了 runtime.DefaultUnstructuredConverter 實現了 runtime.unstructuredConverter 接口。

// source code from: https://github.com/kubernetes/apimachinery/blob/master/pkg/runtime/converter.go
//
// UnstructuredConverter is an interface for converting between interface{}
// and map[string]interface representation.
type UnstructuredConverter interface {
 ToUnstructured(obj interface{}) (map[string]interface{}, error)
 FromUnstructured(u map[string]interface{}, obj interface{}) error
}

小結

爲了便於記憶,現在對前面介紹的各種接口以及實現做一個小結:

  1. runtime.Object 接口是所有 API 單體資源對象的根類,各個 API 對象的編碼與解碼依賴於該接口類型;
  2. schema.ObjectKind 接口是對 API 資源對象類型的抽象,可以用來獲取或者設置 GVK;
  3. metav1.Object 接口是 API 資源對象屬性的抽象,用來存取資源對象的屬性;
  4. metav1.ListInterface 接口是 API 對象列表屬性的抽象,用來存取資源對象列表的屬性;
  5. metav1.TypeMeta 結構體實現了 schema.ObjectKind 接口,所有的 API 資源類型繼承它;
  6. metav1.ObjectMeta 結構體實現了 metav1.Object 接口,所有的 API 資源類型繼承它;
  7. metav1.ListMeta 結構體實現了 metav1.ListInterface 接口,所有的 API 資源對象列表類型繼承它;
  8. metav1.Unstructured 結構體實現了 runtime.Unstructured 接口,可以用於構建動態客戶端,從 metav1.Unstructured 的實例中可以獲取資源類型元信息與資源對象元信息,還可以獲取到對象的 map[string]interface{} 的通用內容表示;
  9. metav1.Unstructured 與實現了 metav1.Object 接口具體 API 類型進行相互轉化,轉換依賴於 runtime.UnstructuredConverter 的接口方法。

參考資料

[1]

client-go: https://github.com/kubernetes/client-go


原文鏈接:https://morven.life/posts/the_k8s_api-2/



你可能還喜歡

點擊下方圖片即可閱讀

GitHub 又又又多了一個新主題 —— Dimmed Dark 主題!

雲原生是一種信仰 🤘


關注公衆號

後臺回覆◉k8s◉獲取史上最方便快捷的 Kubernetes 高可用部署工具,只需一條命令,連 ssh 都不需要!



點擊 "閱讀原文" 獲取更好的閱讀體驗!


發現朋友圈變“安靜”了嗎?

本文分享自微信公衆號 - 雲原生實驗室(cloud_native_yang)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章