client-go的使用及源码分析
本文個人博客地址:http://www.huweihuang.com/article/source-analysis/client-go-source-analysis/
1. client-go簡介
1.1 client-go說明
? client-go是一個調用kubernetes集群資源對象API的客戶端,即通過client-go實現對kubernetes集群中資源對象(包括deployment、service、ingress、replicaSet、pod、namespace、node等)的增刪改查等操作。大部分對kubernetes進行前置API封裝的二次開發都通過client-go這個第三方包來實現。
? client-go官方文檔:https://github.com/kubernetes/client-go
1.2 示例代碼
git clone https://github.com/huweihuang/client-go.git cd client-go #保證本地HOME目錄有配置kubernetes集群的配置文件 go run client-go.goclient-go.go
package mainimport ("flag""fmt""os""path/filepath""time"metav1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/client-go/kubernetes""k8s.io/client-go/tools/clientcmd" )func main() {var kubeconfig *stringif home := homeDir(); home != "" {kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")} else {kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")}flag.Parse()// uses the current context in kubeconfigconfig, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)if err != nil {panic(err.Error())}// creates the clientsetclientset, 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(10 * time.Second)} }func homeDir() string {if h := os.Getenv("HOME"); h != "" {return h}return os.Getenv("USERPROFILE") // windows }1.3 運行結果
? go run client-go.go There are 9 pods in the cluster There are 7 pods in the cluster There are 7 pods in the cluster There are 7 pods in the cluster There are 7 pods in the cluster2. client-go源碼分析
client-go源碼:https://github.com/kubernetes/client-go
client-go源碼目錄結構
- 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 Kubernetes API objects.
- 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")獲取kubernetes配置文件kubeconfig的絕對路徑。一般路徑為$HOME/.kube/config。該文件主要用來配置本地連接的kubernetes集群。
config內容如下:
apiVersion: v1 clusters: - cluster:server: http://<kube-master-ip>:8080name: k8s contexts: - context:cluster: k8snamespace: defaultuser: ""name: default current-context: default kind: Config preferences: {} users: []2.2 rest.config
通過參數(master的url或者kubeconfig路徑)和BuildConfigFromFlags方法來獲取rest.Config對象,一般是通過參數kubeconfig的路徑。
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)BuildConfigFromFlags函數源碼
k8s.io/client-go/tools/clientcmd/client_config.go
// BuildConfigFromFlags is a helper function that builds configs from a master // url or a kubeconfig filepath. These are passed in 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 not work.")kubeconfig, err := restclient.InClusterConfig()if err == nil {return kubeconfig, nil}glog.Warning("error creating inClusterConfig, falling back to default config: ", err)}return NewNonInteractiveDeferredLoadingClientConfig(&ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},&ConfigOverrides{ClusterInfo: clientcmdapi.Cluster{Server: masterUrl}}).ClientConfig() }2.3 clientset
通過*rest.Config參數和NewForConfig方法來獲取clientset對象,clientset是多個client的集合,每個client可能包含不同版本的方法調用。
clientset, err := kubernetes.NewForConfig(config)2.3.1 NewForConfig
NewForConfig函數就是初始化clientset中的每個client。
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 Clientsetcs.appsV1beta1, err = appsv1beta1.NewForConfig(&configShallowCopy)...cs.coreV1, err = corev1.NewForConfig(&configShallowCopy)... }2.3.2 clientset的結構體
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.DiscoveryClientadmissionregistrationV1alpha1 *admissionregistrationv1alpha1.AdmissionregistrationV1alpha1ClientappsV1beta1 *appsv1beta1.AppsV1beta1ClientappsV1beta2 *appsv1beta2.AppsV1beta2ClientauthenticationV1 *authenticationv1.AuthenticationV1ClientauthenticationV1beta1 *authenticationv1beta1.AuthenticationV1beta1ClientauthorizationV1 *authorizationv1.AuthorizationV1ClientauthorizationV1beta1 *authorizationv1beta1.AuthorizationV1beta1ClientautoscalingV1 *autoscalingv1.AutoscalingV1ClientautoscalingV2beta1 *autoscalingv2beta1.AutoscalingV2beta1ClientbatchV1 *batchv1.BatchV1ClientbatchV1beta1 *batchv1beta1.BatchV1beta1ClientbatchV2alpha1 *batchv2alpha1.BatchV2alpha1ClientcertificatesV1beta1 *certificatesv1beta1.CertificatesV1beta1ClientcoreV1 *corev1.CoreV1ClientextensionsV1beta1 *extensionsv1beta1.ExtensionsV1beta1ClientnetworkingV1 *networkingv1.NetworkingV1ClientpolicyV1beta1 *policyv1beta1.PolicyV1beta1ClientrbacV1 *rbacv1.RbacV1ClientrbacV1beta1 *rbacv1beta1.RbacV1beta1ClientrbacV1alpha1 *rbacv1alpha1.RbacV1alpha1ClientschedulingV1alpha1 *schedulingv1alpha1.SchedulingV1alpha1ClientsettingsV1alpha1 *settingsv1alpha1.SettingsV1alpha1ClientstorageV1beta1 *storagev1beta1.StorageV1beta1ClientstorageV1 *storagev1.StorageV1Client }2.3.3 clientset.Interface
clientset實現了以下的Interface,因此可以通過調用以下方法獲得具體的client。例如:
pods, err := clientset.CoreV1().Pods("").List(metav1.ListOptions{})clientset的方法集接口
k8s.io/client-go/kubernetes/clientset.go
type Interface interface {Discovery() discovery.DiscoveryInterfaceAdmissionregistrationV1alpha1() admissionregistrationv1alpha1.AdmissionregistrationV1alpha1Interface// Deprecated: please explicitly pick a version if possible.Admissionregistration() admissionregistrationv1alpha1.AdmissionregistrationV1alpha1InterfaceAppsV1beta1() appsv1beta1.AppsV1beta1InterfaceAppsV1beta2() appsv1beta2.AppsV1beta2Interface// Deprecated: please explicitly pick a version if possible.Apps() appsv1beta2.AppsV1beta2InterfaceAuthenticationV1() authenticationv1.AuthenticationV1Interface// Deprecated: please explicitly pick a version if possible.Authentication() authenticationv1.AuthenticationV1InterfaceAuthenticationV1beta1() authenticationv1beta1.AuthenticationV1beta1InterfaceAuthorizationV1() authorizationv1.AuthorizationV1Interface// Deprecated: please explicitly pick a version if possible.Authorization() authorizationv1.AuthorizationV1InterfaceAuthorizationV1beta1() authorizationv1beta1.AuthorizationV1beta1InterfaceAutoscalingV1() autoscalingv1.AutoscalingV1Interface// Deprecated: please explicitly pick a version if possible.Autoscaling() autoscalingv1.AutoscalingV1InterfaceAutoscalingV2beta1() autoscalingv2beta1.AutoscalingV2beta1InterfaceBatchV1() batchv1.BatchV1Interface// Deprecated: please explicitly pick a version if possible.Batch() batchv1.BatchV1InterfaceBatchV1beta1() batchv1beta1.BatchV1beta1InterfaceBatchV2alpha1() batchv2alpha1.BatchV2alpha1InterfaceCertificatesV1beta1() certificatesv1beta1.CertificatesV1beta1Interface// Deprecated: please explicitly pick a version if possible.Certificates() certificatesv1beta1.CertificatesV1beta1InterfaceCoreV1() corev1.CoreV1Interface// Deprecated: please explicitly pick a version if possible.Core() corev1.CoreV1InterfaceExtensionsV1beta1() extensionsv1beta1.ExtensionsV1beta1Interface// Deprecated: please explicitly pick a version if possible.Extensions() extensionsv1beta1.ExtensionsV1beta1InterfaceNetworkingV1() networkingv1.NetworkingV1Interface// Deprecated: please explicitly pick a version if possible.Networking() networkingv1.NetworkingV1InterfacePolicyV1beta1() policyv1beta1.PolicyV1beta1Interface// Deprecated: please explicitly pick a version if possible.Policy() policyv1beta1.PolicyV1beta1InterfaceRbacV1() rbacv1.RbacV1Interface// Deprecated: please explicitly pick a version if possible.Rbac() rbacv1.RbacV1InterfaceRbacV1beta1() rbacv1beta1.RbacV1beta1InterfaceRbacV1alpha1() rbacv1alpha1.RbacV1alpha1InterfaceSchedulingV1alpha1() schedulingv1alpha1.SchedulingV1alpha1Interface// Deprecated: please explicitly pick a version if possible.Scheduling() schedulingv1alpha1.SchedulingV1alpha1InterfaceSettingsV1alpha1() settingsv1alpha1.SettingsV1alpha1Interface// Deprecated: please explicitly pick a version if possible.Settings() settingsv1alpha1.SettingsV1alpha1InterfaceStorageV1beta1() storagev1beta1.StorageV1beta1InterfaceStorageV1() storagev1.StorageV1Interface// Deprecated: please explicitly pick a version if possible.Storage() storagev1.StorageV1Interface }2.4 CoreV1Client
我們以clientset中的CoreV1Client為例做分析。
通過傳入的配置信息rest.Config初始化CoreV1Client對象。
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 := *cif err := setConfigDefaults(&config); err != nil {return nil, err}client, err := rest.RESTClientFor(&config)if err != nil {return nil, err}return &CoreV1Client{client}, nil }corev1.NewForConfig方法本質是調用了rest.RESTClientFor(&config)方法創建RESTClient對象,即CoreV1Client的本質就是一個RESTClient對象。
2.4.2 CoreV1Client結構體
以下是CoreV1Client結構體的定義:
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實現了CoreV1Interface的接口,即以下方法,從而對kubernetes的資源對象進行增刪改查的操作。
k8s.io/client-go/kubernetes/typed/core/v1/core_client.go
//CoreV1Client的方法 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 *CoreV1Client) LimitRanges(namespace string) LimitRangeInterface {...} //Namespaces func (c *CoreV1Client) Namespaces() NamespaceInterface {...} //Nodes func (c *CoreV1Client) Nodes() NodeInterface {...} func (c *CoreV1Client) PersistentVolumes() PersistentVolumeInterface {...} func (c *CoreV1Client) PersistentVolumeClaims(namespace string) PersistentVolumeClaimInterface {...} //Pods func (c *CoreV1Client) Pods(namespace string) PodInterface {...} func (c *CoreV1Client) 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.InterfaceComponentStatusesGetterConfigMapsGetterEndpointsGetterEventsGetterLimitRangesGetterNamespacesGetterNodesGetterPersistentVolumesGetterPersistentVolumeClaimsGetterPodsGetterPodTemplatesGetterReplicationControllersGetterResourceQuotasGetterSecretsGetterServicesGetterServiceAccountsGetter }CoreV1Interface中包含了各種kubernetes對象的調用接口,例如PodsGetter是對kubernetes中pod對象增刪改查操作的接口。ServicesGetter是對service對象的操作的接口。
2.4.4 PodsGetter
以下我們以PodsGetter接口為例分析CoreV1Client對pod對象的增刪改查接口調用。
示例中的代碼如下:
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().Pods()的方法實際上是調用了newPods()的方法,創建了一個pods對象,pods對象繼承了rest.Interface接口,即最終的實現本質是RESTClient的HTTP調用。
k8s.io/client-go/kubernetes/typed/core/v1/pod.go
// pods implements PodInterface type pods struct {client rest.Interfacens string }pods對象實現了PodInterface接口。PodInterface定義了pods對象的增刪改查等方法。
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) errorDeleteCollection(options *meta_v1.DeleteOptions, listOptions meta_v1.ListOptions) errorGet(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
PodsGetter繼承了PodInterface的接口。
k8s.io/client-go/kubernetes/typed/core/v1/pod.go
// PodsGetter has a method to return a PodInterface. // A group's client should implement this interface. type PodsGetter interface {Pods(namespace string) PodInterface }Pods().List()
pods.List()方法通過RESTClient的HTTP調用來實現對kubernetes的pod資源的獲取。
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 }以上分析了clientset.CoreV1().Pods("").List(metav1.ListOptions{})對pod資源獲取的過程,最終是調用RESTClient的方法實現。
2.5 RESTClient
以下分析RESTClient的創建過程及作用。
RESTClient對象的創建同樣是依賴傳入的config信息。
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 that a RESTClient may require fields that are optional when initializing a Client. // A RESTClient created by this method is generic - it expects to operate on an API that follows // the Kubernetes conventions, but may not be 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.Clientif 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) }RESTClientFor函數調用了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, config ContentConfig, maxQPS float32, maxBurst int, rateLimiter flowcontrol.RateLimiter, client *http.Client) (*RESTClient, error) {base := *baseURL...serializers, err := createSerializers(config)...return &RESTClient{base: &base,versionedAPIPath: versionedAPIPath,contentConfig: config,serializers: *serializers,createBackoffMgr: readExpBackoffConfig,Throttle: throttle,Client: client,}, nil }2.5.3 RESTClient結構體
以下介紹RESTClient的結構體定義,RESTClient結構體中包含了http.Client,即本質上RESTClient就是一個http.Client的封裝實現。
k8s.io/client-go/rest/client.go
// RESTClient imposes common Kubernetes API conventions on a set of resource paths. // The baseURL is expected to point to an HTTP or HTTPS path that is the parent // of one or more resources. The server should return a decodable API resource // object, or an api.Status object which contains information about the reason for // any failure. // // Most consumers should use client.New() to get a Kubernetes API client. type RESTClient struct {// base is the root URL for all invocations of the clientbase *url.URL// versionedAPIPath is a path segment connecting the base URL to the resource rootversionedAPIPath string// contentConfig is the information used to communicate with the server.contentConfig ContentConfig// serializers contain all serializers for underlying content type.serializers Serializers// creates BackoffManager that is passed to requests.createBackoffMgr func() BackoffManager// TODO extract this into a wrapper interface via the RESTClient interface in kubectl.Throttle flowcontrol.RateLimiter// Set specific behavior of the client. If not set http.DefaultClient will be used.Client *http.Client }2.5.4 RESTClient.Interface
RESTClient實現了以下的接口方法:
k8s.io/client-go/rest/client.go
// Interface captures the set of operations for generically interacting with Kubernetes REST apis. type Interface interface {GetRateLimiter() flowcontrol.RateLimiterVerb(verb string) *RequestPost() *RequestPut() *RequestPatch(pt types.PatchType) *RequestGet() *RequestDelete() *RequestAPIVersion() schema.GroupVersion }在調用HTTP方法(Post(),Put(),Get(),Delete() )時,實際上調用了Verb(verb string)函數。
k8s.io/client-go/rest/client.go
// Verb begins a request with a verb (GET, POST, PUT, DELETE). // // Example usage of RESTClient's request building interface: // c, err := NewRESTClient(...) // if err != nil { ... } // resp, err := c.Verb("GET"). // Path("pods"). // SelectorParam("labels", "area=staging"). // Timeout(10*time.Second). // Do() // if err != nil { ... } // list, ok := resp.(*api.PodList) // func (c *RESTClient) Verb(verb string) *Request {backoff := c.createBackoffMgr()if c.Client == nil {return NewRequest(nil, verb, c.base, c.versionedAPIPath, c.contentConfig, c.serializers, backoff, c.Throttle)}return NewRequest(c.Client, verb, c.base, c.versionedAPIPath, c.contentConfig, c.serializers, backoff, c.Throttle) }Verb函數調用了NewRequest方法,最后調用Do()方法實現一個HTTP請求獲取Result。
2.6 總結
client-go對kubernetes資源對象的調用,需要先獲取kubernetes的配置信息,即$HOME/.kube/config。
整個調用的過程如下:
kubeconfig→rest.config→clientset→具體的client(CoreV1Client)→具體的資源對象(pod)→RESTClient→http.Client→HTTP請求的發送及響應
通過clientset中不同的client和client中不同資源對象的方法實現對kubernetes中資源對象的增刪改查等操作,常用的client有CoreV1Client、AppsV1beta1Client、ExtensionsV1beta1Client等。
3. client-go對k8s資源的調用
創建clientset
//獲取kubeconfig kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") //創建config config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) //創建clientset clientset, err := kubernetes.NewForConfig(config) //具體的資源調用見以下例子3.1 deployment
//聲明deployment對象 var deployment *v1beta1.Deployment //構造deployment對象 //創建deployment deployment, err := clientset.AppsV1beta1().Deployments(<namespace>).Create(<deployment>) //更新deployment deployment, err := clientset.AppsV1beta1().Deployments(<namespace>).Update(<deployment>) //刪除deployment err := clientset.AppsV1beta1().Deployments(<namespace>).Delete(<deployment.Name>, &meta_v1.DeleteOptions{}) //查詢deployment deployment, err := clientset.AppsV1beta1().Deployments(<namespace>).Get(<deployment.Name>, meta_v1.GetOptions{}) //列出deployment deploymentList, err := clientset.AppsV1beta1().Deployments(<namespace>).List(&meta_v1.ListOptions{}) //watch deployment watchInterface, err := clientset.AppsV1beta1().Deployments(<namespace>).Watch(&meta_v1.ListOptions{})3.2 service
//聲明service對象 var service *v1.Service //構造service對象 //創建service service, err := clientset.CoreV1().Services(<namespace>).Create(<service>) //更新service service, err := clientset.CoreV1().Services(<namespace>).Update(<service>) //刪除service err := clientset.CoreV1().Services(<namespace>).Delete(<service.Name>, &meta_v1.DeleteOptions{}) //查詢service service, err := clientset.CoreV1().Services(<namespace>).Get(<service.Name>, meta_v1.GetOptions{}) //列出service serviceList, err := clientset.CoreV1().Services(<namespace>).List(&meta_v1.ListOptions{}) //watch service watchInterface, err := clientset.CoreV1().Services(<namespace>).Watch(&meta_v1.ListOptions{})3.3 ingress
//聲明ingress對象 var ingress *v1beta1.Ingress //構造ingress對象 //創建ingress ingress, err := clientset.ExtensionsV1beta1().Ingresses(<namespace>).Create(<ingress>) //更新ingress ingress, err := clientset.ExtensionsV1beta1().Ingresses(<namespace>).Update(<ingress>) //刪除ingress err := clientset.ExtensionsV1beta1().Ingresses(<namespace>).Delete(<ingress.Name>, &meta_v1.DeleteOptions{}) //查詢ingress ingress, err := clientset.ExtensionsV1beta1().Ingresses(<namespace>).Get(<ingress.Name>, meta_v1.GetOptions{}) //列出ingress ingressList, err := clientset.ExtensionsV1beta1().Ingresses(<namespace>).List(&meta_v1.ListOptions{}) //watch ingress watchInterface, err := clientset.ExtensionsV1beta1().Ingresses(<namespace>).Watch(&meta_v1.ListOptions{})3.4 replicaSet
//聲明replicaSet對象 var replicaSet *v1beta1.ReplicaSet //構造replicaSet對象 //創建replicaSet replicaSet, err := clientset.ExtensionsV1beta1().ReplicaSets(<namespace>).Create(<replicaSet>) //更新replicaSet replicaSet, err := clientset.ExtensionsV1beta1().ReplicaSets(<namespace>).Update(<replicaSet>) //刪除replicaSet err := clientset.ExtensionsV1beta1().ReplicaSets(<namespace>).Delete(<replicaSet.Name>, &meta_v1.DeleteOptions{}) //查詢replicaSet replicaSet, err := clientset.ExtensionsV1beta1().ReplicaSets(<namespace>).Get(<replicaSet.Name>, meta_v1.GetOptions{}) //列出replicaSet replicaSetList, err := clientset.ExtensionsV1beta1().ReplicaSets(<namespace>).List(&meta_v1.ListOptions{}) //watch replicaSet watchInterface, err := clientset.ExtensionsV1beta1().ReplicaSets(<namespace>).Watch(&meta_v1.ListOptions{})新版的kubernetes中一般通過deployment來創建replicaSet,再通過replicaSet來控制pod。
3.5 pod
//聲明pod對象 var pod *v1.Pod //創建pod pod, err := clientset.CoreV1().Pods(<namespace>).Create(<pod>) //更新pod pod, err := clientset.CoreV1().Pods(<namespace>).Update(<pod>) //刪除pod err := clientset.CoreV1().Pods(<namespace>).Delete(<pod.Name>, &meta_v1.DeleteOptions{}) //查詢pod pod, err := clientset.CoreV1().Pods(<namespace>).Get(<pod.Name>, meta_v1.GetOptions{}) //列出pod podList, err := clientset.CoreV1().Pods(<namespace>).List(&meta_v1.ListOptions{}) //watch pod watchInterface, err := clientset.CoreV1().Pods(<namespace>).Watch(&meta_v1.ListOptions{})3.6 statefulset
//聲明statefulset對象 var statefulset *v1.StatefulSet //創建statefulset statefulset, err := clientset.AppsV1().StatefulSets(<namespace>).Create(<statefulset>) //更新statefulset statefulset, err := clientset.AppsV1().StatefulSets(<namespace>).Update(<statefulset>) //刪除statefulset err := clientset.AppsV1().StatefulSets(<namespace>).Delete(<statefulset.Name>, &meta_v1.DeleteOptions{}) //查詢statefulset statefulset, err := clientset.AppsV1().StatefulSets(<namespace>).Get(<statefulset.Name>, meta_v1.GetOptions{}) //列出statefulset statefulsetList, err := clientset.AppsV1().StatefulSets(<namespace>).List(&meta_v1.ListOptions{}) //watch statefulset watchInterface, err := clientset.AppsV1().StatefulSets(<namespace>).Watch(&meta_v1.ListOptions{})? 通過以上對kubernetes的資源對象的操作函數可以看出,每個資源對象都有增刪改查等方法,基本調用邏輯類似。一般二次開發只需要創建deployment、service、ingress三個資源對象即可,pod對象由deployment包含的replicaSet來控制創建和刪除。函數調用的入參一般只有NAMESPACE和kubernetesObject兩個參數,部分操作有Options的參數。在創建前,需要對資源對象構造數據,可以理解為編輯一個資源對象的yaml文件,然后通過kubectl create -f xxx.yaml來創建對象。
參考文檔
https://github.com/kubernetes/client-go
總結
以上是生活随笔為你收集整理的client-go的使用及源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 支付宝实现当面付扫描支付退款及退款查询
- 下一篇: 520送什么礼物好呢、适合送女友的礼物推