1. 程式人生 > >kubernetes client-go包使用示例

kubernetes client-go包使用示例

前言

本文將歸檔到kubernetes-handbook的【開發指南—client-go示例】章節中,最終版本以kubernetes-handbook中為準。

client-go示例

訪問kubernetes叢集有幾下幾種方式:

方式 特點 支持者
Kubernetes dashboard 直接通過Web UI進行操作,簡單直接,可定製化程度低 官方支援
kubectl 命令列操作,功能最全,但是比較複雜,適合對其進行進一步的分裝,定製功能,版本適配最好 官方支援
從kubernetes的程式碼中抽離出來的客戶端包,簡單易用,但需要小心區分kubernetes的API版本 官方支援
python客戶端,kubernetes-incubator 官方支援
fabric8中的一部分,kubernetes的java客戶端 redhat

kubernetes-client-go-sample

程式碼如下:

package main

import (
    "flag"
    "fmt"
    "os"
    "path/filepath"

    "k8s.io/apimachinery/pkg/api/errors"
    metav1 "k8s.io/apimachinery/pkg/apis/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.String
("kubeconfig", "", "absolute path to the kubeconfig file") } deploymentName := flag.String("deployment", "", "deployment name") imageName := flag.String("image", "", "new image name") appName := flag.String("app", "app", "application name") flag.Parse() if *deploymentName == "" { fmt.Println("You must specify the deployment name.") os.Exit(0) } if *imageName == "" { fmt.Println("You must specify the new image name.") os.Exit(0) } // use the current context in kubeconfig config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) if err != nil { panic(err.Error()) } // create the clientset clientset, err := kubernetes.NewForConfig(config) if err != nil { panic(err.Error()) } deployment, err := clientset.AppsV1beta1().Deployments("default").Get(*deploymentName, metav1.GetOptions{}) if err != nil { panic(err.Error()) } if errors.IsNotFound(err) { fmt.Printf("Deployment not found\n") } else if statusError, isStatus := err.(*errors.StatusError); isStatus { fmt.Printf("Error getting deployment%v\n", statusError.ErrStatus.Message) } else if err != nil { panic(err.Error()) } else { fmt.Printf("Found deployment\n") name := deployment.GetName() fmt.Println("name ->", name) containers := &deployment.Spec.Template.Spec.Containers found := false for i := range *containers { c := *containers if c[i].Name == *appName { found = true fmt.Println("Old image ->", c[i].Image) fmt.Println("New image ->", *imageName) c[i].Image = *imageName } } if found == false { fmt.Println("The application container not exist in the deployment pods.") os.Exit(0) } _, err := clientset.AppsV1beta1().Deployments("default").Update(deployment) if err != nil { panic(err.Error()) } } } func homeDir() string { if h := os.Getenv("HOME"); h != "" { return h } return os.Getenv("USERPROFILE") // windows }

我們使用kubeconfig檔案認證連線kubernetes叢集,該檔案預設的位置是$HOME/.kube/config

該程式碼編譯後可以直接在kubernetes叢集之外,任何一個可以連線到API server的機器上執行。

編譯執行

$ go get github.com/rootsongjc/kubernetes-client-go-sample
$ cd $GOPATH/src/github.com/rootsongjc/kubernetes-client-go-sample
$ make
$ ./update-deployment-image -h
Usage of ./update-deployment-image:
  -alsologtostderr
        log to standard error as well as files
  -app string
        application name (default "app")
  -deployment string
        deployment name
  -image string
        new image name
  -kubeconfig string
        (optional) absolute path to the kubeconfig file (default "/Users/jimmy/.kube/config")
  -log_backtrace_at value
        when logging hits line file:N, emit a stack trace
  -log_dir string
        If non-empty, write log files in this directory
  -logtostderr
        log to standard error instead of files
  -stderrthreshold value
        logs at or above this threshold go to stderr
  -v value
        log level for V logs
  -vmodule value
        comma-separated list of pattern=N settings for file-filtered logging

使用不存在的image更新

 $ ./update-deployment-image -deployment filebeat-test -image sz-pg-oam-docker-hub-001.tendcloud.com/library/analytics-docker-test:Build_9 
Found deployment
name -> filebeat-test
Old image -> sz-pg-oam-docker-hub-001.tendcloud.com/library/analytics-docker-test:Build_8
New image -> sz-pg-oam-docker-hub-001.tendcloud.com/library/analytics-docker-test:Build_9

檢視Deployment的event。

