github.com/olli-ai/jx/v2@v2.0.400-0.20210921045218-14731b4dd448/pkg/cmd/metrics.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/olli-ai/jx/v2/pkg/cmd/helper"
     7  
     8  	"time"
     9  
    10  	"github.com/jenkins-x/jx-logging/pkg/log"
    11  	"github.com/olli-ai/jx/v2/pkg/cmd/opts"
    12  	"github.com/olli-ai/jx/v2/pkg/cmd/templates"
    13  	"github.com/olli-ai/jx/v2/pkg/kube"
    14  	"github.com/olli-ai/jx/v2/pkg/util"
    15  	"github.com/spf13/cobra"
    16  )
    17  
    18  type MetricsOptions struct {
    19  	*opts.CommonOptions
    20  
    21  	Namespace string
    22  	Filter    string
    23  	Duration  string
    24  	Selector  string
    25  	Metric    string
    26  }
    27  
    28  var (
    29  	MetricsLong = templates.LongDesc(`
    30  		Gets the metrics of the newest pod for a Deployment.
    31  
    32  `)
    33  
    34  	MetricsExample = templates.Examples(`
    35  		# displays metrics of the latest pod in deployment myapp
    36  		jx metrics myapp
    37  
    38  		# Tails the metrics of the container foo in the latest pod in deployment myapp
    39  		jx metrics myapp -c foo
    40  `)
    41  )
    42  
    43  func NewCmdMetrics(commonOpts *opts.CommonOptions) *cobra.Command {
    44  	options := &MetricsOptions{
    45  		CommonOptions: commonOpts,
    46  	}
    47  	cmd := &cobra.Command{
    48  		Use:     "metrics [deployment]",
    49  		Short:   "Gets the metrics of the latest pod for a deployment",
    50  		Long:    MetricsLong,
    51  		Example: MetricsExample,
    52  		Aliases: []string{"metrics"},
    53  		Run: func(cmd *cobra.Command, args []string) {
    54  			options.Cmd = cmd
    55  			options.Args = args
    56  			err := options.Run()
    57  			helper.CheckErr(err)
    58  		},
    59  	}
    60  
    61  	cmd.Flags().StringVarP(&options.Namespace, "namespace", "n", "", "the namespace to look for the Deployment. Defaults to the current namespace")
    62  	cmd.Flags().StringVarP(&options.Filter, "filter", "f", "", "Filters the available deployments if no deployment argument is provided")
    63  	cmd.Flags().StringVarP(&options.Duration, "duration", "d", "", "The duration to query (e.g. 1.5h, 20s, 5m")
    64  	cmd.Flags().StringVarP(&options.Selector, "selector", "s", "", "The pod selector to use to query for pods")
    65  	cmd.Flags().StringVarP(&options.Metric, "metric", "m", "", "The heapster metric name")
    66  	return cmd
    67  }
    68  
    69  func (o *MetricsOptions) Run() error {
    70  	args := o.Args
    71  
    72  	client, curNs, err := o.KubeClientAndNamespace()
    73  	if err != nil {
    74  		return err
    75  	}
    76  
    77  	ns := o.Namespace
    78  	if ns == "" {
    79  		ns = curNs
    80  	}
    81  	pod := ""
    82  	selector := o.Selector
    83  	if selector == "" {
    84  		names, err := kube.GetDeploymentNames(client, ns, o.Filter)
    85  		if err != nil {
    86  			return err
    87  		}
    88  		name := ""
    89  		if len(args) == 0 {
    90  			if len(names) == 0 {
    91  				return fmt.Errorf("There are no Deployments running")
    92  			}
    93  			n, err := util.PickName(names, "Pick Deployment:", "", o.GetIOFileHandles())
    94  			if err != nil {
    95  				return err
    96  			}
    97  			name = n
    98  		} else {
    99  			name = args[0]
   100  			if util.StringArrayIndex(names, name) < 0 {
   101  				return util.InvalidArg(name, names)
   102  			}
   103  		}
   104  
   105  		p, err := o.WaitForReadyPodForDeployment(client, ns, name, names, false)
   106  		if err != nil {
   107  			return err
   108  		}
   109  
   110  		pod = p
   111  		if pod == "" {
   112  			return fmt.Errorf("No pod found for namespace %s with name %s", ns, name)
   113  		}
   114  	}
   115  
   116  	if o.Duration != "" || o.Metric != "" {
   117  		start := ""
   118  		end := ""
   119  		if o.Duration != "" && pod != "" {
   120  			d, err := time.ParseDuration(o.Duration)
   121  			if err != nil {
   122  				return fmt.Errorf("Failed to parse duration %s due to %s", o.Duration, err)
   123  			}
   124  			e := time.Now()
   125  			s := e.Add(-d)
   126  			start = s.Format(time.RFC3339)
   127  			end = e.Format(time.RFC3339)
   128  		}
   129  
   130  		heapster := kube.HeapterConfig{
   131  			KubeClient: client,
   132  		}
   133  		data, err := heapster.GetPodMetrics(ns, pod, selector, o.Metric, start, end)
   134  		if err != nil {
   135  			return err
   136  		}
   137  		log.Logger().Infof("%s", string(data))
   138  		return nil
   139  	}
   140  
   141  	if selector != "" {
   142  		args = []string{"top", "pod", "--selector", selector, "--namespace", ns}
   143  	} else {
   144  		args = []string{"top", "pod", pod, "--namespace", ns}
   145  	}
   146  
   147  	err = o.RunCommand("kubectl", args...)
   148  	if err != nil {
   149  		return err
   150  	}
   151  	return nil
   152  }