-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
scraper.go
477 lines (410 loc) · 13.8 KB
/
scraper.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package azuremonitorreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/azuremonitorreceiver"
import (
"bytes"
"context"
"fmt"
"regexp"
"sort"
"strings"
"sync"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/arm"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/monitor/armmonitor"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"go.opentelemetry.io/collector/receiver"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/azuremonitorreceiver/internal/metadata"
)
var (
timeGrains = map[string]int64{
"PT1M": 60,
"PT5M": 300,
"PT15M": 900,
"PT30M": 1800,
"PT1H": 3600,
"PT6H": 21600,
"PT12H": 43200,
"P1D": 86400,
}
aggregations = []string{
"Average",
"Count",
"Maximum",
"Minimum",
"Total",
}
)
const (
attributeLocation = "location"
attributeName = "name"
attributeResourceGroup = "resource_group"
attributeResourceType = "type"
metadataPrefix = "metadata_"
tagPrefix = "tags_"
)
type azureResource struct {
attributes map[string]*string
metricsByCompositeKey map[metricsCompositeKey]*azureResourceMetrics
metricsDefinitionsUpdated time.Time
tags map[string]*string
}
type metricsCompositeKey struct {
dimensions string // comma separated sorted dimensions
timeGrain string
}
type azureResourceMetrics struct {
metrics []string
metricsValuesUpdated time.Time
}
type void struct{}
func newScraper(conf *Config, settings receiver.CreateSettings) *azureScraper {
return &azureScraper{
cfg: conf,
settings: settings.TelemetrySettings,
mb: metadata.NewMetricsBuilder(conf.MetricsBuilderConfig, settings),
azIDCredentialsFunc: azidentity.NewClientSecretCredential,
azIDWorkloadFunc: azidentity.NewWorkloadIdentityCredential,
armClientFunc: armresources.NewClient,
armMonitorDefinitionsClientFunc: armmonitor.NewMetricDefinitionsClient,
armMonitorMetricsClientFunc: armmonitor.NewMetricsClient,
mutex: &sync.Mutex{},
}
}
type azureScraper struct {
cred azcore.TokenCredential
clientResources armClient
clientMetricsDefinitions metricsDefinitionsClientInterface
clientMetricsValues metricsValuesClient
cfg *Config
settings component.TelemetrySettings
resources map[string]*azureResource
resourcesUpdated time.Time
mb *metadata.MetricsBuilder
azIDCredentialsFunc func(string, string, string, *azidentity.ClientSecretCredentialOptions) (*azidentity.ClientSecretCredential, error)
azIDWorkloadFunc func(options *azidentity.WorkloadIdentityCredentialOptions) (*azidentity.WorkloadIdentityCredential, error)
armClientOptions *arm.ClientOptions
armClientFunc func(string, azcore.TokenCredential, *arm.ClientOptions) (*armresources.Client, error)
armMonitorDefinitionsClientFunc func(string, azcore.TokenCredential, *arm.ClientOptions) (*armmonitor.MetricDefinitionsClient, error)
armMonitorMetricsClientFunc func(string, azcore.TokenCredential, *arm.ClientOptions) (*armmonitor.MetricsClient, error)
mutex *sync.Mutex
}
type armClient interface {
NewListPager(options *armresources.ClientListOptions) *runtime.Pager[armresources.ClientListResponse]
}
func (s *azureScraper) getArmClientOptions() *arm.ClientOptions {
var cloudToUse cloud.Configuration
switch s.cfg.Cloud {
case azureGovernmentCloud:
cloudToUse = cloud.AzureGovernment
default:
cloudToUse = cloud.AzurePublic
}
options := arm.ClientOptions{
ClientOptions: azcore.ClientOptions{
Cloud: cloudToUse,
},
}
return &options
}
func (s *azureScraper) getArmClient() armClient {
client, _ := s.armClientFunc(s.cfg.SubscriptionID, s.cred, s.armClientOptions)
return client
}
type metricsDefinitionsClientInterface interface {
NewListPager(resourceURI string, options *armmonitor.MetricDefinitionsClientListOptions) *runtime.Pager[armmonitor.MetricDefinitionsClientListResponse]
}
func (s *azureScraper) getMetricsDefinitionsClient() metricsDefinitionsClientInterface {
client, _ := s.armMonitorDefinitionsClientFunc(s.cfg.SubscriptionID, s.cred, s.armClientOptions)
return client
}
type metricsValuesClient interface {
List(ctx context.Context, resourceURI string, options *armmonitor.MetricsClientListOptions) (
armmonitor.MetricsClientListResponse, error,
)
}
func (s *azureScraper) GetMetricsValuesClient() metricsValuesClient {
client, _ := s.armMonitorMetricsClientFunc(s.cfg.SubscriptionID, s.cred, s.armClientOptions)
return client
}
func (s *azureScraper) start(_ context.Context, _ component.Host) (err error) {
if err = s.loadCredentials(); err != nil {
return err
}
s.armClientOptions = s.getArmClientOptions()
s.clientResources = s.getArmClient()
s.clientMetricsDefinitions = s.getMetricsDefinitionsClient()
s.clientMetricsValues = s.GetMetricsValuesClient()
s.resources = map[string]*azureResource{}
return
}
func (s *azureScraper) loadCredentials() (err error) {
switch s.cfg.Authentication {
case servicePrincipal:
if s.cred, err = s.azIDCredentialsFunc(s.cfg.TenantID, s.cfg.ClientID, s.cfg.ClientSecret, nil); err != nil {
return err
}
case workloadIdentity:
if s.cred, err = s.azIDWorkloadFunc(nil); err != nil {
return err
}
default:
return fmt.Errorf("unknown authentication %v", s.cfg.Authentication)
}
return nil
}
func (s *azureScraper) scrape(ctx context.Context) (pmetric.Metrics, error) {
s.getResources(ctx)
resourcesIdsWithDefinitions := make(chan string)
go func() {
defer close(resourcesIdsWithDefinitions)
for resourceID := range s.resources {
s.getResourceMetricsDefinitions(ctx, resourceID)
resourcesIdsWithDefinitions <- resourceID
}
}()
var wg sync.WaitGroup
for resourceID := range resourcesIdsWithDefinitions {
wg.Add(1)
go func(resourceID string) {
defer wg.Done()
s.getResourceMetricsValues(ctx, resourceID)
}(resourceID)
}
wg.Wait()
return s.mb.Emit(
metadata.WithAzureMonitorSubscriptionID(s.cfg.SubscriptionID),
metadata.WithAzureMonitorTenantID(s.cfg.TenantID),
), nil
}
func (s *azureScraper) getResources(ctx context.Context) {
if time.Since(s.resourcesUpdated).Seconds() < s.cfg.CacheResources {
return
}
existingResources := map[string]void{}
for id := range s.resources {
existingResources[id] = void{}
}
filter := s.getResourcesFilter()
opts := &armresources.ClientListOptions{
Filter: &filter,
}
pager := s.clientResources.NewListPager(opts)
for pager.More() {
nextResult, err := pager.NextPage(ctx)
if err != nil {
s.settings.Logger.Error("failed to get Azure Resources data", zap.Error(err))
return
}
for _, resource := range nextResult.Value {
if _, ok := s.resources[*resource.ID]; !ok {
resourceGroup := getResourceGroupFromID(*resource.ID)
attributes := map[string]*string{
attributeName: resource.Name,
attributeResourceGroup: &resourceGroup,
attributeResourceType: resource.Type,
}
if resource.Location != nil {
attributes[attributeLocation] = resource.Location
}
s.resources[*resource.ID] = &azureResource{
attributes: attributes,
tags: resource.Tags,
}
}
delete(existingResources, *resource.ID)
}
}
if len(existingResources) > 0 {
for idToDelete := range existingResources {
delete(s.resources, idToDelete)
}
}
s.resourcesUpdated = time.Now()
}
func getResourceGroupFromID(id string) string {
var s = regexp.MustCompile(`\/resourcegroups/([^\/]+)\/`)
match := s.FindStringSubmatch(strings.ToLower(id))
if len(match) == 2 {
return match[1]
}
return ""
}
func (s *azureScraper) getResourcesFilter() string {
// TODO: switch to parsing services from
// https://learn.microsoft.com/en-us/azure/azure-monitor/essentials/metrics-supported
resourcesTypeFilter := strings.Join(s.cfg.Services, "' or resourceType eq '")
resourcesGroupFilterString := ""
if len(s.cfg.ResourceGroups) > 0 {
resourcesGroupFilterString = fmt.Sprintf(" and (resourceGroup eq '%s')",
strings.Join(s.cfg.ResourceGroups, "' or resourceGroup eq '"))
}
return fmt.Sprintf("(resourceType eq '%s')%s", resourcesTypeFilter, resourcesGroupFilterString)
}
func (s *azureScraper) getResourceMetricsDefinitions(ctx context.Context, resourceID string) {
if time.Since(s.resources[resourceID].metricsDefinitionsUpdated).Seconds() < s.cfg.CacheResourcesDefinitions {
return
}
s.resources[resourceID].metricsByCompositeKey = map[metricsCompositeKey]*azureResourceMetrics{}
pager := s.clientMetricsDefinitions.NewListPager(resourceID, nil)
for pager.More() {
nextResult, err := pager.NextPage(ctx)
if err != nil {
s.settings.Logger.Error("failed to get Azure Metrics definitions data", zap.Error(err))
return
}
for _, v := range nextResult.Value {
timeGrain := *v.MetricAvailabilities[0].TimeGrain
name := *v.Name.Value
compositeKey := metricsCompositeKey{timeGrain: timeGrain}
if len(v.Dimensions) > 0 {
var dimensionsSlice []string
for _, dimension := range v.Dimensions {
if len(strings.TrimSpace(*dimension.Value)) > 0 {
dimensionsSlice = append(dimensionsSlice, *dimension.Value)
}
}
sort.Strings(dimensionsSlice)
compositeKey.dimensions = strings.Join(dimensionsSlice, ",")
}
s.storeMetricsDefinition(resourceID, name, compositeKey)
}
}
s.resources[resourceID].metricsDefinitionsUpdated = time.Now()
}
func (s *azureScraper) storeMetricsDefinition(resourceID, name string, compositeKey metricsCompositeKey) {
if _, ok := s.resources[resourceID].metricsByCompositeKey[compositeKey]; ok {
s.resources[resourceID].metricsByCompositeKey[compositeKey].metrics = append(
s.resources[resourceID].metricsByCompositeKey[compositeKey].metrics, name,
)
} else {
s.resources[resourceID].metricsByCompositeKey[compositeKey] = &azureResourceMetrics{metrics: []string{name}}
}
}
func (s *azureScraper) getResourceMetricsValues(ctx context.Context, resourceID string) {
res := *s.resources[resourceID]
for compositeKey, metricsByGrain := range res.metricsByCompositeKey {
if time.Since(metricsByGrain.metricsValuesUpdated).Seconds() < float64(timeGrains[compositeKey.timeGrain]) {
continue
}
metricsByGrain.metricsValuesUpdated = time.Now()
start := 0
for start < len(metricsByGrain.metrics) {
end := start + s.cfg.MaximumNumberOfMetricsInACall
if end > len(metricsByGrain.metrics) {
end = len(metricsByGrain.metrics)
}
opts := getResourceMetricsValuesRequestOptions(
metricsByGrain.metrics,
compositeKey.dimensions,
compositeKey.timeGrain,
start,
end,
)
start = end
result, err := s.clientMetricsValues.List(
ctx,
resourceID,
&opts,
)
if err != nil {
s.settings.Logger.Error("failed to get Azure Metrics values data", zap.Error(err))
return
}
for _, metric := range result.Value {
for _, timeseriesElement := range metric.Timeseries {
if timeseriesElement.Data != nil {
attributes := map[string]*string{}
for name, value := range res.attributes {
attributes[name] = value
}
for _, value := range timeseriesElement.Metadatavalues {
name := metadataPrefix + *value.Name.Value
attributes[name] = value.Value
}
if s.cfg.AppendTagsAsAttributes {
for tagName, value := range res.tags {
name := tagPrefix + tagName
attributes[name] = value
}
}
for _, metricValue := range timeseriesElement.Data {
s.processTimeseriesData(resourceID, metric, metricValue, attributes)
}
}
}
}
}
}
}
func getResourceMetricsValuesRequestOptions(
metrics []string,
dimensionsStr string,
timeGrain string,
start int,
end int,
) armmonitor.MetricsClientListOptions {
resType := strings.Join(metrics[start:end], ",")
filter := armmonitor.MetricsClientListOptions{
Metricnames: &resType,
Interval: to.Ptr(timeGrain),
Timespan: to.Ptr(timeGrain),
Aggregation: to.Ptr(strings.Join(aggregations, ",")),
}
if len(dimensionsStr) > 0 {
var dimensionsFilter bytes.Buffer
dimensions := strings.Split(dimensionsStr, ",")
for i, dimension := range dimensions {
dimensionsFilter.WriteString(dimension)
dimensionsFilter.WriteString(" eq '*' ")
if i < len(dimensions)-1 {
dimensionsFilter.WriteString(" and ")
}
}
dimensionFilterString := dimensionsFilter.String()
filter.Filter = &dimensionFilterString
}
return filter
}
func (s *azureScraper) processTimeseriesData(
resourceID string,
metric *armmonitor.Metric,
metricValue *armmonitor.MetricValue,
attributes map[string]*string,
) {
s.mutex.Lock()
defer s.mutex.Unlock()
ts := pcommon.NewTimestampFromTime(time.Now())
aggregationsData := []struct {
name string
value *float64
}{
{"Average", metricValue.Average},
{"Count", metricValue.Count},
{"Maximum", metricValue.Maximum},
{"Minimum", metricValue.Minimum},
{"Total", metricValue.Total},
}
for _, aggregation := range aggregationsData {
if aggregation.value != nil {
s.mb.AddDataPoint(
resourceID,
*metric.Name.Value,
aggregation.name,
string(*metric.Unit),
attributes,
ts,
*aggregation.value,
)
}
}
}