Welcome to my GitHub


Content: all the original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOps and so on;

About the DiscoveryClient

  • This is the fifth article in the Client-Go series, which focuses on the final type of client: Unlike ClientSet and DynamicClient, which we studied earlier, which are oriented towards resource objects (such as creating Deployment instances and viewing POD instances), DiscoveryClient focuses on resources. For example, to see what groups, versions and resources Kubernetes currently has, the following is the field and association method of DiscoveryClient data structure. Once again, you can see the familiar RESTClient field. There are also several methods related to Group, Version and Resource:

  • The DiscoveryClient data structure has two fields: RestClient and LegacyPrefix. The LegacyPrefix? < FONT color=”red”>/ API

    appears to be part of the URL:

  • Pick one of the DiscoveryClient associated methods and see the red box below. Sure enough, LegacyPrefix is part of the URL:

  • Compared to the other clients, DiscoveryClient is a little easier, just go straight to the real world!

Need to confirm

  • The actual demand is very simple: from Kubernetes query all the Group, Version, Resource information, printed in the console;

Download the source code

  • This source may be downloaded in the lot to in actual combat, address and link information shown in the following table (https://github.com/zq2599/blo… :
The name of the link note
Project home page https://github.com/zq2599/blo… The project’s home page on GitHub
Git repository address (HTTPS) https://github.com/zq2599/blo… The project source warehouse address, HTTPS protocol
Git repository address (SSH) mailto:[email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  • The tutorials for the client-go tutorials are under the client-go-tutorials > folder, as shown in the red box below:

  • DiscoveryClientDemo >


  • Create a new folder discoveryClientDemo and execute the following commands to create a new module:
go mod init discoveryclientdemo
  • IO/API and k8s. IO /client-go. Make sure the version matches the Kubernetes environment:
Go get k8s.io/[email protected] go get k8s.io/ right
  • The second value returned by the ServerGroupSandResources method, which has slices in its data structure and slices in each element of the slice, is the information for each resource:
package main import ( "flag" "fmt" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/discovery" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" "path/filepath" ) func main() { var kubeconfig If home:=homedir. Homedir (); if home:=homedir. Homedir (); home ! = "" {// If the kubeconfig parameter is entered, the value of this parameter is the absolute path of the kubeconfig file. // If no kubeconfig parameter is entered, ~/.kube/config kubeconfig = Flag.string ("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")} else {// If you can't get the current user's home directory, there is no way to set the default directory for kubeconfig, You can only take kubeconFig = Flag.String (" kubeconFig ", "", "Absolute path to the kubeconfig file")} flag.parse () // Load the kubeconfig configuration file from the native, So the first parameter to an empty string config, err: = clientcmd. BuildConfigFromFlags (", "* kubeconfig) / / kubeconfig loaded directly out of the failure if err! = nil {panic(err.error ())} // create new discoveryClient instance discoveryClient, err := discovery.NewDiscoveryClientForConfig(config) if err ! = nil {panic(err.error ())} // Get all group and resource data apiGroup, apiResourceListSlice, err := discoveryClient.ServerGroupsAndResources() if err ! = nil {panic(err.error ())} fmt.printf (" apiGroup :\n\n %v\n\n\n\n", apiGroup) // apiResouceListSlice is a slice, For _, singLeapIResourceList := range apiResourceListSlice {// GroupVersion is a string, For example "apps/v1" groupVerionStr: = singleAPIResourceList. GroupVersion gv / / ParseGroupVersion method into a string data structure, err := schema.ParseGroupVersion(groupVerionStr) if err ! = nil { panic(err.Error()) } fmt.Println("*****************************************************************") Fmt.printf ("GV string [%v]\nGV struct [%#v]\ nResources :\n\n", groupVerionStr, GV) // APIResources is a slice, Inside is all resources for _, under the current GroupVersion singleAPIResource: = range singleAPIResourceList. APIResources {FMT. Printf (" % v \ n ", singleAPIResource.Name) } } }
  • go run main.go
. ***************************************************************** GV string [discovery.k8s.io/v1beta1] GV struct [schema.GroupVersion{Group:"discovery.k8s.io", Version:"v1beta1"}] resources : endpointslices ***************************************************************** GV string [flowcontrol.apiserver.k8s.io/v1beta1] GV struct [schema.GroupVersion{Group:"flowcontrol.apiserver.k8s.io", Version:"v1beta1"}] resources : flowschemas flowschemas/status prioritylevelconfigurations prioritylevelconfigurations/status
  • This is the basic use of DiscoveryClient. Do you think this is too easy? Let’s take a look at the surrounding environment of DiscoveryClient.

How to use DiscoveryClient in Kubectl

  • kubectl api-versions
zhaoqin@zhaoqindeMBP-2 discoveryclientdemo % kubectl api-versions
  • By looking at the Kubectl source code, we can see that the above command was implemented using DiscoveryClient, as shown in the red box below:

  • It is not clear whether “O.DiscoveryClient” in red box 2 above is DiscoveryClient or not. cachedDiscoveryInterface > :
type APIVersionsOptions struct {
    discoveryClient discovery.CachedDiscoveryInterface

  • The GVR doesn’t change very often, so there’s no need to go to the API Server every time. For details on the cache, please refer to: The staging/SRC/k8s. IO/client – go/discovery/cached/disk/cached_discovery. Go, here is not carried out;
  • At this point, Client-Go’s four client tools and the relevant source code of the shallow level of analysis is all completed, when you do Client-Go development, I hope these content can provide you with some reference;

You are not alone, Xin Chen original all the way

  1. Java series
  2. Spring series
  3. The Docker series
  4. Kubernetes series
  5. Database + middleware series
  6. The conversation series

Welcome to pay attention to the public number: programmer Xin Chen

WeChat search “programmer Xin Chen”, I am Xin Chen, looking forward to traveling with you in the JAVA world…