-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
91 lines (77 loc) · 1.93 KB
/
query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/*
Copyright © 2023 Suman Vanan suman.vanan@live.com
*/
package cmd
import (
"bufio"
"context"
"fmt"
"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"
"log"
"os"
"strings"
"time"
"github.com/spf13/cobra"
)
// queryCmd represents the query command
var queryCmd = &cobra.Command{
Use: "query",
Short: "Run a PromQL query",
Long: `Run a PromQL query`,
Run: func(cmd *cobra.Command, args []string) {
input := getUserInput()
// todo: validate user input
query(input)
},
}
func getUserInput() string {
fmt.Println("Enter a PromQL query:")
scanner := bufio.NewScanner(os.Stdin)
var lines []string
for {
scanner.Scan()
line := scanner.Text()
// break the loop if line is empty
if len(line) == 0 {
break
}
lines = append(lines, line)
}
err := scanner.Err()
if err != nil {
log.Fatal(err)
}
return strings.Join(lines, " ")
}
func query(query string) {
client, err := api.NewClient(api.Config{
Address: "http://localhost:9090",
})
if err != nil {
fmt.Printf("Error creating client: %v\n", err)
os.Exit(1)
}
v1api := v1.NewAPI(client)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
result, warnings, err := v1api.Query(ctx, query, time.Now(), v1.WithTimeout(5*time.Second))
if err != nil {
fmt.Printf("Error querying Prometheus: %v\n", err)
os.Exit(1)
}
if len(warnings) > 0 {
fmt.Printf("Warnings: %v\n", warnings)
}
fmt.Printf("Result:\n%v\n", result)
}
func init() {
rootCmd.AddCommand(queryCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// queryCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// queryCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}