forked from rancher/rke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
k8s.go
53 lines (46 loc) · 1.21 KB
/
k8s.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package k8s
import (
"bytes"
"time"
yamlutil "k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
const (
DefaultRetries = 5
DefaultSleepSeconds = 5
)
type k8sCall func(*kubernetes.Clientset, interface{}) error
func NewClient(kubeConfigPath string) (*kubernetes.Clientset, error) {
// use the current admin kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", kubeConfigPath)
if err != nil {
return nil, err
}
K8sClientSet, err := kubernetes.NewForConfig(config)
if err != nil {
return nil, err
}
return K8sClientSet, nil
}
func decodeYamlResource(resource interface{}, yamlManifest string) error {
decoder := yamlutil.NewYAMLToJSONDecoder(bytes.NewReader([]byte(yamlManifest)))
return decoder.Decode(&resource)
}
func retryTo(runFunc k8sCall, k8sClient *kubernetes.Clientset, resource interface{}, retries, sleepSeconds int) error {
var err error
if retries == 0 {
retries = DefaultRetries
}
if sleepSeconds == 0 {
sleepSeconds = DefaultSleepSeconds
}
for i := 0; i < retries; i++ {
if err = runFunc(k8sClient, resource); err != nil {
time.Sleep(time.Second * time.Duration(sleepSeconds))
continue
}
return nil
}
return err
}