This article personal blog address: http://www.huweihuang.com/article/source-analysis/client-go-source-analysis/ 1 client-go Introduction 1.1 client-go Description
Client-go is a client that invokes the Kubernetes cluster resource object API, that is, through client-go implementation of resource objects in the Kubernetes cluster (including deployment, service, Ingress, Replicaset , pod, namespace, node, etc.) of the additions and deletions to check and other operations. Most of the two development of Kubernetes API encapsulation is implemented by client-go this third party package.
Client-go Official Documentation: HTTPS://GITHUB.COM/KUBERNETES/CLIENT-GO 1.2 Sample code
git clone https://github.com/huweihuang/client-go.git
cd client-go
#保证本地HOME目录有配置kubernetes集群的配置文件
Go Run Client-go.go
Client-go.go
Package main import ("Flag" "FMT" "OS" "Path/filepath" "Time" METAV1 "k8s.io/apimachinery/pkg/a Pis/meta/v1 "" "K8s.io/client-go/kubernetes" "K8s.io/client-go/tools/clientcmd") func main () {var kubeconfig *string If home: = Homedir (); Home!= "" {kubeconfig = flag. String ("Kubeconfig", filepath. Join (Home, ". Kube", "config"), "(optional) absolute path to the Kubeconfig file")} else {kubeconfig = Flag.s Tring ("Kubeconfig", "", "absolute path to the Kubeconfig file")} flag. Parse ()//uses in Kubeconfig config, err: = Clientcmd. Buildconfigfromflags ("", *kubeconfig) if Err!= nil {panic (err. Error ())}//creates the Clientset clientset, err: = Kubernetes. Newforconfig (config) If err!= nil {panic (err. Error ())} for {pods, err: = Clientset. CoreV1 (). Pods (""). List (METAV1. listoptions{}) If err!= nil {panic (err.
Error ()) } FMT. Printf ("There are%d pods in the cluster\n", Len (pods. Items)) time. Sleep (all * time. Second)} func homedir () string {if h: = OS. Getenv ("Home"); H!= "" {return H} return OS. Getenv ("userprofile")//Windows}
1.3 Running Results
➜go Run Client-go.go
There are 9 pods in the cluster There are
7 pods at the cluster
There are 7 pods in the Cluster
There are 7 pods in the cluster There are
7 pods in the cluster
2. Client-go Source Analysis
client-go source : Https://github.com/kubernetes/client-go
client-go Source directory structure The Kubernetes package contains the Clientset to access Kubernetes API. The discovery package is used to discover APIs supported by a kubernetes API server. The dynamic package contains a dynamic client that can perform generic operations on arbitrary API kubernetes. The transport package is used to set up auth and start a connection. The Tools/cache package is useful for writing controllers. 2.1 Kubeconfig
Kubeconfig = flag. String ("Kubeconfig", filepath. Join (Home, ". Kube", "config"), "(optional) absolute path to the Kubeconfig file")
Gets the absolute path of the kubernetes configuration file kubeconfig. The general path is $home/.kube/config. This file is primarily used to configure kubernetes clusters that are locally connected.
The contents of config are as follows:
APIVERSION:V1
Clusters:
-cluster:
server:http://<kube-master-ip>:8080
name:k8s
Contexts:
-Context:
cluster:k8s
namespace:default
User: ""
name:default
Current-context:default
kind:config
preferences: {}
users: []
2.2 Rest.config
The Rest.config object is obtained by the parameter (master's URL or kubeconfig path) and the Buildconfigfromflags method, typically through the path of the parameter kubeconfig.
Config, err: = Clientcmd. Buildconfigfromflags ("", *kubeconfig)
buildconfigfromflags function Source code
K8s.io/client-go/tools/clientcmd/client_config.go
Buildconfigfromflags is a helper function this builds configs from a master//URL or a kubeconfig filepath. These are passed into as command line flags for cluster//components. Warnings should reflect this usage. If neither MasterUrl or Kubeconfigpath//are passed in we fallback to inclusterconfig.
If Inclusterconfig fails, we fallback//to the default Config. Func buildconfigfromflags (MasterUrl, Kubeconfigpath string) (*restclient. Config, error) {if Kubeconfigpath = = "" && MasterUrl = = "" {Glog. WARNINGF ("Neither--kubeconfig nor--master was specified." Using the Inclusterconfig.
This might is not work. ") Kubeconfig, err: = Restclient. Inclusterconfig () If Err = = Nil {return kubeconfig, nil} glog. Warning ("Error creating inclusterconfig, falling back to default Config:", err)} return Newnoninteractivedeferre Dloadingclientconfig (&clientconfigloadingrules{explicitpath:kubeconfigpath}, &Amp Configoverrides{clusterinfo:clientcmdapi. Cluster{server:masterurl}}). ClientConfig ()}
2.3 Clientset
Through the *rest. Config parameter and newforconfig method to get the Clientset object, Clientset is a collection of multiple clients, each client may contain different versions of method calls.
Clientset, err: = Kubernetes. Newforconfig (config)
2.3.1 Newforconfig
The Newforconfig function is the initialization of each client in the Clientset.
K8s.io/client-go/kubernetes/clientset.go
Newforconfig creates a new clientset for the given config.
Func Newforconfig (c *rest. Config) (*clientset, error) {
configshallowcopy: = *c
...
var cs clientset
cs.appsv1beta1, err = appsv1beta1. Newforconfig (&configshallowcopy) ...
CS.COREV1, err = Corev1. Newforconfig (&configshallowcopy) ...
}
2.3.2 Clientset Structural body
K8s.io/client-go/kubernetes/clientset.go
Clientset contains the clients for groups.
Each group has exactly one//version included in a clientset. Type clientset struct {*discovery. Discoveryclient admissionregistrationv1alpha1 *ADMISSIONREGISTRATIONV1ALPHA1. Admissionregistrationv1alpha1client appsv1beta1 *appsv1beta1. Appsv1beta1client appsv1beta2 *appsv1beta2. Appsv1beta2client authenticationV1 *authenticationv1. Authenticationv1client authenticationv1beta1 *authenticationv1beta1. Authenticationv1beta1client authorizationV1 *authorizationv1. Authorizationv1client authorizationv1beta1 *authorizationv1beta1. Authorizationv1beta1client autoscalingV1 *autoscalingv1. Autoscalingv1client autoscalingv2beta1 *autoscalingv2beta1. Autoscalingv2beta1client batchV1 *batchv1. Batchv1client batchv1beta1 *batchv1beta1. Batchv1beta1client BATCHV2ALPHA1 *batchv2alpha1. Batchv2alpha1client certificatesv1beta1 *certificatesv1beta1. Certificatesv1beta1client coreV1 *corev1. Corev1client extensionsv1beta1 *extensionsv1beta1. Extensionsv1beta1client networkingV1 *networkingv1. Networkingv1client policyv1beta1 *policyv1beta1. Policyv1beta1client rbacV1 *rbacv1. Rbacv1client rbacv1beta1 *rbacv1beta1. Rbacv1beta1client rbacv1alpha1 *RBACV1ALPHA1. Rbacv1alpha1client schedulingv1alpha1 *SCHEDULINGV1ALPHA1. Schedulingv1alpha1client settingsv1alpha1 *SETTINGSV1ALPHA1. Settingsv1alpha1client storagev1beta1 *storagev1beta1. Storagev1beta1client storageV1 *storagev1. Storagev1client}
2.3.3 Clientset. Interface
Clientset implements the following interface, so you can obtain a specific client by calling the following methods. For example:
Pods, err: = Clientset. CoreV1 (). Pods (""). List (METAV1. listoptions{})
Clientset Method Set interface
K8s.io/client-go/kubernetes/clientset.go
Type Interface Interface {Discovery () Discovery. Discoveryinterface admissionregistrationv1alpha1 () admissionregistrationv1alpha1.
Admissionregistrationv1alpha1interface//Deprecated:please explicitly pick a version if possible. Admissionregistration () admissionregistrationv1alpha1. Admissionregistrationv1alpha1interface appsv1beta1 () appsv1beta1. Appsv1beta1interface appsv1beta2 () appsv1beta2.
Appsv1beta2interface//Deprecated:please explicitly pick a version if possible. Apps () appsv1beta2. Appsv1beta2interface AuthenticationV1 () authenticationv1.
Authenticationv1interface//Deprecated:please explicitly pick a version if possible. Authentication () Authenticationv1. Authenticationv1interface authenticationv1beta1 () authenticationv1beta1. Authenticationv1beta1interface AuthorizationV1 () authorizationv1.
Authorizationv1interface//Deprecated:please explicitly pick a version if possible. Authorization () authorizationv1. AuthorizatIonv1interface authorizationv1beta1 () authorizationv1beta1. Authorizationv1beta1interface AutoscalingV1 () autoscalingv1.
Autoscalingv1interface//Deprecated:please explicitly pick a version if possible. AutoScaling () autoscalingv1. Autoscalingv1interface autoscalingv2beta1 () autoscalingv2beta1. Autoscalingv2beta1interface BatchV1 () batchv1.
Batchv1interface//Deprecated:please explicitly pick a version if possible. Batch () batchv1. Batchv1interface batchv1beta1 () batchv1beta1. Batchv1beta1interface batchv2alpha1 () batchv2alpha1. Batchv2alpha1interface certificatesv1beta1 () certificatesv1beta1.
Certificatesv1beta1interface//Deprecated:please explicitly pick a version if possible. Certificates () certificatesv1beta1. Certificatesv1beta1interface CoreV1 () corev1.
Corev1interface//Deprecated:please explicitly pick a version if possible. Core () Corev1. Corev1interface extensionsv1beta1 () extensionsv1beta1. Extensionsv1beta1inteRface//Deprecated:please explicitly pick a version if possible. Extensions () extensionsv1beta1. Extensionsv1beta1interface NetworkingV1 () networkingv1.
Networkingv1interface//Deprecated:please explicitly pick a version if possible. Networking () networkingv1. Networkingv1interface policyv1beta1 () policyv1beta1.
Policyv1beta1interface//Deprecated:please explicitly pick a version if possible. Policy () policyv1beta1. Policyv1beta1interface RbacV1 () rbacv1.
Rbacv1interface//Deprecated:please explicitly pick a version if possible. Rbac () rbacv1. Rbacv1interface rbacv1beta1 () rbacv1beta1. Rbacv1beta1interface rbacv1alpha1 () rbacv1alpha1. Rbacv1alpha1interface schedulingv1alpha1 () schedulingv1alpha1.
Schedulingv1alpha1interface//Deprecated:please explicitly pick a version if possible. scheduling () Schedulingv1alpha1. Schedulingv1alpha1interface settingsv1alpha1 () settingsv1alpha1. Settingsv1alpha1interface//deprecated: Please explicitly pick a version if possible. Settings () settingsv1alpha1. Settingsv1alpha1interface storagev1beta1 () storagev1beta1. Storagev1beta1interface StorageV1 () storagev1.
Storagev1interface//Deprecated:please explicitly pick a version if possible. Storage () Storagev1. Storagev1interface}
2.4 corev1client
We take the corev1client in Clientset as an example to do analysis.
Rest through the incoming configuration information. Config to initialize the Corev1client object.
K8s.io/client-go/kubernetes/clientset.go
CS.COREV1, err = Corev1. Newforconfig (&configshallowcopy)
2.4.1 Corev1. Newforconfig
K8s.io/client-go/kubernetes/typed/core/v1/core_client.go
Newforconfig creates a new corev1client for the given config.
Func Newforconfig (c *rest. Config) (*corev1client, error) {
config: = *c
If err: = Setconfigdefaults (&config); Err!= nil {return
ni L, Err
}
client, err: = rest. Restclientfor (&config)
If err!= nil {return
nil, err
} return
&corev1client{client}, nil< c12/>}
Corev1. The essence of the Newforconfig method is to invoke the Rest.restclientfor (&config) method to create the Restclient object, that is, the nature of Corev1client is a Restclient object. 2.4.2 corev1client Structural body
The following is the definition of the corev1client structure:
K8s.io/client-go/kubernetes/typed/core/v1/core_client.go
Corev1client is used to interact with features provided by the group.
Type corev1client struct {
restclient rest. Interface
}
Corev1client implements the Corev1interface interface, that is, the following methods, which can be used to check the Kubernetes resource objects.
K8s.io/client-go/kubernetes/typed/core/v1/core_client.go
Corev1client method Func (c *corev1client) componentstatuses () componentstatusinterface {...}//configmaps func (c * corev1client) Configmaps (namespace string) configmapinterface {...}//endpoints func (c *corev1client) endpoints ( namespace string) Endpointsinterface {...} func (c *corev1client) Events (namespace string) eventinterface {...} func (c *c orev1client) Limitranges (namespace string) limitrangeinterface {...}//namespaces func (c *corev1client) namespaces () Namespaceinterface {...}//nodes func (c *corev1client) Nodes () nodeinterface {...} func (c *corev1client) Persistentvolum ES () persistentvolumeinterface {...} func (c *corev1client) Persistentvolumeclaims (namespace String) Persistentvolumeclaiminterface {...}//pods func (c *corev1client) Pods (namespace string) podinterface {...} func (c *core v1client) Podtemplates (namespace string) podtemplateinterface {...}//replicationcontrollers func (c *corev1client) Replicationcontrollers (Namespace String) replicationcontrollerinterface{...} Func (c *corev1client) Resourcequotas (namespace string) resourcequotainterface {...} func (c *corev1client) Secrets ( namespace string) Secretinterface {...}//services func (c *corev1client) Services (namespace string) Serviceinterface {..
.} Func (c *corev1client) serviceaccounts (namespace string) Serviceaccountinterface {...}
2.4.3 Corev1interface
K8s.io/client-go/kubernetes/typed/core/v1/core_client.go
Type Corev1interface Interface {
restclient () rest. Interface
componentstatusesgetter
configmapsgetter
endpointsgetter
eventsgetter
Limitrangesgetter
namespacesgetter
nodesgetter
persistentvolumesgetter
Persistentvolumeclaimsgetter
podsgetter
podtemplatesgetter
replicationcontrollersgetter
Resourcequotasgetter
secretsgetter
servicesgetter
serviceaccountsgetter
}
The corev1interface contains the invocation interfaces of various kubernetes objects, for example, Podsgetter is an interface for adding and deleting Pod objects in kubernetes. Servicesgetter is an interface to the operation of a service object. 2.4.4 Podsgetter
Here we take the Podsgetter interface as an example to analyze the corev1client of the Pod object and check the interface call.
The code in the example is as follows:
Pods, err: = Clientset. CoreV1 (). Pods (""). List (METAV1. listoptions{})
CoreV1 (). Pods ()
K8s.io/client-go/kubernetes/typed/core/v1/core_client.go
Func (c *corev1client) Pods (namespace string) Podinterface {return
newpods (c, namespace)
}
newpods ()
K8s.io/client-go/kubernetes/typed/core/v1/pod.go
Newpods returns a Pods
func newpods (c *corev1client, namespace string) *pods {return
&pods{client:c
. Restclient (),
ns: namespace,
}
}
CoreV1 (). The Pods () method actually calls the Newpods () method, creates a Pods object, and the Pods object inherits rest. The interface interface, the ultimate implementation essence, is the restclient http invocation.
K8s.io/client-go/kubernetes/typed/core/v1/pod.go
Pods implements Podinterface
type pods struct {
client rest. Interface
ns string
}
The Pods object implements the Podinterface interface. The Podinterface defines the method of pods object's deletion, modification and checking.
K8s.io/client-go/kubernetes/typed/core/v1/pod.go
Podinterface has methods to work with Pod resources.
Type Podinterface Interface {
Create (*V1). Pod) (*V1. Pod, error)
Update (*v1. Pod) (*V1. Pod, error)
UpdateStatus (*v1. Pod) (*V1. Pod, error)
Delete (name string, Options *meta_v1.) deleteoptions) Error
deletecollection (Options *meta_v1. Deleteoptions, Listoptions meta_v1. listoptions) Error Get
(name string, Options Meta_v1. getoptions) (*V1. Pod, error)
List (opts meta_v1. listoptions) (*V1. Podlist, error)
Watch (opts meta_v1. listoptions) (watch. Interface, error)
Patch (name string, pt types. Patchtype, data []byte, Subresources ... string) (Result *v1. Pod, err Error)
podexpansion
}
Podsgetter
The Podsgetter inherits the Podinterface interface.
K8s.io/client-go/kubernetes/typed/core/v1/pod.go
Podsgetter has a to return a podinterface.
A group ' s client should implement this interface.
Type Podsgetter Interface {
Pods (namespace String) Podinterface
}
Pods (). List ()
Pods. The List () method achieves the acquisition of Kubernetes's pod resources through restclient http invocation.
K8s.io/client-go/kubernetes/typed/core/v1/pod.go
List takes label and field selectors, and returns the list of Pods that match those selectors.
Func (c *pods) List (opts Meta_v1. listoptions) (Result *v1. Podlist, err Error) {result
= &v1. podlist{}
Err = C.client.get ().
Namespace (C.NS).
Resource ("pods").
Versionedparams (&opts, scheme. PARAMETERCODEC).
Do ().
into [result]
return
}
The above analysis Clientset. CoreV1 (). Pods (""). List (METAV1. listoptions{}) The process of acquiring the pod resource is ultimately called the Restclient method implementation. 2.5 restclient
The following analysis restclient the creation process and the role.
The creation of the Restclient object is also dependent on the incoming config information.
K8s.io/client-go/kubernetes/typed/core/v1/core_client.go
Client, Err: = rest. Restclientfor (&config)
2.5.1 Rest. Restclientfor
K8s.io/client-go/rest/config.go
//Restclientfor returns a restclient that satisfies the requested attributes on a client Config Object.
Note "A restclient may require fields" are optional when initializing a Client. A Restclient created by the-is generic-it expects to operate on an API that follows//the Kubernetes convent
Ions, but May is the kubernetes API. Func restclientfor (config *config) (*restclient, error) {... QPS: = config. QPS ... burst: = config. Burst ... baseurl, versionedapipath, err: = defaultserverurlfor (config) ... transport, err: = Transportfor (config) ... var httpclient *http. Client if Transport!= http. Defaulttransport {httpclient = &http. Client{transport:transport} if config. Timeout > 0 {httpclient.timeout = config. Timeout} return Newrestclient (BaseURL, Versionedapipath, config. Contentconfig, QPS, burst, config. Ratelimiter, HttpClient)}
The RESTCLIENTFOR function calls the initialization function of the newrestclient. 2.5.2 newrestclient
K8s.io/client-go/rest/client.go
Newrestclient creates a new restclient. This client performs generic REST functions
//such as GET, put, Post, and Delete on specified paths. Codec controls encoding and
//decoding of responses from the server.
Func newrestclient (BaseURL *url. URL, Versionedapipath String,