funcmain() { 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.String("kubeconfig", "", "absolute path to the kubeconfig file") } flag.Parse() // uses the current context 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(10 * time.Second) } }
funchomeDir()string { if h := os.Getenv("HOME"); h != "" { return h } return os.Getenv("USERPROFILE") // windows }
1.3 运行结果
1 2 3 4 5 6
➜ 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 cluster
// 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. funcBuildConfigFromFlags(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() }
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 }
// PodsGetter has a method to return a PodInterface. // A group's client should implement this interface. type PodsGetter interface { Pods(namespace string) PodInterface }
// 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 }
// 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. funcRESTClientFor(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 } }
// 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 client base *url.URL // versionedAPIPath is a path segment connecting the base URL to the resource root versionedAPIPath 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 }