-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
375 lines (324 loc) · 10.4 KB
/
client.go
File metadata and controls
375 lines (324 loc) · 10.4 KB
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
// Copyright 2023 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 cloudtrace
import (
"context"
"errors"
"fmt"
"math"
"strings"
"time"
trace "cloud.google.com/go/trace/apiv1"
"cloud.google.com/go/trace/apiv1/tracepb"
resourcemanager "cloud.google.com/go/resourcemanager/apiv3"
resourcemanagerpb "cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb"
"github.com/grafana/grafana-plugin-sdk-go/backend/log"
"golang.org/x/oauth2"
"google.golang.org/api/impersonate"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/protobuf/types/known/timestamppb"
cloudtracepb "cloud.google.com/go/trace/apiv1/tracepb"
)
const testConnectionTimeWindow = time.Hour * 24 * 30 // 30 days
// API implements the methods we need to query traces and list projects from GCP
type API interface {
// ListTraces retrieves all traces matching some query filter up to the given limit
ListTraces(context.Context, *TracesQuery) ([]*cloudtracepb.Trace, error)
// GetTrace retrieves a trace matching a trace ID
GetTrace(context.Context, *TraceQuery) (*cloudtracepb.Trace, error)
// TestConnection queries for any trace from the given project
TestConnection(ctx context.Context, projectID string) error
// ListProjects returns the project IDs of all visible projects.
// If query is non-empty it is forwarded to the Resource Manager search filter.
ListProjects(ctx context.Context, query string) ([]string, error)
// Close closes the underlying connection to the GCP API
Close() error
}
// Client wraps a GCP trace client to fetch traces and spans,
// and a resourcemanager client to list projects
type Client struct {
tClient *trace.Client
rClient *resourcemanager.ProjectsClient
}
func universeDomainOpts(universeDomain string) []option.ClientOption {
if universeDomain == "" {
return nil
}
return []option.ClientOption{option.WithUniverseDomain(universeDomain)}
}
// NewClient creates a new Client using jsonCreds for authentication
func NewClient(ctx context.Context, jsonCreds []byte, universeDomain string) (*Client, error) {
opts := append([]option.ClientOption{
option.WithCredentialsJSON(jsonCreds),
option.WithUserAgent("googlecloud-trace-datasource"),
}, universeDomainOpts(universeDomain)...)
client, err := trace.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
rClient, err := resourcemanager.NewProjectsClient(ctx, opts...)
if err != nil {
_ = client.Close()
return nil, err
}
return &Client{
tClient: client,
rClient: rClient,
}, nil
}
// NewClientWithGCE creates a new Client using GCE metadata for authentication
func NewClientWithGCE(ctx context.Context, universeDomain string) (*Client, error) {
opts := append([]option.ClientOption{
option.WithUserAgent("googlecloud-trace-datasource"),
}, universeDomainOpts(universeDomain)...)
client, err := trace.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
rClient, err := resourcemanager.NewProjectsClient(ctx, opts...)
if err != nil {
_ = client.Close()
return nil, err
}
return &Client{
tClient: client,
rClient: rClient,
}, nil
}
// NewClientWithImpersonation creates a new Client using service account impersonation
func NewClientWithImpersonation(ctx context.Context, jsonCreds []byte, impersonateSA string, universeDomain string) (*Client, error) {
var ts oauth2.TokenSource
var err error
impersonateOpts := append([]option.ClientOption{}, universeDomainOpts(universeDomain)...)
if jsonCreds == nil {
ts, err = impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{
TargetPrincipal: impersonateSA,
Scopes: []string{"https://www.googleapis.com/auth/cloud-platform"},
}, impersonateOpts...)
} else {
impersonateOpts = append(impersonateOpts, option.WithCredentialsJSON(jsonCreds))
ts, err = impersonate.CredentialsTokenSource(ctx, impersonate.CredentialsConfig{
TargetPrincipal: impersonateSA,
Scopes: []string{"https://www.googleapis.com/auth/cloud-platform"},
}, impersonateOpts...)
}
if err != nil {
return nil, err
}
opts := append([]option.ClientOption{
option.WithTokenSource(ts),
option.WithUserAgent("googlecloud-trace-datasource"),
}, universeDomainOpts(universeDomain)...)
client, err := trace.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
rClient, err := resourcemanager.NewProjectsClient(ctx, opts...)
if err != nil {
_ = client.Close()
return nil, err
}
return &Client{
tClient: client,
rClient: rClient,
}, nil
}
// NewClientWithAccessToken creates a new Client using an access token for authentication.
// Since the datasource is re-created whenever the token changes, we can treat this token as static.
func NewClientWithAccessToken(ctx context.Context, accessToken string, universeDomain string) (*Client, error) {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: accessToken})
opts := append([]option.ClientOption{
option.WithTokenSource(ts),
option.WithUserAgent("googlecloud-trace-datasource"),
}, universeDomainOpts(universeDomain)...)
client, err := trace.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
rClient, err := resourcemanager.NewProjectsClient(ctx, opts...)
if err != nil {
_ = client.Close()
return nil, err
}
return &Client{
tClient: client,
rClient: rClient,
}, nil
}
// NewClientWithPassThrough creates a new Client using OAuth browser credentials
func NewClientWithPassThrough(ctx context.Context, headers map[string]string, universeDomain string) (*Client, error) {
token, found := strings.CutPrefix(headers["Authorization"], "Bearer ")
if !found || token == "" {
return nil, errors.New("missing or invalid Authorization header")
}
opts := append([]option.ClientOption{
option.WithTokenSource(
oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: token,
}),
),
option.WithUserAgent("googlecloud-trace-datasource"),
}, universeDomainOpts(universeDomain)...)
client, err := trace.NewClient(ctx, opts...)
if err != nil {
return nil, err
}
rClient, err := resourcemanager.NewProjectsClient(ctx, opts...)
if err != nil {
_ = client.Close()
return nil, err
}
return &Client{
tClient: client,
rClient: rClient,
}, nil
}
// Close closes the underlying connection to the GCP API
func (c *Client) Close() error {
c.rClient.Close()
return c.tClient.Close()
}
// TracesQuery is the information from a Grafana query needed to query GCP for traces
type TracesQuery struct {
ProjectID string
Filter string
Limit int64
TimeRange TimeRange
}
// TraceQuery is the information from a Grafana query needed to query GCP for a trace
type TraceQuery struct {
ProjectID string
TraceID string
}
// ListProjects returns the project IDs of all visible projects.
// If query is non-empty it is forwarded to the Resource Manager
// SearchProjects API which supports free-text search (AIP-160).
// Results are capped at maxProjects.
const maxProjects = 100
func (c *Client) ListProjects(ctx context.Context, query string) ([]string, error) {
projectIDs := []string{}
req := &resourcemanagerpb.SearchProjectsRequest{
Query: query,
PageSize: maxProjects,
}
it := c.rClient.SearchProjects(ctx, req)
for {
project, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
if project.State != resourcemanagerpb.Project_ACTIVE {
continue
}
projectIDs = append(projectIDs, project.ProjectId)
if len(projectIDs) >= maxProjects {
break
}
}
return projectIDs, nil
}
// TestConnection queries for any trace from the given project
func (c *Client) TestConnection(ctx context.Context, projectID string) error {
start := time.Now()
listCtx, cancel := context.WithTimeout(ctx, time.Duration(time.Minute*1))
defer func() {
cancel()
log.DefaultLogger.Info("Finished testConnection", "duration", time.Since(start).String())
}()
it := c.tClient.ListTraces(listCtx, &cloudtracepb.ListTracesRequest{
ProjectId: projectID,
PageSize: 1,
StartTime: timestamppb.New(time.Now().Add(-testConnectionTimeWindow)),
})
if listCtx.Err() != nil {
return errors.New("timeout")
}
entry, err := it.Next()
if err == iterator.Done {
return errors.New("no entries")
}
if err == context.DeadlineExceeded {
return errors.New("list entries: timeout")
}
if err != nil {
return fmt.Errorf("list entries: %w", err)
}
if entry == nil {
return errors.New("no entries")
}
return nil
}
// ListTraces retrieves all traces matching some query filter up to the given limit
func (c *Client) ListTraces(ctx context.Context, q *TracesQuery) ([]*cloudtracepb.Trace, error) {
// Never exceed the maximum page size
pageSize := int32(math.Min(float64(q.Limit), 1000))
req := cloudtracepb.ListTracesRequest{
ProjectId: q.ProjectID,
Filter: q.Filter,
StartTime: timestamppb.New(q.TimeRange.From),
EndTime: timestamppb.New(q.TimeRange.To),
OrderBy: "start desc",
PageSize: pageSize,
View: tracepb.ListTracesRequest_ROOTSPAN,
}
start := time.Now()
defer func() {
log.DefaultLogger.Info("Finished listing traces", "duration", time.Since(start).String())
}()
it := c.tClient.ListTraces(ctx, &req)
if it == nil {
return nil, errors.New("nil response")
}
var i int64
entries := []*cloudtracepb.Trace{}
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.DefaultLogger.Error("error getting page", "error", err)
break
}
entries = append(entries, resp)
i++
if i >= q.Limit {
break
}
}
return entries, nil
}
// GetTrace retrieves a single trace given a trace ID
func (c *Client) GetTrace(ctx context.Context, q *TraceQuery) (*cloudtracepb.Trace, error) {
req := cloudtracepb.GetTraceRequest{
ProjectId: q.ProjectID,
TraceId: q.TraceID,
}
start := time.Now()
defer func() {
log.DefaultLogger.Info(fmt.Sprintf("Finished getting trace: %s", q.TraceID), "duration", time.Since(start).String())
}()
trace, err := c.tClient.GetTrace(ctx, &req)
if err != nil {
return nil, err
}
if trace == nil {
return nil, errors.New("nil response")
}
return trace, nil
}