-
Notifications
You must be signed in to change notification settings - Fork 98
/
metrics.go
1601 lines (1480 loc) · 51.1 KB
/
metrics.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
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2022 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
//
// https://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 file contains the rewritten googlecloud metrics exporter which no longer takes
// dependency on the OpenCensus stackdriver exporter.
package collector
import (
"context"
"encoding/hex"
"errors"
"fmt"
"math"
"net/url"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
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/genproto/googleapis/api/distribution"
"google.golang.org/genproto/googleapis/api/label"
metricpb "google.golang.org/genproto/googleapis/api/metric"
monitoredrespb "google.golang.org/genproto/googleapis/api/monitoredres"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/encoding/gzip"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/timestamppb"
"go.opencensus.io/plugin/ocgrpc"
"go.opencensus.io/stats/view"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pmetric"
"github.com/fsnotify/fsnotify"
"github.com/tidwall/wal"
"go.uber.org/zap"
"github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/collector/internal/datapointstorage"
"github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/collector/internal/normalization"
"github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping"
)
// self-observability reporting meters/tracers/loggers.
type selfObservability struct {
// Logger to use for this exporter.
log *zap.Logger
}
// MetricsExporter is the GCM exporter that uses pdata directly.
type MetricsExporter struct {
// write ahead log handles exporter retries in-order to handle network outages
wal *exporterWAL
obs selfObservability
// shutdownC is a channel for signaling a graceful shutdown
shutdownC chan struct{}
// mdCache tracks the metric descriptors that have already been sent to GCM
mdCache map[string]*monitoringpb.CreateMetricDescriptorRequest
// A channel that receives metric descriptor and sends them to GCM once
metricDescriptorC chan *monitoringpb.CreateMetricDescriptorRequest
client monitoringClient
// Only used for testing purposes in lieu of initializing a fake client
exportFunc func(context.Context, *monitoringpb.CreateTimeSeriesRequest) error
// requestOpts applies options to the context for requests, such as additional headers.
requestOpts []func(*context.Context, requestInfo)
mapper metricMapper
cfg Config
// goroutines tracks the currently running child tasks
goroutines sync.WaitGroup
timeout time.Duration
}
type exporterWAL struct {
*wal.Log
// the full path of the WAL (user-configured directory + "gcp_metrics_wal")
path string
maxBackoff time.Duration
mutex sync.Mutex
}
// requestInfo is meant to abstract info from CreateMetricsDescriptorRequests and
// CreateTimeSeriesRequests that is shared by requestOpts functions.
type requestInfo struct {
projectName string
}
// metricMapper is the part that transforms metrics. Separate from MetricsExporter since it has
// all pure functions.
type metricMapper struct {
normalizer normalization.Normalizer
obs selfObservability
cfg Config
}
// Constants we use when translating summary metrics into GCP.
const (
SummaryCountPrefix = "_count"
SummarySumSuffix = "_sum"
)
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
// The default amount of time to retry a data point on network outage when
// WAL is enabled before discarding. Users can override by setting MetricConfig.WALConfig.MaxBackoff.
defaultWalMaxBackoff = time.Duration(3600 * time.Second)
)
const (
// The specific unit that needs to be present in an integer-valued metric so
// that it can be treated as a boolean.
specialIntToBoolUnit = "{gcp.BOOL}"
)
type labels map[string]string
// monitoringClient is the subset of monitoring.MetricClient this exporter uses,
// and allows us to mock the implementation for testing.
type monitoringClient interface {
CreateTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest, opts ...gax.CallOption) error
CreateServiceTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest, opts ...gax.CallOption) error
Close() error
CreateMetricDescriptor(ctx context.Context, req *monitoringpb.CreateMetricDescriptorRequest, opts ...gax.CallOption) (*metricpb.MetricDescriptor, error)
}
func (me *MetricsExporter) Shutdown(ctx context.Context) error {
// TODO: pass ctx to goroutines so that we can use its deadline
close(me.shutdownC)
c := make(chan struct{})
go func() {
// Wait until all goroutines are done
me.goroutines.Wait()
close(c)
}()
select {
case <-ctx.Done():
me.obs.log.Error("Error waiting for async tasks to finish.", zap.Error(ctx.Err()))
case <-c:
}
if me.client != nil {
return me.client.Close()
}
return nil
}
func NewGoogleCloudMetricsExporter(
ctx context.Context,
cfg Config,
log *zap.Logger,
version string,
timeout time.Duration,
) (*MetricsExporter, error) {
// TODO: https://github.com/GoogleCloudPlatform/opentelemetry-operations-go/pull/537#discussion_r1038290097
//nolint:errcheck
view.Register(MetricViews()...)
//nolint:errcheck
view.Register(ocgrpc.DefaultClientViews...)
setVersionInUserAgent(&cfg, version)
obs := selfObservability{log: log}
normalizer := normalization.NewDisabledNormalizer()
mExp := &MetricsExporter{
cfg: cfg,
obs: obs,
mapper: metricMapper{
obs: obs,
cfg: cfg,
normalizer: normalizer,
},
// We create a buffered channel for metric descriptors.
// MetricDescritpors are asychronously sent and optimistic.
// We only get Unit/Description/Display name from them, so it's ok
// to drop / conserve resources for sending timeseries.
metricDescriptorC: make(chan *monitoringpb.CreateMetricDescriptorRequest, cfg.MetricConfig.CreateMetricDescriptorBufferSize),
mdCache: make(map[string]*monitoringpb.CreateMetricDescriptorRequest),
shutdownC: make(chan struct{}),
timeout: timeout,
}
mExp.exportFunc = mExp.exportToTimeSeries
mExp.requestOpts = make([]func(*context.Context, requestInfo), 0)
if cfg.DestinationProjectQuota {
mExp.requestOpts = append(mExp.requestOpts, func(ctx *context.Context, ri requestInfo) {
*ctx = metadata.NewOutgoingContext(*ctx, metadata.New(map[string]string{"x-goog-user-project": strings.TrimPrefix(ri.projectName, "projects/")}))
})
}
return mExp, nil
}
func (me *MetricsExporter) Start(ctx context.Context, _ component.Host) error {
me.shutdownC = make(chan struct{})
if me.cfg.MetricConfig.CumulativeNormalization {
me.mapper.normalizer = normalization.NewStandardNormalizer(me.shutdownC, me.obs.log)
}
clientOpts, err := generateClientOptions(ctx, &me.cfg.MetricConfig.ClientConfig, &me.cfg, monitoring.DefaultAuthScopes())
if err != nil {
return err
}
client, err := monitoring.NewMetricClient(ctx, clientOpts...)
if err != nil {
return err
}
if me.cfg.MetricConfig.ClientConfig.Compression == 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)))
}
me.client = client
if me.cfg.MetricConfig.WALConfig != nil {
_, _, err = me.setupWAL()
if err != nil {
return err
}
// start WAL popper routine
me.goroutines.Add(1)
go me.runWALReadAndExportLoop(ctx)
}
// Fire up the metric descriptor exporter.
me.goroutines.Add(1)
go me.exportMetricDescriptorRunner()
return nil
}
// setupWAL creates the WAL.
// This function is also used to re-sync after writes, so it closes the existing WAL if present.
// It returns the FirstIndex, LastIndex, and any error.
func (me *MetricsExporter) setupWAL() (uint64, uint64, error) {
err := me.closeWAL()
if err != nil {
return 0, 0, err
}
if me.wal == nil {
me.wal = &exporterWAL{}
}
walPath := filepath.Join(me.cfg.MetricConfig.WALConfig.Directory, "gcp_metrics_wal")
me.wal.path = walPath
metricWal, err := wal.Open(walPath, &wal.Options{LogFormat: 1})
if err != nil {
return 0, 0, err
}
me.wal.Log = metricWal
// default to 1 hour exponential backoff
me.wal.maxBackoff = defaultWalMaxBackoff
if me.cfg.MetricConfig.WALConfig.MaxBackoff != 0 {
me.wal.maxBackoff = me.cfg.MetricConfig.WALConfig.MaxBackoff
}
// sync existing WAL indices
rIndex, err := me.wal.FirstIndex()
if err != nil {
return 0, 0, err
}
wIndex, err := me.wal.LastIndex()
if err != nil {
return 0, 0, err
}
return rIndex, wIndex, nil
}
func (me *MetricsExporter) closeWAL() error {
if me.wal != nil && me.wal.Log != nil {
err := me.wal.Log.Close()
me.wal.Log = nil
return err
}
return nil
}
// PushMetrics calls pushes pdata metrics to GCM, creating metric descriptors if necessary.
func (me *MetricsExporter) PushMetrics(ctx context.Context, m pmetric.Metrics) error {
if me.client == nil {
return errors.New("not started")
}
if me.wal != nil {
me.wal.mutex.Lock()
defer me.wal.mutex.Unlock()
}
// map from project -> []timeseries. This groups timeseries by the project
// they need to be sent to. Each project's timeseries are sent in a
// separate request later.
pendingTimeSeries := map[string][]*monitoringpb.TimeSeries{}
// add extra metrics from the ExtraMetrics() extension point, combine into a new copy
if me.cfg.MetricConfig.ExtraMetrics != nil {
metricsCopy := pmetric.NewMetrics()
m.ResourceMetrics().CopyTo(metricsCopy.ResourceMetrics())
me.cfg.MetricConfig.ExtraMetrics(metricsCopy)
m = metricsCopy
}
rms := m.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
rm := rms.At(i)
monitoredResource := me.cfg.MetricConfig.MapMonitoredResource(rm.Resource())
extraResourceLabels := attributesToLabels(filterAttributes(rm.Resource().Attributes(), me.cfg.MetricConfig.ServiceResourceLabels, me.cfg.MetricConfig.ResourceFilters))
projectID := me.cfg.ProjectID
// override project ID with gcp.project.id, if present
if projectFromResource, found := rm.Resource().Attributes().Get(resourcemapping.ProjectIDAttributeKey); found {
projectID = projectFromResource.AsString()
}
sms := rm.ScopeMetrics()
for j := 0; j < sms.Len(); j++ {
sm := sms.At(j)
instrumentationScopeLabels := me.mapper.instrumentationScopeToLabels(sm.Scope())
metricLabels := mergeLabels(nil, instrumentationScopeLabels, extraResourceLabels)
mes := sm.Metrics()
for k := 0; k < mes.Len(); k++ {
metric := mes.At(k)
pendingTimeSeries[projectID] = append(pendingTimeSeries[projectID], me.mapper.metricToTimeSeries(monitoredResource, metricLabels, metric, projectID)...)
// We only send metric descriptors if we're configured *and* we're not sending service timeseries.
if me.cfg.MetricConfig.SkipCreateMetricDescriptor || me.cfg.MetricConfig.CreateServiceTimeSeries {
continue
}
for _, md := range me.mapper.metricDescriptor(metric, metricLabels) {
if md == nil {
continue
}
req := &monitoringpb.CreateMetricDescriptorRequest{
Name: projectName(projectID),
MetricDescriptor: md,
}
select {
case me.metricDescriptorC <- req:
default:
// Ignore drops, we'll catch descriptor next time around.
}
}
}
}
}
var errs []error
// timeseries for each project are batched and exported separately
for projectID, projectTS := range pendingTimeSeries {
// Batch and export
for len(projectTS) > 0 {
var sendSize int
if len(projectTS) < sendBatchSize {
sendSize = len(projectTS)
} else {
sendSize = sendBatchSize
}
var ts []*monitoringpb.TimeSeries
ts, projectTS = projectTS[:sendSize], projectTS[sendSize:]
req := &monitoringpb.CreateTimeSeriesRequest{
Name: projectName(projectID),
TimeSeries: ts,
}
if me.wal != nil {
// push request onto the WAL
bytes, err := proto.Marshal(req)
if err != nil {
errs = append(errs, fmt.Errorf("failed to marshal protobuf to bytes: %+v", err))
continue
}
writeIndex, err := me.wal.LastIndex()
if err != nil {
errs = append(errs, fmt.Errorf("failed to get LastIndex of WAL: %+v", err))
continue
}
err = me.wal.Write(writeIndex+1, bytes)
if err != nil {
errs = append(errs, fmt.Errorf("failed to write to WAL: %+v", err))
continue
}
} else {
// otherwise export directly
errs = append(errs, me.export(ctx, req))
}
}
}
return errors.Join(errs...)
}
// exportToTimeSeries is the default exporting call to GCM.
// Broken into its own function for unit testing.
func (me *MetricsExporter) exportToTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest) error {
var err error
if me.cfg.MetricConfig.CreateServiceTimeSeries {
err = me.createServiceTimeSeries(ctx, req)
} else {
err = me.createTimeSeries(ctx, req)
}
return err
}
// export sends a CreateTimeSeriesRequest to GCM and reports failed/successful points based on the response.
func (me *MetricsExporter) export(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest) error {
// if this is an empty request, skip it
// empty requests are used by the WAL to signal the end of pending data
if len(req.String()) == 0 {
return nil
}
err := me.exportFunc(ctx, req)
s := status.Convert(err)
st := statusCodeToString(s)
succeededPoints := len(req.TimeSeries)
failedPoints := 0
for _, detail := range s.Details() {
if summary, ok := detail.(*monitoringpb.CreateTimeSeriesSummary); ok {
failedPoints = int(summary.TotalPointCount - summary.SuccessPointCount)
succeededPoints = int(summary.SuccessPointCount)
}
}
// always record the number of successful points
recordPointCountDataPoint(ctx, succeededPoints, "OK")
if failedPoints > 0 {
recordPointCountDataPoint(ctx, failedPoints, st)
}
return err
}
// readWALAndExport pops the next CreateTimeSeriesRequest from the WAL and tries exporting it.
// If the export is successful (or fails for a non-retryable error), the read index is incremented
// so the next entry in the WAL can be read by a subsequent call to readWALAndExport().
// If the export fails for a (retryable) network error, it will keep trying to export the same entry
// until success or the backoff max is reached.
func (me *MetricsExporter) readWALAndExport(ctx context.Context) error {
me.wal.mutex.Lock()
defer me.wal.mutex.Unlock()
// close and reopen the WAL to sync indices
readIndex, writeIndex, err := me.setupWAL()
if err != nil {
return err
}
bytes, err := me.wal.Read(readIndex)
if err == nil {
req := new(monitoringpb.CreateTimeSeriesRequest)
if err = proto.Unmarshal(bytes, req); err != nil {
return err
}
// on network failures, retry exponentially a max of 11 times (2^12s > 48 hours, older than allowed by GCM)
// or until user-configured max backoff is hit.
backoff := 0
for i := 0; i < 12; i++ {
err = me.export(ctx, req)
if err != nil {
me.obs.log.Warn(fmt.Sprintf("error exporting to GCM: %+v", err))
}
// retry at same read index if retryable (network) error
if isNotRecoverable(err) {
break
}
me.obs.log.Error("retryable error, retrying request")
backoff = 1 << i
if time.Duration(backoff)*time.Second >= me.wal.maxBackoff {
break
}
time.Sleep(time.Duration(backoff) * time.Second)
}
// If we are at the last index, and this last index is not an empty request
// (we use empty requests to fill out the end of a log, and if we didn't check for them
// this would loop constantly adding empty requests onto the end)
if readIndex == writeIndex && len(req.String()) > 0 {
// This indicates that we are trying to truncate the last item in the WAL.
// If that is the case, write an empty request so we can truncate the last real request
// (the WAL library requires at least 1 entry).
// Doing so prevents double-exporting in the event of a collector restart.
emptyReq := &monitoringpb.CreateTimeSeriesRequest{}
bytes, bytesErr := proto.Marshal(emptyReq)
if bytesErr != nil {
return bytesErr
}
writeIndex++
err = me.wal.Write(writeIndex, bytes)
if err != nil {
return err
}
}
// Truncate if readIndex < writeIndex.
// This only happens if there are more entries in the WAL
// OR, we are at the last real entry and added an "empty" entry above, in which we also increment writeIndex.
// otherwise, we've reached the end of the WAL and should be at an empty entry, which the export drops.
// If that's the case, and we try to truncate (ie, move readIndex+1), the library returns ErrOutOfRange.
if readIndex >= writeIndex {
// wal.ErrNotFound is used by wal.Read() to indicate the end of the WAL, but
// the wal library doesn't know about our hackery around empty entries.
// So it's used by us to indicate the same.
return wal.ErrNotFound
}
err = me.wal.TruncateFront(readIndex + 1)
if err != nil {
return err
}
}
return err
}
// watchWAL watches the WAL directory for a write then returns to the
// continuallyPopWAL() loop.
func (me *MetricsExporter) watchWALFile(ctx context.Context) error {
me.goroutines.Add(1)
defer me.goroutines.Done()
walWatcher, err := fsnotify.NewWatcher()
if err != nil {
return err
}
err = walWatcher.Add(me.wal.path)
if err != nil {
return err
}
watchCh := make(chan error)
var wErr error
go func() {
defer func() {
watchCh <- wErr
close(watchCh)
walWatcher.Close()
}()
select {
case <-me.shutdownC:
return
case <-ctx.Done():
wErr = ctx.Err()
return
case event, ok := <-walWatcher.Events:
if !ok {
return
}
switch event.Op {
case fsnotify.Remove:
wErr = fmt.Errorf("WAL file deleted")
case fsnotify.Rename:
wErr = fmt.Errorf("WAL file renamed")
case fsnotify.Write:
wErr = nil
}
case watchErr, ok := <-walWatcher.Errors:
if ok {
wErr = watchErr
}
}
}()
err = <-watchCh
return err
}
func (me *MetricsExporter) runWALReadAndExportLoop(ctx context.Context) {
defer me.goroutines.Done()
defer func() {
if err := me.wal.Close(); err != nil {
me.obs.log.Error(fmt.Sprintf("error closing WAL: %+v\n", err))
}
}()
for {
select {
case <-ctx.Done():
return
case <-me.shutdownC:
// do one last final read/export then return
// otherwise the runner goroutine could leave some hanging metrics unexported
for {
err := me.readWALAndExport(ctx)
if err != nil {
if !errors.Is(err, wal.ErrOutOfRange) {
me.obs.log.Error(fmt.Sprintf("error flushing remaining WAL entries: %+v", err))
}
break
}
}
return
default:
err := me.readWALAndExport(ctx)
if err == nil {
continue
}
// ErrNotFound from wal.Read() means the index is either 0 or out of
// bounds (indicating we're probably at the end of the WAL). That error
// will trigger a file watch for new writes (below this). For other
// errors, fail.
// ErrNotFound can be expected occasionally if we've reached the end of
// the WAL, so don't bother logging those.
if !errors.Is(err, wal.ErrNotFound) {
me.obs.log.Error(fmt.Sprintf("error reading WAL and exporting: %+v", err))
}
// Must have been ErrNotFound, start a file watch and block waiting for updates.
if err = me.watchWALFile(ctx); err != nil {
me.obs.log.Error(fmt.Sprintf("error watching WAL and exporting: %+v", err))
}
}
}
}
// Reads metric descriptors from the md channel, and reports them (once) to GCM.
func (me *MetricsExporter) exportMetricDescriptorRunner() {
defer me.goroutines.Done()
// We iterate over all metric descritpors until the channel is closed.
// Note: if we get terminated, this will still attempt to export all descriptors
// prior to shutdown.
for {
select {
case <-me.shutdownC:
for {
// We are shutting down. Publish all the pending
// items on the channel before we stop.
select {
case md := <-me.metricDescriptorC:
me.exportMetricDescriptor(md)
default:
// Return and continue graceful shutdown.
return
}
}
case md := <-me.metricDescriptorC:
me.exportMetricDescriptor(md)
}
}
}
func projectName(projectID string) string {
return fmt.Sprintf("projects/%s", projectID)
}
// isNotRecoverable returns true if the error is permanent.
func isNotRecoverable(err error) bool {
s := status.Convert(err)
return !(s.Code() == codes.DeadlineExceeded || s.Code() == codes.Unavailable)
}
// Helper method to send metric descriptors to GCM.
func (me *MetricsExporter) exportMetricDescriptor(req *monitoringpb.CreateMetricDescriptorRequest) {
cacheKey := fmt.Sprintf("%s/%s", req.Name, req.MetricDescriptor.Type)
if _, exists := me.mdCache[cacheKey]; exists {
return
}
ctx, cancel := context.WithTimeout(context.Background(), me.timeout)
defer cancel()
for _, opt := range me.requestOpts {
opt(&ctx, requestInfo{projectName: req.Name})
}
_, err := me.client.CreateMetricDescriptor(ctx, req)
if err != nil {
if isNotRecoverable(err) {
// cache if the error is non-recoverable
me.mdCache[cacheKey] = req
}
// TODO: Log-once on error, per metric descriptor?
me.obs.log.Error("Unable to send metric descriptor.", zap.Error(err), zap.Any("metric_descriptor", req.MetricDescriptor))
return
}
// cache if we are successful
me.mdCache[cacheKey] = req
}
// Sends a user-custom-metric timeseries.
func (me *MetricsExporter) createTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest) error {
ctx, cancel := context.WithTimeout(ctx, me.timeout)
defer cancel()
for _, opt := range me.requestOpts {
opt(&ctx, requestInfo{projectName: req.Name})
}
return me.client.CreateTimeSeries(ctx, req)
}
// Sends a service timeseries.
func (me *MetricsExporter) createServiceTimeSeries(ctx context.Context, req *monitoringpb.CreateTimeSeriesRequest) error {
ctx, cancel := context.WithTimeout(ctx, me.timeout)
defer cancel()
for _, opt := range me.requestOpts {
opt(&ctx, requestInfo{projectName: req.Name})
}
return me.client.CreateServiceTimeSeries(ctx, req)
}
func (m *metricMapper) instrumentationScopeToLabels(is pcommon.InstrumentationScope) labels {
isLabels := make(labels)
if !m.cfg.MetricConfig.InstrumentationLibraryLabels {
return isLabels
}
instrumentationSource := sanitizeUTF8(is.Name())
if len(instrumentationSource) > 0 {
isLabels["instrumentation_source"] = instrumentationSource
}
instrumentationVersion := sanitizeUTF8(is.Version())
if len(instrumentationVersion) > 0 {
isLabels["instrumentation_version"] = instrumentationVersion
}
return isLabels
}
func (m *metricMapper) metricToTimeSeries(
resource *monitoredrespb.MonitoredResource,
extraLabels labels,
metric pmetric.Metric,
projectID string,
) []*monitoringpb.TimeSeries {
timeSeries := []*monitoringpb.TimeSeries{}
switch metric.Type() {
case pmetric.MetricTypeSum:
sum := metric.Sum()
points := sum.DataPoints()
for i := 0; i < points.Len(); i++ {
ts := m.sumPointToTimeSeries(resource, extraLabels, metric, sum, points.At(i))
timeSeries = append(timeSeries, ts...)
}
case pmetric.MetricTypeGauge:
gauge := metric.Gauge()
points := gauge.DataPoints()
for i := 0; i < points.Len(); i++ {
ts := m.gaugePointToTimeSeries(resource, extraLabels, metric, gauge, points.At(i))
timeSeries = append(timeSeries, ts...)
}
case pmetric.MetricTypeSummary:
summary := metric.Summary()
points := summary.DataPoints()
for i := 0; i < points.Len(); i++ {
ts := m.summaryPointToTimeSeries(resource, extraLabels, metric, summary, points.At(i))
timeSeries = append(timeSeries, ts...)
}
case pmetric.MetricTypeHistogram:
hist := metric.Histogram()
points := hist.DataPoints()
for i := 0; i < points.Len(); i++ {
ts := m.histogramToTimeSeries(resource, extraLabels, metric, hist, points.At(i), projectID)
timeSeries = append(timeSeries, ts...)
}
case pmetric.MetricTypeExponentialHistogram:
eh := metric.ExponentialHistogram()
points := eh.DataPoints()
for i := 0; i < points.Len(); i++ {
ts := m.exponentialHistogramToTimeSeries(resource, extraLabels, metric, eh, points.At(i), projectID)
timeSeries = append(timeSeries, ts...)
}
default:
m.obs.log.Error("Unsupported metric data type", zap.Any("data_type", metric.Type()))
}
return timeSeries
}
func (m *metricMapper) summaryPointToTimeSeries(
resource *monitoredrespb.MonitoredResource,
extraLabels labels,
metric pmetric.Metric,
sum pmetric.Summary,
point pmetric.SummaryDataPoint,
) []*monitoringpb.TimeSeries {
if point.Flags().NoRecordedValue() {
// Drop points without a value.
return nil
}
// Normalize the summary point.
metricIdentifier := datapointstorage.Identifier(resource, extraLabels, metric, point.Attributes())
normalizedPoint, keep := m.normalizer.NormalizeSummaryDataPoint(point, metricIdentifier)
if !keep {
return nil
}
point = normalizedPoint
sumType, countType, quantileType, err := m.summaryMetricTypes(metric)
if err != nil {
m.obs.log.Debug("Failed to get metric type (i.e. name) for summary metric. Dropping the metric.", zap.Error(err), zap.Any("metric", metric))
return nil
}
startTime := timestamppb.New(point.StartTimestamp().AsTime())
endTime := timestamppb.New(point.Timestamp().AsTime())
result := []*monitoringpb.TimeSeries{
{
Resource: resource,
Unit: metric.Unit(),
MetricKind: metricpb.MetricDescriptor_CUMULATIVE,
ValueType: metricpb.MetricDescriptor_DOUBLE,
Points: []*monitoringpb.Point{{
Interval: &monitoringpb.TimeInterval{
StartTime: startTime,
EndTime: endTime,
},
Value: &monitoringpb.TypedValue{Value: &monitoringpb.TypedValue_DoubleValue{
DoubleValue: point.Sum(),
}},
}},
Metric: &metricpb.Metric{
Type: sumType,
Labels: mergeLabels(
attributesToLabels(point.Attributes()),
extraLabels,
),
},
},
{
Resource: resource,
Unit: metric.Unit(),
MetricKind: metricpb.MetricDescriptor_CUMULATIVE,
ValueType: metricpb.MetricDescriptor_DOUBLE,
Points: []*monitoringpb.Point{{
Interval: &monitoringpb.TimeInterval{
StartTime: startTime,
EndTime: endTime,
},
Value: &monitoringpb.TypedValue{Value: &monitoringpb.TypedValue_DoubleValue{
DoubleValue: float64(point.Count()),
}},
}},
Metric: &metricpb.Metric{
Type: countType,
Labels: mergeLabels(
attributesToLabels(point.Attributes()),
extraLabels,
),
},
},
}
quantiles := point.QuantileValues()
for i := 0; i < quantiles.Len(); i++ {
quantile := quantiles.At(i)
pLabel := labels{
"quantile": strconv.FormatFloat(quantile.Quantile(), 'f', -1, 64),
}
result = append(result, &monitoringpb.TimeSeries{
Resource: resource,
Unit: metric.Unit(),
MetricKind: metricpb.MetricDescriptor_GAUGE,
ValueType: metricpb.MetricDescriptor_DOUBLE,
Points: []*monitoringpb.Point{{
Interval: &monitoringpb.TimeInterval{
EndTime: endTime,
},
Value: &monitoringpb.TypedValue{Value: &monitoringpb.TypedValue_DoubleValue{
DoubleValue: quantile.Value(),
}},
}},
Metric: &metricpb.Metric{
Type: quantileType,
Labels: mergeLabels(
attributesToLabels(point.Attributes()),
extraLabels,
pLabel,
),
},
})
}
return result
}
func (m *metricMapper) exemplar(ex pmetric.Exemplar, projectID string) *distribution.Distribution_Exemplar {
ctx := context.TODO()
attachments := []*anypb.Any{}
// TODO: Look into still sending exemplars with no span.
if traceID, spanID := ex.TraceID(), ex.SpanID(); !traceID.IsEmpty() && !spanID.IsEmpty() {
sctx, err := anypb.New(&monitoringpb.SpanContext{
// TODO - make sure project id is correct.
SpanName: fmt.Sprintf("projects/%s/traces/%s/spans/%s", projectID, hex.EncodeToString(traceID[:]), hex.EncodeToString(spanID[:])),
})
if err == nil {
attachments = append(attachments, sctx)
} else {
// This happens in the event of logic error (e.g. missing required fields).
// As such we complaining loudly to fail our unit tests.
recordExemplarFailure(ctx, 1)
}
}
if ex.FilteredAttributes().Len() > 0 {
attr, err := anypb.New(&monitoringpb.DroppedLabels{
Label: attributesToLabels(ex.FilteredAttributes()),
})
if err == nil {
attachments = append(attachments, attr)
} else {
// This happens in the event of logic error (e.g. missing required fields).
// As such we complaining loudly to fail our unit tests.
recordExemplarFailure(ctx, 1)
}
}
var val float64
switch ex.ValueType() {
case pmetric.ExemplarValueTypeDouble:
val = ex.DoubleValue()
case pmetric.ExemplarValueTypeInt:
val = float64(ex.IntValue())
}
return &distribution.Distribution_Exemplar{
Value: val,
Timestamp: timestamppb.New(ex.Timestamp().AsTime()),
Attachments: attachments,
}
}
func (m *metricMapper) exemplars(exs pmetric.ExemplarSlice, projectID string) []*distribution.Distribution_Exemplar {
exemplars := make([]*distribution.Distribution_Exemplar, exs.Len())
for i := 0; i < exs.Len(); i++ {
exemplars[i] = m.exemplar(exs.At(i), projectID)
}
sort.Slice(exemplars, func(i, j int) bool {
return exemplars[i].Value < exemplars[j].Value
})
return exemplars
}
// histogramPoint maps a histogram data point into a GCM point.
func (m *metricMapper) histogramPoint(point pmetric.HistogramDataPoint, projectID string) *monitoringpb.TypedValue {
counts := make([]int64, point.BucketCounts().Len())
var mean, deviation, prevBound float64
for i := 0; i < point.BucketCounts().Len(); i++ {
counts[i] = int64(point.BucketCounts().At(i))
}
if !math.IsNaN(point.Sum()) && point.Count() > 0 { // Avoid divide-by-zero
mean = float64(point.Sum() / float64(point.Count()))
}
bounds := point.ExplicitBounds()
if m.cfg.MetricConfig.EnableSumOfSquaredDeviation {
// Calculate the sum of squared deviation.
for i := 0; i < bounds.Len(); i++ {
// Assume all points in the bucket occur at the middle of the bucket range
middleOfBucket := (prevBound + bounds.At(i)) / 2
deviation += float64(counts[i]) * (middleOfBucket - mean) * (middleOfBucket - mean)
prevBound = bounds.At(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
deviation += float64(counts[len(counts)-1]) * (middleOfInfBucket - mean) * (middleOfInfBucket - mean)
}
return &monitoringpb.TypedValue{
Value: &monitoringpb.TypedValue_DistributionValue{
DistributionValue: &distribution.Distribution{
Count: int64(point.Count()),
Mean: mean,
BucketCounts: counts,
SumOfSquaredDeviation: deviation,
BucketOptions: &distribution.Distribution_BucketOptions{
Options: &distribution.Distribution_BucketOptions_ExplicitBuckets{
ExplicitBuckets: &distribution.Distribution_BucketOptions_Explicit{
Bounds: bounds.AsRaw(),
},
},
},
Exemplars: m.exemplars(point.Exemplars(), projectID),
},
},
}
}