From a3376e8f365274593ceea5f7be0317b07ef1243f Mon Sep 17 00:00:00 2001 From: Daisy T Date: Wed, 18 Jul 2018 16:27:28 +0200 Subject: [PATCH] add query labels command to promtool (#4346) Signed-off-by: Daisy T --- cmd/promtool/main.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/cmd/promtool/main.go b/cmd/promtool/main.go index 56c99b689..d5daca383 100644 --- a/cmd/promtool/main.go +++ b/cmd/promtool/main.go @@ -89,6 +89,10 @@ func main() { debugAllCmd := debugCmd.Command("all", "Fetch all debug information.") debugAllServer := debugAllCmd.Arg("server", "Prometheus server to get all debug information from.").Required().String() + queryLabelsCmd := queryCmd.Command("labels", "Run labels query.") + queryLabelsServer := queryLabelsCmd.Arg("server", "Prometheus server to query.").Required().URL() + queryLabelsName := queryLabelsCmd.Arg("name", "Label name to provide label values for.").Required().String() + switch kingpin.MustParse(app.Parse(os.Args[1:])) { case checkConfigCmd.FullCommand(): os.Exit(CheckConfig(*configFiles...)) @@ -119,6 +123,9 @@ func main() { case debugAllCmd.FullCommand(): os.Exit(debugAll(*debugAllServer)) + + case queryLabelsCmd.FullCommand(): + os.Exit(QueryLabels(*queryLabelsServer, *queryLabelsName)) } } @@ -519,6 +526,36 @@ func QuerySeries(url *url.URL, matchers []string, start string, end string) int return 0 } +// QueryLabels queries for label values against a Prometheus server. +func QueryLabels(url *url.URL, name string) int { + config := api.Config{ + Address: url.String(), + } + + // Create new client. + c, err := api.NewClient(config) + if err != nil { + fmt.Fprintln(os.Stderr, "error creating API client:", err) + return 1 + } + + // Run query against client. + api := v1.NewAPI(c) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + val, err := api.LabelValues(ctx, name) + cancel() + + if err != nil { + fmt.Fprintln(os.Stderr, "query error:", err) + return 1 + } + + for _, v := range val { + fmt.Println(v) + } + return 0 +} + func parseTime(s string) (time.Time, error) { if t, err := strconv.ParseFloat(s, 64); err == nil { s, ns := math.Modf(t)