diff --git a/pkg/kubectl/cmd/top/top.go b/pkg/kubectl/cmd/top/top.go index 27e6e725ae4..08744512880 100644 --- a/pkg/kubectl/cmd/top/top.go +++ b/pkg/kubectl/cmd/top/top.go @@ -27,6 +27,11 @@ import ( metricsapi "k8s.io/metrics/pkg/apis/metrics" ) +const ( + sortByCPU = "cpu" + sortByMemory = "memory" +) + var ( supportedMetricsAPIVersions = []string{ "v1beta1", diff --git a/pkg/kubectl/cmd/top/top_node.go b/pkg/kubectl/cmd/top/top_node.go index 073b2ccdc0c..7009a56db66 100644 --- a/pkg/kubectl/cmd/top/top_node.go +++ b/pkg/kubectl/cmd/top/top_node.go @@ -40,6 +40,7 @@ import ( type TopNodeOptions struct { ResourceName string Selector string + SortBy string NoHeaders bool NodeClient corev1client.CoreV1Interface HeapsterOptions HeapsterTopOptions @@ -113,6 +114,7 @@ func NewCmdTopNode(f cmdutil.Factory, o *TopNodeOptions, streams genericclioptio Aliases: []string{"nodes", "no"}, } cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)") + cmd.Flags().StringVar(&o.SortBy, "sort-by", o.Selector, "If non-empty, sort nodes list using specified field. The field can be either 'cpu' or 'memory'.") cmd.Flags().BoolVar(&o.NoHeaders, "no-headers", o.NoHeaders, "If present, print output without headers") o.HeapsterOptions.Bind(cmd.Flags()) @@ -150,6 +152,11 @@ func (o *TopNodeOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args [] } func (o *TopNodeOptions) Validate() error { + if len(o.SortBy) > 0 { + if o.SortBy != sortByCPU && o.SortBy != sortByMemory { + return errors.New("--sort-by accepts only cpu or memory") + } + } if len(o.ResourceName) > 0 && len(o.Selector) > 0 { return errors.New("only one of NAME or --selector can be provided") } @@ -213,7 +220,7 @@ func (o TopNodeOptions) RunTopNode() error { allocatable[n.Name] = n.Status.Allocatable } - return o.Printer.PrintNodeMetrics(metrics.Items, allocatable, o.NoHeaders) + return o.Printer.PrintNodeMetrics(metrics.Items, allocatable, o.NoHeaders, o.SortBy) } func getNodeMetricsFromMetricsAPI(metricsClient metricsclientset.Interface, resourceName string, selector labels.Selector) (*metricsapi.NodeMetricsList, error) { diff --git a/pkg/kubectl/cmd/top/top_pod.go b/pkg/kubectl/cmd/top/top_pod.go index 63938cab376..387fad8f615 100644 --- a/pkg/kubectl/cmd/top/top_pod.go +++ b/pkg/kubectl/cmd/top/top_pod.go @@ -43,6 +43,7 @@ type TopPodOptions struct { ResourceName string Namespace string Selector string + SortBy string AllNamespaces bool PrintContainers bool NoHeaders bool @@ -102,6 +103,7 @@ func NewCmdTopPod(f cmdutil.Factory, o *TopPodOptions, streams genericclioptions Aliases: []string{"pods", "po"}, } cmd.Flags().StringVarP(&o.Selector, "selector", "l", o.Selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)") + cmd.Flags().StringVar(&o.SortBy, "sort-by", o.Selector, "If non-empty, sort pods list using specified field. The field can be either 'cpu' or 'memory'.") cmd.Flags().BoolVar(&o.PrintContainers, "containers", o.PrintContainers, "If present, print usage of containers within a pod.") cmd.Flags().BoolVarP(&o.AllNamespaces, "all-namespaces", "A", o.AllNamespaces, "If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace.") cmd.Flags().BoolVar(&o.NoHeaders, "no-headers", o.NoHeaders, "If present, print output without headers.") @@ -144,6 +146,11 @@ func (o *TopPodOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []s } func (o *TopPodOptions) Validate() error { + if len(o.SortBy) > 0 { + if o.SortBy != sortByCPU && o.SortBy != sortByMemory { + return errors.New("--sort-by accepts only cpu or memory") + } + } if len(o.ResourceName) > 0 && len(o.Selector) > 0 { return errors.New("only one of NAME or --selector can be provided") } @@ -194,7 +201,7 @@ func (o TopPodOptions) RunTopPod() error { return err } - return o.Printer.PrintPodMetrics(metrics.Items, o.PrintContainers, o.AllNamespaces, o.NoHeaders) + return o.Printer.PrintPodMetrics(metrics.Items, o.PrintContainers, o.AllNamespaces, o.NoHeaders, o.SortBy) } func getMetricsFromMetricsAPI(metricsClient metricsclientset.Interface, namespace, resourceName string, allNamespaces bool, selector labels.Selector) (*metricsapi.PodMetricsList, error) { diff --git a/pkg/kubectl/metricsutil/metrics_printer.go b/pkg/kubectl/metricsutil/metrics_printer.go index c02af149cd4..fe8464452b7 100644 --- a/pkg/kubectl/metricsutil/metrics_printer.go +++ b/pkg/kubectl/metricsutil/metrics_printer.go @@ -53,16 +53,114 @@ func NewTopCmdPrinter(out io.Writer) *TopCmdPrinter { return &TopCmdPrinter{out: out} } -func (printer *TopCmdPrinter) PrintNodeMetrics(metrics []metricsapi.NodeMetrics, availableResources map[string]v1.ResourceList, noHeaders bool) error { +type NodeMetricsSorter struct { + metrics []metricsapi.NodeMetrics + sortBy string + usages []v1.ResourceList +} + +func (n *NodeMetricsSorter) Len() int { + return len(n.metrics) +} + +func (n *NodeMetricsSorter) Swap(i, j int) { + n.metrics[i], n.metrics[j] = n.metrics[j], n.metrics[i] +} + +func (n *NodeMetricsSorter) Less(i, j int) bool { + switch n.sortBy { + case "cpu": + qi := n.usages[i][v1.ResourceCPU] + qj := n.usages[j][v1.ResourceCPU] + return qi.Value() > qj.Value() + case "memory": + qi := n.usages[i][v1.ResourceMemory] + qj := n.usages[j][v1.ResourceMemory] + return qi.Value() > qj.Value() + default: + return n.metrics[i].Name < n.metrics[j].Name + } +} + +func NewNodeMetricsSorter(metrics []metricsapi.NodeMetrics, sortBy string) (*NodeMetricsSorter, error) { + var usages = make([]v1.ResourceList, len(metrics)) + if len(sortBy) > 0 { + for i, v := range metrics { + if err := scheme.Scheme.Convert(&v.Usage, &usages[i], nil); err != nil { + return nil, err + } + } + } + + return &NodeMetricsSorter{ + metrics: metrics, + sortBy: sortBy, + usages: usages, + }, nil +} + +type PodMetricsSorter struct { + metrics []metricsapi.PodMetrics + sortBy string + withNamespace bool + podMetrics []v1.ResourceList +} + +func (p *PodMetricsSorter) Len() int { + return len(p.metrics) +} + +func (p *PodMetricsSorter) Swap(i, j int) { + p.metrics[i], p.metrics[j] = p.metrics[j], p.metrics[i] +} + +func (p *PodMetricsSorter) Less(i, j int) bool { + switch p.sortBy { + case "cpu": + qi := p.podMetrics[i][v1.ResourceCPU] + qj := p.podMetrics[j][v1.ResourceCPU] + return qi.Value() > qj.Value() + case "memory": + qi := p.podMetrics[i][v1.ResourceMemory] + qj := p.podMetrics[j][v1.ResourceMemory] + return qi.Value() > qj.Value() + default: + if p.withNamespace && p.metrics[i].Namespace != p.metrics[j].Namespace { + return p.metrics[i].Namespace < p.metrics[j].Namespace + } + return p.metrics[i].Name < p.metrics[j].Name + } +} + +func NewPodMetricsSorter(metrics []metricsapi.PodMetrics, printContainers bool, withNamespace bool, sortBy string) (*PodMetricsSorter, error) { + var podMetrics = make([]v1.ResourceList, len(metrics)) + if len(sortBy) > 0 { + for i, v := range metrics { + podMetrics[i], _, _ = getPodMetrics(&v, printContainers) + } + } + + return &PodMetricsSorter{ + metrics: metrics, + sortBy: sortBy, + withNamespace: withNamespace, + podMetrics: podMetrics, + }, nil +} + +func (printer *TopCmdPrinter) PrintNodeMetrics(metrics []metricsapi.NodeMetrics, availableResources map[string]v1.ResourceList, noHeaders bool, sortBy string) error { if len(metrics) == 0 { return nil } w := printers.GetNewTabWriter(printer.out) defer w.Flush() - sort.Slice(metrics, func(i, j int) bool { - return metrics[i].Name < metrics[j].Name - }) + n, err := NewNodeMetricsSorter(metrics, sortBy) + if err != nil { + return err + } + sort.Sort(n) + if !noHeaders { printColumnNames(w, NodeColumns) } @@ -87,7 +185,7 @@ func (printer *TopCmdPrinter) PrintNodeMetrics(metrics []metricsapi.NodeMetrics, return nil } -func (printer *TopCmdPrinter) PrintPodMetrics(metrics []metricsapi.PodMetrics, printContainers bool, withNamespace bool, noHeaders bool) error { +func (printer *TopCmdPrinter) PrintPodMetrics(metrics []metricsapi.PodMetrics, printContainers bool, withNamespace bool, noHeaders bool, sortBy string) error { if len(metrics) == 0 { return nil } @@ -103,12 +201,12 @@ func (printer *TopCmdPrinter) PrintPodMetrics(metrics []metricsapi.PodMetrics, p printColumnNames(w, PodColumns) } - sort.Slice(metrics, func(i, j int) bool { - if withNamespace && metrics[i].Namespace != metrics[j].Namespace { - return metrics[i].Namespace < metrics[j].Namespace - } - return metrics[i].Name < metrics[j].Name - }) + p, err := NewPodMetricsSorter(metrics, printContainers, withNamespace, sortBy) + if err != nil { + return err + } + sort.Sort(p) + for _, m := range metrics { err := printSinglePodMetrics(w, &m, printContainers, withNamespace) if err != nil { @@ -126,26 +224,9 @@ func printColumnNames(out io.Writer, names []string) { } func printSinglePodMetrics(out io.Writer, m *metricsapi.PodMetrics, printContainersOnly bool, withNamespace bool) error { - containers := make(map[string]v1.ResourceList) - podMetrics := make(v1.ResourceList) - for _, res := range MeasuredResources { - podMetrics[res], _ = resource.ParseQuantity("0") - } - - for _, c := range m.Containers { - var usage v1.ResourceList - err := scheme.Scheme.Convert(&c.Usage, &usage, nil) - if err != nil { - return err - } - containers[c.Name] = usage - if !printContainersOnly { - for _, res := range MeasuredResources { - quantity := podMetrics[res] - quantity.Add(usage[res]) - podMetrics[res] = quantity - } - } + podMetrics, containers, err := getPodMetrics(m, printContainersOnly) + if err != nil { + return err } if printContainersOnly { for contName := range containers { @@ -172,6 +253,30 @@ func printSinglePodMetrics(out io.Writer, m *metricsapi.PodMetrics, printContain return nil } +func getPodMetrics(m *metricsapi.PodMetrics, printContainersOnly bool) (v1.ResourceList, map[string]v1.ResourceList, error) { + containers := make(map[string]v1.ResourceList) + podMetrics := make(v1.ResourceList) + for _, res := range MeasuredResources { + podMetrics[res], _ = resource.ParseQuantity("0") + } + + for _, c := range m.Containers { + var usage v1.ResourceList + if err := scheme.Scheme.Convert(&c.Usage, &usage, nil); err != nil { + return nil, nil, err + } + containers[c.Name] = usage + if !printContainersOnly { + for _, res := range MeasuredResources { + quantity := podMetrics[res] + quantity.Add(usage[res]) + podMetrics[res] = quantity + } + } + } + return podMetrics, containers, nil +} + func printMetricsLine(out io.Writer, metrics *ResourceMetricsInfo) { printValue(out, metrics.Name) printAllResourceUsages(out, metrics)