-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics_monitoring_exporter.go
346 lines (308 loc) · 10.6 KB
/
metrics_monitoring_exporter.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
/*
Copyright 2024 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// This is a modified version of https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/blob/exporter/metric/v0.46.0/exporter/metric/metric.go
package spanner
import (
"context"
"errors"
"fmt"
"math"
"reflect"
"sync"
"time"
monitoring "cloud.google.com/go/monitoring/apiv3/v2"
"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
"go.opentelemetry.io/otel/attribute"
otelmetric "go.opentelemetry.io/otel/sdk/metric"
otelmetricdata "go.opentelemetry.io/otel/sdk/metric/metricdata"
"google.golang.org/api/option"
"google.golang.org/genproto/googleapis/api/distribution"
googlemetricpb "google.golang.org/genproto/googleapis/api/metric"
monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres"
"google.golang.org/protobuf/types/known/timestamppb"
)
const (
spannerResourceType = "spanner_instance_client"
// The number of timeserieses to send to Google Cloud Monitoring in a single request. This
// is a hard limit in the GCM API, so we never want to exceed 200.
// https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.timeSeries/create
sendBatchSize = 200
)
var (
monitoredResLabelsSet = map[string]bool{
monitoredResLabelKeyProject: true,
monitoredResLabelKeyInstance: true,
monitoredResLabelKeyInstanceConfig: true,
monitoredResLabelKeyLocation: true,
monitoredResLabelKeyClientHash: true,
}
errShutdown = fmt.Errorf("exporter is shutdown")
)
type errUnexpectedAggregationKind struct {
kind string
}
func (e errUnexpectedAggregationKind) Error() string {
return fmt.Sprintf("the metric kind is unexpected: %v", e.kind)
}
// monitoringExporter is the implementation of OpenTelemetry metric exporter for
// Google Cloud Monitoring.
// Default exporter for built-in metrics
type monitoringExporter struct {
shutdown chan struct{}
client *monitoring.MetricClient
shutdownOnce sync.Once
projectID string
}
func newMonitoringExporter(ctx context.Context, project string, opts ...option.ClientOption) (*monitoringExporter, error) {
client, err := monitoring.NewMetricClient(ctx, opts...)
if err != nil {
return nil, err
}
return &monitoringExporter{
client: client,
shutdown: make(chan struct{}),
projectID: project,
}, nil
}
// ForceFlush does nothing, the exporter holds no state.
func (e *monitoringExporter) ForceFlush(ctx context.Context) error { return ctx.Err() }
// Shutdown shuts down the client connections.
func (e *monitoringExporter) Shutdown(ctx context.Context) error {
err := errShutdown
e.shutdownOnce.Do(func() {
close(e.shutdown)
err = errors.Join(ctx.Err(), e.client.Close())
})
return err
}
// Export exports OpenTelemetry Metrics to Google Cloud Monitoring.
func (me *monitoringExporter) Export(ctx context.Context, rm *otelmetricdata.ResourceMetrics) error {
select {
case <-me.shutdown:
return errShutdown
default:
}
return me.exportTimeSeries(ctx, rm)
}
// Temporality returns the Temporality to use for an instrument kind.
func (me *monitoringExporter) Temporality(ik otelmetric.InstrumentKind) otelmetricdata.Temporality {
return otelmetricdata.CumulativeTemporality
}
// Aggregation returns the Aggregation to use for an instrument kind.
func (me *monitoringExporter) Aggregation(ik otelmetric.InstrumentKind) otelmetric.Aggregation {
return otelmetric.DefaultAggregationSelector(ik)
}
// exportTimeSeries create TimeSeries from the records in cps.
// res should be the common resource among all TimeSeries, such as instance id, application name and so on.
func (me *monitoringExporter) exportTimeSeries(ctx context.Context, rm *otelmetricdata.ResourceMetrics) error {
tss, err := me.recordsToTimeSeriesPbs(rm)
if len(tss) == 0 {
return err
}
name := fmt.Sprintf("projects/%s", me.projectID)
errs := []error{err}
for i := 0; i < len(tss); i += sendBatchSize {
j := i + sendBatchSize
if j >= len(tss) {
j = len(tss)
}
req := &monitoringpb.CreateTimeSeriesRequest{
Name: name,
TimeSeries: tss[i:j],
}
errs = append(errs, me.client.CreateServiceTimeSeries(ctx, req))
}
return errors.Join(errs...)
}
// recordToMetricAndMonitoredResourcePbs converts data from records to Metric and Monitored resource proto type for Cloud Monitoring.
func (me *monitoringExporter) recordToMetricAndMonitoredResourcePbs(metrics otelmetricdata.Metrics, attributes attribute.Set) (*googlemetricpb.Metric, *monitoredrespb.MonitoredResource) {
mr := &monitoredrespb.MonitoredResource{
Type: spannerResourceType,
Labels: map[string]string{},
}
labels := make(map[string]string)
addAttributes := func(attr *attribute.Set) {
iter := attr.Iter()
for iter.Next() {
kv := iter.Attribute()
labelKey := string(kv.Key)
if _, isResLabel := monitoredResLabelsSet[labelKey]; isResLabel {
// Add labels to monitored resource
mr.Labels[labelKey] = kv.Value.Emit()
} else {
// Add labels to metric
labels[labelKey] = kv.Value.Emit()
}
}
}
addAttributes(&attributes)
return &googlemetricpb.Metric{
Type: metrics.Name,
Labels: labels,
}, mr
}
func (me *monitoringExporter) recordsToTimeSeriesPbs(rm *otelmetricdata.ResourceMetrics) ([]*monitoringpb.TimeSeries, error) {
var (
tss []*monitoringpb.TimeSeries
errs []error
)
for _, scope := range rm.ScopeMetrics {
if scope.Scope.Name != builtInMetricsMeterName {
// Filter out metric data for instruments that are not part of the spanner builtin metrics
continue
}
for _, metrics := range scope.Metrics {
ts, err := me.recordToTimeSeriesPb(metrics)
errs = append(errs, err)
tss = append(tss, ts...)
}
}
return tss, errors.Join(errs...)
}
// recordToTimeSeriesPb converts record to TimeSeries proto type with common resource.
// ref. https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries
func (me *monitoringExporter) recordToTimeSeriesPb(m otelmetricdata.Metrics) ([]*monitoringpb.TimeSeries, error) {
var tss []*monitoringpb.TimeSeries
var errs []error
if m.Data == nil {
return nil, nil
}
switch a := m.Data.(type) {
case otelmetricdata.Histogram[float64]:
for _, point := range a.DataPoints {
metric, mr := me.recordToMetricAndMonitoredResourcePbs(m, point.Attributes)
ts, err := histogramToTimeSeries(point, m, mr)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = metric
tss = append(tss, ts)
}
case otelmetricdata.Sum[int64]:
for _, point := range a.DataPoints {
metric, mr := me.recordToMetricAndMonitoredResourcePbs(m, point.Attributes)
var ts *monitoringpb.TimeSeries
var err error
ts, err = sumToTimeSeries[int64](point, m, mr)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = metric
tss = append(tss, ts)
}
default:
errs = append(errs, errUnexpectedAggregationKind{kind: reflect.TypeOf(m.Data).String()})
}
return tss, errors.Join(errs...)
}
func sumToTimeSeries[N int64 | float64](point otelmetricdata.DataPoint[N], metrics otelmetricdata.Metrics, mr *monitoredrespb.MonitoredResource) (*monitoringpb.TimeSeries, error) {
interval, err := toNonemptyTimeIntervalpb(point.StartTime, point.Time)
if err != nil {
return nil, err
}
value, valueType := numberDataPointToValue[N](point)
return &monitoringpb.TimeSeries{
Resource: mr,
Unit: string(metrics.Unit),
MetricKind: googlemetricpb.MetricDescriptor_CUMULATIVE,
ValueType: valueType,
Points: []*monitoringpb.Point{{
Interval: interval,
Value: value,
}},
}, nil
}
func histogramToTimeSeries[N int64 | float64](point otelmetricdata.HistogramDataPoint[N], metrics otelmetricdata.Metrics, mr *monitoredrespb.MonitoredResource) (*monitoringpb.TimeSeries, error) {
interval, err := toNonemptyTimeIntervalpb(point.StartTime, point.Time)
if err != nil {
return nil, err
}
distributionValue := histToDistribution(point)
return &monitoringpb.TimeSeries{
Resource: mr,
Unit: string(metrics.Unit),
MetricKind: googlemetricpb.MetricDescriptor_CUMULATIVE,
ValueType: googlemetricpb.MetricDescriptor_DISTRIBUTION,
Points: []*monitoringpb.Point{{
Interval: interval,
Value: &monitoringpb.TypedValue{
Value: &monitoringpb.TypedValue_DistributionValue{
DistributionValue: distributionValue,
},
},
}},
}, nil
}
func toNonemptyTimeIntervalpb(start, end time.Time) (*monitoringpb.TimeInterval, error) {
// The end time of a new interval must be at least a millisecond after the end time of the
// previous interval, for all non-gauge types.
// https://cloud.google.com/monitoring/api/ref_v3/rpc/google.monitoring.v3#timeinterval
if end.Sub(start).Milliseconds() <= 1 {
end = start.Add(time.Millisecond)
}
startpb := timestamppb.New(start)
endpb := timestamppb.New(end)
err := errors.Join(
startpb.CheckValid(),
endpb.CheckValid(),
)
if err != nil {
return nil, err
}
return &monitoringpb.TimeInterval{
StartTime: startpb,
EndTime: endpb,
}, nil
}
func histToDistribution[N int64 | float64](hist otelmetricdata.HistogramDataPoint[N]) *distribution.Distribution {
counts := make([]int64, len(hist.BucketCounts))
for i, v := range hist.BucketCounts {
counts[i] = int64(v)
}
var mean float64
if !math.IsNaN(float64(hist.Sum)) && hist.Count > 0 { // Avoid divide-by-zero
mean = float64(hist.Sum) / float64(hist.Count)
}
return &distribution.Distribution{
Count: int64(hist.Count),
Mean: mean,
BucketCounts: counts,
BucketOptions: &distribution.Distribution_BucketOptions{
Options: &distribution.Distribution_BucketOptions_ExplicitBuckets{
ExplicitBuckets: &distribution.Distribution_BucketOptions_Explicit{
Bounds: hist.Bounds,
},
},
},
}
}
func numberDataPointToValue[N int64 | float64](
point otelmetricdata.DataPoint[N],
) (*monitoringpb.TypedValue, googlemetricpb.MetricDescriptor_ValueType) {
switch v := any(point.Value).(type) {
case int64:
return &monitoringpb.TypedValue{Value: &monitoringpb.TypedValue_Int64Value{
Int64Value: v,
}},
googlemetricpb.MetricDescriptor_INT64
case float64:
return &monitoringpb.TypedValue{Value: &monitoringpb.TypedValue_DoubleValue{
DoubleValue: v,
}},
googlemetricpb.MetricDescriptor_DOUBLE
}
// It is impossible to reach this statement
return nil, googlemetricpb.MetricDescriptor_INT64
}