-
Notifications
You must be signed in to change notification settings - Fork 98
/
traces.go
175 lines (159 loc) · 6 KB
/
traces.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
// Copyright 2021 OpenTelemetry Authors
//
// 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 collector contains the wrapper for OpenTelemetry-GoogleCloud
// exporter to be used in opentelemetry-collector.
package collector
import (
"context"
"errors"
"fmt"
"strings"
"time"
traceapi "cloud.google.com/go/trace/apiv2"
"go.opencensus.io/plugin/ocgrpc"
"go.opencensus.io/stats/view"
"go.opentelemetry.io/collector/pdata/ptrace"
"go.opentelemetry.io/otel/attribute"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"golang.org/x/oauth2/google"
"google.golang.org/api/impersonate"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
cloudtrace "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace"
)
// TraceExporter is a wrapper struct of OT cloud trace exporter
type TraceExporter struct {
texporter *cloudtrace.Exporter
}
func (te *TraceExporter) Shutdown(ctx context.Context) error {
return te.texporter.Shutdown(ctx)
}
func setVersionInUserAgent(cfg *Config, version string) {
cfg.UserAgent = strings.ReplaceAll(cfg.UserAgent, "{{version}}", version)
}
func generateClientOptions(ctx context.Context, clientCfg *ClientConfig, cfg *Config, scopes []string) ([]option.ClientOption, error) {
var copts []option.ClientOption
// option.WithUserAgent is used by the Trace exporter, but not the Metric exporter (see comment below)
if cfg.UserAgent != "" {
copts = append(copts, option.WithUserAgent(cfg.UserAgent))
}
if clientCfg.Endpoint != "" {
if clientCfg.UseInsecure {
// option.WithGRPCConn option takes precedent over all other supplied options so the
// following user agent will be used by both exporters if we reach this branch
dialOpts := []grpc.DialOption{
grpc.WithStatsHandler(&ocgrpc.ClientHandler{}),
grpc.WithTransportCredentials(insecure.NewCredentials()),
}
if cfg.UserAgent != "" {
dialOpts = append(dialOpts, grpc.WithUserAgent(cfg.UserAgent))
}
conn, err := grpc.Dial(clientCfg.Endpoint, dialOpts...)
if err != nil {
return nil, fmt.Errorf("cannot configure grpc conn: %w", err)
}
copts = append(copts, option.WithGRPCConn(conn))
} else {
copts = append(copts, option.WithEndpoint(clientCfg.Endpoint))
}
}
if cfg.ImpersonateConfig.TargetPrincipal != "" {
if cfg.ProjectID == "" {
creds, err := google.FindDefaultCredentials(ctx, scopes...)
if err != nil {
return nil, fmt.Errorf("error finding default application credentials: %v", err)
}
if creds.ProjectID == "" {
return nil, errors.New("no project found with application default credentials")
}
cfg.ProjectID = creds.ProjectID
}
tokenSource, err := impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{
TargetPrincipal: cfg.ImpersonateConfig.TargetPrincipal,
Delegates: cfg.ImpersonateConfig.Delegates,
Subject: cfg.ImpersonateConfig.Subject,
Scopes: scopes,
})
if err != nil {
return nil, err
}
copts = append(copts, option.WithTokenSource(tokenSource))
} else if !clientCfg.UseInsecure {
creds, err := google.FindDefaultCredentials(ctx, scopes...)
if err != nil {
return nil, fmt.Errorf("error finding default application credentials: %v", err)
}
copts = append(copts, option.WithCredentials(creds))
if cfg.ProjectID == "" {
if creds.ProjectID == "" {
return nil, errors.New("no project found with application default credentials")
}
cfg.ProjectID = creds.ProjectID
}
}
if clientCfg.GRPCPoolSize > 0 {
copts = append(copts, option.WithGRPCConnectionPool(clientCfg.GRPCPoolSize))
}
if clientCfg.GetClientOptions != nil {
copts = append(copts, clientCfg.GetClientOptions()...)
}
return copts, nil
}
func NewGoogleCloudTracesExporter(ctx context.Context, cfg Config, version string, timeout time.Duration) (*TraceExporter, error) {
view.Register(ocgrpc.DefaultClientViews...)
setVersionInUserAgent(&cfg, version)
topts := []cloudtrace.Option{
cloudtrace.WithProjectID(cfg.ProjectID),
cloudtrace.WithTimeout(timeout),
}
if cfg.TraceConfig.AttributeMappings != nil {
topts = append(topts, cloudtrace.WithAttributeMapping(mappingFuncFromAKM(cfg.TraceConfig.AttributeMappings)))
}
copts, err := generateClientOptions(ctx, &cfg.TraceConfig.ClientConfig, &cfg, traceapi.DefaultAuthScopes())
if err != nil {
return nil, err
}
topts = append(topts, cloudtrace.WithTraceClientOptions(copts))
exp, err := cloudtrace.New(topts...)
if err != nil {
return nil, fmt.Errorf("error creating GoogleCloud Trace exporter: %w", err)
}
return &TraceExporter{texporter: exp}, nil
}
func mappingFuncFromAKM(akm []AttributeMapping) func(attribute.Key) attribute.Key {
// convert list to map for easy lookups
mapFromConfig := make(map[string]string, len(akm))
for _, mapping := range akm {
mapFromConfig[mapping.Key] = mapping.Replacement
}
return func(input attribute.Key) attribute.Key {
// if a replacement was specified in the config, use it.
if replacement, ok := mapFromConfig[string(input)]; ok {
return attribute.Key(replacement)
}
// otherwise, leave the attribute as-is
return input
}
}
// PushTraces calls texporter.ExportSpan for each span in the given traces
func (te *TraceExporter) PushTraces(ctx context.Context, td ptrace.Traces) error {
resourceSpans := td.ResourceSpans()
spans := make([]sdktrace.ReadOnlySpan, 0, td.SpanCount())
for i := 0; i < resourceSpans.Len(); i++ {
sd := pdataResourceSpansToOTSpanData(resourceSpans.At(i))
spans = append(spans, sd...)
}
return te.texporter.ExportSpans(ctx, spans)
}