使用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文件中定义再多的资源类型也不怕了

参考:RESTMapper解读(一)-DefaultRESTMapper-v1.5.2 | fankangbest

使用 client-go 控制原生及拓展的 Kubernetes API | PPT 实录_Kubernetes中文社区

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值