/
main.go
99 lines (80 loc) · 2.7 KB
/
main.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
92
93
94
95
96
97
98
99
package main
import (
"context"
"fmt"
"os"
"strings"
"time"
_ "github.com/olekukonko/tablewriter"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/sandipb/gcp-prom-query/pkg/prom"
"gopkg.in/alecthomas/kingpin.v2"
)
const appName = "gcp-prom-query"
var (
version = "unset"
commit = "unset"
date = "unset"
)
var (
debugLevel = kingpin.Flag("debug", "Debug level logging").Short('d').Bool()
timeoutSeconds = kingpin.Flag("timeout", "Timeout in seconds for the query").Short('t').Default("10").Int()
promServer = kingpin.Flag("prom-api", "URL to API server. Used when gcp-project is not provided.").Short('u').Default("localhost:9090").String()
project = kingpin.Flag("gcp-project", "Name of the GCP project. If not given, uses 'prom-api'").Short('p').String()
token = kingpin.Flag("gcp-token", "Name of the GCP project. Required if project is given. Can also be provided via env var GCP_ACCESS_TOKEN").
Short('a').Envar("GCP_ACCESS_TOKEN").String()
instant = kingpin.Command("instant", "Instant query")
unixTS = instant.Flag("now", "Time to run instant query as Unix epoch time").Int64()
query = instant.Arg("query", "Promql query").Required().String()
_ = kingpin.Command("version", "Show version")
)
const helpText = `Runs query on the gcp prometheus api`
func setup() string {
kingpin.CommandLine.HelpFlag.Short('h')
kingpin.CommandLine.Help = helpText
cmd := kingpin.Parse()
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339})
if *debugLevel {
log.Logger = log.Logger.Level(zerolog.DebugLevel)
} else {
log.Logger = log.Logger.Level(zerolog.InfoLevel)
}
if *project != "" && *token == "" {
kingpin.Fatalf("Token is required if project is specified")
}
if *project != "" {
*promServer = fmt.Sprintf("https://monitoring.googleapis.com/v1/projects/%s/location/global/prometheus", *project)
} else {
if !strings.HasPrefix(*promServer, "http") {
*promServer = "http://" + *promServer
}
}
if *unixTS == 0 {
*unixTS = int64(time.Now().Unix())
}
return cmd
}
func printVersion() {
fmt.Printf("%s %s, commit %s, built %s\n", appName, version, commit, date)
os.Exit(0)
}
func main() {
cmd := setup()
log.Debug().Msgf("Using prometheus server: %#v", *promServer)
client, err := prom.GetAPIClient(*promServer, *token)
if err != nil {
log.Fatal().Err(err).Msg("Could not create prometheus client")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(*timeoutSeconds)*time.Second)
defer cancel()
switch cmd {
case "instant":
err = prom.PrintInstant(ctx, client, *query, time.Unix(*unixTS, 0))
case "version":
printVersion()
}
if err != nil {
log.Fatal().Err(err).Send()
}
}