<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          深入 kubernetes API 的源碼實(shí)現(xiàn)

          共 43673字,需瀏覽 88分鐘

           ·

          2021-03-26 11:14


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

          api

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

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

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

          從編程的角度來看,序列化的 pod 對象最終會被發(fā)送到 API-Server 并解碼為 Pod 類型的 Go 結(jié)構(gòu)體,同時 YAML 中的各個字段會被賦值給該 Go 結(jié)構(gòu)體。那么,Pod 類型在 Go 語言結(jié)構(gòu)體中是怎么定義的呢?

          // source code from https://github.com/kubernetes/api/blob/master/core/v1/types.go
          type Pod struct {
              // 從TypeMeta字段名可以看出該字段定義Pod類型的元信息,類似于面向?qū)ο缶幊汤锩?/span>
              // Class本身的元信息,類似于Pod類型的API分組、API版本等
              metav1.TypeMeta `json:",inline"`
              // ObjectMeta字段定義單個Pod對象的元信息。每個kubernetes資源對象都有自己的元信息,
              // 例如名字、命名空間、標(biāo)簽、注釋等等,kuberentes把這些公共的屬性提取出來就是
              // metav1.ObjectMeta,成為了API對象類型的父類
              metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`
              // PodSpec表示Pod類型的對象定義規(guī)范,最為代表性的就是CPU、內(nèi)存的資源使用。
              // 這個字段和YAML中spec字段對應(yīng)
              Spec PodSpec `json:"spec,omitempty" protobuf:"bytes,2,opt,name=spec"`
              // PodStatus表示Pod的狀態(tài),比如是運(yùn)行還是掛起、Pod的IP等等。Kubernetes會根據(jù)pod在
              // 集群中的實(shí)際狀態(tài)來更新PodStatus字段
              Status PodStatus `json:"status,omitempty" protobuf:"bytes,3,opt,name=status"`
          }

          從上面 Pod 定義的結(jié)構(gòu)體可以看出,它繼承了 metav1.TypeMeta 和 metav1.ObjectMeta 兩個類型,metav1.TypeMeta 對應(yīng) YAML 中的 kind 與 apiVersion 段,而 metav1.ObjectMeta 則對應(yīng) metadata 字段。這其實(shí)也可以從 Go 結(jié)構(gòu)體的字段 json 標(biāo)簽看得出來。除了 metav1.TypeMeta 和 metav1.ObjectMeta 字段,Pod 結(jié)構(gòu)體同時還定義了 Spec 和 Status 兩個成員變量。如果去查看 k8s.io/api 倉庫中其他 API 資源結(jié)構(gòu)體的定義就會發(fā)現(xiàn) kubernetes 絕大部分 API 資源類型都是這樣的結(jié)構(gòu),這也就是說 kubernetes API 資源類型都繼承 metav1.TypeMeta 和 metav1.ObjectMeta,前者用于定義資源類型的屬性,后者用于定義資源對象的公共屬性;Spec 用于定義 API 資源類型的私有屬性,也是不同 API 資源類型之間的區(qū)別所在;Status 則是用于描述每個資源對象的狀態(tài),這和每個資源類型緊密相關(guān)的。

          關(guān)于 metav1.TypeMeta 和 metav1.ObjectMeta 字段從語義上也很好理解,這兩個類型作為所有 kubernetes API 資源對象的基類,每個 API 資源對象需要 metav1.TypeMeta 字段用于描述自己是什么類型,這樣才能構(gòu)造相應(yīng)類型的對象,所以相同類型的所有資源對象的 metav1.TypeMeta 字段都是相同的,但是 metav1.ObjectMeta 則不同,它是定義資源對象實(shí)例的屬性,即所有資源對象都應(yīng)該具備的屬性。這部分就是和對象本身相關(guān),和類型無關(guān),所以相同類型的資源對象的 metav1.ObjectMeta 可能是不同的。

          在 kubernetes 的 API 資源對象中除了單體對象外,還有對象列表類型,用于描述一組相同類型的對象列表。對象列表的典型應(yīng)用場景就是列舉,對象列表就可以表達(dá)一組資源對象??赡苡行┳x者會問為什么不用對象的 slice,例如[]Pod,伴隨著筆者對對象列表的解釋讀者就會理解,此處以 PodList 為例進(jìn)行分析:

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

          在開始下一節(jié)的內(nèi)容之前,我們先做個小結(jié):

          1. metav1.TypeMeta 和 metav1.ObjectMeta 是所有 API 單體資源對象的父類;
          2. metav1.TypeMeta 和 metav1.ListMeta 是所有 API 資源對象列表的父類;
          3. metav1.TypeMeta 是所有 API 資源對象的父類,因?yàn)樗械馁Y源對象都要說明表示是什么類型;

          metav1

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

          metav1.TypeMeta

          metav1.TypeMeta 用來描述 kubernetes API 資源對象類型的元信息,包括資源類型的名字以及對應(yīng) 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"`
          }

          細(xì)心的同學(xué)還會發(fā)現(xiàn) metav1.TypeMeta 實(shí)現(xiàn)了 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 對象的實(shí)例(也就是任何 kubernetes API 資源對象)都可以通過 GetObjectKind() 方法獲取到 schema.ObjectKind 類型對象,而 TypeMeta 對象的實(shí)例本身也實(shí)現(xiàn)了 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 則用來定義資源對象實(shí)例的屬性,即所有資源對象都應(yīng)該具備的屬性。這部分就是和對象本身相關(guān),和類型無關(guān),所以相同類型的資源對象的 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 還實(shí)現(xiàn)了 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
          }

          因?yàn)?kubernetes 所有單體資源對象都繼承了 metav1.ObjectMeta,那么所有的 API 資源對象就都實(shí)現(xiàn)了 metav1.Object 和 metav1.MetaAccessor 接口。kubernetes 中有很多地方訪問 API 資源對象的元信息并且不區(qū)分對象類型,只要是 metav1.Object 接口類型的對象都可以訪問。

          metav1.ListMeta

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

          // 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 結(jié)構(gòu)體,metav1.ListMeta 還實(shí)現(xiàn)了 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 的時候我們發(fā)現(xiàn) schema.ObjecKind 是所有 API 資源類型的抽象,metav1.Object 是所有 API 單體資源對象屬性的抽象,那么同時實(shí)現(xiàn)這兩個接口的類型對象不就可以訪問任何 API 對象的公共屬性了嗎?是的,對于每一個特定的類型,如 Pod、Deployment 等,它們確實(shí)可以獲取當(dāng)前 API 對象的公共屬性。有沒有一種所有特定類型的統(tǒng)一父類,同時擁有 schema.ObjecKind 和 metav1.Object 兩個接口,這樣就可以表示任何特定類型的對象。這就是本節(jié)要討論 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 接口只有這兩個方法,不應(yīng)該有 GetObjectMeta() 方法來獲取 metav1.ObjectMeta 對象嗎?仔細(xì)往下看的話會發(fā)現(xiàn),這里使用了不一樣的實(shí)現(xiàn)方式:

          // 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 資源類型都需要實(shí)現(xiàn) GetObjectMeta() 方法了。

          還有個問題是為什么沒有看到 API 資源類型實(shí)現(xiàn) runtime.Object.DeepCopyObject() 方法?那是因?yàn)樯羁截惙椒ㄊ蔷唧w API 資源類型需要重載實(shí)現(xiàn)的,存在類型依賴,作為 API 資源類型的父類不能統(tǒng)一實(shí)現(xiàn)。一般來說,深拷貝方法是由工具自動生成的,定義在 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 與具體實(shí)現(xiàn) rutime.Object 接口的類型(如 Pod、Deployment、Service 等等)不同,如果說,各個實(shí)現(xiàn) rutime.Object 接口的類型主要用于 client-go[1] 類型化的靜態(tài)客戶端,那么 metav1.Unstructured 則用于動態(tài)客戶端。

          在看 metav1.Unstructured 源碼實(shí)現(xiàn)之前,我們先了解一下什么是結(jié)構(gòu)化數(shù)據(jù)與非結(jié)構(gòu)化數(shù)據(jù)。結(jié)構(gòu)化數(shù)據(jù),顧名思義,就是數(shù)據(jù)中的字段名與字段值都是固定的,例如一個 JSON 格式的字符串表示一個學(xué)生的信息:

          {

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

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

          type Student struct {

           ID int
           Name String
          }

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

          // 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{}
          }

          事實(shí)上,metav1.Unstructured 是 apimachinery 中 runtime.Unstructured 接口的具體實(shí)現(xiàn),runtime.Unstructured 接口定義了非結(jié)構(gòu)化數(shù)據(jù)的操作接口方法列表,它提供程序來處理資源的通用屬性,例如 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 的定義并不能發(fā)揮什么作用,真正重要的是其實(shí)現(xiàn)的方法,借助這些方法可以靈活的處理非結(jié)構(gòu)化數(shù)據(jù)。metav1.Unstructured 實(shí)現(xiàn)了存取類型元信息與對象元信息的方法,除此之外,它也實(shí)現(xiàn)了 runtime.Unstructured 接口中的所有方法。

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

          以下示例演示了如何將 YAML 清單讀為非結(jié)構(gòu)化,非結(jié)構(gòu)化并將其編碼回 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 語言的反射機(jī)制可以實(shí)現(xiàn) metav1.Unstructured 對象與具體資源對象的相互轉(zhuǎn)換,runtime.unstructuredConverter 接口定義了 metav1.Unstructured 對象與具體資源對象的相互轉(zhuǎn)換方法,并且內(nèi)置了 runtime.DefaultUnstructuredConverter 實(shí)現(xiàn)了 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
          }

          小結(jié)

          為了便于記憶,現(xiàn)在對前面介紹的各種接口以及實(shí)現(xiàn)做一個小結(jié):

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

          參考資料

          [1]

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


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



          你可能還喜歡

          點(diǎn)擊下方圖片即可閱讀

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

          云原生是一種信仰 ??


          關(guān)注公眾號

          后臺回復(fù)?k8s?獲取史上最方便快捷的 Kubernetes 高可用部署工具,只需一條命令,連 ssh 都不需要!



          點(diǎn)擊 "閱讀原文" 獲取更好的閱讀體驗(yàn)!


          發(fā)現(xiàn)朋友圈變“安靜”了嗎?

          瀏覽 90
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評論
          圖片
          表情
          推薦
          點(diǎn)贊
          評論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  女人一级A片色黄情免费 | 香蕉网-大香蕉网 | 高清无码啪啪视频 | 婷婷五月天婷婷五月天婷婷五月天色 | 亚洲人xxxxc |