/
utils.go
514 lines (436 loc) · 13.2 KB
/
utils.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
// Contains functions that don't really belong anywhere else.
package google
import (
"fmt"
"log"
"os"
"sort"
"strings"
"time"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"google.golang.org/api/googleapi"
)
type TerraformResourceDataChange interface {
GetChange(string) (interface{}, interface{})
}
type TerraformResourceData interface {
HasChange(string) bool
GetOkExists(string) (interface{}, bool)
GetOk(string) (interface{}, bool)
Get(string) interface{}
Set(string, interface{}) error
SetId(string)
Id() string
GetProviderMeta(interface{}) error
Timeout(key string) time.Duration
}
type TerraformResourceDiff interface {
HasChange(string) bool
GetChange(string) (interface{}, interface{})
Get(string) interface{}
GetOk(string) (interface{}, bool)
Clear(string) error
ForceNew(string) error
}
// getRegionFromZone returns the region from a zone for Google cloud.
func getRegionFromZone(zone string) string {
if zone != "" && len(zone) > 2 {
region := zone[:len(zone)-2]
return region
}
return ""
}
// Infers the region based on the following (in order of priority):
// - `region` field in resource schema
// - region extracted from the `zone` field in resource schema
// - provider-level region
// - region extracted from the provider-level zone
func getRegion(d TerraformResourceData, config *Config) (string, error) {
return getRegionFromSchema("region", "zone", d, config)
}
// getProject reads the "project" field from the given resource data and falls
// back to the provider's value if not given. If the provider's value is not
// given, an error is returned.
func getProject(d TerraformResourceData, config *Config) (string, error) {
return getProjectFromSchema("project", d, config)
}
// getBillingProject reads the "billing_project" field from the given resource data and falls
// back to the provider's value if not given. If no value is found, an error is returned.
func getBillingProject(d TerraformResourceData, config *Config) (string, error) {
return getBillingProjectFromSchema("billing_project", d, config)
}
// getProjectFromDiff reads the "project" field from the given diff and falls
// back to the provider's value if not given. If the provider's value is not
// given, an error is returned.
func getProjectFromDiff(d *schema.ResourceDiff, config *Config) (string, error) {
res, ok := d.GetOk("project")
if ok {
return res.(string), nil
}
if config.Project != "" {
return config.Project, nil
}
return "", fmt.Errorf("%s: required field is not set", "project")
}
func getRouterLockName(region string, router string) string {
return fmt.Sprintf("router/%s/%s", region, router)
}
func handleNotFoundError(err error, d *schema.ResourceData, resource string) error {
if isGoogleApiErrorWithCode(err, 404) {
log.Printf("[WARN] Removing %s because it's gone", resource)
// The resource doesn't exist anymore
d.SetId("")
return nil
}
return errwrap.Wrapf(
fmt.Sprintf("Error when reading or editing %s: {{err}}", resource), err)
}
func isGoogleApiErrorWithCode(err error, errCode int) bool {
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
return ok && gerr != nil && gerr.Code == errCode
}
func isApiNotEnabledError(err error) bool {
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
if !ok {
return false
}
if gerr == nil {
return false
}
if gerr.Code != 403 {
return false
}
for _, e := range gerr.Errors {
if e.Reason == "accessNotConfigured" {
return true
}
}
return false
}
func isFailedPreconditionError(err error) bool {
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
if !ok {
return false
}
if gerr == nil {
return false
}
if gerr.Code != 400 {
return false
}
for _, e := range gerr.Errors {
if e.Reason == "failedPrecondition" {
return true
}
}
return false
}
func isConflictError(err error) bool {
if e, ok := err.(*googleapi.Error); ok && (e.Code == 409 || e.Code == 412) {
return true
} else if !ok && errwrap.ContainsType(err, &googleapi.Error{}) {
e := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
if e.Code == 409 || e.Code == 412 {
return true
}
}
return false
}
// expandLabels pulls the value of "labels" out of a TerraformResourceData as a map[string]string.
func expandLabels(d TerraformResourceData) map[string]string {
return expandStringMap(d, "labels")
}
// expandEnvironmentVariables pulls the value of "environment_variables" out of a schema.ResourceData as a map[string]string.
func expandEnvironmentVariables(d *schema.ResourceData) map[string]string {
return expandStringMap(d, "environment_variables")
}
// expandBuildEnvironmentVariables pulls the value of "build_environment_variables" out of a schema.ResourceData as a map[string]string.
func expandBuildEnvironmentVariables(d *schema.ResourceData) map[string]string {
return expandStringMap(d, "build_environment_variables")
}
// expandStringMap pulls the value of key out of a TerraformResourceData as a map[string]string.
func expandStringMap(d TerraformResourceData, key string) map[string]string {
v, ok := d.GetOk(key)
if !ok {
return map[string]string{}
}
return convertStringMap(v.(map[string]interface{}))
}
func convertStringMap(v map[string]interface{}) map[string]string {
m := make(map[string]string)
for k, val := range v {
m[k] = val.(string)
}
return m
}
func convertStringArr(ifaceArr []interface{}) []string {
return convertAndMapStringArr(ifaceArr, func(s string) string { return s })
}
func convertAndMapStringArr(ifaceArr []interface{}, f func(string) string) []string {
var arr []string
for _, v := range ifaceArr {
if v == nil {
continue
}
arr = append(arr, f(v.(string)))
}
return arr
}
func mapStringArr(original []string, f func(string) string) []string {
var arr []string
for _, v := range original {
arr = append(arr, f(v))
}
return arr
}
func convertStringArrToInterface(strs []string) []interface{} {
arr := make([]interface{}, len(strs))
for i, str := range strs {
arr[i] = str
}
return arr
}
func convertStringSet(set *schema.Set) []string {
s := make([]string, 0, set.Len())
for _, v := range set.List() {
s = append(s, v.(string))
}
sort.Strings(s)
return s
}
func golangSetFromStringSlice(strings []string) map[string]struct{} {
set := map[string]struct{}{}
for _, v := range strings {
set[v] = struct{}{}
}
return set
}
func stringSliceFromGolangSet(sset map[string]struct{}) []string {
ls := make([]string, 0, len(sset))
for s := range sset {
ls = append(ls, s)
}
sort.Strings(ls)
return ls
}
func reverseStringMap(m map[string]string) map[string]string {
o := map[string]string{}
for k, v := range m {
o[v] = k
}
return o
}
func mergeStringMaps(a, b map[string]string) map[string]string {
merged := make(map[string]string)
for k, v := range a {
merged[k] = v
}
for k, v := range b {
merged[k] = v
}
return merged
}
func mergeSchemas(a, b map[string]*schema.Schema) map[string]*schema.Schema {
merged := make(map[string]*schema.Schema)
for k, v := range a {
merged[k] = v
}
for k, v := range b {
merged[k] = v
}
return merged
}
func mergeResourceMaps(ms ...map[string]*schema.Resource) (map[string]*schema.Resource, error) {
merged := make(map[string]*schema.Resource)
duplicates := []string{}
for _, m := range ms {
for k, v := range m {
if _, ok := merged[k]; ok {
duplicates = append(duplicates, k)
}
merged[k] = v
}
}
var err error
if len(duplicates) > 0 {
err = fmt.Errorf("saw duplicates in mergeResourceMaps: %v", duplicates)
}
return merged, err
}
func extractFirstMapConfig(m []interface{}) map[string]interface{} {
if len(m) == 0 {
return map[string]interface{}{}
}
return m[0].(map[string]interface{})
}
func lockedCall(lockKey string, f func() error) error {
mutexKV.Lock(lockKey)
defer mutexKV.Unlock(lockKey)
return f()
}
// This is a Printf sibling (Nprintf; Named Printf), which handles strings like
// Nprintf("Hello %{target}!", map[string]interface{}{"target":"world"}) == "Hello world!".
// This is particularly useful for generated tests, where we don't want to use Printf,
// since that would require us to generate a very particular ordering of arguments.
func Nprintf(format string, params map[string]interface{}) string {
for key, val := range params {
format = strings.Replace(format, "%{"+key+"}", fmt.Sprintf("%v", val), -1)
}
return format
}
// serviceAccountFQN will attempt to generate the fully qualified name in the format of:
// "projects/(-|<project>)/serviceAccounts/<service_account_id>@<project>.iam.gserviceaccount.com"
// A project is required if we are trying to build the FQN from a service account id and
// and error will be returned in this case if no project is set in the resource or the
// provider-level config
func serviceAccountFQN(serviceAccount string, d TerraformResourceData, config *Config) (string, error) {
// If the service account id is already the fully qualified name
if strings.HasPrefix(serviceAccount, "projects/") {
return serviceAccount, nil
}
// If the service account id is an email
if strings.Contains(serviceAccount, "@") {
return "projects/-/serviceAccounts/" + serviceAccount, nil
}
// Get the project from the resource or fallback to the project
// in the provider configuration
project, err := getProject(d, config)
if err != nil {
return "", err
}
return fmt.Sprintf("projects/-/serviceAccounts/%s@%s.iam.gserviceaccount.com", serviceAccount, project), nil
}
func paginatedListRequest(project, baseUrl, userAgent string, config *Config, flattener func(map[string]interface{}) []interface{}) ([]interface{}, error) {
res, err := sendRequest(config, "GET", project, baseUrl, userAgent, nil)
if err != nil {
return nil, err
}
ls := flattener(res)
pageToken, ok := res["pageToken"]
for ok {
if pageToken.(string) == "" {
break
}
url := fmt.Sprintf("%s?pageToken=%s", baseUrl, pageToken.(string))
res, err = sendRequest(config, "GET", project, url, userAgent, nil)
if err != nil {
return nil, err
}
ls = append(ls, flattener(res))
pageToken, ok = res["pageToken"]
}
return ls, nil
}
func getInterconnectAttachmentLink(config *Config, project, region, ic, userAgent string) (string, error) {
if !strings.Contains(ic, "/") {
icData, err := config.NewComputeClient(userAgent).InterconnectAttachments.Get(
project, region, ic).Do()
if err != nil {
return "", fmt.Errorf("Error reading interconnect attachment: %s", err)
}
ic = icData.SelfLink
}
return ic, nil
}
// Given two sets of references (with "from" values in self link form),
// determine which need to be added or removed // during an update using
// addX/removeX APIs.
func calcAddRemove(from []string, to []string) (add, remove []string) {
add = make([]string, 0)
remove = make([]string, 0)
for _, u := range to {
found := false
for _, v := range from {
if compareSelfLinkOrResourceName("", v, u, nil) {
found = true
break
}
}
if !found {
add = append(add, u)
}
}
for _, u := range from {
found := false
for _, v := range to {
if compareSelfLinkOrResourceName("", u, v, nil) {
found = true
break
}
}
if !found {
remove = append(remove, u)
}
}
return add, remove
}
func stringInSlice(arr []string, str string) bool {
for _, i := range arr {
if i == str {
return true
}
}
return false
}
func migrateStateNoop(v int, is *terraform.InstanceState, meta interface{}) (*terraform.InstanceState, error) {
return is, nil
}
func expandString(v interface{}, d TerraformResourceData, config *Config) (string, error) {
return v.(string), nil
}
func changeFieldSchemaToForceNew(sch *schema.Schema) {
sch.ForceNew = true
switch sch.Type {
case schema.TypeList:
case schema.TypeSet:
if nestedR, ok := sch.Elem.(*schema.Resource); ok {
for _, nestedSch := range nestedR.Schema {
changeFieldSchemaToForceNew(nestedSch)
}
}
}
}
func generateUserAgentString(d TerraformResourceData, currentUserAgent string) (string, error) {
var m providerMeta
err := d.GetProviderMeta(&m)
if err != nil {
return currentUserAgent, err
}
if m.ModuleName != "" {
return strings.Join([]string{currentUserAgent, m.ModuleName}, " "), nil
}
return currentUserAgent, nil
}
func SnakeToPascalCase(s string) string {
split := strings.Split(s, "_")
for i := range split {
split[i] = strings.Title(split[i])
}
return strings.Join(split, "")
}
func multiEnvSearch(ks []string) string {
for _, k := range ks {
if v := os.Getenv(k); v != "" {
return v
}
}
return ""
}
func GetCurrentUserEmail(config *Config, userAgent string) (string, error) {
// See https://github.com/golang/oauth2/issues/306 for a recommendation to do this from a Go maintainer
// URL retrieved from https://accounts.google.com/.well-known/openid-configuration
res, err := sendRequest(config, "GET", "", "https://openidconnect.googleapis.com/v1/userinfo", userAgent, nil)
if err != nil {
return "", fmt.Errorf("error retrieving userinfo for your provider credentials. have you enabled the 'https://www.googleapis.com/auth/userinfo.email' scope? error: %s", err)
}
return res["email"].(string), nil
}
func checkStringMap(v interface{}) map[string]string {
m, ok := v.(map[string]string)
if ok {
return m
}
return convertStringMap(v.(map[string]interface{}))
}