Welcome to my GitHub

Github.com/zq2599/blog…

Content: All original articles and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.

About the DiscoveryClient

  • This article is the fifth in the series of client-Go Actual Combat. The main character is the last type of client: Unlike DiscoveryClient, where Clientset and dynamicClient are both resource-oriented (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, here are the DiscoveryClient data structure fields and associated methods. Again, you see the familiar restClient field. There are also a number of methods related to groups, versions, and resources:

  • The DiscoveryClient data structure has two fields: restClient and LegacyPrefix. What is the LegacyPrefix? Take a look at the method used to create an Instance of DiscoveryClient, shown in the red box below, which is a fixed string/API that looks like part of the URL:

  • Select one of the DiscoveryClient’s association methods, and see the red box below. Sure enough, LegacyPrefix is part of the URL:

  • Compared to the other clients, DiscoveryClient is a little simpler, so let’s just do it!

Need to confirm

  • Query all Group, Version and Resource information from Kubernetes and print them out on the console.

Download the source code

  • This actual source code can be downloaded from GitHub, address and link information as shown in the following table (github.com/zq2599/blog…
The name of the link note
Project home page Github.com/zq2599/blog… The project’s home page on GitHub
Git Repository address (HTTPS) Github.com/zq2599/blog… The project source repository address, HTTPS protocol
Git Repository address (SSH) [email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  • There are multiple folders in the Git project. Client-go-related applications are in the client-go-tutorials folder, as shown in the red box below:

  • There are multiple subfolders under the client-go-tutorials folder, and the corresponding source code of this article is in the DiscoveryClientDemo directory, as shown in the red box below:

coding

  • Create a new folder discoveryClientDemo and run the following command in it to create a module:
go mod init discoveryclientdemo
Copy the code
  • Add k8s. IO/API and k8s. IO /client-go dependencies, note that the version matches the Kubernetes environment:
Go get k8s. IO /[email protected] Go get k8s. IO /[email protected]Copy the code
  • The second value returned by the ServerGroupsAndResources method has slices in the data structure and slices in each element of the slices. This 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(a) {

	var kubeconfig *string

	// home is the home directory and can be used as the default value if it is available
	ifhome:=homedir.HomeDir(); home ! ="" {
		// If the kubeconfig parameter is entered, the value of this parameter is the absolute path to the Kubeconfig file.
		// If the kubeconfig parameter is not entered, use the default path ~/.kube/config
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube"."config"), "(optional) absolute path to the kubeconfig file")}else {
		// If the current user's home directory is not available, there is no way to set the default kubeconfig directory
		kubeconfig = flag.String("kubeconfig".""."absolute path to the kubeconfig file")
	}

	flag.Parse()

	// Load the kubeconfig configuration file from the native, so the first argument is an empty string
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)

	// Kubeconfig failed to load
	iferr ! =nil {
		panic(err.Error())
	}

	// Create an Instance of discoveryClient
	discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)

	iferr ! =nil {
		panic(err.Error())
	}

	// Get all group and resource data
	APIGroup, APIResourceListSlice, err := discoveryClient.ServerGroupsAndResources()

	iferr ! =nil {
		panic(err.Error())
	}

	// Look at the Group information first
	fmt.Printf("APIGroup :\n\n %v\n\n\n\n",APIGroup)

	// APIResourceListSlice is a slice in which each element represents a GroupVersion and its resources
	for _, singleAPIResourceList := range APIResourceListSlice {

		// GroupVersion is a string, such as "apps/v1"
		groupVerionStr := singleAPIResourceList.GroupVersion

		// The ParseGroupVersion method turns the string into a data structure
		gv, err := schema.ParseGroupVersion(groupVerionStr)

		iferr ! =nil {
			panic(err.Error())
		}

		fmt.Println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *")
		fmt.Printf("GV string [%v]\nGV struct [%#v]\nresources :\n\n", groupVerionStr, gv)

		// The APIResources field is a slice that contains all resources under the current GroupVersion
		for _, singleAPIResource := range singleAPIResourceList.APIResources {
			fmt.Printf("%v\n", singleAPIResource.Name)
		}
	}
}
Copy the code
  • Run the go run main.go command to intercept the following part of the execution result, and all resources are printed out:
. ***************************************************************** 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/statusCopy the code
  • This is the basic usage of DiscoveryClient. If you think this is too easy, let’s take a look at the surrounding scene of DiscoveryClient.

How to use DiscoveryClient in Kubectl

  • The kubectl api-versions command returns all Group+Version combinations for the current Kubernetes environment, as shown below:
zhaoqin@zhaoqindeMBP-2 discoveryclientdemo % kubectl api-versions
admissionregistration.k8s.io/v1
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
authentication.k8s.io/v1
...
Copy the code
  • By viewing the kubectl source code, it can be seen that DiscoveryClient is used behind the above commands, as shown in the red box below:

  • One more thing is unclear: is O.DisCoveryClient in red box 2 in the picture above DiscoveryClient? Although the name is similar, I took a look at the discovery and discovered something new. As follows, the data structure of discoveryClient is CachedDiscoveryInterface:
type APIVersionsOptions struct {
	discoveryClient discovery.CachedDiscoveryInterface

	genericclioptions.IOStreams
}
Copy the code
  • The name CachedDiscoveryInterface indicates that Kubectl caches the GVR data locally. The GVR does not change very often, so there is no need to go to the API Server to pull it every time. The staging/SRC/k8s. IO/client – go/discovery/cached/disk/cached_discovery. Go, here is not carried out;

  • So far, client-go four kinds of client tools actual combat and related source code of shallow level 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 is with you 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 follow the public number: programmer Xin Chen

Wechat search “Programmer Chen”, I am Chen, looking forward to enjoying the Java world with you…

Github.com/zq2599/blog…