-
Notifications
You must be signed in to change notification settings - Fork 104
/
Copy pathmetric.go
890 lines (818 loc) · 29.4 KB
/
metric.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
// Copyright 2021 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.
package metric
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"math"
"net/url"
"reflect"
"sort"
"strings"
"sync"
"time"
"unicode"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/sdk/instrumentation"
"go.opentelemetry.io/otel/sdk/metric"
"go.opentelemetry.io/otel/sdk/metric/metricdata"
"go.opentelemetry.io/otel/sdk/resource"
"go.opentelemetry.io/otel/trace"
monitoring "cloud.google.com/go/monitoring/apiv3/v2"
"cloud.google.com/go/monitoring/apiv3/v2/monitoringpb"
"github.com/googleapis/gax-go/v2"
"google.golang.org/api/option"
"google.golang.org/genproto/googleapis/api/distribution"
"google.golang.org/genproto/googleapis/api/label"
googlemetricpb "google.golang.org/genproto/googleapis/api/metric"
monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres"
"google.golang.org/grpc"
"google.golang.org/grpc/encoding/gzip"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/timestamppb"
"github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping"
)
const (
// The number of timeserieses to send to GCM in a single request. This
// is a hard limit in the GCM API, so we never want to exceed 200.
sendBatchSize = 200
cloudMonitoringMetricDescriptorNameFormat = "workload.googleapis.com/%s"
platformMappingMonitoredResourceKey = "gcp.resource_type"
)
// key is used to judge the uniqueness of the record descriptor.
type key struct {
name string
libraryname string
}
func keyOf(metrics metricdata.Metrics, library instrumentation.Scope) key {
return key{
name: metrics.Name,
libraryname: library.Name,
}
}
// metricExporter is the implementation of OpenTelemetry metric exporter for
// Google Cloud Monitoring.
type metricExporter struct {
o *options
shutdown chan struct{}
// mdCache is the cache to hold MetricDescriptor to avoid creating duplicate MD.
mdCache map[key]*googlemetricpb.MetricDescriptor
client *monitoring.MetricClient
mdLock sync.RWMutex
shutdownOnce sync.Once
}
// ForceFlush does nothing, the exporter holds no state.
func (e *metricExporter) ForceFlush(ctx context.Context) error { return ctx.Err() }
// Shutdown shuts down the client connections.
func (e *metricExporter) Shutdown(ctx context.Context) error {
err := errShutdown
e.shutdownOnce.Do(func() {
close(e.shutdown)
err = errors.Join(ctx.Err(), e.client.Close())
})
return err
}
// newMetricExporter returns an exporter that uploads OTel metric data to Google Cloud Monitoring.
func newMetricExporter(o *options) (*metricExporter, error) {
if strings.TrimSpace(o.projectID) == "" {
return nil, errBlankProjectID
}
clientOpts := append([]option.ClientOption{option.WithGRPCDialOption(grpc.WithUserAgent(userAgent))}, o.monitoringClientOptions...)
ctx := o.context
if ctx == nil {
ctx = context.Background()
}
client, err := monitoring.NewMetricClient(ctx, clientOpts...)
if err != nil {
return nil, err
}
if o.compression == "gzip" {
client.CallOptions.GetMetricDescriptor = append(client.CallOptions.GetMetricDescriptor,
gax.WithGRPCOptions(grpc.UseCompressor(gzip.Name)))
client.CallOptions.CreateMetricDescriptor = append(client.CallOptions.CreateMetricDescriptor,
gax.WithGRPCOptions(grpc.UseCompressor(gzip.Name)))
client.CallOptions.CreateTimeSeries = append(client.CallOptions.CreateTimeSeries,
gax.WithGRPCOptions(grpc.UseCompressor(gzip.Name)))
client.CallOptions.CreateServiceTimeSeries = append(client.CallOptions.CreateServiceTimeSeries,
gax.WithGRPCOptions(grpc.UseCompressor(gzip.Name)))
}
cache := map[key]*googlemetricpb.MetricDescriptor{}
e := &metricExporter{
o: o,
mdCache: cache,
client: client,
shutdown: make(chan struct{}),
}
return e, nil
}
var errShutdown = fmt.Errorf("exporter is shutdown")
// Export exports OpenTelemetry Metrics to Google Cloud Monitoring.
func (me *metricExporter) Export(ctx context.Context, rm *metricdata.ResourceMetrics) error {
select {
case <-me.shutdown:
return errShutdown
default:
}
if me.o.destinationProjectQuota {
ctx = metadata.NewOutgoingContext(ctx, metadata.New(map[string]string{"x-goog-user-project": strings.TrimPrefix(me.o.projectID, "projects/")}))
}
return errors.Join(
me.exportMetricDescriptor(ctx, rm),
me.exportTimeSeries(ctx, rm),
)
}
// Temporality returns the Temporality to use for an instrument kind.
func (me *metricExporter) Temporality(ik metric.InstrumentKind) metricdata.Temporality {
return metric.DefaultTemporalitySelector(ik)
}
// Aggregation returns the Aggregation to use for an instrument kind.
func (me *metricExporter) Aggregation(ik metric.InstrumentKind) metric.Aggregation {
return metric.DefaultAggregationSelector(ik)
}
// exportMetricDescriptor create MetricDescriptor from the record
// if the descriptor is not registered in Cloud Monitoring yet.
func (me *metricExporter) exportMetricDescriptor(ctx context.Context, rm *metricdata.ResourceMetrics) error {
// We only send metric descriptors if we're configured *and* we're not sending service timeseries.
if me.o.disableCreateMetricDescriptors {
return nil
}
me.mdLock.Lock()
defer me.mdLock.Unlock()
mds := make(map[key]*googlemetricpb.MetricDescriptor)
extraLabels := me.extraLabelsFromResource(rm.Resource)
for _, scope := range rm.ScopeMetrics {
for _, metrics := range scope.Metrics {
k := keyOf(metrics, scope.Scope)
if _, ok := me.mdCache[k]; ok {
continue
}
if _, localok := mds[k]; !localok {
md := me.recordToMdpb(metrics, extraLabels)
mds[k] = md
}
}
}
// TODO: This process is synchronous and blocks longer time if records in cps
// have many different descriptors. In the cps.ForEach above, it should spawn
// goroutines to send CreateMetricDescriptorRequest asynchronously in the case
// the descriptor does not exist in global cache (me.mdCache).
// See details in #26.
var errs []error
for kmd, md := range mds {
err := me.createMetricDescriptorIfNeeded(ctx, md)
if err == nil {
me.mdCache[kmd] = md
}
errs = append(errs, err)
}
return errors.Join(errs...)
}
func (me *metricExporter) createMetricDescriptorIfNeeded(ctx context.Context, md *googlemetricpb.MetricDescriptor) error {
mdReq := &monitoringpb.GetMetricDescriptorRequest{
Name: fmt.Sprintf("projects/%s/metricDescriptors/%s", me.o.projectID, md.Type),
}
_, err := me.client.GetMetricDescriptor(ctx, mdReq)
if err == nil {
// If the metric descriptor already exists, skip the CreateMetricDescriptor call.
// Metric descriptors cannot be updated without deleting them first, so there
// isn't anything we can do here:
// https://cloud.google.com/monitoring/custom-metrics/creating-metrics#md-modify
return nil
}
req := &monitoringpb.CreateMetricDescriptorRequest{
Name: fmt.Sprintf("projects/%s", me.o.projectID),
MetricDescriptor: md,
}
_, err = me.client.CreateMetricDescriptor(ctx, req)
return err
}
// 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 *metricExporter) exportTimeSeries(ctx context.Context, rm *metricdata.ResourceMetrics) error {
tss, err := me.recordsToTspbs(rm)
if len(tss) == 0 {
return err
}
name := fmt.Sprintf("projects/%s", me.o.projectID)
errs := []error{err}
for i := 0; i < len(tss); i += sendBatchSize {
j := i + sendBatchSize
if j >= len(tss) {
j = len(tss)
}
// TODO: When this exporter is rewritten, support writing to multiple
// projects based on the "gcp.project.id" resource.
req := &monitoringpb.CreateTimeSeriesRequest{
Name: name,
TimeSeries: tss[i:j],
}
if me.o.createServiceTimeSeries {
errs = append(errs, me.client.CreateServiceTimeSeries(ctx, req))
} else {
errs = append(errs, me.client.CreateTimeSeries(ctx, req))
}
}
return errors.Join(errs...)
}
func (me *metricExporter) extraLabelsFromResource(res *resource.Resource) *attribute.Set {
set, _ := attribute.NewSetWithFiltered(res.Attributes(), me.o.resourceAttributeFilter)
return &set
}
// descToMetricType converts descriptor to MetricType proto type.
// Basically this returns default value ("workload.googleapis.com/[metric type]").
func (me *metricExporter) descToMetricType(desc metricdata.Metrics) string {
if formatter := me.o.metricDescriptorTypeFormatter; formatter != nil {
return formatter(desc)
}
return fmt.Sprintf(cloudMonitoringMetricDescriptorNameFormat, desc.Name)
}
// metricTypeToDisplayName takes a GCM metric type, like (workload.googleapis.com/MyCoolMetric) and returns the display name.
func metricTypeToDisplayName(mURL string) string {
// strip domain, keep path after domain.
u, err := url.Parse(fmt.Sprintf("metrics://%s", mURL))
if err != nil || u.Path == "" {
return mURL
}
return strings.TrimLeft(u.Path, "/")
}
// recordToMdpb extracts data and converts them to googlemetricpb.MetricDescriptor.
func (me *metricExporter) recordToMdpb(metrics metricdata.Metrics, extraLabels *attribute.Set) *googlemetricpb.MetricDescriptor {
name := metrics.Name
typ := me.descToMetricType(metrics)
kind, valueType := recordToMdpbKindType(metrics.Data)
// Detailed explanations on MetricDescriptor proto is not documented on
// generated Go packages. Refer to the original proto file.
// https://github.com/googleapis/googleapis/blob/50af053/google/api/metric.proto#L33
return &googlemetricpb.MetricDescriptor{
Name: name,
DisplayName: metricTypeToDisplayName(typ),
Type: typ,
MetricKind: kind,
ValueType: valueType,
Unit: string(metrics.Unit),
Description: metrics.Description,
Labels: labelDescriptors(metrics, extraLabels),
}
}
func labelDescriptors(metrics metricdata.Metrics, extraLabels *attribute.Set) []*label.LabelDescriptor {
labels := []*label.LabelDescriptor{}
seenKeys := map[string]struct{}{}
addAttributes := func(attr *attribute.Set) {
iter := attr.Iter()
for iter.Next() {
kv := iter.Attribute()
// Skip keys that have already been set
if _, ok := seenKeys[normalizeLabelKey(string(kv.Key))]; ok {
continue
}
labels = append(labels, &label.LabelDescriptor{
Key: normalizeLabelKey(string(kv.Key)),
})
seenKeys[normalizeLabelKey(string(kv.Key))] = struct{}{}
}
}
addAttributes(extraLabels)
switch a := metrics.Data.(type) {
case metricdata.Gauge[int64]:
for _, pt := range a.DataPoints {
addAttributes(&pt.Attributes)
}
case metricdata.Gauge[float64]:
for _, pt := range a.DataPoints {
addAttributes(&pt.Attributes)
}
case metricdata.Sum[int64]:
for _, pt := range a.DataPoints {
addAttributes(&pt.Attributes)
}
case metricdata.Sum[float64]:
for _, pt := range a.DataPoints {
addAttributes(&pt.Attributes)
}
case metricdata.Histogram[float64]:
for _, pt := range a.DataPoints {
addAttributes(&pt.Attributes)
}
case metricdata.Histogram[int64]:
for _, pt := range a.DataPoints {
addAttributes(&pt.Attributes)
}
}
return labels
}
type attributes struct {
attrs attribute.Set
}
func (attrs *attributes) GetString(key string) (string, bool) {
value, ok := attrs.attrs.Value(attribute.Key(key))
return value.AsString(), ok
}
// resourceToMonitoredResourcepb converts resource in OTel to MonitoredResource
// proto type for Cloud Monitoring.
//
// https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.monitoredResourceDescriptors
func (me *metricExporter) resourceToMonitoredResourcepb(res *resource.Resource) *monitoredrespb.MonitoredResource {
platformMrType, platformMappingRequested := res.Set().Value(platformMappingMonitoredResourceKey)
// check if platform mapping is requested and possible
if platformMappingRequested && platformMrType.AsString() == me.o.monitoredResourceDescription.mrType {
// assemble attributes required to construct this MR
attributeMap := make(map[string]string)
for expectedLabel := range me.o.monitoredResourceDescription.mrLabels {
value, found := res.Set().Value(attribute.Key(expectedLabel))
if found {
attributeMap[expectedLabel] = value.AsString()
}
}
return &monitoredrespb.MonitoredResource{
Type: platformMrType.AsString(),
Labels: attributeMap,
}
}
gmr := resourcemapping.ResourceAttributesToMonitoringMonitoredResource(&attributes{
attrs: attribute.NewSet(res.Attributes()...),
})
newLabels := make(map[string]string, len(gmr.Labels))
for k, v := range gmr.Labels {
newLabels[k] = sanitizeUTF8(v)
}
mr := &monitoredrespb.MonitoredResource{
Type: gmr.Type,
Labels: newLabels,
}
return mr
}
// recordToMdpbKindType return the mapping from OTel's record descriptor to
// Cloud Monitoring's MetricKind and ValueType.
func recordToMdpbKindType(a metricdata.Aggregation) (googlemetricpb.MetricDescriptor_MetricKind, googlemetricpb.MetricDescriptor_ValueType) {
switch agg := a.(type) {
case metricdata.Gauge[int64]:
return googlemetricpb.MetricDescriptor_GAUGE, googlemetricpb.MetricDescriptor_INT64
case metricdata.Gauge[float64]:
return googlemetricpb.MetricDescriptor_GAUGE, googlemetricpb.MetricDescriptor_DOUBLE
case metricdata.Sum[int64]:
if agg.IsMonotonic {
return googlemetricpb.MetricDescriptor_CUMULATIVE, googlemetricpb.MetricDescriptor_INT64
}
return googlemetricpb.MetricDescriptor_GAUGE, googlemetricpb.MetricDescriptor_INT64
case metricdata.Sum[float64]:
if agg.IsMonotonic {
return googlemetricpb.MetricDescriptor_CUMULATIVE, googlemetricpb.MetricDescriptor_DOUBLE
}
return googlemetricpb.MetricDescriptor_GAUGE, googlemetricpb.MetricDescriptor_DOUBLE
case metricdata.Histogram[int64], metricdata.Histogram[float64]:
return googlemetricpb.MetricDescriptor_CUMULATIVE, googlemetricpb.MetricDescriptor_DISTRIBUTION
default:
return googlemetricpb.MetricDescriptor_METRIC_KIND_UNSPECIFIED, googlemetricpb.MetricDescriptor_VALUE_TYPE_UNSPECIFIED
}
}
// recordToMpb converts data from records to Metric proto type for Cloud Monitoring.
func (me *metricExporter) recordToMpb(metrics metricdata.Metrics, attributes attribute.Set, library instrumentation.Scope, extraLabels *attribute.Set) *googlemetricpb.Metric {
me.mdLock.RLock()
defer me.mdLock.RUnlock()
k := keyOf(metrics, library)
md, ok := me.mdCache[k]
if !ok {
md = me.recordToMdpb(metrics, extraLabels)
}
labels := make(map[string]string)
addAttributes := func(attr *attribute.Set) {
iter := attr.Iter()
for iter.Next() {
kv := iter.Attribute()
labels[normalizeLabelKey(string(kv.Key))] = sanitizeUTF8(kv.Value.Emit())
}
}
addAttributes(extraLabels)
addAttributes(&attributes)
return &googlemetricpb.Metric{
Type: md.Type,
Labels: labels,
}
}
// recordToTspb converts record to TimeSeries proto type with common resource.
// ref. https://cloud.google.com/monitoring/api/ref_v3/rest/v3/TimeSeries
func (me *metricExporter) recordToTspb(m metricdata.Metrics, mr *monitoredrespb.MonitoredResource, library instrumentation.Scope, extraLabels *attribute.Set) ([]*monitoringpb.TimeSeries, error) {
var tss []*monitoringpb.TimeSeries
var errs []error
if m.Data == nil {
return nil, nil
}
switch a := m.Data.(type) {
case metricdata.Gauge[int64]:
for _, point := range a.DataPoints {
ts, err := gaugeToTimeSeries[int64](point, m, mr)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
case metricdata.Gauge[float64]:
for _, point := range a.DataPoints {
ts, err := gaugeToTimeSeries[float64](point, m, mr)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
case metricdata.Sum[int64]:
for _, point := range a.DataPoints {
var ts *monitoringpb.TimeSeries
var err error
if a.IsMonotonic {
ts, err = sumToTimeSeries[int64](point, m, mr)
} else {
// Send non-monotonic sums as gauges
ts, err = gaugeToTimeSeries[int64](point, m, mr)
}
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
case metricdata.Sum[float64]:
for _, point := range a.DataPoints {
var ts *monitoringpb.TimeSeries
var err error
if a.IsMonotonic {
ts, err = sumToTimeSeries[float64](point, m, mr)
} else {
// Send non-monotonic sums as gauges
ts, err = gaugeToTimeSeries[float64](point, m, mr)
}
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
case metricdata.Histogram[int64]:
for _, point := range a.DataPoints {
ts, err := histogramToTimeSeries(point, m, mr, me.o.enableSumOfSquaredDeviation, me.o.projectID)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
case metricdata.Histogram[float64]:
for _, point := range a.DataPoints {
ts, err := histogramToTimeSeries(point, m, mr, me.o.enableSumOfSquaredDeviation, me.o.projectID)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
case metricdata.ExponentialHistogram[int64]:
for _, point := range a.DataPoints {
ts, err := expHistogramToTimeSeries(point, m, mr, me.o.enableSumOfSquaredDeviation, me.o.projectID)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
case metricdata.ExponentialHistogram[float64]:
for _, point := range a.DataPoints {
ts, err := expHistogramToTimeSeries(point, m, mr, me.o.enableSumOfSquaredDeviation, me.o.projectID)
if err != nil {
errs = append(errs, err)
continue
}
ts.Metric = me.recordToMpb(m, point.Attributes, library, extraLabels)
tss = append(tss, ts)
}
default:
errs = append(errs, errUnexpectedAggregationKind{kind: reflect.TypeOf(m.Data).String()})
}
return tss, errors.Join(errs...)
}
func (me *metricExporter) recordsToTspbs(rm *metricdata.ResourceMetrics) ([]*monitoringpb.TimeSeries, error) {
mr := me.resourceToMonitoredResourcepb(rm.Resource)
extraLabels := me.extraLabelsFromResource(rm.Resource)
var (
tss []*monitoringpb.TimeSeries
errs []error
)
for _, scope := range rm.ScopeMetrics {
for _, metrics := range scope.Metrics {
ts, err := me.recordToTspb(metrics, mr, scope.Scope, extraLabels)
errs = append(errs, err)
tss = append(tss, ts...)
}
}
return tss, errors.Join(errs...)
}
func sanitizeUTF8(s string) string {
return strings.ToValidUTF8(s, "�")
}
func gaugeToTimeSeries[N int64 | float64](point metricdata.DataPoint[N], metrics metricdata.Metrics, mr *monitoredrespb.MonitoredResource) (*monitoringpb.TimeSeries, error) {
value, valueType := numberDataPointToValue(point)
timestamp := timestamppb.New(point.Time)
if err := timestamp.CheckValid(); err != nil {
return nil, err
}
return &monitoringpb.TimeSeries{
Resource: mr,
Unit: string(metrics.Unit),
MetricKind: googlemetricpb.MetricDescriptor_GAUGE,
ValueType: valueType,
Points: []*monitoringpb.Point{{
Interval: &monitoringpb.TimeInterval{
EndTime: timestamp,
},
Value: value,
}},
}, nil
}
func sumToTimeSeries[N int64 | float64](point metricdata.DataPoint[N], metrics metricdata.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
}
// TODO(@dashpole): Refactor to pass control-coupling lint check.
//
//nolint:revive
func histogramToTimeSeries[N int64 | float64](point metricdata.HistogramDataPoint[N], metrics metricdata.Metrics, mr *monitoredrespb.MonitoredResource, enableSOSD bool, projectID string) (*monitoringpb.TimeSeries, error) {
interval, err := toNonemptyTimeIntervalpb(point.StartTime, point.Time)
if err != nil {
return nil, err
}
distributionValue := histToDistribution(point, projectID)
if enableSOSD {
setSumOfSquaredDeviation(point, distributionValue)
}
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 expHistogramToTimeSeries[N int64 | float64](point metricdata.ExponentialHistogramDataPoint[N], metrics metricdata.Metrics, mr *monitoredrespb.MonitoredResource, enableSOSD bool, projectID string) (*monitoringpb.TimeSeries, error) {
interval, err := toNonemptyTimeIntervalpb(point.StartTime, point.Time)
if err != nil {
return nil, err
}
distributionValue := expHistToDistribution(point, projectID)
// TODO: Implement "setSumOfSquaredDeviationExpHist" for parameter "enableSOSD" functionality.
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 metricdata.HistogramDataPoint[N], projectID string) *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,
},
},
},
Exemplars: toDistributionExemplar[N](hist.Exemplars, projectID),
}
}
func expHistToDistribution[N int64 | float64](hist metricdata.ExponentialHistogramDataPoint[N], projectID string) *distribution.Distribution {
// First calculate underflow bucket with all negatives + zeros.
underflow := hist.ZeroCount
negativeBuckets := hist.NegativeBucket.Counts
for i := 0; i < len(negativeBuckets); i++ {
underflow += negativeBuckets[i]
}
// Next, pull in remaining buckets.
counts := make([]int64, len(hist.PositiveBucket.Counts)+2)
bucketOptions := &distribution.Distribution_BucketOptions{}
counts[0] = int64(underflow)
positiveBuckets := hist.PositiveBucket.Counts
for i := 0; i < len(positiveBuckets); i++ {
counts[i+1] = int64(positiveBuckets[i])
}
// Overflow bucket is always empty
counts[len(counts)-1] = 0
if len(hist.PositiveBucket.Counts) == 0 {
// We cannot send exponential distributions with no positive buckets,
// instead we send a simple overflow/underflow histogram.
bucketOptions.Options = &distribution.Distribution_BucketOptions_ExplicitBuckets{
ExplicitBuckets: &distribution.Distribution_BucketOptions_Explicit{
Bounds: []float64{0},
},
}
} else {
// Exponential histogram
growth := math.Exp2(math.Exp2(-float64(hist.Scale)))
scale := math.Pow(growth, float64(hist.PositiveBucket.Offset))
bucketOptions.Options = &distribution.Distribution_BucketOptions_ExponentialBuckets{
ExponentialBuckets: &distribution.Distribution_BucketOptions_Exponential{
GrowthFactor: growth,
Scale: scale,
NumFiniteBuckets: int32(len(counts) - 2),
},
}
}
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: bucketOptions,
Exemplars: toDistributionExemplar[N](hist.Exemplars, projectID),
}
}
func toDistributionExemplar[N int64 | float64](Exemplars []metricdata.Exemplar[N], projectID string) []*distribution.Distribution_Exemplar {
var exemplars []*distribution.Distribution_Exemplar
for _, e := range Exemplars {
attachments := []*anypb.Any{}
if hasValidSpanContext(e) {
sctx, err := anypb.New(&monitoringpb.SpanContext{
SpanName: fmt.Sprintf("projects/%s/traces/%s/spans/%s", projectID, hex.EncodeToString(e.TraceID[:]), hex.EncodeToString(e.SpanID[:])),
})
if err == nil {
attachments = append(attachments, sctx)
}
}
if len(e.FilteredAttributes) > 0 {
attr, err := anypb.New(&monitoringpb.DroppedLabels{
Label: attributesToLabels(e.FilteredAttributes),
})
if err == nil {
attachments = append(attachments, attr)
}
}
exemplars = append(exemplars, &distribution.Distribution_Exemplar{
Value: float64(e.Value),
Timestamp: timestamppb.New(e.Time),
Attachments: attachments,
})
}
sort.Slice(exemplars, func(i, j int) bool {
return exemplars[i].Value < exemplars[j].Value
})
return exemplars
}
func attributesToLabels(attrs []attribute.KeyValue) map[string]string {
labels := make(map[string]string, len(attrs))
for _, attr := range attrs {
labels[normalizeLabelKey(string(attr.Key))] = sanitizeUTF8(attr.Value.Emit())
}
return labels
}
var (
nilTraceID trace.TraceID
nilSpanID trace.SpanID
)
func hasValidSpanContext[N int64 | float64](e metricdata.Exemplar[N]) bool {
return !bytes.Equal(e.TraceID[:], nilTraceID[:]) && !bytes.Equal(e.SpanID[:], nilSpanID[:])
}
func setSumOfSquaredDeviation[N int64 | float64](hist metricdata.HistogramDataPoint[N], dist *distribution.Distribution) {
var prevBound float64
// Calculate the sum of squared deviation.
for i := 0; i < len(hist.Bounds); i++ {
// Assume all points in the bucket occur at the middle of the bucket range
middleOfBucket := (prevBound + hist.Bounds[i]) / 2
dist.SumOfSquaredDeviation += float64(dist.BucketCounts[i]) * (middleOfBucket - dist.Mean) * (middleOfBucket - dist.Mean)
prevBound = hist.Bounds[i]
}
// The infinity bucket is an implicit +Inf bound after the list of explicit bounds.
// Assume points in the infinity bucket are at the top of the previous bucket
middleOfInfBucket := prevBound
if len(dist.BucketCounts) > 0 {
dist.SumOfSquaredDeviation += float64(dist.BucketCounts[len(dist.BucketCounts)-1]) * (middleOfInfBucket - dist.Mean) * (middleOfInfBucket - dist.Mean)
}
}
func numberDataPointToValue[N int64 | float64](
point metricdata.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
}
// https://github.com/googleapis/googleapis/blob/c4c562f89acce603fb189679836712d08c7f8584/google/api/metric.proto#L149
//
// > The label key name must follow:
// >
// > * Only upper and lower-case letters, digits and underscores (_) are
// > allowed.
// > * Label name must start with a letter or digit.
// > * The maximum length of a label name is 100 characters.
//
// Note: this does not truncate if a label is too long.
func normalizeLabelKey(s string) string {
if len(s) == 0 {
return s
}
s = strings.Map(sanitizeRune, s)
if unicode.IsDigit(rune(s[0])) {
s = "key_" + s
}
return s
}
// converts anything that is not a letter or digit to an underscore.
func sanitizeRune(r rune) rune {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
return r
}
// Everything else turns into an underscore
return '_'
}