Skip to content

Commit

Permalink
优化 kubectl 相关命令
Browse files Browse the repository at this point in the history
  • Loading branch information
guoyk93 committed Jun 29, 2020
1 parent 4cde8c1 commit ef0d2e0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 26 deletions.
31 changes: 5 additions & 26 deletions pkg/cmd/kubectl.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,13 @@
package cmd

import (
"log"
"time"
)

const KubectlPatchRetries = 3

func RunKubectlVersion(kubeconfig string) error {
return Run("kubectl", "--kubeconfig", kubeconfig, "version")
return RunRetries(KubectlPatchRetries, "kubectl", "--kubeconfig", kubeconfig,
"version")
}

func RunKubectlPatch(kubeconfig, namespace, workload, workloadType, patch string) (err error) {
i := 0
for {
if err = Run("kubectl",
"--kubeconfig", kubeconfig,
"--namespace", namespace,
"patch", workloadType+"s/"+workload,
"-p", patch,
); err == nil {
return
}

i++
if i > KubectlPatchRetries {
return
}

log.Printf("部署失败,5s 后重试")
time.Sleep(time.Second * 5)
}
func RunKubectlPatch(kubeconfig, namespace, workload, workloadType, patch string) error {
return RunRetries(KubectlPatchRetries, "kubectl", "--kubeconfig", kubeconfig,
"--namespace", namespace, "patch", workloadType+"s/"+workload, "-p", patch)
}
19 changes: 19 additions & 0 deletions pkg/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"os"
"os/exec"
"strings"
"time"
)

func Run(name string, args ...string) (err error) {
Expand All @@ -18,3 +19,21 @@ func Run(name string, args ...string) (err error) {
}
return
}

func RunRetries(retry int, name string, args ...string) (err error) {
if retry < 1 {
retry = 1
}
for {
if err = Run(name, args...); err == nil {
return
}

retry--
if retry == 0 {
return
}
time.Sleep(time.Second * 5)
log.Printf("5s 后重试, 剩余 %d", retry)
}
}

0 comments on commit ef0d2e0

Please sign in to comment.