-
Notifications
You must be signed in to change notification settings - Fork 25
/
kubectl.go
281 lines (232 loc) · 6.22 KB
/
kubectl.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package clients
import (
"fmt"
"os"
"path"
"path/filepath"
"time"
"github.com/hashicorp/go-hclog"
"golang.org/x/xerrors"
"helm.sh/helm/v3/pkg/kube"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/tools/clientcmd"
)
// Kubernetes defines an interface for a Kuberenetes client
type Kubernetes interface {
SetConfig(string) error
GetPods(string) (*v1.PodList, error)
HealthCheckPods(selectors []string, timeout time.Duration) error
Apply(files []string, waitUntilReady bool) error
Delete(files []string) error
}
// KubernetesImpl is a concrete implementation of a Kubernetes client
type KubernetesImpl struct {
clientset *kubernetes.Clientset
client corev1.CoreV1Interface
configPath string
timeout time.Duration
l hclog.Logger
}
// NewKubernetes creates a new client for interacting with Kubernetes clusters
func NewKubernetes(t time.Duration, l hclog.Logger) Kubernetes {
return &KubernetesImpl{timeout: t, l: l}
}
// SetConfig for the Kubernetes cluster
func (k *KubernetesImpl) SetConfig(kubeconfig string) error {
k.configPath = kubeconfig
st := time.Now()
for {
err := k.setConfig()
if err == nil {
break
}
if time.Now().Sub(st) > k.timeout {
return xerrors.Errorf("Error waiting for kubeclient: %w", err)
}
}
return nil
}
// setConfig retries setting the config and building the client APIs
// it is possible that the cluster is not fully ready when
// this operation is first called
func (k *KubernetesImpl) setConfig() error {
config, err := clientcmd.BuildConfigFromFlags("", k.configPath)
if err != nil {
return err
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
return err
}
k.clientset = clientset
k.client = clientset.CoreV1()
return nil
}
// GetPods returns the Kubernetes pods based on the label selector
func (k *KubernetesImpl) GetPods(selector string) (*v1.PodList, error) {
lo := metav1.ListOptions{
LabelSelector: selector,
}
pl, err := k.client.Pods("").List(lo)
if err != nil {
return nil, err
}
return pl, nil
}
// Apply Kubernetes YAML files at path
// if waitUntilReady is true then the client will block until all resources have been created
func (k *KubernetesImpl) Apply(files []string, waitUntilReady bool) error {
allFiles, err := buildFileList(files)
if err != nil {
return err
}
s := kube.GetConfig(k.configPath, "default", "default")
kc := kube.New(s)
// process the files
for _, f := range allFiles {
k.l.Debug("Applying Kubernetes config", "file", f)
err := applyFile(f, waitUntilReady, kc)
if err != nil {
return err
}
}
return nil
}
// Delete Kuberentes YAML files at path
func (k *KubernetesImpl) Delete(files []string) error {
allFiles, err := buildFileList(files)
if err != nil {
return err
}
s := kube.GetConfig(k.configPath, "default", "default")
kc := kube.New(s)
// process the files
for _, f := range allFiles {
k.l.Debug("Removing Kubernetes config", "file", f)
err := deleteFile(f, kc)
if err != nil {
return err
}
}
return nil
}
// HealthCheckPods uses the given selector to check that all pods are started
// and running.
// selectors are checked sequentially
// pods = ["component=server,app=consul", "component=client,app=consul"]
func (k *KubernetesImpl) HealthCheckPods(selectors []string, timeout time.Duration) error {
// check all pods are running
for _, s := range selectors {
k.l.Debug("Health checking pods", "selector", s)
err := k.healthCheckSingle(s, timeout)
if err != nil {
return err
}
}
return nil
}
// healthCheckSingle checks for running containers with the given selector
func (k *KubernetesImpl) healthCheckSingle(selector string, timeout time.Duration) error {
st := time.Now()
for {
if time.Now().Sub(st) > timeout {
return fmt.Errorf("Timeout waiting for pods %s to start", selector)
}
// GetPods may return an error if the API server is not available
pl, err := k.GetPods(selector)
if err != nil {
continue
}
// there should be at least 1 pod
if len(pl.Items) < 1 {
continue
}
allRunning := true
for _, pod := range pl.Items {
if pod.Status.Phase != "Running" {
allRunning = false
k.l.Debug("Pod not running", "pod", pod.Name, "namespace", pod.Namespace, "status", pod.Status.Phase)
break
}
// check the individual status
for _, s := range pod.Status.ContainerStatuses {
if !s.Ready {
allRunning = false
k.l.Debug("Pod not ready", "pod", pod.Name, "namespace", pod.Namespace, "container", s.Name)
}
}
}
if allRunning {
break
}
// backoff
time.Sleep(2 * time.Second)
}
return nil
}
func buildFileList(files []string) ([]string, error) {
allFiles := make([]string, 0)
for _, f := range files {
// parse all of the config into a string
fi, err := os.Stat(f)
if err != nil {
return nil, err
}
if fi.IsDir() {
// add all the yaml files in the directory
files, err := filepath.Glob(path.Join(f, "*.yaml"))
if err != nil {
return nil, err
}
allFiles = append(allFiles, files...)
// add all the yml files in the directory
files, err = filepath.Glob(path.Join(f, "*.yml"))
if err != nil {
return nil, err
}
allFiles = append(allFiles, files...)
} else {
allFiles = append(allFiles, f)
}
}
return allFiles, nil
}
func applyFile(path string, waitUntilReady bool, kc *kube.Client) error {
f, err := os.Open(path)
if err != nil {
return xerrors.Errorf("Unable to open file: %w", err)
}
defer f.Close()
r, err := kc.Build(f, true)
if err != nil {
return xerrors.Errorf("Unable to build resources for file %s: %w", path, err)
}
_, err = kc.Create(r)
if err != nil {
return xerrors.Errorf("Unable to create resources for file %s: %w", path, err)
}
if waitUntilReady {
return kc.WatchUntilReady(r, 30*time.Second)
}
return nil
}
func deleteFile(path string, kc *kube.Client) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
r, err := kc.Build(f, false)
if err != nil {
return err
}
_, errs := kc.Delete(r)
if errs != nil {
//TODO need to handle this better
return xerrors.Errorf("Error deleting configuration for file %s: %w", path, errs)
}
return nil
}