In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces you how to carry out k8s-client-go source code analysis, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Topic Client-go source directory structure
Plain Text
one
[root@normal11 k8s-client-go] # tree. -L 1
two
.
three
├── CHANGELOG.md
four
├── code-of-conduct.md
five
├── CONTRIBUTING.md
six
├── discovery
seven
├── dynamic
eight
├── examples
nine
├── Godeps
ten
├── go.mod
eleven
├── go.sum
twelve
├── informers
thirteen
├── INSTALL.md
fourteen
├── kubernetes
fifteen
├── kubernetes_test
sixteen
├── LICENSE
seventeen
├── listers
eighteen
├── metadata
nineteen
├── OWNERS
twenty
├── pkg
twenty-one
├── plugin
twenty-two
├── README.md
twenty-three
├── rest
twenty-four
├── restmapper
twenty-five
├── scale
twenty-six
├── SECURITY_CONTACTS
twenty-seven
├── testing
twenty-eight
├── third_party
twenty-nine
├── tools
thirty
├── transport
thirty-one
└── util
thirty-two
thirty-three
The client-go code base has been integrated into the Kubernetes source code, so the content shown in the book is the source code structure in the Kubernetes source code, while here it shows the original content in the Client-go code library, so there are some contents other than the source code, such as README, example, go.mod and so on. Let's talk about the function of each catalog, which is quoted from books:
Editing
Delete
Several Client-go clients
The following figure is a simple summary, where ClientSet, DynamicClient, and DiscoveryClient are all based on RESTClient encapsulation.
RESTClient
The most basic client encapsulates HTTP Request and implements RESTFul-style API.
Case code:
Plain Text
one
Package main
two
three
Import (
four
"fmt"
five
six
Corev1 "k8s.io/api/core/v1"
seven
Metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
eight
"k8s.io/client-go/kubernetes/scheme"
nine
"k8s.io/client-go/rest"
ten
"k8s.io/client-go/tools/clientcmd"
eleven
)
twelve
thirteen
Func main () {
fourteen
Config, err: = clientcmd.BuildConfigFromFlags ("," / root/.kube/config ")
fifteen
If err! = nil {
sixteen
Panic (err.Error ())
seventeen
}
eighteen
nineteen
Config.APIPath = "api"
twenty
Config.GroupVersion = & corev1.SchemeGroupVersion
twenty-one
Config.NegotiatedSerializer = scheme.Codecs
twenty-two
twenty-three
RestClient, err: = rest.RESTClientFor (config)
twenty-four
If err! = nil {
twenty-five
Panic (err.Error ())
twenty-six
}
twenty-seven
twenty-eight
Result: = & corev1.NodeList {}
twenty-nine
Err = restClient.Get (). Namespace ("). Resource (" nodes "). VersionedParams (& metav1.ListOptions {Limit: 100}, scheme.ParameterCodec). Do (). Into (result)
thirty
If err! = nil {
thirty-one
Panic (err)
thirty-two
}
thirty-three
thirty-four
For _, d: = range result.Items {
thirty-five
Fmt.Printf ("Node Name% v\ n", d.Name)
thirty-six
}
thirty-seven
}
thirty-eight
thirty-nine
The expected running result will print the node in the K8S cluster
ClientSet
The RESTClient is encapsulated by object classification, and the clients of specific resources can be instantiated.
Exposed by Resource and Version. For example, instantiate a Deploy client that operates only the appsv1 version
ClientSet can be thought of as a collection client of a series of resources. The disadvantage is that you cannot access CRD directly.
You can access CRD resources after you generate ClientSet with CRD resources through the client-gen code generator. (not tested)
Case code:
Plain Text
one
Package main
two
three
Import (
four
Apiv1 "k8s.io/api/core/v1"
five
Metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
six
"k8s.io/client-go/kubernetes"
seven
"k8s.io/client-go/tools/clientcmd"
eight
)
nine
ten
Func main () {
eleven
Config, err: = clientcmd.BuildConfigFromFlags ("," / root/.kube/config ")
twelve
If err! = nil {
thirteen
Panic (err)
fourteen
}
fifteen
Clientset, err: = kubernetes.NewForConfig (config)
sixteen
If err! = nil {
seventeen
Panic (err)
eighteen
}
nineteen
twenty
PodClient = clientset.CoreV1 () .Pods (apiv1.NamespaceDefault)
twenty-one
twenty-two
List, err: = podClient.List (metav1.ListOptions {Limit: 500})
twenty-three
If err! = nil {
twenty-four
Panic (err)
twenty-five
}
twenty-six
For _, d: = range list.Items {
twenty-seven
If d.Name = "" {
twenty-eight
}
twenty-nine
/ / fmt.Printf ("NAME:%v\ t NAME:%v\ t STATUS:% + v\ n", d.Namespace, d.Name, d.Status)
thirty
}
thirty-one
thirty-two
/ / request namespace is deploy under default
thirty-three
DeploymentClient = clientset.AppsV1 () .Deployments (apiv1.NamespaceDefault)
thirty-four
DeployList, err2: = deploymentClient.List (metav1.ListOptions {Limit: 500})
thirty-five
If err2! = nil {
thirty-six
Panic (err2)
thirty-seven
}
thirty-eight
For _, d: = range deployList.Items {
thirty-nine
If d.Name = "" {
forty
forty-one
}
forty-two
/ / fmt.Printf ("NAME:%v\ t NAME:%v\ t STATUS:% + v\ n", d.Namespace, d.Name, d.Status)
forty-three
}
forty-four
forty-five
/ / request ds resources. Todo can try it if you are interested.
forty-six
/ / clientset.AppsV1 () .DaemonSets ()
forty-seven
forty-eight
}
forty-nine
fifty
The code prints 500 Pod and 500 deploy obtained from the K8S cluster. At present, the print statement is a comment. If you want to see the effect, you need to delete the comment first.
There is also a small content left in the case code to request access to daemonset resources. Those who are interested can give it a try.
DynamicClient
This is a dynamic client that operates on any resource in K8S, including CRD.
The result returned by the request is map [string] interface {}
Code case:
Plain Text
one
Package main
two
three
Import (
four
"fmt"
five
six
Apiv1 "k8s.io/api/core/v1"
seven
Corev1 "k8s.io/api/core/v1"
eight
Metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
nine
"k8s.io/apimachinery/pkg/runtime"
ten
"k8s.io/apimachinery/pkg/runtime/schema"
eleven
"k8s.io/client-go/dynamic"
twelve
"k8s.io/client-go/tools/clientcmd"
thirteen
)
fourteen
fifteen
Func main () {
sixteen
Config, err: = clientcmd.BuildConfigFromFlags ("," / root/.kube/config ")
seventeen
If err! = nil {
eighteen
Panic (err)
nineteen
}
twenty
twenty-one
DymaicClient, err: = dynamic.NewForConfig (config)
twenty-two
CheckErr (err)
twenty-three
/ / map [string] interface {}
twenty-four
twenty-five
/ / TODO acquires CRD resources. Here is the CRD resource that acquired TIDB.
twenty-six
/ / gvr: = schema.GroupVersionResource {Version: "v1alpha1", Resource: "tidbclusters", Group: "pingcap.com"}
twenty-seven
/ / unstructObj, err: = dymaicClient.Resource (gvr) .Namespace ("tidb-cluster") .List (metav1.ListOptions {Limit: 500})
twenty-eight
/ / checkErr (err)
twenty-nine
/ / fmt.Println (unstructObj)
thirty
thirty-one
Gvr: = schema.GroupVersionResource {Version: "v1", Resource: "pods"}
thirty-two
UnstructObj, err: = dymaicClient.Resource (gvr) .Namespace (apiv1.NamespaceDefault) .List (metav1.ListOptions {Limit: 500})
thirty-three
CheckErr (err)
thirty-four
/ / fmt.Println (unstructObj)
thirty-five
PodList: = & corev1.PodList {}
thirty-six
Err = runtime.DefaultUnstructuredConverter.FromUnstructured (unstructObj.UnstructuredContent (), podList)
thirty-seven
CheckErr (err)
thirty-eight
For _, d: = range podList.Items {
thirty-nine
Fmt.Printf ("NAME:%v\ t NAME:%v\ t STATUS:% + v\ n", d.Namespace, d.Name, d.Status)
forty
}
forty-one
forty-two
}
forty-three
forty-four
Func checkErr (err error) {
forty-five
If err! = nil {
forty-six
Panic (err)
forty-seven
}
forty-eight
}
forty-nine
fifty
This case prints 500 pod under namespace as default. Similarly, there is also a todo in the case. Get CRD resources. If you are interested, you can have a try. If there is no TIDB resource in the K8S cluster, you can change it into the CRD resource you want.
There are already tidbclusters resources in the code to get the v1alpha1 version. If you do not know the information related to CRD, you can follow these steps to find out the corresponding information:
Get the Group and Resource of the resource through kubectl api-resources
Find the corresponding version of Group through kubectl api-versions
In this way, the GVR (Group, Version, Resource) of the resource is available.
DiscoveryClient
This is a discovery client. In the previous client, you need to know the Resource and Version of the resource to find what you want.
There is too much information to remember, and this client is used to obtain resource groups, versions, and so on.
The api-resources and api-versions used previously are implemented through the discoveryClient client, and the source code is pkg/kubectl/cmd/apiresources/apiresources.gopkg/kubectl/cmd/apiresources/apiversions.go in the Kubernetes source library.
Plain Text
one
/ / RunAPIResources does the work
two
Func (o * APIResourceOptions) RunAPIResources (cmd * cobra.Command, f cmdutil.Factory) error {
three
W: = printers.GetNewTabWriter (o.Out)
four
Defer w.Flush ()
five
six
/ / get a DiscoveryClient client
seven
Discoveryclient, err: = f.ToDiscoveryClient ()
eight
If err! = nil {
nine
Return err
ten
}
eleven
twelve
thirteen
Plain Text
one
/ / RunAPIVersions does the work
two
Func (o * APIVersionsOptions) RunAPIVersions () error {
three
/ / Always request fresh data from the server
four
O.discoveryClient.Invalidate ()
five
six
/ / obtain group related information through discoveryClient
seven
GroupList, err: = o.discoveryClient.ServerGroups ()
eight
If err! = nil {
nine
Return fmt.Errorf ("couldn't get available api versions from server:% v", err)
ten
}
Case code:
Get the GVR in the cluster
Plain Text
one
Package main
two
three
Import (
four
"fmt"
five
"k8s.io/apimachinery/pkg/runtime/schema"
six
"k8s.io/client-go/discovery"
seven
"k8s.io/client-go/tools/clientcmd"
eight
)
nine
ten
Func main () {
eleven
Config, err: = clientcmd.BuildConfigFromFlags ("," / root/.kube/config ")
twelve
If err! = nil {
thirteen
Panic (err.Error ())
fourteen
}
15
sixteen
DiscoveryClient, err: = discovery.NewDiscoveryClientForConfig (config)
seventeen
If err! = nil {
18
Panic (err.Error ())
nineteen
}
twenty
twenty-one
_, APIResourceList, err: = discoveryClient.ServerGroupsAndResources ()
twenty-two
If err! = nil {
twenty-three
Panic (err.Error ())
twenty-four
}
twenty-five
For _, list: = range APIResourceList {
twenty-six
Gv, err: = schema.ParseGroupVersion (list.GroupVersion)
twenty-seven
If err! = nil {
twenty-eight
Panic (err.Error ())
twenty-nine
}
thirty
For _, resource: = range list.APIResources {
thirty-one
Fmt.Printf ("name:% v, group:% v, version% v\ n", resource.Name, gv.Group, gv.Version)
thirty-two
}
thirty-three
}
thirty-four
}
Expected result: print the GVR in the cluster
Plain Text
one
[root@normal11 discoveryclient] # go run main.go
two
Name: bindings, group:, version v1
three
Name: componentstatuses, group:, version v1
four
Name: configmaps, group:, version v1
five
Name: endpoints, group:, version v1
six
...
DiscoveryClient is cached locally after the data is requested. The default storage locations are ~ / .kube / cache and ~ / .kube/http-cache. By default, it is synchronized with API Server every 10 minutes. On how to carry out k8s-client-go source code analysis to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.