...
1 package kclient
2
3 import (
4 "fmt"
5 "reflect"
6
7 "k8s.io/client-go/tools/clientcmd"
8 )
9
10
11
12
13
14 func (c *Client) Refresh() (bool, error) {
15 newClient, err := New()
16 if err != nil {
17 return false, err
18 }
19
20 oldCluster, oldNs, err := getContext(c)
21 if err != nil {
22 return false, err
23 }
24 newCluster, newNs, err := getContext(newClient)
25 if err != nil {
26 return false, err
27 }
28
29 if oldCluster != newCluster {
30 return false, fmt.Errorf("cluster changed (%q -> %q), won't refresh the configuration", oldCluster, newCluster)
31 }
32 if oldNs != newNs {
33 return false, fmt.Errorf("namespace changed (%q -> %q), won't refresh the configuration", oldNs, newNs)
34 }
35
36 updated, err := isConfigUpdated(c.GetConfig(), newClient.GetConfig())
37 if err != nil {
38 return false, err
39 }
40
41 if updated {
42 *c = *newClient
43 }
44 return updated, nil
45 }
46
47 func getContext(c *Client) (cluster string, namespace string, err error) {
48 raw, err := c.GetConfig().RawConfig()
49 if err != nil {
50 return "", "", err
51 }
52
53 currentCtx := raw.Contexts[raw.CurrentContext]
54 return currentCtx.Cluster, currentCtx.Namespace, nil
55 }
56
57 func isConfigUpdated(oldC, newC clientcmd.ClientConfig) (bool, error) {
58 oldRaw, err := oldC.RawConfig()
59 if err != nil {
60 return false, err
61 }
62 newRaw, err := newC.RawConfig()
63 if err != nil {
64 return false, err
65 }
66 return !reflect.DeepEqual(oldRaw, newRaw), nil
67 }
68
View as plain text