$ kubectl describe deployment filebeat-test   
Name:           filebeat-test
Namespace:      default
CreationTimestamp:  Fri, 19 May 2017 15:12:28 +0800
Labels:         k8s-app=filebeat-test
Selector:       k8s-app=filebeat-test
Replicas:       2 updated | 3 total | 2 available | 2 unavailable
StrategyType:       RollingUpdate
MinReadySeconds:    0
RollingUpdateStrategy:  1 max unavailable, 1 max surge
Conditions:
  Type      Status  Reason
  ----      ------  ------
  Available     True    MinimumReplicasAvailable
  Progressing   True    ReplicaSetUpdated
OldReplicaSets: filebeat-test-2365467882 (2/2 replicas created)
NewReplicaSet:  filebeat-test-2470325483 (2/2 replicas created)
Events:
  FirstSeen LastSeen    Count   From                SubObjectPath   Type        ReasoMessage
  --------- --------    -----   ----                -------------   --------    ------------
  2h        1m      3   {deployment-controller }            Normal      ScalingReplicaSet   Scaled down replica set filebeat-test-2365467882 to 2
  1m        1m      1   {deployment-controller }            Normal      ScalingReplicaSet   Scaled up replica set filebeat-test-2470325483 to 1
  1m        1m      1   {deployment-controller }            Normal      ScalingReplicaSet   Scaled up replica set filebeat-test-2470325483 to 2

可以看到老的ReplicaSet從3個replica減少到了2個,有2個使用新配置的replica不可用,目前可用的replica是2個。

這是因為我們指定的映象不存在,檢視Deployment的pod的狀態。

$ kubectl get pods -l k8s-app=filebeat-test
NAME                             READY     STATUS             RESTARTS   AGE
filebeat-test-2365467882-4zwx8   2/2       Running            0          33d
filebeat-test-2365467882-rqskl   2/2       Running            0          33d
filebeat-test-2470325483-6vjbw   1/2       ImagePullBackOff   0          4m
filebeat-test-2470325483-gc14k   1/2       ImagePullBackOff   0          4m

我們可以看到有兩個pod正在拉取image。

還原為原先的映象

將image設定為原來的映象。

$ ./update-deployment-image -deployment filebeat-test -image sz-pg-oam-docker-hub-001.tendcloud.com/library/analytics-docker-test:Build_8
Found deployment
name -> filebeat-test
Old image -> sz-pg-oam-docker-hub-001.tendcloud.com/library/analytics-docker-test:Build_9
New image -> sz-pg-oam-docker-hub-001.tendcloud.com/library/analytics-docker-test:Build_8

現在再檢視Deployment的狀態。

$ kubectl describe deployment filebeat-test   
Name:           filebeat-test
Namespace:      default
CreationTimestamp:  Fri, 19 May 2017 15:12:28 +0800
Labels:         k8s-app=filebeat-test
Selector:       k8s-app=filebeat-test
Replicas:       3 updated | 3 total | 3 available | 0 unavailable
StrategyType:       RollingUpdate
MinReadySeconds:    0
RollingUpdateStrategy:  1 max unavailable, 1 max surge
Conditions:
  Type      Status  Reason
  ----      ------  ------
  Available     True    MinimumReplicasAvailable
  Progressing   True    NewReplicaSetAvailable
OldReplicaSets: <none>
NewReplicaSet:  filebeat-test-2365467882 (3/3 replicas created)
Events:
  FirstSeen LastSeen    Count   From                SubObjectPath   Type        ReasoMessage
  --------- --------    -----   ----                -------------   --------    ------------
  2h        8m      3   {deployment-controller }            Normal      ScalingReplicaSet   Scaled down replica set filebeat-test-2365467882 to 2
  8m        8m      1   {deployment-controller }            Normal      ScalingReplicaSet   Scaled up replica set filebeat-test-2470325483 to 1
  8m        8m      1   {deployment-controller }            Normal      ScalingReplicaSet   Scaled up replica set filebeat-test-2470325483 to 2
  2h        1m      3   {deployment-controller }            Normal      ScalingReplicaSet   Scaled up replica set filebeat-test-2365467882 to 3
  1m        1m      1   {deployment-controller }            Normal      ScalingReplicaSet   Scaled down replica set filebeat-test-2470325483 to 0

可以看到available的replica個數恢復成3了。

其實在使用該命令的過程中,通過kubernetes dashboard的頁面上檢視Deployment的狀態更直觀,更加方便故障排查。

使用kubernetes dashboard進行故障排查

這也是dashboard最大的優勢,簡單、直接、高效。