在開發中碰到一個場景,在一個yaml文件中同時定義了deployment和service兩種資源類型(可能還有更多個),然後需要對該yaml文件進行解析,並對解析出的資源對象進行過一系列操作。如果使用typed clients你的代碼也許會像下面這樣:
//僞代碼
var deployment apps_v1.Deployment{}
var service core_v1.Service{}
var Raw []byte
var data map[string]interface{}
clientset, err := kubernetes.NewForConfig(&config)
b,err :=ioutil.ReadFile("template.yaml")
d := yaml.NewYAMLOrJSONDecoder(bytes.NewReader(b), 4096)
for {
d.decode(&Raw)
json.Unmarshal(Raw, &data)
if data["kind"] == "Deployment"{
//處理邏輯
clientset.AppsV1.deployment()
}
if data["kind"] == "Service"{
//處理邏輯
clientset.CoreV1.service()
}
}
如果yaml文件中還有ingress,configmap等等多個資源類型,每增加一種,你都需要重新定義一個資源對象,增加一個判斷。是不是相當繁瑣?
還好client-go中提供了dynamic client,使用該clientset後,代碼變成如下:
//僞代碼
client, err := dynamic.NewForConfig(config)
resp, err =client.Resource(gvr).Namespace(namespace).Get(name,metav1.GetOptions{})
看到沒,接下去只需要解析出gvr對象,就能對所有資源類型進行響應操作,那接下來我們解決下一個問題,怎麼解析出gvr。
在解析出gvr對象前,我們先了解下什麼是RESTMapper。RESTMapper是一個interface,定義在/pkg/meta/interfaces.go中:
// RESTMapper allows clients to map resources to kind, and map kind and version
// to interfaces for manipulating those objects. It is primarily intended for
// consumers of Kubernetes compatible REST APIs as defined in docs/devel/api-conventions.md.
//
// The Kubernetes API provides versioned resources and object kinds which are scoped
// to API groups. In other words, kinds and resources should not be assumed to be
// unique across groups.
//
// TODO: split into sub-interfaces
type RESTMapper interface {
// KindFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
KindFor(resource schema.GroupVersionResource) (schema.GroupVersionKind, error)
// KindsFor takes a partial resource and returns the list of potential kinds in priority order
KindsFor(resource schema.GroupVersionResource) ([]schema.GroupVersionKind, error)
// ResourceFor takes a partial resource and returns the single match. Returns an error if there are multiple matches
ResourceFor(input schema.GroupVersionResource) (schema.GroupVersionResource, error)
// ResourcesFor takes a partial resource and returns the list of potential resource in priority order
ResourcesFor(input schema.GroupVersionResource) ([]schema.GroupVersionResource, error)
// RESTMapping identifies a preferred resource mapping for the provided group kind.
RESTMapping(gk schema.GroupKind, versions ...string) (*RESTMapping, error)
// RESTMappings returns all resource mappings for the provided group kind if no
// version search is provided. Otherwise identifies a preferred resource mapping for
// the provided version(s).
RESTMappings(gk schema.GroupKind, versions ...string) ([]*RESTMapping, error)
ResourceSingularizer(resource string) (singular string, err error)
}
是不是在這個接口中看到了gvk和gvr了,我們再看下RESTMapping是什麼:
// RESTMapping contains the information needed to deal with objects of a specific
// resource and kind in a RESTful manner.
type RESTMapping struct {
// Resource is the GroupVersionResource (location) for this endpoint
Resource schema.GroupVersionResource
// GroupVersionKind is the GroupVersionKind (data format) to submit to this endpoint
GroupVersionKind schema.GroupVersionKind
// Scope contains the information needed to deal with REST Resources that are in a resource hierarchy
Scope RESTScope
}
也就是說我們可以通過RESTMapper接口的RESTMapping方法通過gvk獲得gvr。剩下的問題就是如何解析出gvk以及創建RESTMapper對象,我們通過代碼直觀展現:
//僞代碼
restMapperRes, err := restmapper.GetAPIGroupResources(dc)
restMapper := restmapper.NewDiscoveryRESTMapper(restMapperRes)
for {
//yaml解析成[]byte
obj, gvk, err := unstructured.UnstructuredJSONScheme.Decode([]byte, nil, nil)
mapping, err := restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
resp,err :=dclient.Resource(mapping.Resource).Namespace(namespace).Get(name,metav1.GetOptions{})
}
這樣在單個yaml文件中定義再多的資源類型也不怕了