forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 1
/
describe.go
2052 lines (1830 loc) · 67.8 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 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 kubectl
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/url"
"reflect"
"sort"
"strings"
"time"
"github.com/golang/glog"
"k8s.io/kubernetes/pkg/api"
"k8s.io/kubernetes/pkg/api/errors"
"k8s.io/kubernetes/pkg/api/resource"
"k8s.io/kubernetes/pkg/api/unversioned"
"k8s.io/kubernetes/pkg/apis/autoscaling"
"k8s.io/kubernetes/pkg/apis/batch"
"k8s.io/kubernetes/pkg/apis/extensions"
clientset "k8s.io/kubernetes/pkg/client/clientset_generated/internalclientset"
client "k8s.io/kubernetes/pkg/client/unversioned"
"k8s.io/kubernetes/pkg/fieldpath"
"k8s.io/kubernetes/pkg/fields"
qosutil "k8s.io/kubernetes/pkg/kubelet/qos/util"
"k8s.io/kubernetes/pkg/labels"
"k8s.io/kubernetes/pkg/types"
deploymentutil "k8s.io/kubernetes/pkg/util/deployment"
"k8s.io/kubernetes/pkg/util/intstr"
"k8s.io/kubernetes/pkg/util/sets"
)
// Describer generates output for the named resource or an error
// if the output could not be generated. Implementers typically
// abstract the retrieval of the named object from a remote server.
type Describer interface {
Describe(namespace, name string) (output string, err error)
}
// ObjectDescriber is an interface for displaying arbitrary objects with extra
// information. Use when an object is in hand (on disk, or already retrieved).
// Implementers may ignore the additional information passed on extra, or use it
// by default. ObjectDescribers may return ErrNoDescriber if no suitable describer
// is found.
type ObjectDescriber interface {
DescribeObject(object interface{}, extra ...interface{}) (output string, err error)
}
// ErrNoDescriber is a structured error indicating the provided object or objects
// cannot be described.
type ErrNoDescriber struct {
Types []string
}
// Error implements the error interface.
func (e ErrNoDescriber) Error() string {
return fmt.Sprintf("no describer has been defined for %v", e.Types)
}
func describerMap(c *client.Client) map[unversioned.GroupKind]Describer {
m := map[unversioned.GroupKind]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},
extensions.Kind("ReplicaSet"): &ReplicaSetDescriber{c},
extensions.Kind("HorizontalPodAutoscaler"): &HorizontalPodAutoscalerDescriber{c},
autoscaling.Kind("HorizontalPodAutoscaler"): &HorizontalPodAutoscalerDescriber{c},
extensions.Kind("DaemonSet"): &DaemonSetDescriber{c},
extensions.Kind("Deployment"): &DeploymentDescriber{clientset.FromUnversionedClient(c)},
extensions.Kind("Job"): &JobDescriber{c},
batch.Kind("Job"): &JobDescriber{c},
extensions.Kind("Ingress"): &IngressDescriber{c},
}
return m
}
// List of all resource types we can describe
func DescribableResources() []string {
keys := make([]string, 0)
for k := range describerMap(nil) {
resource := strings.ToLower(k.Kind)
keys = append(keys, resource)
}
return keys
}
// Describer returns the default describe functions for each of the standard
// Kubernetes types.
func DescriberFor(kind unversioned.GroupKind, c *client.Client) (Describer, bool) {
f, ok := describerMap(c)[kind]
return f, ok
}
// DefaultObjectDescriber can describe the default Kubernetes objects.
var DefaultObjectDescriber 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 {
client.Interface
}
func (d *NamespaceDescriber) Describe(namespace, name string) (string, error) {
ns, err := d.Namespaces().Get(name)
if err != nil {
return "", err
}
resourceQuotaList, err := d.ResourceQuotas(name).List(api.ListOptions{})
if err != nil {
return "", err
}
limitRangeList, err := d.LimitRanges(name).List(api.ListOptions{})
if err != nil {
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 {
fmt.Fprintf(out, "Name:\t%s\n", namespace.Name)
fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(namespace.Labels))
fmt.Fprintf(out, "Status:\t%s\n", string(namespace.Status.Phase))
if resourceQuotaList != nil {
fmt.Fprintf(out, "\n")
DescribeResourceQuotas(resourceQuotaList, out)
}
if limitRangeList != nil {
fmt.Fprintf(out, "\n")
DescribeLimitRanges(limitRangeList, out)
}
return nil
})
}
// DescribeLimitRanges merges a set of limit range items into a single tabular description
func DescribeLimitRanges(limitRanges *api.LimitRangeList, w io.Writer) {
if len(limitRanges.Items) == 0 {
fmt.Fprint(w, "No resource limits.\n")
return
}
fmt.Fprintf(w, "Resource Limits\n Type\tResource\tMin\tMax\tDefault Request\tDefault Limit\tMax Limit/Request Ratio\n")
fmt.Fprintf(w, " ----\t--------\t---\t---\t---------------\t-------------\t-----------------------\n")
for _, limitRange := range limitRanges.Items {
for i := range limitRange.Spec.Limits {
item := limitRange.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\t%v\t%v\t%v\t%v\t%v\t%v\n"
fmt.Fprintf(w, msg, item.Type, k, minValue, maxValue, defaultRequestValue, defaultLimitValue, ratioValue)
}
}
}
}
// DescribeResourceQuotas merges a set of quota items into a single tabular description of all quotas
func DescribeResourceQuotas(quotas *api.ResourceQuotaList, w io.Writer) {
if len(quotas.Items) == 0 {
fmt.Fprint(w, "No resource quota.\n")
return
}
sort.Sort(SortableResourceQuotas(quotas.Items))
fmt.Fprint(w, "Resource Quotas")
for _, q := range quotas.Items {
fmt.Fprintf(w, "\n Name:\t%s\n", q.Name)
if len(q.Spec.Scopes) > 0 {
scopes := []string{}
for _, scope := range q.Spec.Scopes {
scopes = append(scopes, string(scope))
}
sort.Strings(scopes)
fmt.Fprintf(w, " Scopes:\t%s\n", strings.Join(scopes, ", "))
for _, scope := range scopes {
helpText := helpTextForResourceQuotaScope(api.ResourceQuotaScope(scope))
if len(helpText) > 0 {
fmt.Fprintf(w, " * %s\n", helpText)
}
}
}
fmt.Fprintf(w, " Resource\tUsed\tHard\n")
fmt.Fprint(w, " --------\t---\t---\n")
resources := []api.ResourceName{}
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]
fmt.Fprintf(w, " %s\t%s\t%s\n", string(resource), usedQuantity.String(), hardQuantity.String())
}
}
}
// LimitRangeDescriber generates information about a limit range
type LimitRangeDescriber struct {
client.Interface
}
func (d *LimitRangeDescriber) Describe(namespace, name string) (string, error) {
lr := d.LimitRanges(namespace)
limitRange, err := lr.Get(name)
if err != nil {
return "", err
}
return describeLimitRange(limitRange)
}
func describeLimitRange(limitRange *api.LimitRange) (string, error) {
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Name:\t%s\n", limitRange.Name)
fmt.Fprintf(out, "Namespace:\t%s\n", limitRange.Namespace)
fmt.Fprintf(out, "Type\tResource\tMin\tMax\tDefault Request\tDefault Limit\tMax Limit/Request Ratio\n")
fmt.Fprintf(out, "----\t--------\t---\t---\t---------------\t-------------\t-----------------------\n")
for i := range limitRange.Spec.Limits {
item := limitRange.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 := "%v\t%v\t%v\t%v\t%v\t%v\t%v\n"
fmt.Fprintf(out, msg, item.Type, k, minValue, maxValue, defaultRequestValue, defaultLimitValue, ratioValue)
}
}
return nil
})
}
// ResourceQuotaDescriber generates information about a resource quota
type ResourceQuotaDescriber struct {
client.Interface
}
func (d *ResourceQuotaDescriber) Describe(namespace, name string) (string, error) {
rq := d.ResourceQuotas(namespace)
resourceQuota, err := rq.Get(name)
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."
case api.ResourceQuotaScopeNotTerminating:
return "Matches all pods that do not have an active deadline."
case api.ResourceQuotaScopeBestEffort:
return "Matches all pods that have best effort quality of service."
case api.ResourceQuotaScopeNotBestEffort:
return "Matches all pods that do not have best effort quality of service."
default:
return ""
}
}
func describeQuota(resourceQuota *api.ResourceQuota) (string, error) {
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Name:\t%s\n", resourceQuota.Name)
fmt.Fprintf(out, "Namespace:\t%s\n", resourceQuota.Namespace)
if len(resourceQuota.Spec.Scopes) > 0 {
scopes := []string{}
for _, scope := range resourceQuota.Spec.Scopes {
scopes = append(scopes, string(scope))
}
sort.Strings(scopes)
fmt.Fprintf(out, "Scopes:\t%s\n", strings.Join(scopes, ", "))
for _, scope := range scopes {
helpText := helpTextForResourceQuotaScope(api.ResourceQuotaScope(scope))
if len(helpText) > 0 {
fmt.Fprintf(out, " * %s\n", helpText)
}
}
}
fmt.Fprintf(out, "Resource\tUsed\tHard\n")
fmt.Fprintf(out, "--------\t----\t----\n")
resources := []api.ResourceName{}
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]
fmt.Fprintf(out, msg, resource, usedQuantity.String(), hardQuantity.String())
}
return nil
})
}
// PodDescriber generates information about a pod and the replication controllers that
// create it.
type PodDescriber struct {
client.Interface
}
func (d *PodDescriber) Describe(namespace, name string) (string, error) {
pod, err := d.Pods(namespace).Get(name)
if err != nil {
eventsInterface := d.Events(namespace)
selector := eventsInterface.GetFieldSelector(&name, &namespace, nil, nil)
options := api.ListOptions{FieldSelector: selector}
events, err2 := eventsInterface.List(options)
if err2 == nil && len(events.Items) > 0 {
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Pod '%v': error '%v', but found events.\n", name, err)
DescribeEvents(events, out)
return nil
})
}
return "", err
}
var events *api.EventList
if ref, err := api.GetReference(pod); err != nil {
glog.Errorf("Unable to construct reference to '%#v': %v", pod, err)
} else {
ref.Kind = ""
events, _ = d.Events(namespace).Search(ref)
}
return describePod(pod, events)
}
func describePod(pod *api.Pod, events *api.EventList) (string, error) {
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Name:\t%s\n", pod.Name)
fmt.Fprintf(out, "Namespace:\t%s\n", pod.Namespace)
fmt.Fprintf(out, "Node:\t%s\n", pod.Spec.NodeName+"/"+pod.Status.HostIP)
if pod.Status.StartTime != nil {
fmt.Fprintf(out, "Start Time:\t%s\n", pod.Status.StartTime.Time.Format(time.RFC1123Z))
}
fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(pod.Labels))
if pod.DeletionTimestamp != nil {
fmt.Fprintf(out, "Status:\tTerminating (expires %s)\n", pod.DeletionTimestamp.Time.Format(time.RFC1123Z))
fmt.Fprintf(out, "Termination Grace Period:\t%ds\n", *pod.DeletionGracePeriodSeconds)
} else {
fmt.Fprintf(out, "Status:\t%s\n", string(pod.Status.Phase))
}
if len(pod.Status.Reason) > 0 {
fmt.Fprintf(out, "Reason:\t%s\n", pod.Status.Reason)
}
if len(pod.Status.Message) > 0 {
fmt.Fprintf(out, "Message:\t%s\n", pod.Status.Message)
}
fmt.Fprintf(out, "IP:\t%s\n", pod.Status.PodIP)
fmt.Fprintf(out, "Controllers:\t%s\n", printControllers(pod.Annotations))
fmt.Fprintf(out, "Containers:\n")
DescribeContainers(pod.Spec.Containers, pod.Status.ContainerStatuses, EnvValueRetriever(pod), out)
if len(pod.Status.Conditions) > 0 {
fmt.Fprint(out, "Conditions:\n Type\tStatus\n")
for _, c := range pod.Status.Conditions {
fmt.Fprintf(out, " %v \t%v \n",
c.Type,
c.Status)
}
}
describeVolumes(pod.Spec.Volumes, out)
if events != nil {
DescribeEvents(events, out)
}
return nil
})
}
func printControllers(annotation map[string]string) string {
value, ok := annotation["kubernetes.io/created-by"]
if ok {
var r api.SerializedReference
err := json.Unmarshal([]byte(value), &r)
if err == nil {
return fmt.Sprintf("%s/%s", r.Reference.Kind, r.Reference.Name)
}
}
return "<none>"
}
func describeVolumes(volumes []api.Volume, out io.Writer) {
if volumes == nil || len(volumes) == 0 {
fmt.Fprint(out, "No volumes.\n")
return
}
fmt.Fprint(out, "Volumes:\n")
for _, volume := range volumes {
fmt.Fprintf(out, " %v:\n", volume.Name)
switch {
case volume.VolumeSource.HostPath != nil:
printHostPathVolumeSource(volume.VolumeSource.HostPath, out)
case volume.VolumeSource.EmptyDir != nil:
printEmptyDirVolumeSource(volume.VolumeSource.EmptyDir, out)
case volume.VolumeSource.GCEPersistentDisk != nil:
printGCEPersistentDiskVolumeSource(volume.VolumeSource.GCEPersistentDisk, out)
case volume.VolumeSource.AWSElasticBlockStore != nil:
printAWSElasticBlockStoreVolumeSource(volume.VolumeSource.AWSElasticBlockStore, out)
case volume.VolumeSource.GitRepo != nil:
printGitRepoVolumeSource(volume.VolumeSource.GitRepo, out)
case volume.VolumeSource.Secret != nil:
printSecretVolumeSource(volume.VolumeSource.Secret, out)
case volume.VolumeSource.ConfigMap != nil:
printConfigMapVolumeSource(volume.VolumeSource.ConfigMap, out)
case volume.VolumeSource.NFS != nil:
printNFSVolumeSource(volume.VolumeSource.NFS, out)
case volume.VolumeSource.ISCSI != nil:
printISCSIVolumeSource(volume.VolumeSource.ISCSI, out)
case volume.VolumeSource.Glusterfs != nil:
printGlusterfsVolumeSource(volume.VolumeSource.Glusterfs, out)
case volume.VolumeSource.PersistentVolumeClaim != nil:
printPersistentVolumeClaimVolumeSource(volume.VolumeSource.PersistentVolumeClaim, out)
case volume.VolumeSource.RBD != nil:
printRBDVolumeSource(volume.VolumeSource.RBD, out)
case volume.VolumeSource.DownwardAPI != nil:
printDownwardAPIVolumeSource(volume.VolumeSource.DownwardAPI, out)
default:
fmt.Fprintf(out, " <unknown>\n")
}
}
}
func printHostPathVolumeSource(hostPath *api.HostPathVolumeSource, out io.Writer) {
fmt.Fprintf(out, " Type:\tHostPath (bare host directory volume)\n"+
" Path:\t%v\n", hostPath.Path)
}
func printEmptyDirVolumeSource(emptyDir *api.EmptyDirVolumeSource, out io.Writer) {
fmt.Fprintf(out, " Type:\tEmptyDir (a temporary directory that shares a pod's lifetime)\n"+
" Medium:\t%v\n", emptyDir.Medium)
}
func printGCEPersistentDiskVolumeSource(gce *api.GCEPersistentDiskVolumeSource, out io.Writer) {
fmt.Fprintf(out, " 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, out io.Writer) {
fmt.Fprintf(out, " 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, out io.Writer) {
fmt.Fprintf(out, " 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, out io.Writer) {
fmt.Fprintf(out, " Type:\tSecret (a volume populated by a Secret)\n"+
" SecretName:\t%v\n", secret.SecretName)
}
func printConfigMapVolumeSource(configMap *api.ConfigMapVolumeSource, out io.Writer) {
fmt.Fprintf(out, " Type:\tConfigMap (a volume populated by a ConfigMap)\n"+
" Name:\t%v\n", configMap.Name)
}
func printNFSVolumeSource(nfs *api.NFSVolumeSource, out io.Writer) {
fmt.Fprintf(out, " 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 printISCSIVolumeSource(iscsi *api.ISCSIVolumeSource, out io.Writer) {
fmt.Fprintf(out, " 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",
iscsi.TargetPortal, iscsi.IQN, iscsi.Lun, iscsi.ISCSIInterface, iscsi.FSType, iscsi.ReadOnly)
}
func printGlusterfsVolumeSource(glusterfs *api.GlusterfsVolumeSource, out io.Writer) {
fmt.Fprintf(out, " 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, out io.Writer) {
fmt.Fprintf(out, " 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, out io.Writer) {
fmt.Fprintf(out, " 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, out io.Writer) {
fmt.Fprintf(out, " Type:\tDownwardAPI (a volume populated by information about the pod)\n Items:\n")
for _, mapping := range d.Items {
fmt.Fprintf(out, " %v -> %v\n", mapping.FieldRef.FieldPath, mapping.Path)
}
}
type PersistentVolumeDescriber struct {
client.Interface
}
func (d *PersistentVolumeDescriber) Describe(namespace, name string) (string, error) {
c := d.PersistentVolumes()
pv, err := c.Get(name)
if err != nil {
return "", err
}
storage := pv.Spec.Capacity[api.ResourceStorage]
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Name:\t%s\n", pv.Name)
fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(pv.Labels))
fmt.Fprintf(out, "Status:\t%s\n", pv.Status.Phase)
if pv.Spec.ClaimRef != nil {
fmt.Fprintf(out, "Claim:\t%s\n", pv.Spec.ClaimRef.Namespace+"/"+pv.Spec.ClaimRef.Name)
} else {
fmt.Fprintf(out, "Claim:\t%s\n", "")
}
fmt.Fprintf(out, "Reclaim Policy:\t%v\n", pv.Spec.PersistentVolumeReclaimPolicy)
fmt.Fprintf(out, "Access Modes:\t%s\n", api.GetAccessModesAsString(pv.Spec.AccessModes))
fmt.Fprintf(out, "Capacity:\t%s\n", storage.String())
fmt.Fprintf(out, "Message:\t%s\n", pv.Status.Message)
fmt.Fprintf(out, "Source:\n")
switch {
case pv.Spec.HostPath != nil:
printHostPathVolumeSource(pv.Spec.HostPath, out)
case pv.Spec.GCEPersistentDisk != nil:
printGCEPersistentDiskVolumeSource(pv.Spec.GCEPersistentDisk, out)
case pv.Spec.AWSElasticBlockStore != nil:
printAWSElasticBlockStoreVolumeSource(pv.Spec.AWSElasticBlockStore, out)
case pv.Spec.NFS != nil:
printNFSVolumeSource(pv.Spec.NFS, out)
case pv.Spec.ISCSI != nil:
printISCSIVolumeSource(pv.Spec.ISCSI, out)
case pv.Spec.Glusterfs != nil:
printGlusterfsVolumeSource(pv.Spec.Glusterfs, out)
case pv.Spec.RBD != nil:
printRBDVolumeSource(pv.Spec.RBD, out)
}
return nil
})
}
type PersistentVolumeClaimDescriber struct {
client.Interface
}
func (d *PersistentVolumeClaimDescriber) Describe(namespace, name string) (string, error) {
c := d.PersistentVolumeClaims(namespace)
pvc, err := c.Get(name)
if err != nil {
return "", err
}
labels := labels.FormatLabels(pvc.Labels)
storage := pvc.Spec.Resources.Requests[api.ResourceStorage]
capacity := ""
accessModes := ""
if pvc.Spec.VolumeName != "" {
accessModes = api.GetAccessModesAsString(pvc.Status.AccessModes)
storage = pvc.Status.Capacity[api.ResourceStorage]
capacity = storage.String()
}
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Name:\t%s\n", pvc.Name)
fmt.Fprintf(out, "Namespace:\t%s\n", pvc.Namespace)
fmt.Fprintf(out, "Status:\t%v\n", pvc.Status.Phase)
fmt.Fprintf(out, "Volume:\t%s\n", pvc.Spec.VolumeName)
fmt.Fprintf(out, "Labels:\t%s\n", labels)
fmt.Fprintf(out, "Capacity:\t%s\n", capacity)
fmt.Fprintf(out, "Access Modes:\t%s\n", accessModes)
return nil
})
}
// DescribeContainers is exported for consumers in other API groups that have container templates
func DescribeContainers(containers []api.Container, containerStatuses []api.ContainerStatus, resolverFn EnvVarResolverFunc, out io.Writer) {
statuses := map[string]api.ContainerStatus{}
for _, status := range containerStatuses {
statuses[status.Name] = status
}
for _, container := range containers {
status, ok := statuses[container.Name]
fmt.Fprintf(out, " %v:\n", container.Name)
if ok {
fmt.Fprintf(out, " Container ID:\t%s\n", status.ContainerID)
}
fmt.Fprintf(out, " Image:\t%s\n", container.Image)
if ok {
fmt.Fprintf(out, " Image ID:\t%s\n", status.ImageID)
}
portString := describeContainerPorts(container.Ports)
if strings.Contains(portString, ",") {
fmt.Fprintf(out, " Ports:\t%s\n", portString)
} else {
fmt.Fprintf(out, " Port:\t%s\n", portString)
}
if len(container.Command) > 0 {
fmt.Fprintf(out, " Command:\n")
for _, c := range container.Command {
fmt.Fprintf(out, " %s\n", c)
}
}
if len(container.Args) > 0 {
fmt.Fprintf(out, " Args:\n")
for _, arg := range container.Args {
fmt.Fprintf(out, " %s\n", arg)
}
}
resourceToQoS := qosutil.GetQoS(&container)
if len(resourceToQoS) > 0 {
fmt.Fprintf(out, " QoS Tier:\n")
}
for resource, qos := range resourceToQoS {
fmt.Fprintf(out, " %s:\t%s\n", resource, qos)
}
if len(container.Resources.Limits) > 0 {
fmt.Fprintf(out, " Limits:\n")
}
for name, quantity := range container.Resources.Limits {
fmt.Fprintf(out, " %s:\t%s\n", name, quantity.String())
}
if len(container.Resources.Requests) > 0 {
fmt.Fprintf(out, " Requests:\n")
}
for name, quantity := range container.Resources.Requests {
fmt.Fprintf(out, " %s:\t%s\n", name, quantity.String())
}
if ok {
describeStatus("State", status.State, out)
if status.LastTerminationState.Terminated != nil {
describeStatus("Last State", status.LastTerminationState, out)
}
fmt.Fprintf(out, " Ready:\t%v\n", printBool(status.Ready))
fmt.Fprintf(out, " Restart Count:\t%d\n", status.RestartCount)
}
if container.LivenessProbe != nil {
probe := DescribeProbe(container.LivenessProbe)
fmt.Fprintf(out, " Liveness:\t%s\n", probe)
}
if container.ReadinessProbe != nil {
probe := DescribeProbe(container.ReadinessProbe)
fmt.Fprintf(out, " Readiness:\t%s\n", probe)
}
fmt.Fprintf(out, " Environment Variables:\n")
for _, e := range container.Env {
if e.ValueFrom != nil && e.ValueFrom.FieldRef != nil {
var valueFrom string
if resolverFn != nil {
valueFrom = resolverFn(e)
}
fmt.Fprintf(out, " %s:\t%s (%s:%s)\n", e.Name, valueFrom, e.ValueFrom.FieldRef.APIVersion, e.ValueFrom.FieldRef.FieldPath)
} else {
fmt.Fprintf(out, " %s:\t%s\n", e.Name, e.Value)
}
}
}
}
func describeContainerPorts(cPorts []api.ContainerPort) string {
ports := []string{}
for _, cPort := range cPorts {
ports = append(ports, fmt.Sprintf("%d/%s", cPort.ContainerPort, cPort.Protocol))
}
return strings.Join(ports, ", ")
}
// DescribeProbe is exported for consumers in other API groups that have probes
func DescribeProbe(probe *api.Probe) string {
attrs := fmt.Sprintf("delay=%ds timeout=%ds period=%ds #success=%d #failure=%d", probe.InitialDelaySeconds, probe.TimeoutSeconds, probe.PeriodSeconds, probe.SuccessThreshold, probe.FailureThreshold)
switch {
case probe.Exec != nil:
return fmt.Sprintf("exec %v %s", probe.Exec.Command, attrs)
case probe.HTTPGet != nil:
url := &url.URL{}
url.Scheme = strings.ToLower(string(probe.HTTPGet.Scheme))
if len(probe.HTTPGet.Port.String()) > 0 {
url.Host = net.JoinHostPort(probe.HTTPGet.Host, probe.HTTPGet.Port.String())
} else {
url.Host = probe.HTTPGet.Host
}
url.Path = probe.HTTPGet.Path
return fmt.Sprintf("http-get %s %s", url.String(), attrs)
case probe.TCPSocket != nil:
return fmt.Sprintf("tcp-socket :%s %s", probe.TCPSocket.Port.String(), attrs)
}
return fmt.Sprintf("unknown %s", attrs)
}
type EnvVarResolverFunc func(e api.EnvVar) string
// EnvValueFrom is exported for use by describers in other packages
func EnvValueRetriever(pod *api.Pod) EnvVarResolverFunc {
return func(e api.EnvVar) string {
internalFieldPath, _, err := api.Scheme.ConvertFieldLabel(e.ValueFrom.FieldRef.APIVersion, "Pod", e.ValueFrom.FieldRef.FieldPath, "")
if err != nil {
return "" // pod validation should catch this on create
}
valueFrom, err := fieldpath.ExtractFieldPathAsString(pod, internalFieldPath)
if err != nil {
return "" // pod validation should catch this on create
}
return valueFrom
}
}
func describeStatus(stateName string, state api.ContainerState, out io.Writer) {
switch {
case state.Running != nil:
fmt.Fprintf(out, " %s:\tRunning\n", stateName)
fmt.Fprintf(out, " Started:\t%v\n", state.Running.StartedAt.Time.Format(time.RFC1123Z))
case state.Waiting != nil:
fmt.Fprintf(out, " %s:\tWaiting\n", stateName)
if state.Waiting.Reason != "" {
fmt.Fprintf(out, " Reason:\t%s\n", state.Waiting.Reason)
}
case state.Terminated != nil:
fmt.Fprintf(out, " %s:\tTerminated\n", stateName)
if state.Terminated.Reason != "" {
fmt.Fprintf(out, " Reason:\t%s\n", state.Terminated.Reason)
}
if state.Terminated.Message != "" {
fmt.Fprintf(out, " Message:\t%s\n", state.Terminated.Message)
}
fmt.Fprintf(out, " Exit Code:\t%d\n", state.Terminated.ExitCode)
if state.Terminated.Signal > 0 {
fmt.Fprintf(out, " Signal:\t%d\n", state.Terminated.Signal)
}
fmt.Fprintf(out, " Started:\t%s\n", state.Terminated.StartedAt.Time.Format(time.RFC1123Z))
fmt.Fprintf(out, " Finished:\t%s\n", state.Terminated.FinishedAt.Time.Format(time.RFC1123Z))
default:
fmt.Fprintf(out, " %s:\tWaiting\n", stateName)
}
}
func printBool(value bool) string {
if value {
return "True"
}
return "False"
}
// ReplicationControllerDescriber generates information about a replication controller
// and the pods it has created.
type ReplicationControllerDescriber struct {
client.Interface
}
func (d *ReplicationControllerDescriber) Describe(namespace, name string) (string, error) {
rc := d.ReplicationControllers(namespace)
pc := d.Pods(namespace)
controller, err := rc.Get(name)
if err != nil {
return "", err
}
running, waiting, succeeded, failed, err := getPodStatusForController(pc, labels.SelectorFromSet(controller.Spec.Selector))
if err != nil {
return "", err
}
events, _ := d.Events(namespace).Search(controller)
return describeReplicationController(controller, events, running, waiting, succeeded, failed)
}
func describeReplicationController(controller *api.ReplicationController, events *api.EventList, running, waiting, succeeded, failed int) (string, error) {
return tabbedString(func(out io.Writer) error {
fmt.Fprintf(out, "Name:\t%s\n", controller.Name)
fmt.Fprintf(out, "Namespace:\t%s\n", controller.Namespace)
if controller.Spec.Template != nil {
fmt.Fprintf(out, "Image(s):\t%s\n", makeImageList(&controller.Spec.Template.Spec))
} else {
fmt.Fprintf(out, "Image(s):\t%s\n", "<unset>")
}
fmt.Fprintf(out, "Selector:\t%s\n", labels.FormatLabels(controller.Spec.Selector))
fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(controller.Labels))
fmt.Fprintf(out, "Replicas:\t%d current / %d desired\n", controller.Status.Replicas, controller.Spec.Replicas)
fmt.Fprintf(out, "Pods Status:\t%d Running / %d Waiting / %d Succeeded / %d Failed\n", running, waiting, succeeded, failed)
if controller.Spec.Template != nil {
describeVolumes(controller.Spec.Template.Spec.Volumes, out)
}
if events != nil {
DescribeEvents(events, out)
}
return nil
})
}
func DescribePodTemplate(template *api.PodTemplateSpec) (string, error) {
return tabbedString(func(out io.Writer) error {
if template == nil {
fmt.Fprintf(out, "<unset>")
return nil
}
fmt.Fprintf(out, "Labels:\t%s\n", labels.FormatLabels(template.Labels))