forked from GoogleCloudPlatform/magic-modules
/
ancestrymanager.go
385 lines (358 loc) · 11.8 KB
/
ancestrymanager.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
// Package ancestrymanager provides an interface to query the ancestry information for a resource.
package ancestrymanager
import (
"fmt"
"strconv"
"strings"
"time"
crmv1 "google.golang.org/api/cloudresourcemanager/v1"
crmv3 "google.golang.org/api/cloudresourcemanager/v3"
"google.golang.org/api/storage/v1"
resources "github.com/GoogleCloudPlatform/terraform-google-conversion/v5/tfplan2cai/converters/google/resources"
"github.com/hashicorp/terraform-provider-google-beta/google-beta/tpgresource"
transport_tpg "github.com/hashicorp/terraform-provider-google-beta/google-beta/transport"
"go.uber.org/zap"
)
// AncestryManager is the interface that fetch ancestors for a resource.
type AncestryManager interface {
// Ancestors returns a list of ancestors.
Ancestors(config *transport_tpg.Config, tfData tpgresource.TerraformResourceData, cai *resources.Asset) ([]string, string, error)
}
type manager struct {
// The logger.
errorLogger *zap.Logger
// cloud resource manager V3 client. If this field is nil, online lookups will
// be disabled.
// cloud resource manager V1 client. If this field is nil, online lookups will
// be disabled.
resourceManagerV3 *crmv3.Service
resourceManagerV1 *crmv1.Service
storageClient *storage.Service
// Cache to prevent multiple network calls for looking up the same
// resource's ancestry. The map key is the resource itself, in the format of
// "<type>/<id>", ancestors are sorted from closest to furthest.
ancestorCache map[string][]string
}
// New returns AncestryManager that can be used to fetch ancestry information.
// Entries takes `projects/<number>` or `folders/<id>` as key and ancestry path
// as value to the offline cache. If the key is not prefix with `projects/` or
// `folders/`, it will be considered as a project. If offline is true, resource
// manager API requests for ancestry will be disabled.
func New(cfg *transport_tpg.Config, offline bool, entries map[string]string, errorLogger *zap.Logger) (AncestryManager, error) {
am := &manager{
ancestorCache: map[string][]string{},
errorLogger: errorLogger,
}
if !offline {
am.resourceManagerV1 = cfg.NewResourceManagerClient(cfg.UserAgent)
am.resourceManagerV3 = cfg.NewResourceManagerV3Client(cfg.UserAgent)
am.storageClient = cfg.NewStorageClient(cfg.UserAgent)
}
err := am.initAncestryCache(entries)
if err != nil {
return nil, err
}
return am, nil
}
func (m *manager) initAncestryCache(entries map[string]string) error {
for item, ancestry := range entries {
if item != "" && ancestry != "" {
ancestors, err := parseAncestryPath(ancestry)
if err != nil {
continue
}
key, err := parseAncestryKey(item)
if err != nil {
return err
}
// ancestry path should include the item itself
if ancestors[0] != key {
ancestors = append([]string{key}, ancestors...)
}
m.store(key, ancestors)
}
}
return nil
}
func parseAncestryKey(val string) (string, error) {
key := normalizeAncestry(val)
ix := strings.LastIndex(key, "/")
if ix == -1 {
// If not containing /, then treat it as a project.
return fmt.Sprintf("projects/%s", key), nil
} else {
k := key[:ix]
if k == "projects" || k == "folders" || k == "organizations" {
return key, nil
}
return "", fmt.Errorf("key with can only start with projects/, folders/, or organizations/")
}
}
// Ancestors uses the resource manager API to get ancestors for resource.
// It implements a cache because many resources share the same ancestors.
func (m *manager) Ancestors(config *transport_tpg.Config, tfData tpgresource.TerraformResourceData, cai *resources.Asset) ([]string, string, error) {
results, err := m.fetchAncestors(config, tfData, cai)
if err != nil {
return nil, "", err
}
parent, err := assetParent(cai, results)
if err != nil {
return nil, "", err
}
return results, parent, nil
}
// fetchAncestors uses the resource manager API to get ancestors for resource.
// It implements a cache because many resources share the same ancestors.
func (m *manager) fetchAncestors(config *transport_tpg.Config, tfData tpgresource.TerraformResourceData, cai *resources.Asset) ([]string, error) {
if cai == nil {
return nil, fmt.Errorf("CAI asset is nil")
}
m.errorLogger.Info(fmt.Sprintf("Retrieving ancestry from resource (type=%s)", cai.Type))
key := ""
orgKey := ""
folderKey := ""
projectKey := ""
orgID, orgOK := getOrganizationFromResource(tfData)
if orgOK {
orgKey = orgID
if !strings.HasPrefix(orgKey, "organizations/") {
orgKey = fmt.Sprintf("organizations/%s", orgKey)
}
}
folderID, folderOK := getFolderFromResource(tfData)
if folderOK {
folderKey = folderID
if !strings.HasPrefix(folderKey, "folders/") {
folderKey = fmt.Sprintf("folders/%s", folderKey)
}
}
project, _ := m.getProjectFromResource(tfData, config, cai)
if project != "" {
projectKey = project
if !strings.HasPrefix(projectKey, "projects/") {
projectKey = fmt.Sprintf("projects/%s", project)
}
}
switch cai.Type {
case "cloudresourcemanager.googleapis.com/Folder":
if folderOK {
key = folderKey
} else if orgOK {
key = orgKey
} else {
return []string{"organizations/unknown"}, nil
}
case "cloudresourcemanager.googleapis.com/Organization":
if !orgOK {
return nil, fmt.Errorf("organization id not found in terraform data")
}
key = orgKey
case "iam.googleapis.com/Role":
// google_organization_iam_custom_role or google_project_iam_custom_role
if orgOK {
key = orgKey
} else if projectKey != "" {
key = projectKey
} else {
return []string{"organizations/unknown"}, nil
}
case "cloudresourcemanager.googleapis.com/Project", "cloudbilling.googleapis.com/ProjectBillingInfo":
// for google_project and google_project_iam resources
var ancestors []string
if projectKey != "" {
ancestors = []string{projectKey}
// Get ancestry from project level with v1 API first.
// This is to avoid requiring folder level permission if
// there is no folder change.
m.getAncestorsWithCache(projectKey)
}
// only folder_id or org_id is allowed for google_project
if orgOK {
// no need to use API to fetch ancestors
ancestors = append(ancestors, fmt.Sprintf("organizations/%s", orgID))
return ancestors, nil
}
if folderOK {
// If folder is changed, then it goes with v3 API, else it will use cache.
key = folderKey
ret, err := m.getAncestorsWithCache(key)
if err != nil {
return nil, err
}
ancestors = append(ancestors, ret...)
return ancestors, nil
}
// neither folder_id nor org_id is specified
if projectKey == "" {
return []string{"organizations/unknown"}, nil
}
key = projectKey
default:
if projectKey == "" {
return []string{"organizations/unknown"}, nil
}
key = projectKey
}
return m.getAncestorsWithCache(key)
}
func (m *manager) getAncestorsWithCache(key string) ([]string, error) {
var ancestors []string
cur := key
for cur != "" {
if cachedAncestors, ok := m.ancestorCache[cur]; ok {
ancestors = append(ancestors, cachedAncestors...)
break
}
if strings.HasPrefix(cur, "organizations/") {
ancestors = append(ancestors, cur)
break
}
if m.resourceManagerV3 == nil || m.resourceManagerV1 == nil {
return nil, fmt.Errorf("resourceManager required to fetch ancestry for %s from the API", cur)
}
if strings.HasPrefix(cur, "projects") {
// fall back to use v1 API GetAncestry to avoid requiring extra folder permission
projectID := strings.TrimPrefix(cur, "projects/")
var resp *crmv1.GetAncestryResponse
var err error
err = transport_tpg.Retry(transport_tpg.RetryOptions{
RetryFunc: func() error {
resp, err = m.resourceManagerV1.Projects.GetAncestry(projectID, &crmv1.GetAncestryRequest{}).Do()
return err
},
Timeout: 2 * time.Minute,
})
if err != nil {
return nil, handleCRMError(cur, err)
}
for _, anc := range resp.Ancestor {
ancestor := normalizeAncestry(fmt.Sprintf("%s/%s", anc.ResourceId.Type, anc.ResourceId.Id))
ancestors = append(ancestors, ancestor)
}
// break out of the loop
cur = ""
} else {
var project *crmv3.Project
var err error
err = transport_tpg.Retry(transport_tpg.RetryOptions{
RetryFunc: func() error {
project, err = m.resourceManagerV3.Projects.Get(cur).Do()
return err
},
Timeout: 2 * time.Minute,
})
if err != nil {
return nil, handleCRMError(cur, err)
}
ancestors = append(ancestors, project.Name)
cur = project.Parent
}
}
m.store(key, ancestors)
return ancestors, nil
}
func handleCRMError(resource string, err error) error {
if isGoogleApiErrorWithCode(err, 403) {
helperURL := "https://cloud.google.com/docs/terraform/policy-validation/troubleshooting#ProjectCallerForbidden"
return fmt.Errorf("user does not have the correct permissions for %s. For more info: %s", resource, helperURL)
}
return err
}
func (m *manager) store(key string, ancestors []string) {
if key == "" || len(ancestors) == 0 {
return
}
if _, ok := m.ancestorCache[key]; !ok {
m.ancestorCache[key] = ancestors
}
// cache ancestors along the ancestry path
for i, ancestor := range ancestors {
if _, ok := m.ancestorCache[ancestor]; !ok {
m.ancestorCache[ancestor] = ancestors[i:]
}
}
}
func parseAncestryPath(path string) ([]string, error) {
normStr := normalizeAncestry(path)
splits := strings.Split(normStr, "/")
if len(splits)%2 != 0 {
return nil, fmt.Errorf("unexpected format of ancestry path %s", path)
}
var ancestors []string
allowedPrefixes := map[string]bool{
"projects": true,
"folders": true,
"organizations": true,
}
for i := 0; i < len(splits); i = i + 2 {
if _, ok := allowedPrefixes[splits[i]]; !ok {
return nil, fmt.Errorf("invalid ancestry path %s with %s", path, splits[i])
}
ancestors = append(ancestors, fmt.Sprintf("%s/%s", splits[i], splits[i+1]))
}
// reverse the sequence
i, j := 0, len(ancestors)-1
for i < j {
ancestors[i], ancestors[j] = ancestors[j], ancestors[i]
i++
j--
}
return ancestors, nil
}
func normalizeAncestry(val string) string {
for _, r := range []struct {
old string
new string
}{
{"organization/", "organizations/"},
{"folder/", "folders/"},
{"project/", "projects/"},
} {
val = strings.ReplaceAll(val, r.old, r.new)
}
return val
}
// getProjectFromResource 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 (m *manager) getProjectFromResource(d tpgresource.TerraformResourceData, config *transport_tpg.Config, cai *resources.Asset) (string, error) {
switch cai.Type {
case "cloudresourcemanager.googleapis.com/Project",
"cloudbilling.googleapis.com/ProjectBillingInfo":
res, ok := d.GetOk("number")
if ok {
return res.(string), nil
}
// Fall back to project_id if number is not available.
res, ok = d.GetOk("project_id")
if ok {
return res.(string), nil
} else {
m.errorLogger.Warn(fmt.Sprintf("Failed to retrieve project_id for %s from resource", cai.Name))
}
case "storage.googleapis.com/Bucket":
if cai.Resource != nil {
res, ok := cai.Resource.Data["project"]
if ok {
return res.(string), nil
}
}
m.errorLogger.Warn(fmt.Sprintf("Failed to retrieve project_id for %s from cai resource", cai.Name))
bucketField, ok := d.GetOk("bucket")
if ok {
bucket := bucketField.(string)
resp, err := m.storageClient.Buckets.Get(bucket).Do()
if err == nil {
projectNum := resp.ProjectNumber
return strconv.Itoa(int(projectNum)), nil
}
m.errorLogger.Warn(fmt.Sprintf("Failed to get bucket %s", bucket))
}
m.errorLogger.Warn("Failed to retrieve bucket field from tf data")
}
return getProjectFromSchema("project", d, config)
}
type NoOpAncestryManager struct{}
func (*NoOpAncestryManager) Ancestors(config *transport_tpg.Config, tfData tpgresource.TerraformResourceData, cai *resources.Asset) ([]string, string, error) {
return nil, "", nil
}