3. DynamicClient
DynamicClient 是一种动态客户端,通过动态指定资源组、资源版本和资源等信息,它可以操作任意的Kubernetes资源,即不仅可以操作 Kubernetes 自身内置的资源,还可操作 CRD。这也是 DynamicClient与之前介绍的 ClientSet 客户端最显著的一个区别。
ClientSet与 DynamicClient 的区别如下。
ClientSet默认只能操作 Kubernetes内置的资源,不能直接操作 CRD,并且使用类型化客户端 ClientSet 时,程序也会与所使用的版本和类型紧密耦合。DynamicClient使用嵌套的 map[string]-interface{] 结构存储 KubernetesAPIServer的返回值,利用反射机制在运行时进行数据绑定,松耦合意味着更高的灵活性,但无法获取强数据类型检查和验证的好处。
在介绍 DynamicClient之前,首先了解一下 Object.runtime接口和 Unstructured结构体,这有助于理解 DynamicClient的实现。
(1) Object.runtime:Kubernetes中所有的资源对象(例如,Pod、Deployment、CRD等)都实现了 Object.runtime接口,其包含 DeepCopyObject和 GetObjectKind方法,分别用于对象深拷贝和获取对象的具体资源类型(Kind)。
(2) Unstructured:Unstructured结构体包含 map[string]interface{} 类型字段,在处理无法预知结构的数据时,将数据值存入 interface{} 中,待运行时利用反射判断。该结构体包含大量工具方法,方便处理非结构化数据。
DynamicClient代码示例见代码清单 2-18。
代码清单 2-18
packagemain
import(
"context"
"fmt"
appsv1"k8s.io/api/apps/v1"
metav1"k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/apimachinery/pkg/runtime""k8s.io/apimachinery/pkg/runtime/schema""k8s.io/client-go/dynamic"
"k8s.io/client-go/tools/clientcmd"
)
funcmain(){
//加载 kubeconfig⽂件,⽣成 config对象
config,err:=clientcmd.BuildConfigFromFlags("","/root/.kube/config")
iferr!=nil{
panic(err)
}
//dynamic.NewForConfig函数通过config实例化 dynamicClient对象
dynamicClient,err:=dynamic.NewForConfig(config)
iferr!=nil{
panic(err)
}
//通过schema.GroupVersionResource设置要请求对象的资源组、资源版本和资源
//设置命名空间和请求参数, 得到 unstructured.UnstructuredList指针类型的PodList
gvr:=schema.GroupVersionResource{Group:"apps",Version:"v1",Resource:"deployments"}
unstructObj,err:=dynamicClient.Resource(gvr).Namespace("kube-system").List(context.TODO(),metav1.ListOptions{Limit:10},
)
iferr!=nil{
panic(err)
}
//通过 runtime.DefaultUnstructuredConverter函数将 unstructured.UnstructuredList
//转为DeploymentList类型
deploymentList:=&appsv1.DeploymentList{}
err=runtime.DefaultUnstructuredConverter.FromUnstructured(
unstructObj.UnstructuredContent(),deploymentList,
)
iferr!=nil{
panic(err)
}
for_,v:=rangedeploymentList.Items{
fmt.Printf(
"KIND:%v\tNAMESPACE:%v\tNAME:%v\n",
v.Kind,v.Namespace,v.Name,
)
}
}
运行以上代码,会获得 Kube-System域中部分Deployment的信息,打印输出见代码清单 2-19。
代码清单 2-19
# 运⾏输出
KIND: Deployment NAMESPACE: kube-system NAME:calico-kube-controllers
KIND: Deployment NAMESPACE: kube-system NAME:coredns
KIND: Deployment NAMESPACE: kube-system NAME:kube-state-metrics
KIND: Deployment NAMESPACE: kube-system NAME:metrics-server
KIND: Deployment NAMESPACE: kube-system NAME:nginx
...
???????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????
????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
代码清单 2-20
func NewForConfig(inConfig *rest.Config) (Interface, error) {
//...
restClient, err := rest.RESTClientFor(config)
//...
return &dynamicClient{client: restClient}, nil
}
???????????????????????????? ???????????????????????????????????????????????????????????????????????????????? ???????????????????????????????????????????????? ????????????????????????????????????????????????????????
???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????
代码清单 2-21
func (c *dynamicClient) Resource(resource schema.GroupVersionResource)
NamespaceableResourceInterface {
return &dynamicResourceClient{client: c, resource: resource}
}
List方法中首先获得 Kubernetes APIServer返回的 Deployment信息,此时数据是二进制格式的 JSON, 利用 UnstructuredJSONScheme解析器将 JSON格式的数据写入 Unstructured/UnstructuredList类型的对象中并返回, 由于使用 runtime.Object接口作为返回类型,因此,后续需要进行类型强制转换,即uncastObj.(*unstructured.
UnstructuredList)或uncastObj.(*unstruc-tured.Unstructured()
见代码清单2-22)。???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? ????????????????????????
代码清单 2-22
func (c *dynamicResourceClient) List(ctx context.Context, opts metav1.
ListOptions) (*unstructured.UnstructuredList, error) {
result := c.client.client.Get().AbsPath(c.makeURLSegments("")...).SpecificallyVersionedParams(&
opts, dynamicParameterCodec, versionV1).Do(ctx)
//...
uncastObj, err := runtime.Decode(unstructured.UnstructuredJSONScheme,
retBytes)
//...
if list, ok := uncastObj.(*unstructured.UnstructuredList); ok {
//...
list, err := uncastObj.(*unstructured.Unstructured).ToList()
//...
}
????此时已经获得 Unstructured/UnstructuredList类型的 Deployment信息,之后将其转化为标准的 Deployment/DeploymentList结构即可,通过 DefaultUnstructuredConverter结构体的 FromUnstructured方法来实现,其利用反射机制将 unstructObj.UnstructuredContent()返回的 map[string]interface{} 类型对象转化为DeploymentList类型对象。