github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/command/metrics.go (about) 1 package command 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/hashicorp/nomad/api" 8 "github.com/posener/complete" 9 ) 10 11 type OperatorMetricsCommand struct { 12 Meta 13 } 14 15 func (c *OperatorMetricsCommand) Help() string { 16 helpText := ` 17 Usage: nomad operator metrics [options] 18 19 Get Nomad metrics 20 21 General Options: 22 23 ` + generalOptionsUsage(usageOptsDefault|usageOptsNoNamespace) + ` 24 25 Metrics Specific Options 26 27 -pretty 28 Pretty prints the JSON output 29 30 -format <format> 31 Specify output format (prometheus) 32 33 -json 34 Output the allocation in its JSON format. 35 36 -t 37 Format and display allocation using a Go template. 38 39 ` 40 41 return strings.TrimSpace(helpText) 42 } 43 44 func (c *OperatorMetricsCommand) Synopsis() string { 45 return "Retrieve Nomad metrics" 46 } 47 48 func (c *OperatorMetricsCommand) AutocompleteFlags() complete.Flags { 49 return mergeAutocompleteFlags(c.Meta.AutocompleteFlags(FlagSetClient), 50 complete.Flags{ 51 "-pretty": complete.PredictAnything, 52 "-format": complete.PredictAnything, 53 "-json": complete.PredictNothing, 54 "-t": complete.PredictAnything, 55 }) 56 } 57 58 func (c *OperatorMetricsCommand) Name() string { return "metrics" } 59 60 func (c *OperatorMetricsCommand) Run(args []string) int { 61 var pretty, json bool 62 var format, tmpl string 63 64 flags := c.Meta.FlagSet(c.Name(), FlagSetClient) 65 flags.Usage = func() { c.Ui.Output(c.Help()) } 66 flags.BoolVar(&pretty, "pretty", false, "") 67 flags.StringVar(&format, "format", "", "") 68 flags.BoolVar(&json, "json", false, "") 69 flags.StringVar(&tmpl, "t", "", "") 70 71 if err := flags.Parse(args); err != nil { 72 c.Ui.Error(fmt.Sprintf("Error parsing flags: %s", err)) 73 return 1 74 } 75 76 args = flags.Args() 77 if l := len(args); l != 0 { 78 c.Ui.Error("This command takes no arguments") 79 c.Ui.Error(commandErrorText(c)) 80 return 1 81 } 82 83 client, err := c.Meta.Client() 84 if err != nil { 85 c.Ui.Error(fmt.Sprintf("Error initializing client: %s", err)) 86 return 1 87 } 88 89 params := map[string]string{} 90 91 if pretty { 92 params["pretty"] = "1" 93 } 94 95 if len(format) > 0 { 96 params["format"] = format 97 } 98 99 query := &api.QueryOptions{ 100 Params: params, 101 } 102 103 if json || len(tmpl) > 0 { 104 metrics, _, err := client.Operator().MetricsSummary(query) 105 if err != nil { 106 c.Ui.Error(fmt.Sprintf("Error querying metrics: %v", err)) 107 return 1 108 } 109 110 out, err := Format(json, tmpl, metrics) 111 if err != nil { 112 c.Ui.Error(err.Error()) 113 return 1 114 } 115 116 c.Ui.Output(out) 117 return 0 118 } else { 119 bs, err := client.Operator().Metrics(query) 120 if err != nil { 121 c.Ui.Error(fmt.Sprintf("Error getting metrics: %v", err)) 122 return 1 123 } 124 125 resp := string(bs) 126 c.Ui.Output(resp) 127 } 128 129 return 0 130 }