-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
284 lines (250 loc) · 7.57 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
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import (
"context"
"fmt"
"net/http"
"net/http/pprof"
"os"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
"golang.org/x/sync/semaphore"
exporter "github.com/nerdswords/yet-another-cloudwatch-exporter/pkg"
v1 "github.com/nerdswords/yet-another-cloudwatch-exporter/pkg/clients/v1"
v2 "github.com/nerdswords/yet-another-cloudwatch-exporter/pkg/clients/v2"
"github.com/nerdswords/yet-another-cloudwatch-exporter/pkg/config"
"github.com/nerdswords/yet-another-cloudwatch-exporter/pkg/logging"
)
const (
enableFeatureFlag = "enable-feature"
htmlVersion = `<html>
<head><title>Yet Another CloudWatch Exporter</title></head>
<body>
<h1>Thanks for using YACE :)</h1>
Version: %s
<p><a href="/metrics">Metrics</a></p>
%s
</body>
</html>`
htmlPprof = `<p><a href="/debug/pprof">Pprof</a><p>`
)
var version = "custom-build"
var sem = semaphore.NewWeighted(1)
var (
addr string
configFile string
debug bool
fips bool
cloudwatchConcurrency int
tagConcurrency int
scrapingInterval int
metricsPerQuery int
labelsSnakeCase bool
profilingEnabled bool
logger logging.Logger
cfg = config.ScrapeConf{}
)
func main() {
app := NewYACEApp()
if err := app.Run(os.Args); err != nil {
logger.Error(err, "Error running yace")
os.Exit(1)
}
}
// NewYACEApp creates a new cli.App implementing the YACE entrypoints and CLI arguments.
func NewYACEApp() *cli.App {
yace := cli.NewApp()
yace.Name = "Yet Another CloudWatch Exporter"
yace.Version = version
yace.Usage = "YACE configured to retrieve CloudWatch metrics through the AWS API"
yace.Description = ""
yace.Authors = []*cli.Author{
{Name: "", Email: ""},
}
yace.Flags = []cli.Flag{
&cli.StringFlag{
Name: "listen-address",
Value: ":5000",
Usage: "The address to listen on",
Destination: &addr,
EnvVars: []string{"listen-address"},
},
&cli.StringFlag{
Name: "config.file",
Value: "config.yml",
Usage: "Path to configuration file",
Destination: &configFile,
EnvVars: []string{"config.file"},
},
&cli.BoolFlag{
Name: "debug",
Value: false,
Usage: "Verbose logging",
Destination: &debug,
EnvVars: []string{"debug"},
},
&cli.BoolFlag{
Name: "fips",
Value: false,
Usage: "Use FIPS compliant AWS API endpoints",
Destination: &fips,
},
&cli.IntFlag{
Name: "cloudwatch-concurrency",
Value: exporter.DefaultCloudWatchAPIConcurrency,
Usage: "Maximum number of concurrent requests to CloudWatch API.",
Destination: &cloudwatchConcurrency,
},
&cli.IntFlag{
Name: "tag-concurrency",
Value: exporter.DefaultTaggingAPIConcurrency,
Usage: "Maximum number of concurrent requests to Resource Tagging API.",
Destination: &tagConcurrency,
},
&cli.IntFlag{
Name: "scraping-interval",
Value: 300,
Usage: "Seconds to wait between scraping the AWS metrics",
Destination: &scrapingInterval,
EnvVars: []string{"scraping-interval"},
},
&cli.IntFlag{
Name: "metrics-per-query",
Value: exporter.DefaultMetricsPerQuery,
Usage: "Number of metrics made in a single GetMetricsData request",
Destination: &metricsPerQuery,
EnvVars: []string{"metrics-per-query"},
},
&cli.BoolFlag{
Name: "labels-snake-case",
Value: exporter.DefaultLabelsSnakeCase,
Usage: "Whether labels should be output in snake case instead of camel case",
Destination: &labelsSnakeCase,
},
&cli.BoolFlag{
Name: "profiling.enabled",
Value: false,
Usage: "Enable pprof endpoints",
Destination: &profilingEnabled,
},
&cli.StringSliceFlag{
Name: enableFeatureFlag,
Usage: "Comma-separated list of enabled features",
},
}
yace.Before = func(ctx *cli.Context) error {
logger = newLogger(debug)
return nil
}
yace.Commands = []*cli.Command{
{
Name: "verify-config", Aliases: []string{"vc"}, Usage: "Loads and attempts to parse config file, then exits. Useful for CI/CD validation",
Flags: []cli.Flag{
&cli.StringFlag{Name: "config.file", Value: "config.yml", Usage: "Path to configuration file.", Destination: &configFile},
},
Action: func(c *cli.Context) error {
logger.Info("Parsing config")
if err := cfg.Load(configFile, logger); err != nil {
logger.Error(err, "Couldn't read config file", "path", configFile)
os.Exit(1)
}
logger.Info("Config file is valid", "path", configFile)
os.Exit(0)
return nil
},
},
{
Name: "version", Aliases: []string{"v"}, Usage: "prints current yace version.",
Action: func(c *cli.Context) error {
fmt.Println(version)
os.Exit(0)
return nil
},
},
}
yace.Action = startScraper
return yace
}
func startScraper(c *cli.Context) error {
logger.Info("Parsing config")
if err := cfg.Load(configFile, logger); err != nil {
return fmt.Errorf("Couldn't read %s: %w", configFile, err)
}
logger.Info("Yace startup completed", "version", version)
featureFlags := c.StringSlice(enableFeatureFlag)
s := NewScraper(featureFlags)
cache := v1.NewClientCache(cfg, fips, logger)
for _, featureFlag := range featureFlags {
if featureFlag == config.AwsSdkV2 {
logger.Info("Using aws sdk v2")
var err error
// Can't override cache while also creating err
cache, err = v2.NewCache(cfg, fips, logger)
if err != nil {
return fmt.Errorf("failed to construct aws sdk v2 client cache: %w", err)
}
}
}
ctx, cancelRunningScrape := context.WithCancel(context.Background())
go s.decoupled(ctx, logger, cache)
mux := http.NewServeMux()
if profilingEnabled {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
mux.HandleFunc("/metrics", s.makeHandler())
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
pprofLink := ""
if profilingEnabled {
pprofLink = htmlPprof
}
_, _ = w.Write([]byte(fmt.Sprintf(htmlVersion, version, pprofLink)))
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
mux.HandleFunc("/reload", func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusNotFound)
return
}
logger.Info("Parsing config")
if err := cfg.Load(configFile, logger); err != nil {
logger.Error(err, "Couldn't read config file", "path", configFile)
return
}
logger.Info("Reset clients cache")
cache = v1.NewClientCache(cfg, fips, logger)
for _, featureFlag := range featureFlags {
if featureFlag == config.AwsSdkV2 {
logger.Info("Using aws sdk v2")
var err error
// Can't override cache while also creating err
cache, err = v2.NewCache(cfg, fips, logger)
if err != nil {
logger.Error(err, "Failed to construct aws sdk v2 client cache", "path", configFile)
return
}
}
}
cancelRunningScrape()
ctx, cancelRunningScrape = context.WithCancel(context.Background())
go s.decoupled(ctx, logger, cache)
})
srv := &http.Server{Addr: addr, Handler: mux}
return srv.ListenAndServe()
}
func newLogger(debug bool) logging.Logger {
l := logrus.New()
l.SetFormatter(&logrus.JSONFormatter{})
l.SetOutput(os.Stdout)
if debug {
l.SetLevel(logrus.DebugLevel)
} else {
l.SetLevel(logrus.InfoLevel)
}
return logging.NewLogger(l)
}