-
Notifications
You must be signed in to change notification settings - Fork 29
/
main.go
207 lines (169 loc) · 5.13 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
package main
import (
"embed"
"encoding/base64"
"errors"
"fmt"
"html/template"
"net/http"
"os"
"runtime"
"time"
"github.com/google/uuid"
"github.com/jessevdk/go-flags"
"github.com/patrickmn/go-cache"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/webdevops/go-common/azuresdk/armclient"
"github.com/webdevops/go-common/azuresdk/azidentity"
"github.com/webdevops/go-common/azuresdk/prometheus/tracing"
"github.com/webdevops/azure-metrics-exporter/config"
)
const (
Author = "webdevops.io"
UserAgent = "azure-metrics-exporter/"
)
var (
argparser *flags.Parser
Opts config.Opts
AzureClient *armclient.ArmClient
AzureResourceTagManager *armclient.ResourceTagManager
prometheusCollectTime *prometheus.SummaryVec
prometheusMetricRequests *prometheus.CounterVec
metricsCache *cache.Cache
azureCache *cache.Cache
//go:embed templates/*.html
templates embed.FS
// Git version information
gitCommit = "<unknown>"
gitTag = "<unknown>"
)
func main() {
initArgparser()
initLogger()
logger.Infof("starting azure-metrics-exporter v%s (%s; %s; by %v)", gitTag, gitCommit, runtime.Version(), Author)
logger.Info(string(Opts.GetJson()))
initSystem()
metricsCache = cache.New(1*time.Minute, 1*time.Minute)
azureCache = cache.New(1*time.Minute, 1*time.Minute)
logger.Infof("init Azure connection")
initAzureConnection()
initMetricCollector()
logger.Infof("starting http server on %s", Opts.Server.Bind)
startHttpServer()
}
func initArgparser() {
argparser = flags.NewParser(&Opts, flags.Default)
_, err := argparser.Parse()
// check if there is an parse error
if err != nil {
var flagsErr *flags.Error
if ok := errors.As(err, &flagsErr); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
} else {
fmt.Println()
argparser.WriteHelp(os.Stdout)
os.Exit(1)
}
}
}
func initAzureConnection() {
var err error
if Opts.Azure.Environment != nil {
if err := os.Setenv(azidentity.EnvAzureEnvironment, *Opts.Azure.Environment); err != nil {
logger.Warnf(`unable to set envvar "%s": %v`, azidentity.EnvAzureEnvironment, err.Error())
}
}
AzureClient, err = armclient.NewArmClientFromEnvironment(logger)
if err != nil {
logger.Fatal(err.Error())
}
AzureClient.SetUserAgent(UserAgent + gitTag)
if err := AzureClient.Connect(); err != nil {
logger.Fatal(err.Error())
}
AzureResourceTagManager, err = AzureClient.TagManager.ParseTagConfig(Opts.Azure.ResourceTags)
if err != nil {
logger.Fatalf(`unable to parse resourceTag configuration "%s": %v"`, Opts.Azure.ResourceTags, err.Error())
}
}
// start and handle prometheus handler
func startHttpServer() {
mux := http.NewServeMux()
// healthz
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
if _, err := fmt.Fprint(w, "Ok"); err != nil {
logger.Error(err)
}
})
// readyz
mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
if _, err := fmt.Fprint(w, "Ok"); err != nil {
logger.Error(err)
}
})
mux.Handle(config.MetricsUrl, tracing.RegisterAzureMetricAutoClean(promhttp.Handler()))
mux.HandleFunc(config.ProbeMetricsResourceUrl, probeMetricsResourceHandler)
mux.HandleFunc(config.ProbeMetricsListUrl, probeMetricsListHandler)
mux.HandleFunc(config.ProbeMetricsSubscriptionUrl, probeMetricsSubscriptionHandler)
mux.HandleFunc(config.ProbeMetricsScrapeUrl, probeMetricsScrapeHandler)
mux.HandleFunc(config.ProbeMetricsResourceGraphUrl, probeMetricsResourceGraphHandler)
// report
tmpl := template.Must(template.ParseFS(templates, "templates/*.html"))
mux.HandleFunc("/query", func(w http.ResponseWriter, r *http.Request) {
cspNonce := base64.StdEncoding.EncodeToString([]byte(uuid.New().String()))
w.Header().Add("Content-Type", "text/html")
w.Header().Add("Referrer-Policy", "same-origin")
w.Header().Add("X-Frame-Options", "DENY")
w.Header().Add("X-XSS-Protection", "1; mode=block")
w.Header().Add("X-Content-Type-Options", "nosniff")
w.Header().Add("Content-Security-Policy",
fmt.Sprintf(
"default-src 'self'; script-src 'nonce-%[1]s'; style-src 'nonce-%[1]s'; img-src 'self' data:",
cspNonce,
),
)
templatePayload := struct {
Nonce string
}{
Nonce: cspNonce,
}
if err := tmpl.ExecuteTemplate(w, "query.html", templatePayload); err != nil {
logger.Error(err)
}
})
srv := &http.Server{
Addr: Opts.Server.Bind,
Handler: mux,
ReadTimeout: Opts.Server.ReadTimeout,
WriteTimeout: Opts.Server.WriteTimeout,
}
logger.Fatal(srv.ListenAndServe())
}
func initMetricCollector() {
prometheusCollectTime = prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: "azurerm_stats_metric_collecttime",
Help: "Azure Insights stats collecttime",
},
[]string{
"subscriptionID",
"handler",
"filter",
},
)
prometheus.MustRegister(prometheusCollectTime)
prometheusMetricRequests = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "azurerm_stats_metric_requests",
Help: "Azure Insights resource requests",
},
[]string{
"subscriptionID",
"handler",
"filter",
"result",
},
)
prometheus.MustRegister(prometheusMetricRequests)
}