-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
452 lines (374 loc) · 12.9 KB
/
client.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
package kubernetes
import (
"bytes"
"context"
"fmt"
"net/http"
"path/filepath"
"strconv"
"strings"
"github.com/pkg/errors"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/cli-runtime/pkg/genericiooptions"
applyv1 "k8s.io/client-go/applyconfigurations/core/v1"
"k8s.io/client-go/kubernetes"
app "k8s.io/client-go/kubernetes/typed/apps/v1"
core "k8s.io/client-go/kubernetes/typed/core/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/portforward"
"k8s.io/client-go/tools/remotecommand"
"k8s.io/client-go/transport/spdy"
"k8s.io/client-go/util/homedir"
"k8s.io/kubectl/pkg/cmd/exec"
"k8s.io/kubectl/pkg/scheme"
"github.com/hckops/hckctl/pkg/client/common"
)
func NewKubeClient(inCluster bool, configPath string) (*KubeClient, error) {
ctx := context.Background()
if inCluster {
return newInClusterKubeClient(ctx)
} else {
return newOutOfClusterKubeClient(ctx, configPath)
}
}
func newOutOfClusterKubeClient(ctx context.Context, configPath string) (*KubeClient, error) {
restConfig, clientSet, err := NewOutOfClusterKubeConfig(configPath)
if err != nil {
return nil, err
}
return &KubeClient{
ctx: ctx,
kubeRestConfig: restConfig,
kubeClientSet: clientSet,
}, nil
}
func NewOutOfClusterKubeConfig(configPath string) (*rest.Config, *kubernetes.Clientset, error) {
kubeConfig := NormalizeKubeConfig(configPath)
restConfig, err := clientcmd.BuildConfigFromFlags("", kubeConfig)
if err != nil {
return nil, nil, errors.Wrap(err, "error out-of-cluster restConfig")
}
clientSet, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return nil, nil, errors.Wrap(err, "error out-of-cluster clientSet")
}
return restConfig, clientSet, nil
}
func NormalizeKubeConfig(configPath string) string {
if strings.TrimSpace(configPath) == "" {
return filepath.Join(homedir.HomeDir(), ".kube", "config")
} else {
// absolute path
return configPath
}
}
func newInClusterKubeClient(ctx context.Context) (*KubeClient, error) {
restConfig, clientSet, err := NewInClusterKubeConfig()
if err != nil {
return nil, err
}
return &KubeClient{
ctx: ctx,
kubeRestConfig: restConfig,
kubeClientSet: clientSet,
}, nil
}
func NewInClusterKubeConfig() (*rest.Config, *kubernetes.Clientset, error) {
restConfig, err := rest.InClusterConfig()
if err != nil {
return nil, nil, errors.Wrap(err, "error in-cluster restConfig")
}
clientSet, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return nil, nil, errors.Wrap(err, "error in-cluster clientSet")
}
return restConfig, clientSet, nil
}
func (client *KubeClient) Close() error {
return errors.New("not implemented")
}
func (client *KubeClient) RestApi() *rest.Config {
return client.kubeRestConfig
}
func (client *KubeClient) CoreApi() core.CoreV1Interface {
return client.kubeClientSet.CoreV1()
}
func (client *KubeClient) AppApi() app.AppsV1Interface {
return client.kubeClientSet.AppsV1()
}
func (client *KubeClient) NamespaceApply(name string) error {
// https://github.com/kubernetes/client-go/issues/1036
_, err := client.CoreApi().Namespaces().Apply(client.ctx, applyv1.Namespace(name), metav1.ApplyOptions{FieldManager: "application/apply-patch"})
if err != nil {
return errors.Wrapf(err, "error namespace apply: name=%s", name)
}
return nil
}
func (client *KubeClient) NamespaceDelete(name string) error {
if err := client.CoreApi().Namespaces().Delete(client.ctx, name, metav1.DeleteOptions{}); err != nil {
return errors.Wrapf(err, "error namespace delete: name=%s", name)
}
return nil
}
func (client *KubeClient) DeploymentCreate(opts *DeploymentCreateOpts) error {
deployment, err := client.AppApi().Deployments(opts.Namespace).Create(client.ctx, opts.Spec, metav1.CreateOptions{})
if err != nil {
return errors.Wrapf(err, "error deployment create: namespace=%s name=%s", opts.Namespace, opts.Spec.Name)
}
// blocks until the deployment is available, then stop watching
watcher, err := client.AppApi().Deployments(opts.Namespace).Watch(client.ctx, metav1.SingleObject(deployment.ObjectMeta))
if err != nil {
return errors.Wrapf(err, "error deployment watch: namespace=%s name=%s", opts.Namespace, deployment.Name)
}
for event := range watcher.ResultChan() {
switch event.Type {
case watch.Modified:
deploymentEvent := event.Object.(*appsv1.Deployment)
for _, condition := range deploymentEvent.Status.Conditions {
opts.OnStatusEventCallback(fmt.Sprintf("watch deployment event: namespace=%s name=%s type=%v condition=%v",
opts.Namespace, deployment.Name, event.Type, condition.Message))
if condition.Type == appsv1.DeploymentAvailable &&
condition.Status == corev1.ConditionTrue {
watcher.Stop()
}
}
default:
return errors.Wrapf(err, "error deployment event: type=%v", event.Type)
}
}
return nil
}
func (client *KubeClient) DeploymentList(namespace string, namePrefix string, labelSelector string) ([]DeploymentInfo, error) {
deployments, err := client.AppApi().Deployments(namespace).List(client.ctx, metav1.ListOptions{
// comma separated values with format <LABEL_KEY>=<SANITIZED_LABEL_VALUE>
LabelSelector: labelSelector,
})
if err != nil {
return nil, errors.Wrapf(err, "error deployment list: namespace=%s", namespace)
}
var result []DeploymentInfo
for _, deployment := range deployments.Items {
// check manually because ListOptions/FieldSelector supports only full name
if !strings.HasPrefix(deployment.Name, namePrefix) {
// skip invalid prefix
continue
}
podInfo, err := client.PodDescribe(&deployment)
if err != nil {
// skip invalid pod
continue
}
result = append(result, newDeploymentInfo(&deployment, podInfo))
}
return result, nil
}
func newDeploymentInfo(deployment *appsv1.Deployment, podInfo *PodInfo) DeploymentInfo {
return DeploymentInfo{
Namespace: deployment.Namespace,
Name: deployment.Name,
Healthy: isDeploymentHealthy(deployment.Status),
PodInfo: podInfo,
}
}
func isDeploymentHealthy(status appsv1.DeploymentStatus) bool {
// all conditions must be true to be healthy
var healthy bool
for _, condition := range status.Conditions {
if condition.Status == corev1.ConditionTrue {
healthy = true
} else {
healthy = false
// mark as unhealthy if at least one condition is false e.g. stuck due to lack of resources
break
}
}
return healthy
}
func (client *KubeClient) DeploymentDescribe(namespace string, name string) (*DeploymentDetails, error) {
deployment, err := client.AppApi().Deployments(namespace).Get(client.ctx, name, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrapf(err, "error deployment describe: namespace=%s name=%s", namespace, name)
}
podInfo, err := client.PodDescribe(deployment)
if err != nil {
return nil, err
}
return newDeploymentDetails(deployment, podInfo), nil
}
func newDeploymentDetails(deployment *appsv1.Deployment, podInfo *PodInfo) *DeploymentDetails {
deploymentInfo := newDeploymentInfo(deployment, podInfo)
return &DeploymentDetails{
Info: &deploymentInfo,
Created: deployment.CreationTimestamp.Time.UTC(),
Annotations: deployment.Annotations,
}
}
func (client *KubeClient) DeploymentDelete(namespace string, name string) error {
err := client.AppApi().Deployments(namespace).Delete(client.ctx, name, metav1.DeleteOptions{})
if err != nil {
return errors.Wrapf(err, "error deployment delete: namespace=%s name=%s", namespace, name)
}
return nil
}
func (client *KubeClient) ServiceCreate(namespace string, spec *corev1.Service) error {
_, err := client.CoreApi().Services(namespace).Create(client.ctx, spec, metav1.CreateOptions{})
if err != nil {
return errors.Wrapf(err, "error service create: namespace=%s name=%s", namespace, spec.Name)
}
return nil
}
func (client *KubeClient) ServiceDescribe(namespace string, name string) (*ServiceInfo, error) {
service, err := client.CoreApi().Services(namespace).Get(client.ctx, name, metav1.GetOptions{})
if err != nil {
return nil, errors.Wrapf(err, "error service describe: namespace=%s name=%s", namespace, name)
}
return newServiceInfo(service), nil
}
func newServiceInfo(service *corev1.Service) *ServiceInfo {
var ports []KubePort
for _, port := range service.Spec.Ports {
ports = append(ports, KubePort{Name: port.Name, Port: strconv.Itoa(int(port.Port))})
}
return &ServiceInfo{
Namespace: service.Namespace,
Name: service.Name,
Ports: ports,
}
}
func (client *KubeClient) ServiceDelete(namespace string, name string) error {
if err := client.CoreApi().Services(namespace).Delete(client.ctx, name, metav1.DeleteOptions{}); err != nil {
return errors.Wrapf(err, "error service delete: namespace=%s name=%s", namespace, name)
}
return nil
}
func (client *KubeClient) PodDescribe(deployment *appsv1.Deployment) (*PodInfo, error) {
labelSet := labels.Set(deployment.Spec.Selector.MatchLabels)
listOptions := metav1.ListOptions{LabelSelector: labelSet.AsSelector().String()}
pods, err := client.CoreApi().Pods(deployment.Namespace).List(client.ctx, listOptions)
if err != nil {
return nil, errors.Wrapf(err, "error pod describe: namespace=%s labels=%v", deployment.Namespace, labelSet)
}
return newPodInfo(deployment.Namespace, pods)
}
func newPodInfo(namespace string, pods *corev1.PodList) (*PodInfo, error) {
if len(pods.Items) != SingleReplica {
return nil, fmt.Errorf("found %d pods, expected only 1 pod for deployment: namespace=%s", len(pods.Items), namespace)
}
podItem := pods.Items[0]
var containers []corev1.Container
for _, c := range podItem.Spec.Containers {
// exclude injected sidecar containers
if !strings.HasPrefix(c.Name, SidecarPrefix) {
containers = append(containers, c)
}
}
if len(containers) != 1 {
return nil, fmt.Errorf("found %d containers, expected only 1 container for pod: namespace=%s", len(podItem.Spec.Containers), namespace)
}
containerItem := podItem.Spec.Containers[0]
var envs []KubeEnv
for _, e := range containerItem.Env {
envs = append(envs, KubeEnv{Key: e.Name, Value: e.Value})
}
return &PodInfo{
Namespace: podItem.Namespace,
PodName: podItem.Name, // pod.Name + unique generated suffix
ContainerName: containerItem.Name,
ImageName: containerItem.Image, // <REPOSITORY>/<NAME>:<VERSION>
Env: envs,
Resource: &KubeResource{
Memory: containerItem.Resources.Requests.Memory().String(),
Cpu: containerItem.Resources.Requests.Cpu().String(),
},
}, nil
}
func (client *KubeClient) PodPortForward(opts *PodPortForwardOpts) error {
restRequest := client.CoreApi().RESTClient().
Post().
Resource("pods").
Namespace(opts.Namespace).
Name(opts.PodId).
SubResource("portforward")
transport, upgrader, err := spdy.RoundTripperFor(client.RestApi())
if err != nil {
return errors.Wrap(err, "error kube round tripper")
}
dialer := spdy.NewDialer(upgrader, &http.Client{Transport: transport}, http.MethodPost, restRequest.URL())
stopChannel := client.ctx.Done()
readyChannel := make(chan struct{}, 1)
out := new(bytes.Buffer)
errOut := new(bytes.Buffer)
forwarder, err := portforward.New(dialer, opts.Ports, stopChannel, readyChannel, out, errOut)
if err != nil {
return errors.Wrap(err, "error kube new portforward")
}
go func() {
if err := forwarder.ForwardPorts(); err != nil {
opts.OnTunnelErrorCallback(err)
}
}()
opts.OnTunnelStartCallback()
if opts.IsWait {
// wait until interrupted
select {
case <-stopChannel:
return errors.Wrap(err, "error kube stopped")
}
} else {
// continue as soon as ready
for range readyChannel {
}
}
if len(errOut.String()) != 0 {
return errors.Wrapf(err, "error kube stream: %s", errOut.String())
}
return nil
}
func (client *KubeClient) PodExec(opts *PodExecOpts) error {
streamOptions := exec.StreamOptions{
Stdin: true,
TTY: opts.IsTty,
IOStreams: genericiooptions.IOStreams{
In: opts.InStream,
Out: opts.OutStream,
ErrOut: opts.ErrStream,
},
}
tty := streamOptions.SetupTTY()
var sizeQueue remotecommand.TerminalSizeQueue
if tty.Raw {
sizeQueue = tty.MonitorSize(tty.GetSize())
streamOptions.ErrOut = nil
}
// exec remote shell
execUrl := client.CoreApi().RESTClient().
Post().
Namespace(opts.Namespace).
Resource("pods").
Name(opts.PodId).
SubResource("exec").
VersionedParams(&corev1.PodExecOptions{
Container: opts.PodName,
Command: []string{common.DefaultShell(opts.Shell)},
Stdin: true,
Stdout: true,
Stderr: true,
TTY: true,
}, scheme.ParameterCodec).
URL()
executor := exec.DefaultRemoteExecutor{}
opts.OnExecCallback()
fn := func() error {
isTty := tty.Raw && opts.IsTty
return executor.Execute(http.MethodPost, execUrl, client.RestApi(), streamOptions.In, streamOptions.Out, streamOptions.ErrOut, isTty, sizeQueue)
}
if err := tty.Safe(fn); err != nil {
return errors.Wrap(err, "terminal session closed")
}
return nil
}