-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
azureresourcemetrics_unmarshaler.go
170 lines (144 loc) · 6.08 KB
/
azureresourcemetrics_unmarshaler.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package azureeventhubreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/azureeventhubreceiver"
import (
"bytes"
"fmt"
"strings"
"time"
eventhub "github.com/Azure/azure-event-hubs-go/v3"
jsoniter "github.com/json-iterator/go"
"github.com/relvacode/iso8601"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
conventions "go.opentelemetry.io/collector/semconv/v1.27.0"
"go.uber.org/zap"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/azureeventhubreceiver/internal/metadata"
)
const azureResourceID = "azure.resource.id"
type azureResourceMetricsUnmarshaler struct {
buildInfo component.BuildInfo
logger *zap.Logger
TimeFormat []string
}
// azureMetricRecords represents an array of Azure metric records
// as exported via an Azure Event Hub
type azureMetricRecords struct {
Records []azureMetricRecord `json:"records"`
}
// azureMetricRecord represents a single Azure Metric following
// the common schema does not exist (yet):
type azureMetricRecord struct {
Time string `json:"time"`
ResourceID string `json:"resourceId"`
MetricName string `json:"metricName"`
TimeGrain string `json:"timeGrain"`
Total float64 `json:"total"`
Count float64 `json:"count"`
Minimum float64 `json:"minimum"`
Maximum float64 `json:"maximum"`
Average float64 `json:"average"`
}
func newAzureResourceMetricsUnmarshaler(buildInfo component.BuildInfo, logger *zap.Logger, timeFormat []string) eventMetricsUnmarshaler {
return azureResourceMetricsUnmarshaler{
buildInfo: buildInfo,
logger: logger,
TimeFormat: timeFormat,
}
}
// UnmarshalMetrics takes a byte array containing a JSON-encoded
// payload with Azure metric records and transforms it into
// an OpenTelemetry pmetric.Metrics object. The data in the Azure
// metric record appears as fields and attributes in the
// OpenTelemetry representation;
func (r azureResourceMetricsUnmarshaler) UnmarshalMetrics(event *eventhub.Event) (pmetric.Metrics, error) {
md := pmetric.NewMetrics()
var azureMetrics azureMetricRecords
decoder := jsoniter.NewDecoder(bytes.NewReader(event.Data))
err := decoder.Decode(&azureMetrics)
if err != nil {
return md, err
}
resourceMetrics := md.ResourceMetrics().AppendEmpty()
resource := resourceMetrics.Resource()
resource.Attributes().PutStr(conventions.AttributeTelemetrySDKName, metadata.ScopeName)
resource.Attributes().PutStr(conventions.AttributeTelemetrySDKLanguage, conventions.AttributeTelemetrySDKLanguageGo)
resource.Attributes().PutStr(conventions.AttributeTelemetrySDKVersion, r.buildInfo.Version)
resource.Attributes().PutStr(conventions.AttributeCloudProvider, conventions.AttributeCloudProviderAzure)
scopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()
metrics := scopeMetrics.Metrics()
metrics.EnsureCapacity(len(azureMetrics.Records) * 5)
resourceID := ""
for _, azureMetric := range azureMetrics.Records {
if resourceID == "" && azureMetric.ResourceID != "" {
resourceID = azureMetric.ResourceID
}
nanos, err := asTimestamp(azureMetric.Time, r.TimeFormat)
if err != nil {
r.logger.Warn("Invalid Timestamp", zap.String("time", azureMetric.Time))
continue
}
var startTimestamp pcommon.Timestamp
if azureMetric.TimeGrain == "PT1M" {
startTimestamp = pcommon.NewTimestampFromTime(nanos.AsTime().Add(-time.Minute))
} else {
r.logger.Warn("Unhandled Time Grain", zap.String("timegrain", azureMetric.TimeGrain))
continue
}
metricTotal := metrics.AppendEmpty()
metricTotal.SetName(strings.ToLower(fmt.Sprintf("%s_%s", strings.ReplaceAll(azureMetric.MetricName, " ", "_"), "Total")))
dpTotal := metricTotal.SetEmptyGauge().DataPoints().AppendEmpty()
dpTotal.SetStartTimestamp(startTimestamp)
dpTotal.SetTimestamp(nanos)
dpTotal.SetDoubleValue(azureMetric.Total)
metricCount := metrics.AppendEmpty()
metricCount.SetName(strings.ToLower(fmt.Sprintf("%s_%s", strings.ReplaceAll(azureMetric.MetricName, " ", "_"), "Count")))
dpCount := metricCount.SetEmptyGauge().DataPoints().AppendEmpty()
dpCount.SetStartTimestamp(startTimestamp)
dpCount.SetTimestamp(nanos)
dpCount.SetDoubleValue(azureMetric.Count)
metricMin := metrics.AppendEmpty()
metricMin.SetName(strings.ToLower(fmt.Sprintf("%s_%s", strings.ReplaceAll(azureMetric.MetricName, " ", "_"), "Minimum")))
dpMin := metricMin.SetEmptyGauge().DataPoints().AppendEmpty()
dpMin.SetStartTimestamp(startTimestamp)
dpMin.SetTimestamp(nanos)
dpMin.SetDoubleValue(azureMetric.Minimum)
metricMax := metrics.AppendEmpty()
metricMax.SetName(strings.ToLower(fmt.Sprintf("%s_%s", strings.ReplaceAll(azureMetric.MetricName, " ", "_"), "Maximum")))
dpMax := metricMax.SetEmptyGauge().DataPoints().AppendEmpty()
dpMax.SetStartTimestamp(startTimestamp)
dpMax.SetTimestamp(nanos)
dpMax.SetDoubleValue(azureMetric.Maximum)
metricAverage := metrics.AppendEmpty()
metricAverage.SetName(strings.ToLower(fmt.Sprintf("%s_%s", strings.ReplaceAll(azureMetric.MetricName, " ", "_"), "Average")))
dpAverage := metricAverage.SetEmptyGauge().DataPoints().AppendEmpty()
dpAverage.SetStartTimestamp(startTimestamp)
dpAverage.SetTimestamp(nanos)
dpAverage.SetDoubleValue(azureMetric.Average)
}
if resourceID != "" {
resourceMetrics.Resource().Attributes().PutStr(azureResourceID, resourceID)
} else {
r.logger.Warn("No ResourceID Set on Metrics!")
}
return md, nil
}
// asTimestamp will parse an ISO8601 string into an OpenTelemetry
// nanosecond timestamp. If the string cannot be parsed, it will
// return zero and the error.
func asTimestamp(s string, formats []string) (pcommon.Timestamp, error) {
var err error
var t time.Time
// Try parsing with provided formats first
for _, format := range formats {
if t, err = time.Parse(format, s); err == nil {
return pcommon.Timestamp(t.UnixNano()), nil
}
}
// Fallback to ISO 8601 parsing if no format matches
if t, err = iso8601.ParseString(s); err == nil {
return pcommon.Timestamp(t.UnixNano()), nil
}
return 0, err
}