forked from iits-consulting/otc-prometheus-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
269 lines (228 loc) · 9.41 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
package main
import (
"errors"
"fmt"
"log"
"net/http"
cmdPackage "github.com/iits-consulting/otc-prometheus-exporter/cmd"
"golang.org/x/exp/maps"
"golang.org/x/exp/slices"
"time"
"github.com/iits-consulting/otc-prometheus-exporter/internal"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/spf13/cobra"
)
func collectMetricsInBackground(config internal.ConfigStruct, logger internal.ILogger) {
go func() {
client, err := internal.NewOtcClientFromConfig(config, logger)
if err != nil {
logger.Panic("Error creating OTC client", "error", err)
}
logger.Info("New OTC Client created!")
var resourceIdToName map[string]string
if config.ResourceIdNameMappingFlag {
resourceIdToName, err = FetchResourceIdToNameMapping(client)
if err != nil {
logger.Panic("Error mapping resource IDs to Names", "error", err)
}
logger.Info("Resource ID names mapped!", "idmaps", resourceIdToName)
}
metrics, err := client.GetMetrics()
if err != nil {
logger.Panic("Unable to get metrics", "error", err, "context", "Initial get metrics call to get metric baseline.")
}
logger.Info("Initial metrics retrieved!")
filteredMetrics, removedMetrics := internal.FilterByNamespaces(metrics, client.Config.Namespaces)
logger.Info("Metrics filtered.")
logger.Debug("Metrics removed.", "removed_metrics", removedMetrics)
internal.PrometheusMetrics = internal.SetupPrometheusMetricsFromOtcMetrics(filteredMetrics, client.Logger)
logger.Info("Prometheus metrics initiated!")
for {
batchedMetricsResponse, err := client.GetMetricDataBatched(filteredMetrics)
if err != nil {
logger.Panic("Unable to retrieve batched metric data", "error", err)
}
logger.Info("Batch metrics retrieved.")
for _, metric := range batchedMetricsResponse {
if len(metric.Datapoints) == 0 {
continue
}
internal.PrometheusMetrics[internal.StandardPrometheusBatchMetricName(metric)].With(
prometheus.Labels{
"unit": metric.Unit,
"resource_id": metric.Dimensions[0].Value,
"resource_name": resourceIdToName[metric.Dimensions[0].Value],
}).Set(metric.Datapoints[len(metric.Datapoints)-1].Average)
logger.Debug("Prometheus metric set", "metric", internal.StandardPrometheusBatchMetricName(metric))
}
time.Sleep(config.WaitDuration)
}
}()
}
func FetchResourceIdToNameMapping(client *internal.OtcWrapper) (map[string]string, error) {
resourceIdToName := make(map[string]string)
if slices.Contains(client.Config.Namespaces, internal.EcsNamespace) {
result, err := client.GetEcsIdNameMapping()
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "ECS Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
if slices.Contains(client.Config.Namespaces, internal.RdsNamespace) {
result, err := client.GetRdsIdNameMapping()
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "RDS Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
if slices.Contains(client.Config.Namespaces, internal.DmsNamespace) {
result, err := client.GetDmsIdNameMapping()
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "DMS Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
if slices.Contains(client.Config.Namespaces, internal.NatNamespace) {
result, err := client.GetNatIdNameMapping()
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "NAT Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
if slices.Contains(client.Config.Namespaces, internal.ElbNamespace) {
result, err := client.GetElbIdNameMapping()
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "ELB Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
if slices.Contains(client.Config.Namespaces, internal.DdsNamespace) {
result, err := client.GetDdsIdNameMapping()
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "DDS Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
if slices.Contains(client.Config.Namespaces, internal.DcsNamespace) {
result, err := client.GetDcsIdNameMapping()
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "DCS Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
if slices.Contains(client.Config.Namespaces, internal.VpcNamespace) {
result, err := client.GetVpcIdNameMapping(client.Config.AuthenticationData.ProjectId)
if err != nil {
client.Logger.Error("Unable to map namespace!", "context", "VPC Name mapping")
return map[string]string{}, err
}
maps.Copy(resourceIdToName, result)
}
client.Logger.Info(fmt.Sprintf("Collected %d resources\n", len(resourceIdToName)))
return resourceIdToName, nil
}
func main() {
var (
port uint16
region string
namespaces []string
username string
password string
accessKey string
secretKey string
projectId string
osDomainName string
fetchResourceIdToname bool
waitDuration uint
logLevel string
)
var rootCmd = &cobra.Command{
Use: "otc-prometheus-exporter",
PreRunE: func(cmd *cobra.Command, args []string) error {
return cmdPackage.InitializeConfig(cmd, map[string]string{
"port": "PORT",
"region": "REGION",
"namespaces": "NAMESPACES",
"os-username": "OS_USERNAME",
"os-password": "OS_PASSWORD",
"access-key": "OS_ACCESS_KEY",
"secret-key": "OS_SECRET_KEY",
"projectId": "OS_PROJECT_ID",
"os-domain-name": "OS_DOMAIN_NAME",
"wait-duration": "WAITDURATION",
"fetch-resource-id-to-name": "FETCH_RESOURCE_ID_TO_NAME",
"log-level": "LOG_LEVEL",
})
},
RunE: func(cmd *cobra.Command, args []string) error {
// Add main log system, passed as dependency
logger := internal.NewLogger(logLevel)
//nolint:errcheck // not relevant
defer logger.Sync()
logger.Info("Env settings",
"port", port,
"region", region,
"namespaces", namespaces,
"waitDuration", waitDuration,
"fetchResourceIdToName", fetchResourceIdToname,
"logging", logLevel)
isAkSkAuthentication := false
switch {
case username != "" && password != "":
isAkSkAuthentication = false
case accessKey != "" && secretKey != "":
isAkSkAuthentication = true
default:
return errors.New("no valid authentication data provided. please provide either username and password or accessKey and secretKey")
}
otcRegion, err := internal.NewOtcRegionFromString(region)
if err != nil {
return err
}
namespaces = internal.ResolveOtcShortHandNamespace(namespaces, logger)
collectMetricsInBackground(internal.ConfigStruct{
Port: int(port),
Namespaces: namespaces,
WaitDuration: time.Duration(waitDuration) * time.Second,
ResourceIdNameMappingFlag: fetchResourceIdToname,
AuthenticationData: internal.AuthenticationData{
Username: username,
Password: password,
AccessKey: accessKey,
SecretKey: secretKey,
IsAkSkAuthentication: isAkSkAuthentication,
ProjectId: projectId,
DomainName: osDomainName,
Region: otcRegion,
},
}, logger)
http.Handle("/metrics", promhttp.Handler())
address := fmt.Sprintf(":%d", port)
err = http.ListenAndServe(address, nil)
return err
},
}
rootCmd.Flags().Uint16VarP(&port, "port", "", 39100, "Port on which metrics are served")
rootCmd.Flags().StringVarP(®ion, "region", "r", "eu-de", "region where your project is located ")
rootCmd.Flags().StringSliceVarP(&namespaces, "namespaces", "n", maps.Values(internal.OtcNamespacesMapping), "namespaces for instances you want to get the metrics from")
rootCmd.Flags().StringVarP(&username, "os-username", "u", "", "user in the OTC with access to the API. Must be provided together with password and can't be provided with AK/SK")
rootCmd.Flags().StringVarP(&password, "os-password", "p", "", "password for the user. Must be provided together with username and can't be provided with AK/SK")
rootCmd.Flags().StringVarP(&accessKey, "access-key", "", "", "you can instead of username/password also provide the users AK and SK")
rootCmd.Flags().StringVarP(&secretKey, "secret-key", "", "", "you can instead of username/password also provide the users AK and SK")
rootCmd.Flags().StringVarP(&projectId, "projectId", "", "", "project from which the metrics should be gathered")
rootCmd.Flags().StringVarP(&osDomainName, "os-domain-name", "", "", "Domainname/Tenant ID")
rootCmd.Flags().BoolVarP(&fetchResourceIdToname, "fetch-resource-id-to-name", "", false, "turns the mapping of resource id to resource name on or off")
rootCmd.Flags().UintVarP(&waitDuration, "wait-duration", "", 60, "time in seconds between two API call fetches")
rootCmd.Flags().StringVarP(&logLevel, "log-level", "", "", "type of logging to use")
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}