-
Notifications
You must be signed in to change notification settings - Fork 54
/
configuration.go
603 lines (558 loc) · 17.8 KB
/
configuration.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
// Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019-Present Datadog, Inc.
package datadog
import (
"context"
"fmt"
"log"
"net/http"
"os"
"runtime"
"strings"
"time"
client "github.com/DataDog/datadog-api-client-go/v2"
)
// contextKeys are used to identify the type of value in the context.
// Since these are string, it is possible to get a short description of the
// context key for logging and debugging using key.String().
type contextKey string
func (c contextKey) String() string {
return "auth " + string(c)
}
var (
// ContextOAuth2 takes an oauth2.TokenSource as authentication for the request.
ContextOAuth2 = contextKey("token")
// ContextBasicAuth takes BasicAuth as authentication for the request.
ContextBasicAuth = contextKey("basic")
// ContextAccessToken takes a string oauth2 access token as authentication for the request.
ContextAccessToken = contextKey("accesstoken")
// ContextAPIKeys takes a string apikey as authentication for the request
ContextAPIKeys = contextKey("apiKeys")
// ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request.
ContextHttpSignatureAuth = contextKey("httpsignature")
// ContextServerIndex uses a server configuration from the index.
ContextServerIndex = contextKey("serverIndex")
// ContextOperationServerIndices uses a server configuration from the index mapping.
ContextOperationServerIndices = contextKey("serverOperationIndices")
// ContextServerVariables overrides a server configuration variables.
ContextServerVariables = contextKey("serverVariables")
// ContextOperationServerVariables overrides a server configuration variables using operation specific values.
ContextOperationServerVariables = contextKey("serverOperationVariables")
)
// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth.
type BasicAuth struct {
UserName string `json:"userName,omitempty"`
Password string `json:"password,omitempty"`
}
// APIKey provides API key based authentication to a request passed via context using ContextAPIKey.
type APIKey struct {
Key string
Prefix string
}
// ServerVariable stores the information about a server variable.
type ServerVariable struct {
Description string
DefaultValue string
EnumValues []string
}
// ServerConfiguration stores the information about a server.
type ServerConfiguration struct {
URL string
Description string
Variables map[string]ServerVariable
}
// ServerConfigurations stores multiple ServerConfiguration items.
type ServerConfigurations []ServerConfiguration
// Configuration stores the configuration of the API client
type Configuration struct {
Host string `json:"host,omitempty"`
Scheme string `json:"scheme,omitempty"`
DefaultHeader map[string]string `json:"defaultHeader,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Debug bool `json:"debug,omitempty"`
Compress bool `json:"compress,omitempty"`
Servers ServerConfigurations
OperationServers map[string]ServerConfigurations
HTTPClient *http.Client
unstableOperations map[string]bool
RetryConfiguration RetryConfiguration
}
// RetryConfiguration stores the configuration of the retry behavior of the api client
type RetryConfiguration struct {
EnableRetry bool
BackOffMultiplier float64
BackOffBase float64
HTTPRetryTimeout time.Duration
MaxRetries int
}
// NewConfiguration returns a new Configuration object.
func NewConfiguration() *Configuration {
cfg := &Configuration{
DefaultHeader: make(map[string]string),
UserAgent: getUserAgent(),
Debug: false,
Compress: true,
Servers: ServerConfigurations{
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "The regional site for Datadog customers.",
DefaultValue: "datadoghq.com",
EnumValues: []string{
"datadoghq.com",
"us3.datadoghq.com",
"us5.datadoghq.com",
"datadoghq.eu",
"ddog-gov.com",
},
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "api",
},
},
},
{
URL: "{protocol}://{name}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"name": {
Description: "Full site DNS name.",
DefaultValue: "api.datadoghq.com",
},
"protocol": {
Description: "The protocol for accessing the API.",
DefaultValue: "https",
},
},
},
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "Any Datadog deployment.",
DefaultValue: "datadoghq.com",
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "api",
},
},
},
},
OperationServers: map[string]ServerConfigurations{
"v1.IPRangesApi.GetIPRanges": {
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "The regional site for Datadog customers.",
DefaultValue: "datadoghq.com",
EnumValues: []string{
"datadoghq.com",
"us3.datadoghq.com",
"us5.datadoghq.com",
"datadoghq.eu",
"ddog-gov.com",
},
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "ip-ranges",
},
},
},
{
URL: "{protocol}://{name}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"name": {
Description: "Full site DNS name.",
DefaultValue: "ip-ranges.datadoghq.com",
},
"protocol": {
Description: "The protocol for accessing the API.",
DefaultValue: "https",
},
},
},
{
URL: "https://{subdomain}.datadoghq.com",
Description: "No description provided",
Variables: map[string]ServerVariable{
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "ip-ranges",
},
},
},
},
"v1.ServiceLevelObjectivesApi.SearchSLO": {
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "The regional site for Datadog customers.",
DefaultValue: "datadoghq.com",
EnumValues: []string{
"datadoghq.com",
"datadoghq.eu",
"us3.datadoghq.com",
"us5.datadoghq.com",
"ddog-gov.com",
},
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "api",
},
},
},
{
URL: "{protocol}://{name}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"name": {
Description: "Full site DNS name.",
DefaultValue: "api.datadoghq.com",
},
"protocol": {
Description: "The protocol for accessing the API.",
DefaultValue: "https",
},
},
},
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "Any Datadog deployment.",
DefaultValue: "datadoghq.com",
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "api",
},
},
},
},
"v1.LogsApi.SubmitLog": {
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "The regional site for Datadog customers.",
DefaultValue: "datadoghq.com",
EnumValues: []string{
"datadoghq.com",
"us3.datadoghq.com",
"us5.datadoghq.com",
"datadoghq.eu",
"ddog-gov.com",
},
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "http-intake.logs",
},
},
},
{
URL: "{protocol}://{name}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"name": {
Description: "Full site DNS name.",
DefaultValue: "http-intake.logs.datadoghq.com",
},
"protocol": {
Description: "The protocol for accessing the API.",
DefaultValue: "https",
},
},
},
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "Any Datadog deployment.",
DefaultValue: "datadoghq.com",
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "http-intake.logs",
},
},
},
},
"v2.LogsApi.SubmitLog": {
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "The regional site for customers.",
DefaultValue: "datadoghq.com",
EnumValues: []string{
"datadoghq.com",
"us3.datadoghq.com",
"us5.datadoghq.com",
"datadoghq.eu",
"ddog-gov.com",
},
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "http-intake.logs",
},
},
},
{
URL: "{protocol}://{name}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"name": {
Description: "Full site DNS name.",
DefaultValue: "http-intake.logs.datadoghq.com",
},
"protocol": {
Description: "The protocol for accessing the API.",
DefaultValue: "https",
},
},
},
{
URL: "https://{subdomain}.{site}",
Description: "No description provided",
Variables: map[string]ServerVariable{
"site": {
Description: "Any Datadog deployment.",
DefaultValue: "datadoghq.com",
},
"subdomain": {
Description: "The subdomain where the API is deployed.",
DefaultValue: "http-intake.logs",
},
},
},
},
},
unstableOperations: map[string]bool{
"v2.ListEvents": false,
"v2.SearchEvents": false,
"v2.CreateIncident": false,
"v2.CreateIncidentIntegration": false,
"v2.DeleteIncident": false,
"v2.DeleteIncidentIntegration": false,
"v2.GetIncident": false,
"v2.GetIncidentIntegration": false,
"v2.ListIncidentAttachments": false,
"v2.ListIncidentIntegrations": false,
"v2.ListIncidents": false,
"v2.SearchIncidents": false,
"v2.UpdateIncident": false,
"v2.UpdateIncidentAttachments": false,
"v2.UpdateIncidentIntegration": false,
"v2.QueryScalarData": false,
"v2.QueryTimeseriesData": false,
"v2.CreateIncidentService": false,
"v2.DeleteIncidentService": false,
"v2.GetIncidentService": false,
"v2.ListIncidentServices": false,
"v2.UpdateIncidentService": false,
"v2.CreateIncidentTeam": false,
"v2.DeleteIncidentTeam": false,
"v2.GetIncidentTeam": false,
"v2.ListIncidentTeams": false,
"v2.UpdateIncidentTeam": false,
},
RetryConfiguration: RetryConfiguration{
EnableRetry: false,
BackOffMultiplier: 2,
BackOffBase: 2,
HTTPRetryTimeout: 60 * time.Second,
MaxRetries: 3,
},
}
return cfg
}
// AddDefaultHeader adds a new HTTP header to the default header in the request.
func (c *Configuration) AddDefaultHeader(key string, value string) {
c.DefaultHeader[key] = value
}
// URL formats template on a index using given variables.
func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) {
if index < 0 || len(sc) <= index {
return "", fmt.Errorf("index %v out of range %v", index, len(sc)-1)
}
server := sc[index]
url := server.URL
// go through variables and replace placeholders
for name, variable := range server.Variables {
if value, ok := variables[name]; ok {
found := bool(len(variable.EnumValues) == 0)
for _, enumValue := range variable.EnumValues {
if value == enumValue {
found = true
}
}
if !found {
return "", fmt.Errorf("the variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues)
}
url = strings.Replace(url, "{"+name+"}", value, -1)
} else {
url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1)
}
}
return url, nil
}
// ServerURL returns URL based on server settings.
func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) {
return c.Servers.URL(index, variables)
}
func getServerIndex(ctx context.Context) (int, error) {
si := ctx.Value(ContextServerIndex)
if si != nil {
if index, ok := si.(int); ok {
return index, nil
}
return 0, ReportError("invalid type %T should be int", si)
}
return 0, nil
}
func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) {
osi := ctx.Value(ContextOperationServerIndices)
if osi != nil {
operationIndices, ok := osi.(map[string]int)
if !ok {
return 0, ReportError("invalid type %T should be map[string]int", osi)
}
index, ok := operationIndices[endpoint]
if ok {
return index, nil
}
}
return getServerIndex(ctx)
}
func getServerVariables(ctx context.Context) (map[string]string, error) {
sv := ctx.Value(ContextServerVariables)
if sv != nil {
if variables, ok := sv.(map[string]string); ok {
return variables, nil
}
return nil, ReportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv)
}
return nil, nil
}
func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) {
osv := ctx.Value(ContextOperationServerVariables)
if osv != nil {
operationVariables, ok := osv.(map[string]map[string]string)
if !ok {
return nil, ReportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv)
}
variables, ok := operationVariables[endpoint]
if ok {
return variables, nil
}
}
return getServerVariables(ctx)
}
// ServerURLWithContext returns a new server URL given an endpoint.
func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) {
sc, ok := c.OperationServers[endpoint]
if !ok {
sc = c.Servers
}
if ctx == nil {
return sc.URL(0, nil)
}
index, err := getServerOperationIndex(ctx, endpoint)
if err != nil {
return "", err
}
variables, err := getServerOperationVariables(ctx, endpoint)
if err != nil {
return "", err
}
return sc.URL(index, variables)
}
// GetUnstableOperations returns a slice with all unstable operation Ids.
func (c *Configuration) GetUnstableOperations() []string {
ids := make([]string, len(c.unstableOperations))
for id := range c.unstableOperations {
ids = append(ids, id)
}
return ids
}
// SetUnstableOperationEnabled sets an unstable operation as enabled (true) or disabled (false).
// This function accepts operation ID as an argument - this is the name of the method on the API class, e.g. "CreateFoo"
// Returns true if the operation is marked as unstable and thus was enabled/disabled, false otherwise.
func (c *Configuration) SetUnstableOperationEnabled(operation string, enabled bool) bool {
if _, ok := c.unstableOperations[operation]; ok {
c.unstableOperations[operation] = enabled
return true
}
log.Printf("WARNING: '%s' is not an unstable operation, can't enable/disable", operation)
return false
}
// IsUnstableOperation determines whether an operation is an unstable operation.
// This function accepts operation ID as an argument - this is the name of the method on the API class, e.g. "CreateFoo".
func (c *Configuration) IsUnstableOperation(operation string) bool {
_, present := c.unstableOperations[operation]
return present
}
// IsUnstableOperationEnabled determines whether an unstable operation is enabled.
// This function accepts operation ID as an argument - this is the name of the method on the API class, e.g. "CreateFoo"
// Returns true if the operation is unstable and it is enabled, false otherwise.
func (c *Configuration) IsUnstableOperationEnabled(operation string) bool {
if enabled, present := c.unstableOperations[operation]; present {
return enabled
}
log.Printf("WARNING: '%s' is not an unstable operation, is always enabled", operation)
return false
}
func getUserAgent() string {
return fmt.Sprintf(
"datadog-api-client-go/%s (go %s; os %s; arch %s)",
client.Version,
runtime.Version(),
runtime.GOOS,
runtime.GOARCH,
)
}
// NewDefaultContext returns a new context setup with environment variables.
func NewDefaultContext(ctx context.Context) context.Context {
if ctx == nil {
ctx = context.Background()
}
if site, ok := os.LookupEnv("DD_SITE"); ok {
ctx = context.WithValue(
ctx,
ContextServerVariables,
map[string]string{"site": site},
)
}
keys := make(map[string]APIKey)
if apiKey, ok := os.LookupEnv("DD_API_KEY"); ok {
keys["apiKeyAuth"] = APIKey{Key: apiKey}
}
if apiKey, ok := os.LookupEnv("DD_APP_KEY"); ok {
keys["appKeyAuth"] = APIKey{Key: apiKey}
}
ctx = context.WithValue(
ctx,
ContextAPIKeys,
keys,
)
return ctx
}