forked from spacelift-io/prometheus-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve_command.go
185 lines (155 loc) · 5.3 KB
/
serve_command.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package main
import (
"errors"
"fmt"
"net/http"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/urfave/cli/v2"
"go.uber.org/zap"
"golang.org/x/net/context"
"github.com/spacelift-io/prometheus-exporter/client/session"
"github.com/spacelift-io/prometheus-exporter/logging"
)
var (
listenAddress string
flagListenAddress = &cli.StringFlag{
Name: "listen-address",
Aliases: []string{"l"},
Value: ":9953",
Usage: "The address to listen on for HTTP requests",
EnvVars: []string{"SPACELIFT_PROMEX_LISTEN_ADDRESS"},
Destination: &listenAddress,
}
apiEndpoint string
flagAPIEndpoint = &cli.StringFlag{
Name: "api-endpoint",
Aliases: []string{"e"},
Usage: "Your spacelift API endpoint (e.g. https://myaccount.app.spacelift.io)",
EnvVars: []string{"SPACELIFT_PROMEX_API_ENDPOINT"},
Required: true,
Destination: &apiEndpoint,
}
apiKeyID string
flagAPIKeyID = &cli.StringFlag{
Name: "api-key-id",
Aliases: []string{"k"},
Usage: "Your spacelift API key ID",
EnvVars: []string{"SPACELIFT_PROMEX_API_KEY_ID"},
Required: true,
Destination: &apiKeyID,
}
apiKeySecret string
flagAPIKeySecret = &cli.StringFlag{
Name: "api-key-secret",
Aliases: []string{"s"},
Usage: "Your spacelift API key secret",
EnvVars: []string{"SPACELIFT_PROMEX_API_KEY_SECRET"},
Required: true,
Destination: &apiKeySecret,
}
isDevelopment bool
flagIsDevelopment = &cli.BoolFlag{
Name: "is-development",
Aliases: []string{"d"},
Usage: "Uses settings appropriate during local development",
EnvVars: []string{"SPACELIFT_PROMEX_IS_DEVELOPMENT"},
Destination: &isDevelopment,
}
scrapeTimeout time.Duration
flagScrapeTimeout = &cli.DurationFlag{
Name: "scrape-timeout",
Aliases: []string{"t"},
Usage: "The maximum duration to wait for a response from the Spacelift API during scraping",
EnvVars: []string{"SPACELIFT_PROMEX_SCRAPE_TIMEOUT"},
Value: time.Second * 5,
Destination: &scrapeTimeout,
}
)
var serveCommand *cli.Command = &cli.Command{
Name: "serve",
Usage: "Starts the Prometheus exporter",
Flags: []cli.Flag{
flagListenAddress,
flagAPIEndpoint,
flagAPIKeyID,
flagAPIKeySecret,
flagIsDevelopment,
flagScrapeTimeout,
},
Action: func(cliCtx *cli.Context) error {
ctx := logging.Init(cliCtx.Context, isDevelopment)
logger := logging.FromContext(ctx).Sugar()
if scrapeTimeout <= 0 {
return cli.Exit("scrape-timeout must be greater than 0", ExitCodeStartupError)
}
if url, err := url.Parse(apiEndpoint); err != nil || url.Scheme == "" || url.Host == "" {
return cli.Exit(fmt.Sprintf("api-endpoint %q does not seem to be a valid URL", apiEndpoint), ExitCodeStartupError)
}
logger.Info("Prepping exporter for lift-off")
session, err := func() (session.Session, error) {
sessionCtx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
return session.New(sessionCtx, http.DefaultClient, apiEndpoint, apiKeyID, apiKeySecret)
}()
if err != nil {
logger.Fatalw("failed to create Spacelift API session", zap.Error(err))
return cli.Exit("could not create session from Spacelift API key", ExitCodeStartupError)
}
logger.Info("Successfully created Spacelift API session")
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`
<html>
<head>
<title>Spacelift Prometheus Exporter</title>
</head>
<body>
Welcome to the Spacelift Prometheus exporter! Please find the available metrics at <a href="/metrics">/metrics</a>.
</body>
</html>`))
}))
// Create a new registry.
reg := prometheus.NewRegistry()
collector, err := newSpaceliftCollector(ctx, http.DefaultClient, session, scrapeTimeout)
if err != nil {
return cli.Exit(fmt.Sprintf("could not create Spacelift collector: %v", err), ExitCodeStartupError)
}
reg.MustRegister(collector)
// Expose the registered metrics via HTTP.
http.Handle("/metrics", promhttp.HandlerFor(
reg,
promhttp.HandlerOpts{
// Opt into OpenMetrics to support exemplars.
EnableOpenMetrics: true,
},
))
http.Handle("/health", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Countdown complete - ready to serve metrics!"))
}))
listenAddress := cliCtx.String(flagListenAddress.Name)
logger.Info("Ready for launch! Listening on ", listenAddress)
server := http.Server{Addr: listenAddress, ReadHeaderTimeout: time.Second * 5}
go func() {
if err := server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Fatalw("Error running HTTP server", zap.Error(err))
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
// Wait for interrupt signal to gracefully shutdown the server.
<-stop
logger.Info("Received stop signal - shutting down exporter")
ctx, cancel := context.WithTimeout(ctx, time.Second*5)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Errorw("Failed to gracefully shutdown exporter", zap.Error(err))
}
logger.Info("Exporter has landed successfully!")
return nil
},
}