使用client-go 之dynamicclient(二)

在开发中碰到一个场景,在一个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文件中定义再多的资源类型也不怕了

参考:https://fankangbest.github.io/2017/07/22/RESTMapper%E8%A7%A3%E8%AF%BB(%E4%B8%80)-DefaultRESTMapper-v1-5-2/

https://www.kubernetes.org.cn/1309.html

你可能感兴趣的:(k8s,client-go)