-
Notifications
You must be signed in to change notification settings - Fork 287
Expand file tree
/
Copy pathconfigure_clients.go
More file actions
698 lines (604 loc) · 20.7 KB
/
configure_clients.go
File metadata and controls
698 lines (604 loc) · 20.7 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
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
package provider
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"maps"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"syscall"
"time"
onCallAPI "github.com/grafana/amixr-api-go-client"
"github.com/grafana/grafana-app-sdk/k8s"
"github.com/grafana/grafana-app-sdk/resource"
assertsapi "github.com/grafana/grafana-asserts-public-clients/go/gcom"
"github.com/grafana/grafana-com-public-clients/go/gcom"
goapi "github.com/grafana/grafana-openapi-client-go/client"
"github.com/grafana/k6-cloud-openapi-client-go/k6"
"github.com/grafana/machine-learning-go-client/mlapi"
"github.com/grafana/slo-openapi-client/go/slo"
SMAPI "github.com/grafana/synthetic-monitoring-api-go-client"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
"github.com/go-openapi/strfmt"
"github.com/hashicorp/go-retryablehttp"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/grafana/terraform-provider-grafana/v4/internal/common"
"github.com/grafana/terraform-provider-grafana/v4/internal/common/cloudproviderapi"
"github.com/grafana/terraform-provider-grafana/v4/internal/common/connectionsapi"
"github.com/grafana/terraform-provider-grafana/v4/internal/common/fleetmanagementapi"
"github.com/grafana/terraform-provider-grafana/v4/internal/common/frontendo11yapi"
"github.com/grafana/terraform-provider-grafana/v4/internal/common/k6providerapi"
"github.com/grafana/terraform-provider-grafana/v4/internal/resources/grafana"
)
func CreateClients(providerConfig ProviderConfig) (*common.Client, error) {
var err error
c := &common.Client{}
if !providerConfig.Auth.IsNull() && !providerConfig.URL.IsNull() {
if err = createGrafanaAPIClient(c, providerConfig); err != nil {
return nil, err
}
if err = createGrafanaAppPlatformClient(c, providerConfig); err != nil {
return nil, err
}
if err = createMLClient(c, providerConfig); err != nil {
return nil, err
}
if err = createSLOClient(c, providerConfig); err != nil {
return nil, err
}
}
if !providerConfig.CloudAccessPolicyToken.IsNull() {
if err := createCloudClient(c, providerConfig); err != nil {
return nil, err
}
}
if !providerConfig.SMAccessToken.IsNull() {
versionString := providerConfig.Version.ValueString()
if versionString == "" {
versionString = "unknown"
}
c.SMAPI = SMAPI.NewClient(providerConfig.SMURL.ValueString(), providerConfig.SMAccessToken.ValueString(), getRetryClient(providerConfig))
c.SMAPI.SetCustomClientID("terraform")
c.SMAPI.SetCustomClientVersion(versionString)
}
if !providerConfig.OncallURL.IsNull() && (!providerConfig.OncallAccessToken.IsNull() || (!providerConfig.Auth.IsNull() && !providerConfig.URL.IsNull())) {
var onCallClient *onCallAPI.Client
onCallClient, err = createOnCallClient(providerConfig)
if err != nil {
return nil, err
}
onCallClient.UserAgent = providerConfig.UserAgent.ValueString()
c.OnCallClient = onCallClient
}
if !providerConfig.CloudProviderAccessToken.IsNull() {
if err := createCloudProviderClient(c, providerConfig); err != nil {
return nil, err
}
}
if !providerConfig.ConnectionsAPIAccessToken.IsNull() {
if err := createConnectionsClient(c, providerConfig); err != nil {
return nil, err
}
}
if !providerConfig.FleetManagementAuth.IsNull() {
if err := createFleetManagementClient(c, providerConfig); err != nil {
return nil, err
}
}
if !providerConfig.FrontendO11yAPIAccessToken.IsNull() || !providerConfig.CloudAccessPolicyToken.IsNull() {
if err := createFrontendO11yClient(c, providerConfig); err != nil {
return nil, err
}
}
// Create Asserts client if we have Grafana authentication
if err := createAssertsClientIfConfigured(c, providerConfig); err != nil {
return nil, err
}
if !providerConfig.K6AccessToken.IsNull() && !providerConfig.StackID.IsNull() {
if err := createK6Client(c, providerConfig); err != nil {
return nil, err
}
}
grafana.StoreDashboardSHA256 = providerConfig.StoreDashboardSha256.ValueBool()
return c, nil
}
func createGrafanaAPIClient(client *common.Client, providerConfig ProviderConfig) error {
tlsClientConfig, err := parseTLSconfig(providerConfig)
if err != nil {
return err
}
tlsConfig, err := tlsClientConfig.TLSConfig()
if err != nil {
return err
}
client.GrafanaAPIURL = providerConfig.URL.ValueString()
client.GrafanaAPIURLParsed, err = url.Parse(providerConfig.URL.ValueString())
if err != nil {
return fmt.Errorf("failed to parse API url: %v", err.Error())
}
if client.GrafanaAPIURLParsed.Scheme == "http" && strings.Contains(client.GrafanaAPIURLParsed.Host, "grafana.net") {
return fmt.Errorf("http not supported in Grafana Cloud. Use the https scheme")
}
apiPath, err := url.JoinPath(client.GrafanaAPIURLParsed.Path, "api")
if err != nil {
return fmt.Errorf("failed to join API path: %v", err.Error())
}
userInfo, orgID, apiKey, err := parseAuth(providerConfig)
if err != nil {
return err
}
if orgID > 1 && apiKey != "" {
return fmt.Errorf("org_id is only supported with basic auth. API keys are already org-scoped")
}
cfg := goapi.TransportConfig{
Host: client.GrafanaAPIURLParsed.Host,
BasePath: apiPath,
Schemes: []string{client.GrafanaAPIURLParsed.Scheme},
NumRetries: int(providerConfig.Retries.ValueInt64()),
RetryTimeout: time.Second * time.Duration(providerConfig.RetryWait.ValueInt64()),
RetryStatusCodes: setToStringArray(providerConfig.RetryStatusCodes.Elements()),
TLSConfig: tlsConfig,
BasicAuth: userInfo,
OrgID: orgID,
APIKey: apiKey,
}
if cfg.HTTPHeaders, err = getHTTPHeadersMap(providerConfig); err != nil {
return err
}
cfg.HTTPHeaders["User-Agent"] = providerConfig.UserAgent.ValueString()
client.GrafanaAPI = goapi.NewHTTPClientWithConfig(strfmt.Default, &cfg)
client.GrafanaAPIConfig = &cfg
return nil
}
func createGrafanaAppPlatformClient(client *common.Client, cfg ProviderConfig) error {
rcfg := rest.Config{
UserAgent: cfg.UserAgent.ValueString(),
Host: cfg.URL.ValueString(),
APIPath: "/apis",
}
tlsClientConfig, err := parseTLSconfig(cfg)
if err != nil {
return err
}
// Kubernetes really is wonderful, huh.
// tl;dr it has it's own TLSClientConfig,
// and it's not compatible with the one from the "crypto/tls" package.
rcfg.TLSClientConfig = rest.TLSClientConfig{
Insecure: tlsClientConfig.InsecureSkipVerify,
}
if len(tlsClientConfig.CertData) > 0 {
rcfg.CertData = tlsClientConfig.CertData
}
if len(tlsClientConfig.KeyData) > 0 {
rcfg.KeyData = tlsClientConfig.KeyData
}
if len(tlsClientConfig.CAData) > 0 {
rcfg.CAData = tlsClientConfig.CAData
}
userInfo, orgID, apiKey, err := parseAuth(cfg)
if err != nil {
return err
}
switch {
case apiKey != "":
if orgID > 1 {
return fmt.Errorf("org_id is only supported with basic auth. API keys are already org-scoped")
}
rcfg.BearerToken = apiKey
case userInfo != nil:
rcfg.Username = userInfo.Username()
if p, ok := userInfo.Password(); ok {
rcfg.Password = p
}
}
client.GrafanaOrgID = cfg.OrgID.ValueInt64()
client.GrafanaStackID = cfg.StackID.ValueInt64()
client.GrafanaAppPlatformAPIClientID = cfg.UserAgent.ValueString()
appPlatformTLSConfig, _ := tlsClientConfig.TLSConfig()
client.GrafanaHTTPClient = newGrafanaHTTPClient(appPlatformTLSConfig, userInfo, apiKey, client.GrafanaAPIConfig)
client.GrafanaAppPlatformAPI = k8s.NewClientRegistry(rcfg, k8s.ClientConfig{
NegotiatedSerializerProvider: func(kind resource.Kind) runtime.NegotiatedSerializer {
return &k8s.KindNegotiatedSerializer{
Kind: kind,
}
},
})
return nil
}
func createMLClient(client *common.Client, providerConfig ProviderConfig) error {
mlcfg := mlapi.Config{
BasicAuth: client.GrafanaAPIConfig.BasicAuth,
BearerToken: client.GrafanaAPIConfig.APIKey,
Client: getRetryClient(providerConfig),
}
mlURL := client.GrafanaAPIURL
if !strings.HasSuffix(mlURL, "/") {
mlURL += "/"
}
mlURL += "api/plugins/grafana-ml-app/resources"
var err error
client.MLAPI, err = mlapi.New(mlURL, mlcfg)
return err
}
func createSLOClient(client *common.Client, providerConfig ProviderConfig) error {
var err error
sloConfig := slo.NewConfiguration()
sloConfig.Host = client.GrafanaAPIURLParsed.Host
sloConfig.Scheme = client.GrafanaAPIURLParsed.Scheme
sloConfig.DefaultHeader, err = getHTTPHeadersMap(providerConfig)
sloConfig.DefaultHeader["Authorization"] = "Bearer " + providerConfig.Auth.ValueString()
sloConfig.UserAgent = providerConfig.UserAgent.ValueString()
sloConfig.HTTPClient = getRetryClient(providerConfig)
client.SLOClient = slo.NewAPIClient(sloConfig)
return err
}
func createCloudClient(client *common.Client, providerConfig ProviderConfig) error {
openAPIConfig := gcom.NewConfiguration()
parsedURL, err := url.Parse(providerConfig.CloudAPIURL.ValueString())
if err != nil {
return err
}
openAPIConfig.Host = parsedURL.Host
openAPIConfig.Scheme = parsedURL.Scheme
openAPIConfig.HTTPClient = getRetryClient(providerConfig)
openAPIConfig.DefaultHeader["Authorization"] = "Bearer " + providerConfig.CloudAccessPolicyToken.ValueString()
openAPIConfig.UserAgent = providerConfig.UserAgent.String()
httpHeaders, err := getHTTPHeadersMap(providerConfig)
if err != nil {
return err
}
maps.Copy(openAPIConfig.DefaultHeader, httpHeaders)
client.GrafanaCloudAPI = gcom.NewAPIClient(openAPIConfig)
return nil
}
func createOnCallClient(providerConfig ProviderConfig) (*onCallAPI.Client, error) {
authToken := providerConfig.OncallAccessToken.ValueString()
if authToken == "" {
// prefer OncallAccessToken if it was set, otherwise use Grafana auth (service account) token
authToken = providerConfig.Auth.ValueString()
}
return onCallAPI.NewWithGrafanaURL(providerConfig.OncallURL.ValueString(), authToken, providerConfig.URL.ValueString())
}
func createCloudProviderClient(client *common.Client, providerConfig ProviderConfig) error {
providerHeaders, err := getHTTPHeadersMap(providerConfig)
if err != nil {
return fmt.Errorf("failed to get provider default HTTP headers: %w", err)
}
providerHeaders["User-Agent"] = providerConfig.UserAgent.ValueString()
apiClient, err := cloudproviderapi.NewClient(
providerConfig.CloudProviderAccessToken.ValueString(),
providerConfig.CloudProviderURL.ValueString(),
getRetryClient(providerConfig),
providerHeaders,
)
if err != nil {
return err
}
client.CloudProviderAPI = apiClient
return nil
}
func createFrontendO11yClient(client *common.Client, providerConfig ProviderConfig) error {
providerHeaders, err := getHTTPHeadersMap(providerConfig)
if err != nil {
return fmt.Errorf("failed to get provider default HTTP headers: %w", err)
}
var token string
if providerConfig.FrontendO11yAPIAccessToken.IsNull() {
token = providerConfig.CloudAccessPolicyToken.ValueString()
} else {
token = providerConfig.FrontendO11yAPIAccessToken.ValueString()
}
cURL, err := url.Parse(providerConfig.CloudAPIURL.ValueString())
if err != nil {
return err
}
cHostParts := strings.Split(cURL.Host, ".")
if len(cHostParts) < 2 {
return fmt.Errorf("invalid cloud url")
}
// https://grafana.com -> grafana.net
cHost := fmt.Sprintf("%s.net", cHostParts[len(cHostParts)-2])
apiClient, err := frontendo11yapi.NewClient(
providerConfig.FrontendO11YAPIURL.ValueString(),
cHost,
token,
getRetryClient(providerConfig),
providerConfig.UserAgent.ValueString(),
providerHeaders,
)
if err != nil {
return err
}
client.FrontendO11yAPIClient = apiClient
return nil
}
func createConnectionsClient(client *common.Client, providerConfig ProviderConfig) error {
providerHeaders, err := getHTTPHeadersMap(providerConfig)
if err != nil {
return fmt.Errorf("failed to get provider default HTTP headers: %w", err)
}
apiClient, err := connectionsapi.NewClient(
providerConfig.ConnectionsAPIAccessToken.ValueString(),
providerConfig.ConnectionsAPIURL.ValueString(),
getRetryClient(providerConfig),
providerConfig.UserAgent.ValueString(),
providerHeaders,
)
if err != nil {
return err
}
client.ConnectionsAPIClient = apiClient
return nil
}
func createK6Client(client *common.Client, providerConfig ProviderConfig) error {
k6Cfg := k6.NewConfiguration()
if !providerConfig.K6URL.IsNull() {
k6Cfg.Servers = []k6.ServerConfiguration{
{URL: providerConfig.K6URL.ValueString()},
}
}
k6Cfg.UserAgent = providerConfig.UserAgent.ValueString()
k6Cfg.HTTPClient = getRetryClient(providerConfig)
httpHeaders, err := getHTTPHeadersMap(providerConfig)
if err != nil {
return err
}
maps.Copy(k6Cfg.DefaultHeader, httpHeaders)
var stackID int32
if stackID, err = common.ToInt32(providerConfig.StackID.ValueInt64()); err != nil {
return fmt.Errorf("could not convert stack_id to int32: %s", err.Error())
}
client.K6APIClient = k6.NewAPIClient(k6Cfg)
client.K6APIConfig = &k6providerapi.K6APIConfig{
Token: providerConfig.K6AccessToken.ValueString(),
StackID: stackID,
}
return nil
}
func createFleetManagementClient(client *common.Client, providerConfig ProviderConfig) error {
providerHeaders, err := getHTTPHeadersMap(providerConfig)
if err != nil {
return fmt.Errorf("failed to get provider default HTTP headers: %w", err)
}
client.FleetManagementClient = fleetmanagementapi.NewClient(
providerConfig.FleetManagementAuth.ValueString(),
providerConfig.FleetManagementURL.ValueString(),
getRetryClient(providerConfig),
providerConfig.UserAgent.ValueString(),
providerHeaders,
)
return nil
}
// Sets a custom HTTP Header on all requests coming from the Grafana Terraform Provider to Grafana-Terraform-Provider: true
// in addition to any headers set within the `http_headers` field or the `GRAFANA_HTTP_HEADERS` environment variable
func getHTTPHeadersMap(providerConfig ProviderConfig) (map[string]string, error) {
headers := map[string]string{
"Grafana-Terraform-Provider": "true",
"Grafana-Terraform-Provider-Version": providerConfig.Version.ValueString(),
}
for k, v := range providerConfig.HTTPHeaders.Elements() {
if vString, ok := v.(types.String); ok {
headers[k] = vString.ValueString()
} else {
return nil, fmt.Errorf("invalid header value for %s: %v", k, v)
}
}
return headers, nil
}
func createAssertsClientIfConfigured(client *common.Client, providerConfig ProviderConfig) error {
if !providerConfig.Auth.IsNull() && !providerConfig.URL.IsNull() {
return createAssertsClient(client, providerConfig)
}
return nil
}
func createAssertsClient(client *common.Client, providerConfig ProviderConfig) error {
providerHeaders, err := getHTTPHeadersMap(providerConfig)
if err != nil {
return fmt.Errorf("failed to get provider default HTTP headers: %w", err)
}
// Create configuration for the generated Asserts client
cfg := assertsapi.NewConfiguration()
cfg.Host = client.GrafanaAPIURLParsed.Host
cfg.Scheme = client.GrafanaAPIURLParsed.Scheme
cfg.UserAgent = providerConfig.UserAgent.ValueString()
cfg.HTTPClient = getRetryClient(providerConfig)
// Override the server configuration to point to Grafana plugin API
// The generated client expects /v1/config/... paths, so we set the base to the plugin resources path
baseURL := fmt.Sprintf("%s://%s/api/plugins/grafana-asserts-app/resources/asserts/api-server", cfg.Scheme, cfg.Host)
cfg.Servers = assertsapi.ServerConfigurations{
{
URL: baseURL,
Description: "Grafana Cloud API Gateway for Asserts",
},
}
// Set default headers including authorization
if cfg.DefaultHeader == nil {
cfg.DefaultHeader = make(map[string]string)
}
// Add provider headers
maps.Copy(cfg.DefaultHeader, providerHeaders)
// Add authorization header - this will be overridden per request with stack-specific auth
cfg.DefaultHeader["Authorization"] = "Bearer " + providerConfig.Auth.ValueString()
// Create the API client
apiClient := assertsapi.NewAPIClient(cfg)
client.AssertsAPIClient = apiClient
return nil
}
func createTempFileIfLiteral(value string) (path string, tempFile bool, err error) {
if value == "" {
return "", false, nil
}
if _, err := os.Stat(value); errors.Is(err, os.ErrNotExist) || errors.Is(err, syscall.ENAMETOOLONG) {
// value is not a file path, assume it's a literal
f, err := os.CreateTemp("", "grafana-provider-tls")
if err != nil {
return "", false, err
}
if _, err := f.WriteString(value); err != nil {
return "", false, err
}
if err := f.Close(); err != nil {
return "", false, err
}
return f.Name(), true, nil
}
return value, false, nil
}
func parseAuth(providerConfig ProviderConfig) (*url.Userinfo, int64, string, error) {
auth := strings.SplitN(providerConfig.Auth.ValueString(), ":", 2)
var orgID int64 = 1
if len(auth) == 2 {
user := strings.TrimSpace(auth[0])
pass := strings.TrimSpace(auth[1])
return url.UserPassword(user, pass), orgID, "", nil
} else if auth[0] != "anonymous" {
apiKey := strings.TrimSpace(auth[0])
return nil, 0, apiKey, nil
}
return nil, 0, "", nil
}
type TLSConfig struct {
CAData []byte
CertData []byte
KeyData []byte
InsecureSkipVerify bool
}
func (t TLSConfig) TLSConfig() (*tls.Config, error) {
pool, err := x509.SystemCertPool()
if err != nil {
return nil, fmt.Errorf("failed to get system certificate pool: %w", err)
}
res := &tls.Config{
// gosec is stating the obvious here.
// G402: TLS InsecureSkipVerify may be true. (gosec)
// nolint: gosec
InsecureSkipVerify: t.InsecureSkipVerify,
RootCAs: pool,
}
if len(t.CAData) > 0 {
if !res.RootCAs.AppendCertsFromPEM(t.CAData) {
return nil, fmt.Errorf("failed to append CA data")
}
}
if len(t.CertData) > 0 && len(t.KeyData) > 0 {
cert, err := tls.X509KeyPair(t.CertData, t.KeyData)
if err != nil {
return nil, err
}
res.Certificates = []tls.Certificate{cert}
}
return res, nil
}
func parseTLSconfig(providerConfig ProviderConfig) (*TLSConfig, error) {
res := &TLSConfig{
InsecureSkipVerify: providerConfig.InsecureSkipVerify.ValueBool(),
}
tlsKeyFile, tempFile, err := createTempFileIfLiteral(providerConfig.TLSKey.ValueString())
if err != nil {
return nil, err
}
if tempFile {
defer os.Remove(tlsKeyFile)
}
tlsCertFile, tempFile, err := createTempFileIfLiteral(providerConfig.TLSCert.ValueString())
if err != nil {
return nil, err
}
if tempFile {
defer os.Remove(tlsCertFile)
}
caCertFile, tempFile, err := createTempFileIfLiteral(providerConfig.CACert.ValueString())
if err != nil {
return nil, err
}
if tempFile {
defer os.Remove(caCertFile)
}
if caCertFile != "" {
ca, err := os.ReadFile(caCertFile)
if err != nil {
return nil, err
}
res.CAData = ca
}
if tlsCertFile != "" {
certData, err := os.ReadFile(tlsCertFile)
if err != nil {
return nil, err
}
res.CertData = certData
}
if tlsKeyFile != "" {
keyData, err := os.ReadFile(tlsKeyFile)
if err != nil {
return nil, err
}
res.KeyData = keyData
}
return res, nil
}
func setToStringArray(set []attr.Value) []string {
var result []string
for _, v := range set {
result = append(result, v.(types.String).ValueString())
}
return result
}
// newGrafanaHTTPClient builds an *http.Client with TLS, auth, and headers
// matching the provider configuration. Used by the generic app platform
// resource for bootdata and discovery calls.
func newGrafanaHTTPClient(tlsConfig *tls.Config, userInfo *url.Userinfo, apiKey string, apiConfig *goapi.TransportConfig) *http.Client {
transport := http.DefaultTransport.(*http.Transport).Clone()
if tlsConfig != nil {
transport.TLSClientConfig = tlsConfig.Clone()
}
return &http.Client{
Transport: &grafanaHTTPRoundTripper{
base: transport,
userInfo: userInfo,
apiKey: apiKey,
apiConfig: apiConfig,
},
}
}
// grafanaHTTPRoundTripper injects auth and headers into every request,
// matching the provider's Grafana API configuration.
type grafanaHTTPRoundTripper struct {
base http.RoundTripper
userInfo *url.Userinfo
apiKey string
apiConfig *goapi.TransportConfig
}
func (rt *grafanaHTTPRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
if rt.apiConfig != nil {
for key, value := range rt.apiConfig.HTTPHeaders {
req.Header.Set(key, value)
}
if rt.apiConfig.OrgID > 0 {
req.Header.Set("X-Grafana-Org-Id", strconv.FormatInt(rt.apiConfig.OrgID, 10))
}
}
switch {
case rt.apiKey != "":
req.Header.Set("Authorization", "Bearer "+rt.apiKey)
case rt.userInfo != nil:
password, _ := rt.userInfo.Password()
req.SetBasicAuth(rt.userInfo.Username(), password)
}
return rt.base.RoundTrip(req)
}
func getRetryClient(providerConfig ProviderConfig) *http.Client {
retryClient := retryablehttp.NewClient()
retryClient.RetryMax = int(providerConfig.Retries.ValueInt64())
if wait := providerConfig.RetryWait.ValueInt64(); wait > 0 {
retryClient.RetryWaitMin = time.Second * time.Duration(wait)
retryClient.RetryWaitMax = time.Second * time.Duration(wait)
}
return retryClient.StandardClient()
}