DiscoveryClient是什么
我们前面学习的3种Client:RESTClient、Clientset、DynamicClient,都是用来操作 kubernetes 资源的,我们目前还缺少一个用于检索 kuberentes资源的 Client
DiscoveryClient 就是这样一个 Client。用于检索 kuberentes集群中支持的 API 资源的相关信息,例如版本、组、资源类型等。
DiscoveryClient 提供了一组方法来查询和获取这些信息,以便在编写 Controller 或 Operator 时,能够动态地了解集群中可用的资源。
DiscoveryClient结构体
位于 staging/src/k8s.io/client-go/discovery/discovery_client.go
DiscoveryClient 结构体很简单
LegacyPrefix 字段表示旧版本资源的访问前缀,一般值都是/api。Kubernetes 1.16 以前,资源的访问前缀都是 /api,1.16及之后,全面改成 /apis,为了兼容旧资源,这里特意保存了一个常量字符串 /api1 2 3 4 5 6 7 type DiscoveryClient struct { restClient restclient.Interface LegacyPrefix string // Forces the client to request only "unaggregated" (legacy) discovery. UseLegacyDiscovery bool }
DiscoveryClient的常用方法 1、discovery.NewDiscoveryClientForConfig()方法
位于 /client-go/discovery/discovery_client.go,是一个函数,位于discovery包下,所以直接点就可以使用
该方法用于创建一个 DiscoveryClient 实例,入参也是 *rest.Config 类型
1 2 3 4 5 6 7 8 9 10 11 func NewDiscoveryClientForConfig(c *restclient.Config) (*DiscoveryClient, error) { config := *c if err := setDiscoveryDefaults(&config); err != nil { return nil, err } httpClient, err := restclient.HTTPClientFor(&config) if err != nil { return nil, err } return NewDiscoveryClientForConfigAndClient(&config, httpClient) }
2、DiscoveryClient的实例方法
DiscoveryClient 实现了接口的所有方法,用于获取API资源的各种信息
ServerGroupsInterface等这些接口,内部也有很多方法1 2 3 4 5 6 7 8 9 10 11 12 type DiscoveryInterface interface { RESTClient() restclient.Interface ServerGroupsInterface ServerResourcesInterface ServerVersionInterface OpenAPISchemaInterface OpenAPIV3SchemaInterface // Returns copy of current discovery client that will only // receive the legacy discovery format, or pointer to current // discovery client if it does not support legacy-only discovery. WithLegacy() DiscoveryInterface }
CachedDiscoveryClient 和 DiscoveryClient 的区别
在查看 DiscoveryInterface 的时候,除了 DiscoveryClient,还有一个实现类 CachedDiscoveryClient
顾名思义,CachedDiscoveryClient 就是实现了缓存机制的 DiscoveryClient 的封装
CachedDiscoveryClient 在 DiscoveryClient 的基础上增加了一层缓存,用于缓存获取的资源信息,以减少对 API Server 的频繁请求。
在首次调用时,CachedDiscoveryClient 会从 API Server 获取资源信息,并将其缓存在本地。之后的调用会直接从缓存中获取资源信息,而不需要再次向 API Server 发送请求。
因为 集群部署完成后,API 资源基本很少变化,所以缓存下来可以很好的提高请求效率。
kubectl 工具内部,kubectl api-versions命令其实就是使用了这个CachedDiscoveryClient,所以多次执行kubectl api-versions命令,其实只有第一次请求了API Server,后续都是直接使用的 本地缓存。
DiscoveryClient 使用示例
需求:获取 当前kubernetes集群 的 所有资源列表
代码编写1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 func main() { // 1、先创建一个客户端配置config config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile) if err != nil { panic(err.Error()) } // 2、使用 discovery.NewDiscoveryClientForConfig(),创建一个 DiscoveryClient 对象 discoveryClient, err := discovery.NewDiscoveryClientForConfig(config) if err != nil { panic(err.Error()) } // 3、使用 DiscoveryClient.ServerGroupsAndResources(),获取所有资源列表 _, resourceLists, err := discoveryClient.ServerGroupsAndResources() if err != nil { panic(err.Error()) } // 4、遍历资源列表,打印出资源组和资源名称 for _, resource := range resourceLists { fmt.Printf("resource groupVersion: %s\n", resource.GroupVersion) for _, resource := range resource.APIResources { fmt.Printf("resource name: %s\n", resource.Name) } fmt.Println("--------------------------") } }
输出结果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 resource groupVersion: v1 resource name: bindings resource name: componentstatuses resource name: configmaps resource name: endpoints resource name: events resource name: limitranges resource name: namespaces resource name: namespaces/finalize resource name: namespaces/status resource name: nodes resource name: nodes/proxy resource name: nodes/status resource name: persistentvolumeclaims resource name: persistentvolumeclaims/status resource name: persistentvolumes resource name: persistentvolumes/status resource name: pods resource name: pods/attach resource name: pods/binding resource name: pods/eviction resource name: pods/exec resource name: pods/log resource name: pods/portforward resource name: pods/proxy resource name: pods/status resource name: podtemplates resource name: replicationcontrollers resource name: replicationcontrollers/scale resource name: replicationcontrollers/status resource name: resourcequotas resource name: resourcequotas/status resource name: secrets resource name: serviceaccounts resource name: services resource name: services/proxy resource name: services/status -------------------------- resource groupVersion: apiregistration.k8s.io/v1 resource name: apiservices resource name: apiservices/status -------------------------- resource groupVersion: apiregistration.k8s.io/v1beta1 resource name: apiservices resource name: apiservices/status -------------------------- resource groupVersion: extensions/v1beta1 resource name: ingresses resource name: ingresses/status -------------------------- resource groupVersion: apps/v1 resource name: controllerrevisions resource name: daemonsets resource name: daemonsets/status resource name: deployments resource name: deployments/scale resource name: deployments/status resource name: replicasets resource name: replicasets/scale resource name: replicasets/status resource name: statefulsets resource name: statefulsets/scale resource name: statefulsets/status -------------------------- resource groupVersion: events.k8s.io/v1beta1 resource name: events -------------------------- resource groupVersion: authentication.k8s.io/v1 resource name: tokenreviews -------------------------- resource groupVersion: authentication.k8s.io/v1beta1 resource name: tokenreviews -------------------------- resource groupVersion: authorization.k8s.io/v1 resource name: localsubjectaccessreviews resource name: selfsubjectaccessreviews resource name: selfsubjectrulesreviews resource name: subjectaccessreviews -------------------------- resource groupVersion: authorization.k8s.io/v1beta1 resource name: localsubjectaccessreviews resource name: selfsubjectaccessreviews resource name: selfsubjectrulesreviews resource name: subjectaccessreviews -------------------------- resource groupVersion: autoscaling/v1 resource name: horizontalpodautoscalers resource name: horizontalpodautoscalers/status -------------------------- resource groupVersion: autoscaling/v2beta1 resource name: horizontalpodautoscalers resource name: horizontalpodautoscalers/status -------------------------- resource groupVersion: autoscaling/v2beta2 resource name: horizontalpodautoscalers resource name: horizontalpodautoscalers/status -------------------------- resource groupVersion: batch/v1 resource name: jobs resource name: jobs/status -------------------------- resource groupVersion: batch/v1beta1 resource name: cronjobs resource name: cronjobs/status -------------------------- resource groupVersion: certificates.k8s.io/v1beta1 resource name: certificatesigningrequests resource name: certificatesigningrequests/approval resource name: certificatesigningrequests/status -------------------------- resource groupVersion: networking.k8s.io/v1 resource name: networkpolicies -------------------------- resource groupVersion: networking.k8s.io/v1beta1 resource name: ingresses resource name: ingresses/status -------------------------- resource groupVersion: policy/v1beta1 resource name: poddisruptionbudgets resource name: poddisruptionbudgets/status resource name: podsecuritypolicies -------------------------- resource groupVersion: rbac.authorization.k8s.io/v1 resource name: clusterrolebindings resource name: clusterroles resource name: rolebindings resource name: roles -------------------------- resource groupVersion: rbac.authorization.k8s.io/v1beta1 resource name: clusterrolebindings resource name: clusterroles resource name: rolebindings resource name: roles -------------------------- resource groupVersion: storage.k8s.io/v1 resource name: csinodes resource name: storageclasses resource name: volumeattachments resource name: volumeattachments/status -------------------------- resource groupVersion: storage.k8s.io/v1beta1 resource name: csidrivers resource name: csinodes resource name: storageclasses resource name: volumeattachments -------------------------- resource groupVersion: admissionregistration.k8s.io/v1 resource name: mutatingwebhookconfigurations resource name: validatingwebhookconfigurations -------------------------- resource groupVersion: admissionregistration.k8s.io/v1beta1 resource name: mutatingwebhookconfigurations resource name: validatingwebhookconfigurations -------------------------- resource groupVersion: apiextensions.k8s.io/v1 resource name: customresourcedefinitions resource name: customresourcedefinitions/status -------------------------- resource groupVersion: apiextensions.k8s.io/v1beta1 resource name: customresourcedefinitions resource name: customresourcedefinitions/status -------------------------- resource groupVersion: scheduling.k8s.io/v1 resource name: priorityclasses -------------------------- resource groupVersion: scheduling.k8s.io/v1beta1 resource name: priorityclasses -------------------------- resource groupVersion: coordination.k8s.io/v1 resource name: leases -------------------------- resource groupVersion: coordination.k8s.io/v1beta1 resource name: leases -------------------------- resource groupVersion: node.k8s.io/v1beta1 resource name: runtimeclasses -------------------------- resource groupVersion: discovery.k8s.io/v1beta1 resource name: endpointslices --------------------------