github.com/cilium/cilium@v1.16.2/operator/cmd/metrics_list.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright Authors of Cilium 3 4 package cmd 5 6 import ( 7 "fmt" 8 "os" 9 "regexp" 10 "strings" 11 "text/tabwriter" 12 13 "github.com/go-openapi/strfmt" 14 "github.com/spf13/cobra" 15 16 "github.com/cilium/cilium/api/v1/operator/client" 17 "github.com/cilium/cilium/api/v1/operator/models" 18 "github.com/cilium/cilium/operator/api" 19 "github.com/cilium/cilium/pkg/command" 20 ) 21 22 var ( 23 matchPattern string 24 operatorAddr string 25 ) 26 27 // MetricsListCmd dumps all metrics into stdout 28 var MetricsListCmd = &cobra.Command{ 29 Use: "list", 30 Short: "List all metrics for the operator", 31 Run: func(cmd *cobra.Command, args []string) { 32 c := client.NewHTTPClientWithConfig( 33 strfmt.Default, client.DefaultTransportConfig().WithHost(operatorAddr)) 34 35 res, err := c.Metrics.GetMetrics(nil) 36 if err != nil { 37 log.Fatalf("Cannot get metrics list: %s", err) 38 } 39 40 re, err := regexp.Compile(matchPattern) 41 if err != nil { 42 log.Fatalf("Cannot compile regex: %s", err) 43 } 44 45 metrics := make([]*models.Metric, 0, len(res.Payload)) 46 for _, metric := range res.Payload { 47 if re.MatchString(metric.Name) { 48 metrics = append(metrics, metric) 49 } 50 } 51 52 if command.OutputOption() { 53 if err := command.PrintOutput(metrics); err != nil { 54 os.Exit(1) 55 } 56 return 57 } 58 59 w := tabwriter.NewWriter(os.Stdout, 5, 0, 3, ' ', 0) 60 61 fmt.Fprintln(w, "Metric\tLabels\tValue") 62 for _, metric := range metrics { 63 label := "" 64 if len(metric.Labels) > 0 { 65 labelArray := []string{} 66 for key, value := range metric.Labels { 67 labelArray = append(labelArray, fmt.Sprintf(`%s="%s"`, key, value)) 68 } 69 label = strings.Join(labelArray, " ") 70 } 71 fmt.Fprintf(w, "%s\t%s\t%f\n", metric.Name, label, metric.Value) 72 } 73 w.Flush() 74 }, 75 } 76 77 func init() { 78 MetricsCmd.AddCommand(MetricsListCmd) 79 80 MetricsListCmd.Flags().StringVarP(&matchPattern, "match-pattern", "p", "", "Show only metrics whose names match matchpattern") 81 MetricsListCmd.Flags().StringVarP(&operatorAddr, "server-address", "s", api.OperatorAPIServeAddrDefault, "Address of the operator API server") 82 command.AddOutputOption(MetricsListCmd) 83 }