-
Notifications
You must be signed in to change notification settings - Fork 61
/
k8sutils.go
735 lines (616 loc) · 21.2 KB
/
k8sutils.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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
/*
* Copyright (c) 2021, MegaEase
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package installbase
import (
"context"
"encoding/json"
"fmt"
"os"
"github.com/megaease/easemeshctl/cmd/common"
admissionregv1 "k8s.io/api/admissionregistration/v1"
appsV1 "k8s.io/api/apps/v1"
v1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
apiextensions "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
var (
scheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(scheme)
parameterCodec = runtime.NewParameterCodec(scheme)
encoder = unstructured.NewJSONFallbackEncoder(codecs.LegacyCodec(scheme.PrioritizedVersionsAllGroups()...))
metadataAccessor = meta.NewAccessor()
)
type (
createResourceFunc func() error
getResourceRunc func() (runtime.Object, error)
updateResourceFunc func() error
// PredictFunc is the type of function to predict if the resource is ready.
PredictFunc func(interface{}) bool
// PodStatus is the status of Pod.
PodStatus struct {
Name string
ReadyContainer int
ExpectContainer int
Status string
Restarts int
}
deleteResourceFunc func(kubernetes.Interface, string, string, string) error
// ListPodFunc is the type of function to list pod.
ListPodFunc func(kubernetes.Interface, string) []PodStatus
)
// NewKubernetesClient creates Kubernetes client set.
func NewKubernetesClient() (kubernetes.Interface, clientcmd.ClientConfig, error) {
config := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{})
clientConfig, err := config.ClientConfig()
if err != nil {
return nil, nil, err
}
kubeClient, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
return nil, nil, err
}
return kubeClient, config, nil
}
// NewKubernetesAPIExtensionsClient creates Kubernetes API extensions client.
func NewKubernetesAPIExtensionsClient() (apiextensions.Interface, error) {
config, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(), &clientcmd.ConfigOverrides{}).
ClientConfig()
if err != nil {
return nil, err
}
clientset, err := apiextensions.NewForConfig(config)
if err != nil {
return nil, err
}
return clientset, nil
}
func requestContext() context.Context { return context.TODO() }
func createOptions() metav1.CreateOptions { return metav1.CreateOptions{} }
func getOptions() metav1.GetOptions { return metav1.GetOptions{} }
func updateOptions() metav1.UpdateOptions { return metav1.UpdateOptions{} }
func adaptReplaceObject(old, new runtime.Object) error {
oldAnnots, err := metadataAccessor.Annotations(old)
if err != nil {
return err
}
delete(oldAnnots, v1.LastAppliedConfigAnnotation)
metadataAccessor.SetAnnotations(old, oldAnnots)
lastConfig, err := json.Marshal(old)
if err != nil {
return err
}
newAnnots, err := metadataAccessor.Annotations(new)
if err != nil {
return err
}
if newAnnots == nil {
newAnnots = make(map[string]string)
}
newAnnots[v1.LastAppliedConfigAnnotation] = string(lastConfig)
err = metadataAccessor.SetAnnotations(new, newAnnots)
if err != nil {
return err
}
oldResourceVersion, err := metadataAccessor.ResourceVersion(old)
if err == nil {
metadataAccessor.SetResourceVersion(new, oldResourceVersion)
}
return nil
}
func deployResource(createFn createResourceFunc, updateFn updateResourceFunc) error {
err := createFn()
if err == nil {
return nil
}
if !errors.IsAlreadyExists(err) {
return err
}
return updateFn()
}
// DeployNamespace creates or updates Namespace.
func DeployNamespace(namespace *v1.Namespace, clientSet kubernetes.Interface) error {
createFn := func() error {
_, err := clientSet.CoreV1().Namespaces().
Create(requestContext(), namespace, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.CoreV1().Namespaces().
Get(requestContext(), namespace.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, namespace)
if err != nil {
return err
}
_, err = clientSet.CoreV1().Namespaces().
Update(requestContext(), namespace, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployDeployment creates or updates Deployment.
func DeployDeployment(deployment *appsV1.Deployment, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.AppsV1().Deployments(namespace).
Create(requestContext(), deployment, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.AppsV1().Deployments(namespace).
Get(requestContext(), deployment.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, deployment)
if err != nil {
return err
}
_, err = clientSet.AppsV1().Deployments(namespace).
Update(requestContext(), deployment, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployStatefulset creates or updates StatefulSet.
func DeployStatefulset(statefulset *appsV1.StatefulSet, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.AppsV1().StatefulSets(namespace).
Create(requestContext(), statefulset, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.AppsV1().StatefulSets(namespace).
Get(requestContext(), statefulset.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, statefulset)
if err != nil {
return err
}
_, err = clientSet.AppsV1().StatefulSets(namespace).
Update(requestContext(), statefulset, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployService creates or updates Service.
func DeployService(service *v1.Service, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.CoreV1().Services(namespace).
Create(requestContext(), service, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.CoreV1().Services(namespace).
Get(requestContext(), service.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, service)
if err != nil {
return err
}
// NOTE: https://github.com/helm/helm/issues/6378#issuecomment-557746499
service.Spec.ClusterIP = oldObject.Spec.ClusterIP
service.Spec.ClusterIPs = oldObject.Spec.ClusterIPs
_, err = clientSet.CoreV1().Services(namespace).
Update(requestContext(), service, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployConfigMap creates or updates ConfigMap.
func DeployConfigMap(configMap *v1.ConfigMap, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.CoreV1().ConfigMaps(namespace).
Create(requestContext(), configMap, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.CoreV1().ConfigMaps(namespace).
Get(requestContext(), configMap.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, configMap)
if err != nil {
return err
}
_, err = clientSet.CoreV1().ConfigMaps(namespace).
Update(requestContext(), configMap, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeploySecret creates or updates Secret.
func DeploySecret(secret *v1.Secret, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.CoreV1().Secrets(namespace).
Create(requestContext(), secret, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.CoreV1().Secrets(namespace).
Get(requestContext(), secret.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, secret)
if err != nil {
return err
}
_, err = clientSet.CoreV1().Secrets(namespace).
Update(requestContext(), secret, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployMutatingWebhookConfig creates or updates WebHookConfig.
func DeployMutatingWebhookConfig(mutatingWebhookConfig *admissionregv1.MutatingWebhookConfiguration, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.AdmissionregistrationV1().MutatingWebhookConfigurations().
Create(requestContext(), mutatingWebhookConfig, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.AdmissionregistrationV1().MutatingWebhookConfigurations().
Get(requestContext(), mutatingWebhookConfig.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, mutatingWebhookConfig)
if err != nil {
return err
}
_, err = clientSet.AdmissionregistrationV1().MutatingWebhookConfigurations().
Update(requestContext(), mutatingWebhookConfig, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// ListPersistentVolume lists persistent volumes.
func ListPersistentVolume(clientSet kubernetes.Interface) (*v1.PersistentVolumeList, error) {
return clientSet.CoreV1().PersistentVolumes().List(requestContext(), metav1.ListOptions{})
}
// DeployRole creates or updates Role.
func DeployRole(role *rbacv1.Role, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.RbacV1().Roles(namespace).
Create(requestContext(), role, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.RbacV1().Roles(namespace).
Get(requestContext(), role.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, role)
if err != nil {
return err
}
_, err = clientSet.RbacV1().Roles(namespace).
Update(requestContext(), role, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployRoleBinding creates or updates RoleBinding.
func DeployRoleBinding(roleBinding *rbacv1.RoleBinding, clientSet kubernetes.Interface, namespace string) error {
createFn := func() error {
_, err := clientSet.RbacV1().RoleBindings(namespace).
Create(requestContext(), roleBinding, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.RbacV1().RoleBindings(namespace).
Get(requestContext(), roleBinding.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, roleBinding)
if err != nil {
return err
}
_, err = clientSet.RbacV1().RoleBindings(namespace).
Update(requestContext(), roleBinding, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployClusterRole creates or updates ClusterRole.
func DeployClusterRole(clusterRole *rbacv1.ClusterRole, clientSet kubernetes.Interface) error {
createFn := func() error {
_, err := clientSet.RbacV1().ClusterRoles().
Create(requestContext(), clusterRole, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.RbacV1().ClusterRoles().
Get(requestContext(), clusterRole.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, clusterRole)
if err != nil {
return err
}
_, err = clientSet.RbacV1().ClusterRoles().
Update(requestContext(), clusterRole, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployClusterRoleBinding creates or updates ClusterRoleBinding.
func DeployClusterRoleBinding(clusterRoleBinding *rbacv1.ClusterRoleBinding, clientSet kubernetes.Interface) error {
createFn := func() error {
_, err := clientSet.RbacV1().ClusterRoleBindings().
Create(requestContext(), clusterRoleBinding, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.RbacV1().ClusterRoleBindings().
Get(requestContext(), clusterRoleBinding.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, clusterRoleBinding)
if err != nil {
return err
}
_, err = clientSet.RbacV1().ClusterRoleBindings().
Update(requestContext(), clusterRoleBinding, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// DeployCustomResourceDefinition creates or updates CustomResourceDefinition.
func DeployCustomResourceDefinition(crd *apiextensionsv1.CustomResourceDefinition, clientSet apiextensions.Interface) error {
createFn := func() error {
_, err := clientSet.ApiextensionsV1().CustomResourceDefinitions().
Create(requestContext(), crd, createOptions())
return err
}
updateFn := func() error {
oldObject, err := clientSet.ApiextensionsV1().CustomResourceDefinitions().
Get(requestContext(), crd.Name, getOptions())
if err != nil {
return err
}
err = adaptReplaceObject(oldObject, crd)
if err != nil {
return err
}
_, err = clientSet.ApiextensionsV1().CustomResourceDefinitions().
Update(requestContext(), crd, updateOptions())
return err
}
return deployResource(createFn, updateFn)
}
// StatefulsetReadyPredict returns if the StatefultSet is ready.
func StatefulsetReadyPredict(object interface{}) (ready bool) {
statefulset, ok := object.(*appsV1.StatefulSet)
if !ok {
return
}
return statefulset.Status.ReadyReplicas == *statefulset.Spec.Replicas
}
// DeploymentReadyPredict returns if the Deployment is ready.
func DeploymentReadyPredict(object interface{}) (ready bool) {
deploy, ok := object.(*appsV1.Deployment)
if !ok {
return
}
return deploy.Status.ReadyReplicas == *deploy.Spec.Replicas
}
// CheckStatefulsetResourceStatus checks if the StatefulSet is ready.
func CheckStatefulsetResourceStatus(client kubernetes.Interface, namespace, resourceName string, predict PredictFunc) (bool, error) {
statefulset, err := client.AppsV1().StatefulSets(namespace).Get(requestContext(), resourceName, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return false, nil
}
return false, err
}
return predict(statefulset), nil
}
// CheckDeploymentResourceStatus checks if the Deployment is ready.
func CheckDeploymentResourceStatus(client kubernetes.Interface, namespace, name string, predict PredictFunc) (bool, error) {
deploy, err := client.AppsV1().Deployments(namespace).Get(requestContext(), name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
return false, nil
}
return false, err
}
return predict(deploy), nil
}
// GetMeshControlPlaneEndpoints gets the endpoints of EaseMesh control plane.
func GetMeshControlPlaneEndpoints(client kubernetes.Interface, namespace, resourceName, portName string) ([]string, error) {
service, err := client.CoreV1().Services(namespace).Get(requestContext(), resourceName, metav1.GetOptions{})
if err != nil {
return nil, err
}
nodes, err := client.CoreV1().Nodes().List(requestContext(), metav1.ListOptions{})
if err != nil {
return nil, err
}
var nodePort int32
for _, p := range service.Spec.Ports {
if p.Name == portName {
nodePort = p.NodePort
break
}
}
entrypoints := []string{}
for _, n := range nodes.Items {
for _, i := range n.Status.Addresses {
address := i.Address
// NOTICE: For situation where the node address is not reachable.
if addr := os.Getenv("EMCTL_NODE_ADDRESS"); addr != "" {
address = addr
}
if i.Type == v1.NodeInternalIP {
entrypoints = append(entrypoints, fmt.Sprintf("http://%s:%d", address, nodePort))
}
}
}
return entrypoints, nil
}
// BatchDeployResources deploy resources in batches.
func BatchDeployResources(ctx *StageContext, installFuncs []InstallFunc) error {
for _, fn := range installFuncs {
err := fn.Deploy(ctx)
if err != nil {
return err
}
}
return nil
}
// DeleteStatefulsetResource deletes Statefulset.
func DeleteStatefulsetResource(client kubernetes.Interface, resource, namespace, name string) error {
err := client.AppsV1().StatefulSets(namespace).Delete(context.Background(), name, metav1.DeleteOptions{})
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// DeleteAppsV1Resource deletes resources within group AppV1.
func DeleteAppsV1Resource(client kubernetes.Interface, resource, namespace, name string) error {
err := client.AppsV1().RESTClient().Delete().Resource(resource).Namespace(namespace).Name(name).Do(context.Background()).Error()
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// DeleteCoreV1Resource deletes resources within group CoreV1.
func DeleteCoreV1Resource(client kubernetes.Interface, resource, namespace, name string) error {
err := client.CoreV1().RESTClient().Delete().Resource(resource).Namespace(namespace).Name(name).Do(context.Background()).Error()
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// DeleteRbacV1Resources deletes resources within group RbacV1.
func DeleteRbacV1Resources(client kubernetes.Interface, resources, namespace, name string) error {
err := client.RbacV1().RESTClient().Delete().Resource(resources).Namespace(namespace).Name(name).Do(context.Background()).Error()
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// DeleteAdmissionregV1Resources deletes resources within group AdmissionregV1.
func DeleteAdmissionregV1Resources(client kubernetes.Interface, resources, namespace, name string) error {
// NOTE: RESTClinet can't find mutatingwebhookconfigurations resource.
err := client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(requestContext(), name, metav1.DeleteOptions{})
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// DeleteCertificateV1Beta1Resources deletes resources within group CertificateV1Beta1.
func DeleteCertificateV1Beta1Resources(client kubernetes.Interface, resources, namespace, name string) error {
// NOTE: RESTClinet can't find csr resource.
err := client.CertificatesV1().CertificateSigningRequests().Delete(context.Background(), name, metav1.DeleteOptions{})
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// DeleteCRDResource deletes resources within group CustomResourceDefinitions.
func DeleteCRDResource(client apiextensions.Interface, name string) error {
err := client.ApiextensionsV1().CustomResourceDefinitions().Delete(context.Background(), name, metav1.DeleteOptions{})
if err != nil && !errors.IsNotFound(err) {
return err
}
return nil
}
// DeleteResources deletes resources.
func DeleteResources(client kubernetes.Interface, resourceAndName [][]string, namespace string, deletefunc deleteResourceFunc) {
for _, s := range resourceAndName {
err := deletefunc(client, s[0], namespace, s[1])
if err != nil {
common.OutputErrorf("clear resource %s of %s in %s error: %s\n", s[1], s[0], namespace, err)
}
}
}
func listPodByLabels(client kubernetes.Interface, labels map[string]string, namespace string) []PodStatus {
i := 0
labelSelector := ""
for k, v := range labels {
labelSelector += fmt.Sprintf("%s=%s", k, v)
i++
if i < len(labels) {
labelSelector += ","
}
}
podList, err := client.CoreV1().Pods(namespace).List(context.Background(), metav1.ListOptions{LabelSelector: labelSelector})
if err != nil {
common.OutputErrorf("Ignore error %s", err)
return nil
}
podStatus := []PodStatus{}
for _, p := range podList.Items {
ready, restart := readyAndRestartCount(p.Status.ContainerStatuses)
podStatus = append(podStatus, PodStatus{
Name: p.Name,
ReadyContainer: ready,
ExpectContainer: len(p.Spec.Containers),
Status: string(p.Status.Phase),
Restarts: restart,
})
}
return podStatus
}
func readyAndRestartCount(statuses []v1.ContainerStatus) (readyCount, restartCount int) {
for _, s := range statuses {
if s.Ready {
readyCount++
}
readyCount += int(s.RestartCount)
}
return
}
// AdaptListPodFunc adapts the ListPodFunc with labels.
func AdaptListPodFunc(labels map[string]string) ListPodFunc {
return func(client kubernetes.Interface, namespace string) []PodStatus {
return listPodByLabels(client, labels, namespace)
}
}
// FormatPodStatus formats PodStatus.
func FormatPodStatus(client kubernetes.Interface, namespace string, fn ListPodFunc) (format string) {
pods := fn(client, namespace)
format += fmt.Sprintf("%-45s%-8s%-15s%-10s\n", "Name", "Ready", "Status", "Restarts")
for _, p := range pods {
format += fmt.Sprintf("%-45s%-8s%-15s%-10d\n", p.Name, fmt.Sprintf("%d/%d", p.ReadyContainer, p.ExpectContainer), p.Status, p.Restarts)
}
return
}