forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
describe.go
4023 lines (3584 loc) · 138 KB
/
describe.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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2014 The Kubernetes Authors.
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 internalversion
import (
"bytes"
"crypto/x509"
"fmt"
"io"
"net"
"net/url"
"reflect"
"sort"
"strconv"
"strings"
"text/tabwriter"
"time"
"github.com/golang/glog"
"github.com/fatih/camelcase"
appsv1 "k8s.io/api/apps/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/client-go/dynamic"
externalclient "k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/kubernetes/pkg/api/events"
"k8s.io/kubernetes/pkg/api/legacyscheme"
"k8s.io/kubernetes/pkg/api/ref"
resourcehelper "k8s.io/kubernetes/pkg/api/resource"
"k8s.io/kubernetes/pkg/apis/apps"
"k8s.io/kubernetes/pkg/apis/autoscaling"
"k8s.io/kubernetes/pkg/apis/batch"
"k8s.io/kubernetes/pkg/apis/certificates"
api "k8s.io/kubernetes/pkg/apis/core"
"k8s.io/kubernetes/pkg/apis/core/helper"
"k8s.io/kubernetes/pkg/apis/core/helper/qos"
"k8s.io/kubernetes/pkg/apis/extensions"
"k8s.io/kubernetes/pkg/apis/networking"
"k8s.io/kubernetes/pkg/apis/policy"
"k8s.io/kubernetes/pkg/apis/rbac"
rbacv1helpers "k8s.io/kubernetes/pkg/apis/rbac/v1"
"k8s.io/kubernetes/pkg/apis/scheduling"
"k8s.io/kubernetes/pkg/apis/storage"
storageutil "k8s.io/kubernetes/pkg/apis/storage/util"
clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
coreclient "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset/typed/core/internalversion"
deploymentutil "k8s.io/kubernetes/pkg/controller/deployment/util"
"k8s.io/kubernetes/pkg/fieldpath"
"k8s.io/kubernetes/pkg/printers"
"k8s.io/kubernetes/pkg/registry/rbac/validation"
"k8s.io/kubernetes/pkg/util/slice"
)
// Each level has 2 spaces for PrefixWriter
const (
LEVEL_0 = iota
LEVEL_1
LEVEL_2
LEVEL_3
)
// PrefixWriter can write text at various indentation levels.
type PrefixWriter interface {
// Write writes text with the specified indentation level.
Write(level int, format string, a ...interface{})
// WriteLine writes an entire line with no indentation level.
WriteLine(a ...interface{})
// Flush forces indentation to be reset.
Flush()
}
// prefixWriter implements PrefixWriter
type prefixWriter struct {
out io.Writer
}
var _ PrefixWriter = &prefixWriter{}
// NewPrefixWriter creates a new PrefixWriter.
func NewPrefixWriter(out io.Writer) PrefixWriter {
return &prefixWriter{out: out}
}
func (pw *prefixWriter) Write(level int, format string, a ...interface{}) {
levelSpace := " "
prefix := ""
for i := 0; i < level; i++ {
prefix += levelSpace
}
fmt.Fprintf(pw.out, prefix+format, a...)
}
func (pw *prefixWriter) WriteLine(a ...interface{}) {
fmt.Fprintln(pw.out, a...)
}
func (pw *prefixWriter) Flush() {
if f, ok := pw.out.(flusher); ok {
f.Flush()
}
}
func describerMap(clientConfig *rest.Config) (map[schema.GroupKind]printers.Describer, error) {
c, err := clientset.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
externalclient, err := externalclient.NewForConfig(clientConfig)
if err != nil {
return nil, err
}
m := map[schema.GroupKind]printers.Describer{
api.Kind("Pod"): &PodDescriber{c},
api.Kind("ReplicationController"): &ReplicationControllerDescriber{c},
api.Kind("Secret"): &SecretDescriber{c},
api.Kind("Service"): &ServiceDescriber{c},
api.Kind("ServiceAccount"): &ServiceAccountDescriber{c},
api.Kind("Node"): &NodeDescriber{c},
api.Kind("LimitRange"): &LimitRangeDescriber{c},
api.Kind("ResourceQuota"): &ResourceQuotaDescriber{c},
api.Kind("PersistentVolume"): &PersistentVolumeDescriber{c},
api.Kind("PersistentVolumeClaim"): &PersistentVolumeClaimDescriber{c},
api.Kind("Namespace"): &NamespaceDescriber{c},
api.Kind("Endpoints"): &EndpointsDescriber{c},
api.Kind("ConfigMap"): &ConfigMapDescriber{c},
api.Kind("PriorityClass"): &PriorityClassDescriber{c},
extensions.Kind("ReplicaSet"): &ReplicaSetDescriber{c},
extensions.Kind("NetworkPolicy"): &NetworkPolicyDescriber{c},
extensions.Kind("PodSecurityPolicy"): &PodSecurityPolicyDescriber{c},
autoscaling.Kind("HorizontalPodAutoscaler"): &HorizontalPodAutoscalerDescriber{c},
extensions.Kind("DaemonSet"): &DaemonSetDescriber{c},
extensions.Kind("Deployment"): &DeploymentDescriber{c, externalclient},
extensions.Kind("Ingress"): &IngressDescriber{c},
batch.Kind("Job"): &JobDescriber{c},
batch.Kind("CronJob"): &CronJobDescriber{c, externalclient},
apps.Kind("StatefulSet"): &StatefulSetDescriber{c},
apps.Kind("Deployment"): &DeploymentDescriber{c, externalclient},
apps.Kind("DaemonSet"): &DaemonSetDescriber{c},
apps.Kind("ReplicaSet"): &ReplicaSetDescriber{c},
certificates.Kind("CertificateSigningRequest"): &CertificateSigningRequestDescriber{c},
storage.Kind("StorageClass"): &StorageClassDescriber{c},
policy.Kind("PodDisruptionBudget"): &PodDisruptionBudgetDescriber{c},
rbac.Kind("Role"): &RoleDescriber{externalclient},
rbac.Kind("ClusterRole"): &ClusterRoleDescriber{externalclient},
rbac.Kind("RoleBinding"): &RoleBindingDescriber{externalclient},
rbac.Kind("ClusterRoleBinding"): &ClusterRoleBindingDescriber{externalclient},
networking.Kind("NetworkPolicy"): &NetworkPolicyDescriber{c},
scheduling.Kind("PriorityClass"): &PriorityClassDescriber{c},
}
return m, nil
}
// DescriberFor returns the default describe functions for each of the standard
// Kubernetes types.
func DescriberFor(kind schema.GroupKind, clientConfig *rest.Config) (printers.Describer, bool) {
describers, err := describerMap(clientConfig)
if err != nil {
glog.V(1).Info(err)
return nil, false
}
f, ok := describers[kind]
return f, ok
}
// GenericDescriberFor returns a generic describer for the specified mapping
// that uses only information available from runtime.Unstructured
func GenericDescriberFor(mapping *meta.RESTMapping, dynamic dynamic.Interface, events coreclient.EventsGetter) printers.Describer {
return &genericDescriber{mapping, dynamic, events}
}
type genericDescriber struct {
mapping *meta.RESTMapping
dynamic dynamic.Interface
events coreclient.EventsGetter
}
func (g *genericDescriber) Describe(namespace, name string, describerSettings printers.DescriberSettings) (output string, err error) {
obj, err := g.dynamic.Resource(g.mapping.Resource).Namespace(namespace).Get(name, metav1.GetOptions{})
if err != nil {
return "", err
}
var events *api.EventList
if describerSettings.ShowEvents {
events, _ = g.events.Events(namespace).Search(legacyscheme.Scheme, obj)
}
return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Name:\t%s\n", obj.GetName())
w.Write(LEVEL_0, "Namespace:\t%s\n", obj.GetNamespace())
printLabelsMultiline(w, "Labels", obj.GetLabels())
printAnnotationsMultiline(w, "Annotations", obj.GetAnnotations())
printUnstructuredContent(w, LEVEL_0, obj.UnstructuredContent(), "", ".metadata.name", ".metadata.namespace", ".metadata.labels", ".metadata.annotations")
if events != nil {
DescribeEvents(events, w)
}
return nil
})
}
func printUnstructuredContent(w PrefixWriter, level int, content map[string]interface{}, skipPrefix string, skip ...string) {
fields := []string{}
for field := range content {
fields = append(fields, field)
}
sort.Strings(fields)
for _, field := range fields {
value := content[field]
switch typedValue := value.(type) {
case map[string]interface{}:
skipExpr := fmt.Sprintf("%s.%s", skipPrefix, field)
if slice.ContainsString(skip, skipExpr, nil) {
continue
}
w.Write(level, "%s:\n", smartLabelFor(field))
printUnstructuredContent(w, level+1, typedValue, skipExpr, skip...)
case []interface{}:
skipExpr := fmt.Sprintf("%s.%s", skipPrefix, field)
if slice.ContainsString(skip, skipExpr, nil) {
continue
}
w.Write(level, "%s:\n", smartLabelFor(field))
for _, child := range typedValue {
switch typedChild := child.(type) {
case map[string]interface{}:
printUnstructuredContent(w, level+1, typedChild, skipExpr, skip...)
default:
w.Write(level+1, "%v\n", typedChild)
}
}
default:
skipExpr := fmt.Sprintf("%s.%s", skipPrefix, field)
if slice.ContainsString(skip, skipExpr, nil) {
continue
}
w.Write(level, "%s:\t%v\n", smartLabelFor(field), typedValue)
}
}
}
func smartLabelFor(field string) string {
commonAcronyms := []string{"API", "URL", "UID", "OSB", "GUID"}
splitted := camelcase.Split(field)
for i := 0; i < len(splitted); i++ {
part := splitted[i]
if slice.ContainsString(commonAcronyms, strings.ToUpper(part), nil) {
part = strings.ToUpper(part)
} else {
part = strings.Title(part)
}
splitted[i] = part
}
return strings.Join(splitted, " ")
}
// DefaultObjectDescriber can describe the default Kubernetes objects.
var DefaultObjectDescriber printers.ObjectDescriber
func init() {
d := &Describers{}
err := d.Add(
describeLimitRange,
describeQuota,
describePod,
describeService,
describeReplicationController,
describeDaemonSet,
describeNode,
describeNamespace,
)
if err != nil {
glog.Fatalf("Cannot register describers: %v", err)
}
DefaultObjectDescriber = d
}
// NamespaceDescriber generates information about a namespace
type NamespaceDescriber struct {
clientset.Interface
}
func (d *NamespaceDescriber) Describe(namespace, name string, describerSettings printers.DescriberSettings) (string, error) {
ns, err := d.Core().Namespaces().Get(name, metav1.GetOptions{})
if err != nil {
return "", err
}
resourceQuotaList, err := d.Core().ResourceQuotas(name).List(metav1.ListOptions{})
if err != nil {
if errors.IsNotFound(err) {
// Server does not support resource quotas.
// Not an error, will not show resource quotas information.
resourceQuotaList = nil
} else {
return "", err
}
}
limitRangeList, err := d.Core().LimitRanges(name).List(metav1.ListOptions{})
if err != nil {
if errors.IsNotFound(err) {
// Server does not support limit ranges.
// Not an error, will not show limit ranges information.
limitRangeList = nil
} else {
return "", err
}
}
return describeNamespace(ns, resourceQuotaList, limitRangeList)
}
func describeNamespace(namespace *api.Namespace, resourceQuotaList *api.ResourceQuotaList, limitRangeList *api.LimitRangeList) (string, error) {
return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Name:\t%s\n", namespace.Name)
printLabelsMultiline(w, "Labels", namespace.Labels)
printAnnotationsMultiline(w, "Annotations", namespace.Annotations)
w.Write(LEVEL_0, "Status:\t%s\n", string(namespace.Status.Phase))
if resourceQuotaList != nil {
w.Write(LEVEL_0, "\n")
DescribeResourceQuotas(resourceQuotaList, w)
}
if limitRangeList != nil {
w.Write(LEVEL_0, "\n")
DescribeLimitRanges(limitRangeList, w)
}
return nil
})
}
func describeLimitRangeSpec(spec api.LimitRangeSpec, prefix string, w PrefixWriter) {
for i := range spec.Limits {
item := spec.Limits[i]
maxResources := item.Max
minResources := item.Min
defaultLimitResources := item.Default
defaultRequestResources := item.DefaultRequest
ratio := item.MaxLimitRequestRatio
set := map[api.ResourceName]bool{}
for k := range maxResources {
set[k] = true
}
for k := range minResources {
set[k] = true
}
for k := range defaultLimitResources {
set[k] = true
}
for k := range defaultRequestResources {
set[k] = true
}
for k := range ratio {
set[k] = true
}
for k := range set {
// if no value is set, we output -
maxValue := "-"
minValue := "-"
defaultLimitValue := "-"
defaultRequestValue := "-"
ratioValue := "-"
maxQuantity, maxQuantityFound := maxResources[k]
if maxQuantityFound {
maxValue = maxQuantity.String()
}
minQuantity, minQuantityFound := minResources[k]
if minQuantityFound {
minValue = minQuantity.String()
}
defaultLimitQuantity, defaultLimitQuantityFound := defaultLimitResources[k]
if defaultLimitQuantityFound {
defaultLimitValue = defaultLimitQuantity.String()
}
defaultRequestQuantity, defaultRequestQuantityFound := defaultRequestResources[k]
if defaultRequestQuantityFound {
defaultRequestValue = defaultRequestQuantity.String()
}
ratioQuantity, ratioQuantityFound := ratio[k]
if ratioQuantityFound {
ratioValue = ratioQuantity.String()
}
msg := "%s%s\t%v\t%v\t%v\t%v\t%v\t%v\n"
w.Write(LEVEL_0, msg, prefix, item.Type, k, minValue, maxValue, defaultRequestValue, defaultLimitValue, ratioValue)
}
}
}
// DescribeLimitRanges merges a set of limit range items into a single tabular description
func DescribeLimitRanges(limitRanges *api.LimitRangeList, w PrefixWriter) {
if len(limitRanges.Items) == 0 {
w.Write(LEVEL_0, "No resource limits.\n")
return
}
w.Write(LEVEL_0, "Resource Limits\n Type\tResource\tMin\tMax\tDefault Request\tDefault Limit\tMax Limit/Request Ratio\n")
w.Write(LEVEL_0, " ----\t--------\t---\t---\t---------------\t-------------\t-----------------------\n")
for _, limitRange := range limitRanges.Items {
describeLimitRangeSpec(limitRange.Spec, " ", w)
}
}
// DescribeResourceQuotas merges a set of quota items into a single tabular description of all quotas
func DescribeResourceQuotas(quotas *api.ResourceQuotaList, w PrefixWriter) {
if len(quotas.Items) == 0 {
w.Write(LEVEL_0, "No resource quota.\n")
return
}
sort.Sort(SortableResourceQuotas(quotas.Items))
w.Write(LEVEL_0, "Resource Quotas")
for _, q := range quotas.Items {
w.Write(LEVEL_0, "\n Name:\t%s\n", q.Name)
if len(q.Spec.Scopes) > 0 {
scopes := make([]string, 0, len(q.Spec.Scopes))
for _, scope := range q.Spec.Scopes {
scopes = append(scopes, string(scope))
}
sort.Strings(scopes)
w.Write(LEVEL_0, " Scopes:\t%s\n", strings.Join(scopes, ", "))
for _, scope := range scopes {
helpText := helpTextForResourceQuotaScope(api.ResourceQuotaScope(scope))
if len(helpText) > 0 {
w.Write(LEVEL_0, " * %s\n", helpText)
}
}
}
w.Write(LEVEL_0, " Resource\tUsed\tHard\n")
w.Write(LEVEL_0, " --------\t---\t---\n")
resources := make([]api.ResourceName, 0, len(q.Status.Hard))
for resource := range q.Status.Hard {
resources = append(resources, resource)
}
sort.Sort(SortableResourceNames(resources))
for _, resource := range resources {
hardQuantity := q.Status.Hard[resource]
usedQuantity := q.Status.Used[resource]
w.Write(LEVEL_0, " %s\t%s\t%s\n", string(resource), usedQuantity.String(), hardQuantity.String())
}
}
}
// LimitRangeDescriber generates information about a limit range
type LimitRangeDescriber struct {
clientset.Interface
}
func (d *LimitRangeDescriber) Describe(namespace, name string, describerSettings printers.DescriberSettings) (string, error) {
lr := d.Core().LimitRanges(namespace)
limitRange, err := lr.Get(name, metav1.GetOptions{})
if err != nil {
return "", err
}
return describeLimitRange(limitRange)
}
func describeLimitRange(limitRange *api.LimitRange) (string, error) {
return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Name:\t%s\n", limitRange.Name)
w.Write(LEVEL_0, "Namespace:\t%s\n", limitRange.Namespace)
w.Write(LEVEL_0, "Type\tResource\tMin\tMax\tDefault Request\tDefault Limit\tMax Limit/Request Ratio\n")
w.Write(LEVEL_0, "----\t--------\t---\t---\t---------------\t-------------\t-----------------------\n")
describeLimitRangeSpec(limitRange.Spec, "", w)
return nil
})
}
// ResourceQuotaDescriber generates information about a resource quota
type ResourceQuotaDescriber struct {
clientset.Interface
}
func (d *ResourceQuotaDescriber) Describe(namespace, name string, describerSettings printers.DescriberSettings) (string, error) {
rq := d.Core().ResourceQuotas(namespace)
resourceQuota, err := rq.Get(name, metav1.GetOptions{})
if err != nil {
return "", err
}
return describeQuota(resourceQuota)
}
func helpTextForResourceQuotaScope(scope api.ResourceQuotaScope) string {
switch scope {
case api.ResourceQuotaScopeTerminating:
return "Matches all pods that have an active deadline. These pods have a limited lifespan on a node before being actively terminated by the system."
case api.ResourceQuotaScopeNotTerminating:
return "Matches all pods that do not have an active deadline. These pods usually include long running pods whose container command is not expected to terminate."
case api.ResourceQuotaScopeBestEffort:
return "Matches all pods that do not have resource requirements set. These pods have a best effort quality of service."
case api.ResourceQuotaScopeNotBestEffort:
return "Matches all pods that have at least one resource requirement set. These pods have a burstable or guaranteed quality of service."
default:
return ""
}
}
func describeQuota(resourceQuota *api.ResourceQuota) (string, error) {
return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Name:\t%s\n", resourceQuota.Name)
w.Write(LEVEL_0, "Namespace:\t%s\n", resourceQuota.Namespace)
if len(resourceQuota.Spec.Scopes) > 0 {
scopes := make([]string, 0, len(resourceQuota.Spec.Scopes))
for _, scope := range resourceQuota.Spec.Scopes {
scopes = append(scopes, string(scope))
}
sort.Strings(scopes)
w.Write(LEVEL_0, "Scopes:\t%s\n", strings.Join(scopes, ", "))
for _, scope := range scopes {
helpText := helpTextForResourceQuotaScope(api.ResourceQuotaScope(scope))
if len(helpText) > 0 {
w.Write(LEVEL_0, " * %s\n", helpText)
}
}
}
w.Write(LEVEL_0, "Resource\tUsed\tHard\n")
w.Write(LEVEL_0, "--------\t----\t----\n")
resources := make([]api.ResourceName, 0, len(resourceQuota.Status.Hard))
for resource := range resourceQuota.Status.Hard {
resources = append(resources, resource)
}
sort.Sort(SortableResourceNames(resources))
msg := "%v\t%v\t%v\n"
for i := range resources {
resource := resources[i]
hardQuantity := resourceQuota.Status.Hard[resource]
usedQuantity := resourceQuota.Status.Used[resource]
w.Write(LEVEL_0, msg, resource, usedQuantity.String(), hardQuantity.String())
}
return nil
})
}
// PodDescriber generates information about a pod and the replication controllers that
// create it.
type PodDescriber struct {
clientset.Interface
}
func (d *PodDescriber) Describe(namespace, name string, describerSettings printers.DescriberSettings) (string, error) {
pod, err := d.Core().Pods(namespace).Get(name, metav1.GetOptions{})
if err != nil {
if describerSettings.ShowEvents {
eventsInterface := d.Core().Events(namespace)
selector := eventsInterface.GetFieldSelector(&name, &namespace, nil, nil)
options := metav1.ListOptions{FieldSelector: selector.String()}
events, err2 := eventsInterface.List(options)
if describerSettings.ShowEvents && err2 == nil && len(events.Items) > 0 {
return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Pod '%v': error '%v', but found events.\n", name, err)
DescribeEvents(events, w)
return nil
})
}
}
return "", err
}
var events *api.EventList
if describerSettings.ShowEvents {
if ref, err := ref.GetReference(legacyscheme.Scheme, pod); err != nil {
glog.Errorf("Unable to construct reference to '%#v': %v", pod, err)
} else {
ref.Kind = ""
events, _ = d.Core().Events(namespace).Search(legacyscheme.Scheme, ref)
}
}
return describePod(pod, events)
}
func describePod(pod *api.Pod, events *api.EventList) (string, error) {
return tabbedString(func(out io.Writer) error {
w := NewPrefixWriter(out)
w.Write(LEVEL_0, "Name:\t%s\n", pod.Name)
w.Write(LEVEL_0, "Namespace:\t%s\n", pod.Namespace)
if pod.Spec.Priority != nil {
w.Write(LEVEL_0, "Priority:\t%d\n", *pod.Spec.Priority)
w.Write(LEVEL_0, "PriorityClassName:\t%s\n", stringOrNone(pod.Spec.PriorityClassName))
}
if pod.Spec.NodeName == "" {
w.Write(LEVEL_0, "Node:\t<none>\n")
} else {
w.Write(LEVEL_0, "Node:\t%s\n", pod.Spec.NodeName+"/"+pod.Status.HostIP)
}
if pod.Status.StartTime != nil {
w.Write(LEVEL_0, "Start Time:\t%s\n", pod.Status.StartTime.Time.Format(time.RFC1123Z))
}
printLabelsMultiline(w, "Labels", pod.Labels)
printAnnotationsMultiline(w, "Annotations", pod.Annotations)
if pod.DeletionTimestamp != nil {
w.Write(LEVEL_0, "Status:\tTerminating (lasts %s)\n", translateTimestamp(*pod.DeletionTimestamp))
w.Write(LEVEL_0, "Termination Grace Period:\t%ds\n", *pod.DeletionGracePeriodSeconds)
} else {
w.Write(LEVEL_0, "Status:\t%s\n", string(pod.Status.Phase))
}
if len(pod.Status.Reason) > 0 {
w.Write(LEVEL_0, "Reason:\t%s\n", pod.Status.Reason)
}
if len(pod.Status.Message) > 0 {
w.Write(LEVEL_0, "Message:\t%s\n", pod.Status.Message)
}
w.Write(LEVEL_0, "IP:\t%s\n", pod.Status.PodIP)
if controlledBy := printController(pod); len(controlledBy) > 0 {
w.Write(LEVEL_0, "Controlled By:\t%s\n", controlledBy)
}
if len(pod.Status.NominatedNodeName) > 0 {
w.Write(LEVEL_0, "NominatedNodeName:\t%s\n", pod.Status.NominatedNodeName)
}
if len(pod.Spec.InitContainers) > 0 {
describeContainers("Init Containers", pod.Spec.InitContainers, pod.Status.InitContainerStatuses, EnvValueRetriever(pod), w, "")
}
describeContainers("Containers", pod.Spec.Containers, pod.Status.ContainerStatuses, EnvValueRetriever(pod), w, "")
if len(pod.Status.Conditions) > 0 {
w.Write(LEVEL_0, "Conditions:\n Type\tStatus\n")
for _, c := range pod.Status.Conditions {
w.Write(LEVEL_1, "%v \t%v \n",
c.Type,
c.Status)
}
}
describeVolumes(pod.Spec.Volumes, w, "")
if pod.Status.QOSClass != "" {
w.Write(LEVEL_0, "QoS Class:\t%s\n", pod.Status.QOSClass)
} else {
w.Write(LEVEL_0, "QoS Class:\t%s\n", qos.GetPodQOS(pod))
}
printLabelsMultiline(w, "Node-Selectors", pod.Spec.NodeSelector)
printPodTolerationsMultiline(w, "Tolerations", pod.Spec.Tolerations)
if events != nil {
DescribeEvents(events, w)
}
return nil
})
}
func printController(controllee metav1.Object) string {
if controllerRef := metav1.GetControllerOf(controllee); controllerRef != nil {
return fmt.Sprintf("%s/%s", controllerRef.Kind, controllerRef.Name)
}
return ""
}
func describeVolumes(volumes []api.Volume, w PrefixWriter, space string) {
if volumes == nil || len(volumes) == 0 {
w.Write(LEVEL_0, "%sVolumes:\t<none>\n", space)
return
}
w.Write(LEVEL_0, "%sVolumes:\n", space)
for _, volume := range volumes {
nameIndent := ""
if len(space) > 0 {
nameIndent = " "
}
w.Write(LEVEL_1, "%s%v:\n", nameIndent, volume.Name)
switch {
case volume.VolumeSource.HostPath != nil:
printHostPathVolumeSource(volume.VolumeSource.HostPath, w)
case volume.VolumeSource.EmptyDir != nil:
printEmptyDirVolumeSource(volume.VolumeSource.EmptyDir, w)
case volume.VolumeSource.GCEPersistentDisk != nil:
printGCEPersistentDiskVolumeSource(volume.VolumeSource.GCEPersistentDisk, w)
case volume.VolumeSource.AWSElasticBlockStore != nil:
printAWSElasticBlockStoreVolumeSource(volume.VolumeSource.AWSElasticBlockStore, w)
case volume.VolumeSource.GitRepo != nil:
printGitRepoVolumeSource(volume.VolumeSource.GitRepo, w)
case volume.VolumeSource.Secret != nil:
printSecretVolumeSource(volume.VolumeSource.Secret, w)
case volume.VolumeSource.ConfigMap != nil:
printConfigMapVolumeSource(volume.VolumeSource.ConfigMap, w)
case volume.VolumeSource.NFS != nil:
printNFSVolumeSource(volume.VolumeSource.NFS, w)
case volume.VolumeSource.ISCSI != nil:
printISCSIVolumeSource(volume.VolumeSource.ISCSI, w)
case volume.VolumeSource.Glusterfs != nil:
printGlusterfsVolumeSource(volume.VolumeSource.Glusterfs, w)
case volume.VolumeSource.PersistentVolumeClaim != nil:
printPersistentVolumeClaimVolumeSource(volume.VolumeSource.PersistentVolumeClaim, w)
case volume.VolumeSource.RBD != nil:
printRBDVolumeSource(volume.VolumeSource.RBD, w)
case volume.VolumeSource.Quobyte != nil:
printQuobyteVolumeSource(volume.VolumeSource.Quobyte, w)
case volume.VolumeSource.DownwardAPI != nil:
printDownwardAPIVolumeSource(volume.VolumeSource.DownwardAPI, w)
case volume.VolumeSource.AzureDisk != nil:
printAzureDiskVolumeSource(volume.VolumeSource.AzureDisk, w)
case volume.VolumeSource.VsphereVolume != nil:
printVsphereVolumeSource(volume.VolumeSource.VsphereVolume, w)
case volume.VolumeSource.Cinder != nil:
printCinderVolumeSource(volume.VolumeSource.Cinder, w)
case volume.VolumeSource.PhotonPersistentDisk != nil:
printPhotonPersistentDiskVolumeSource(volume.VolumeSource.PhotonPersistentDisk, w)
case volume.VolumeSource.PortworxVolume != nil:
printPortworxVolumeSource(volume.VolumeSource.PortworxVolume, w)
case volume.VolumeSource.ScaleIO != nil:
printScaleIOVolumeSource(volume.VolumeSource.ScaleIO, w)
case volume.VolumeSource.CephFS != nil:
printCephFSVolumeSource(volume.VolumeSource.CephFS, w)
case volume.VolumeSource.StorageOS != nil:
printStorageOSVolumeSource(volume.VolumeSource.StorageOS, w)
case volume.VolumeSource.FC != nil:
printFCVolumeSource(volume.VolumeSource.FC, w)
case volume.VolumeSource.AzureFile != nil:
printAzureFileVolumeSource(volume.VolumeSource.AzureFile, w)
case volume.VolumeSource.FlexVolume != nil:
printFlexVolumeSource(volume.VolumeSource.FlexVolume, w)
case volume.VolumeSource.Flocker != nil:
printFlockerVolumeSource(volume.VolumeSource.Flocker, w)
default:
w.Write(LEVEL_1, "<unknown>\n")
}
}
}
func printHostPathVolumeSource(hostPath *api.HostPathVolumeSource, w PrefixWriter) {
hostPathType := "<none>"
if hostPath.Type != nil {
hostPathType = string(*hostPath.Type)
}
w.Write(LEVEL_2, "Type:\tHostPath (bare host directory volume)\n"+
" Path:\t%v\n"+
" HostPathType:\t%v\n",
hostPath.Path, hostPathType)
}
func printEmptyDirVolumeSource(emptyDir *api.EmptyDirVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tEmptyDir (a temporary directory that shares a pod's lifetime)\n"+
" Medium:\t%v\n", emptyDir.Medium)
}
func printGCEPersistentDiskVolumeSource(gce *api.GCEPersistentDiskVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tGCEPersistentDisk (a Persistent Disk resource in Google Compute Engine)\n"+
" PDName:\t%v\n"+
" FSType:\t%v\n"+
" Partition:\t%v\n"+
" ReadOnly:\t%v\n",
gce.PDName, gce.FSType, gce.Partition, gce.ReadOnly)
}
func printAWSElasticBlockStoreVolumeSource(aws *api.AWSElasticBlockStoreVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tAWSElasticBlockStore (a Persistent Disk resource in AWS)\n"+
" VolumeID:\t%v\n"+
" FSType:\t%v\n"+
" Partition:\t%v\n"+
" ReadOnly:\t%v\n",
aws.VolumeID, aws.FSType, aws.Partition, aws.ReadOnly)
}
func printGitRepoVolumeSource(git *api.GitRepoVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tGitRepo (a volume that is pulled from git when the pod is created)\n"+
" Repository:\t%v\n"+
" Revision:\t%v\n",
git.Repository, git.Revision)
}
func printSecretVolumeSource(secret *api.SecretVolumeSource, w PrefixWriter) {
optional := secret.Optional != nil && *secret.Optional
w.Write(LEVEL_2, "Type:\tSecret (a volume populated by a Secret)\n"+
" SecretName:\t%v\n"+
" Optional:\t%v\n",
secret.SecretName, optional)
}
func printConfigMapVolumeSource(configMap *api.ConfigMapVolumeSource, w PrefixWriter) {
optional := configMap.Optional != nil && *configMap.Optional
w.Write(LEVEL_2, "Type:\tConfigMap (a volume populated by a ConfigMap)\n"+
" Name:\t%v\n"+
" Optional:\t%v\n",
configMap.Name, optional)
}
func printNFSVolumeSource(nfs *api.NFSVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tNFS (an NFS mount that lasts the lifetime of a pod)\n"+
" Server:\t%v\n"+
" Path:\t%v\n"+
" ReadOnly:\t%v\n",
nfs.Server, nfs.Path, nfs.ReadOnly)
}
func printQuobyteVolumeSource(quobyte *api.QuobyteVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tQuobyte (a Quobyte mount on the host that shares a pod's lifetime)\n"+
" Registry:\t%v\n"+
" Volume:\t%v\n"+
" ReadOnly:\t%v\n",
quobyte.Registry, quobyte.Volume, quobyte.ReadOnly)
}
func printPortworxVolumeSource(pwxVolume *api.PortworxVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tPortworxVolume (a Portworx Volume resource)\n"+
" VolumeID:\t%v\n",
pwxVolume.VolumeID)
}
func printISCSIVolumeSource(iscsi *api.ISCSIVolumeSource, w PrefixWriter) {
initiator := "<none>"
if iscsi.InitiatorName != nil {
initiator = *iscsi.InitiatorName
}
w.Write(LEVEL_2, "Type:\tISCSI (an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod)\n"+
" TargetPortal:\t%v\n"+
" IQN:\t%v\n"+
" Lun:\t%v\n"+
" ISCSIInterface\t%v\n"+
" FSType:\t%v\n"+
" ReadOnly:\t%v\n"+
" Portals:\t%v\n"+
" DiscoveryCHAPAuth:\t%v\n"+
" SessionCHAPAuth:\t%v\n"+
" SecretRef:\t%v\n"+
" InitiatorName:\t%v\n",
iscsi.TargetPortal, iscsi.IQN, iscsi.Lun, iscsi.ISCSIInterface, iscsi.FSType, iscsi.ReadOnly, iscsi.Portals, iscsi.DiscoveryCHAPAuth, iscsi.SessionCHAPAuth, iscsi.SecretRef, initiator)
}
func printISCSIPersistentVolumeSource(iscsi *api.ISCSIPersistentVolumeSource, w PrefixWriter) {
initiatorName := "<none>"
if iscsi.InitiatorName != nil {
initiatorName = *iscsi.InitiatorName
}
w.Write(LEVEL_2, "Type:\tISCSI (an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod)\n"+
" TargetPortal:\t%v\n"+
" IQN:\t%v\n"+
" Lun:\t%v\n"+
" ISCSIInterface\t%v\n"+
" FSType:\t%v\n"+
" ReadOnly:\t%v\n"+
" Portals:\t%v\n"+
" DiscoveryCHAPAuth:\t%v\n"+
" SessionCHAPAuth:\t%v\n"+
" SecretRef:\t%v\n"+
" InitiatorName:\t%v\n",
iscsi.TargetPortal, iscsi.IQN, iscsi.Lun, iscsi.ISCSIInterface, iscsi.FSType, iscsi.ReadOnly, iscsi.Portals, iscsi.DiscoveryCHAPAuth, iscsi.SessionCHAPAuth, iscsi.SecretRef, initiatorName)
}
func printGlusterfsVolumeSource(glusterfs *api.GlusterfsVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tGlusterfs (a Glusterfs mount on the host that shares a pod's lifetime)\n"+
" EndpointsName:\t%v\n"+
" Path:\t%v\n"+
" ReadOnly:\t%v\n",
glusterfs.EndpointsName, glusterfs.Path, glusterfs.ReadOnly)
}
func printPersistentVolumeClaimVolumeSource(claim *api.PersistentVolumeClaimVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tPersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace)\n"+
" ClaimName:\t%v\n"+
" ReadOnly:\t%v\n",
claim.ClaimName, claim.ReadOnly)
}
func printRBDVolumeSource(rbd *api.RBDVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tRBD (a Rados Block Device mount on the host that shares a pod's lifetime)\n"+
" CephMonitors:\t%v\n"+
" RBDImage:\t%v\n"+
" FSType:\t%v\n"+
" RBDPool:\t%v\n"+
" RadosUser:\t%v\n"+
" Keyring:\t%v\n"+
" SecretRef:\t%v\n"+
" ReadOnly:\t%v\n",
rbd.CephMonitors, rbd.RBDImage, rbd.FSType, rbd.RBDPool, rbd.RadosUser, rbd.Keyring, rbd.SecretRef, rbd.ReadOnly)
}
func printRBDPersistentVolumeSource(rbd *api.RBDPersistentVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tRBD (a Rados Block Device mount on the host that shares a pod's lifetime)\n"+
" CephMonitors:\t%v\n"+
" RBDImage:\t%v\n"+
" FSType:\t%v\n"+
" RBDPool:\t%v\n"+
" RadosUser:\t%v\n"+
" Keyring:\t%v\n"+
" SecretRef:\t%v\n"+
" ReadOnly:\t%v\n",
rbd.CephMonitors, rbd.RBDImage, rbd.FSType, rbd.RBDPool, rbd.RadosUser, rbd.Keyring, rbd.SecretRef, rbd.ReadOnly)
}
func printDownwardAPIVolumeSource(d *api.DownwardAPIVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tDownwardAPI (a volume populated by information about the pod)\n Items:\n")
for _, mapping := range d.Items {
if mapping.FieldRef != nil {
w.Write(LEVEL_3, "%v -> %v\n", mapping.FieldRef.FieldPath, mapping.Path)
}
if mapping.ResourceFieldRef != nil {
w.Write(LEVEL_3, "%v -> %v\n", mapping.ResourceFieldRef.Resource, mapping.Path)
}
}
}
func printAzureDiskVolumeSource(d *api.AzureDiskVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tAzureDisk (an Azure Data Disk mount on the host and bind mount to the pod)\n"+
" DiskName:\t%v\n"+
" DiskURI:\t%v\n"+
" Kind: \t%v\n"+
" FSType:\t%v\n"+
" CachingMode:\t%v\n"+
" ReadOnly:\t%v\n",
d.DiskName, d.DataDiskURI, *d.Kind, *d.FSType, *d.CachingMode, *d.ReadOnly)
}
func printVsphereVolumeSource(vsphere *api.VsphereVirtualDiskVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tvSphereVolume (a Persistent Disk resource in vSphere)\n"+
" VolumePath:\t%v\n"+
" FSType:\t%v\n"+
" StoragePolicyName:\t%v\n",
vsphere.VolumePath, vsphere.FSType, vsphere.StoragePolicyName)
}
func printPhotonPersistentDiskVolumeSource(photon *api.PhotonPersistentDiskVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tPhotonPersistentDisk (a Persistent Disk resource in photon platform)\n"+
" PdID:\t%v\n"+
" FSType:\t%v\n",
photon.PdID, photon.FSType)
}
func printCinderVolumeSource(cinder *api.CinderVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tCinder (a Persistent Disk resource in OpenStack)\n"+
" VolumeID:\t%v\n"+
" FSType:\t%v\n"+
" ReadOnly:\t%v\n",
" SecretRef:\t%v\n"+
cinder.VolumeID, cinder.FSType, cinder.ReadOnly, cinder.SecretRef)
}
func printCinderPersistentVolumeSource(cinder *api.CinderPersistentVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tCinder (a Persistent Disk resource in OpenStack)\n"+
" VolumeID:\t%v\n"+
" FSType:\t%v\n"+
" ReadOnly:\t%v\n",
" SecretRef:\t%v\n"+
cinder.VolumeID, cinder.SecretRef, cinder.FSType, cinder.ReadOnly, cinder.SecretRef)
}
func printScaleIOVolumeSource(sio *api.ScaleIOVolumeSource, w PrefixWriter) {
w.Write(LEVEL_2, "Type:\tScaleIO (a persistent volume backed by a block device in ScaleIO)\n"+
" Gateway:\t%v\n"+
" System:\t%v\n"+
" Protection Domain:\t%v\n"+
" Storage Pool:\t%v\n"+
" Storage Mode:\t%v\n"+
" VolumeName:\t%v\n"+
" FSType:\t%v\n"+
" ReadOnly:\t%v\n",
sio.Gateway, sio.System, sio.ProtectionDomain, sio.StoragePool, sio.StorageMode, sio.VolumeName, sio.FSType, sio.ReadOnly)
}
func printScaleIOPersistentVolumeSource(sio *api.ScaleIOPersistentVolumeSource, w PrefixWriter) {
var secretNS, secretName string
if sio.SecretRef != nil {
secretName = sio.SecretRef.Name
secretNS = sio.SecretRef.Namespace
}