-
Notifications
You must be signed in to change notification settings - Fork 32
/
policy_level.go
307 lines (274 loc) · 11.4 KB
/
policy_level.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
package policies
import (
"fmt"
"strings"
"sync"
"github.com/dynatrace-oss/terraform-provider-dynatrace/dynatrace/api"
"github.com/dynatrace-oss/terraform-provider-dynatrace/dynatrace/api/iam"
)
var cachedEnvironmentIDs []string
var envIDFetcMutex sync.Mutex
// GetEnvironmentIDs retrieves all environmentIDs reachable via the given accountID
// The operation is guarded by a mutex
func GetEnvironmentIDs(auth iam.Authenticator) ([]string, error) {
envIDFetcMutex.Lock()
defer envIDFetcMutex.Unlock()
if cachedEnvironmentIDs != nil {
return cachedEnvironmentIDs, nil
}
return getEnvironmentIDs(auth)
}
// CheckPolicyExists attempts to fetch the details of a policy, identified by the given `policyUUID`
// and the presumed `levelType` and `levelID`. If the policy is not defined at the given `levelType`
// and `levelID` it returns false, without returning an error
// An error is returned ONLY if querying for the existence of the policy failed for another reason than `404 Not Found`
func CheckPolicyExists(auth iam.Authenticator, levelType string, levelID string, policyUUID string) (bool, string, error) {
var err error
response := struct {
UUID string `json:"uuid"`
Name string `json:"name"`
}{}
client := iam.NewIAMClient(auth)
if err = iam.GET(client, fmt.Sprintf("https://api.dynatrace.com/iam/v1/repo/%s/%s/policies/%s", levelType, levelID, policyUUID), 200, false, &response); err != nil {
// TODO: this is dirty. The IAM client unfortunately doesn't produce special kinds errors. string compare is the only option atm
if strings.HasPrefix(err.Error(), "response code 404") {
return false, "", nil
}
return false, "", err
}
return true, response.Name, nil
}
// FetchPolicyLevel determines the `levelType` and `levelID` of a policy identified by its UUID
// by trial and error, i.e. requests the policy from the REST API using all known combinations
//
// Option 1: The policy is a global policy (levelType = global, levelID = global)
// Option 2: The policy is on the account level, identified by the argument `accountID` (levelType = account, levelID = `accountID` argument)
// Option 3: The policy is on the environment level. ALL environments reachable via the account are being taken into consideration
//
// # If all attempts fail the returned error contains the UUID in its message
//
// This operation is guarded by a mutex
func FetchPolicyLevel(auth iam.Authenticator, uuid string) (levelType string, levelID string, name string, err error) {
allPoliciesMutex.Lock()
defer allPoliciesMutex.Unlock()
return fetchPolicyLevel(auth, uuid)
}
// fetchPolicyLevel determines the `levelType` and `levelID` of a policy identified by its UUID
// by trial and error, i.e. requests the policy from the REST API using all known combinations
//
// Option 1: The policy is a global policy (levelType = global, levelID = global)
// Option 2: The policy is on the account level, identified by the argument `accountID` (levelType = account, levelID = `accountID` argument)
// Option 3: The policy is on the environment level. ALL environments reachable via the account are being taken into consideration
//
// # If all attempts fail the returned error contains the UUID in its message
//
// This operation is NOT guarded by a mutex. See `FetchPolicyLevel` for a guarded version
func fetchPolicyLevel(auth iam.Authenticator, uuid string) (levelType string, levelID string, name string, err error) {
var exists bool
if exists, name, err = CheckPolicyExists(auth, "global", "global", uuid); err != nil {
return "", "", "", err
}
if exists {
return "global", "global", name, nil
}
accountID := strings.TrimPrefix(auth.AccountID(), "urn:dtaccount:")
if exists, name, err = CheckPolicyExists(auth, "account", accountID, uuid); err != nil {
return "", "", name, err
}
if exists {
return "account", accountID, name, nil
}
var environmentIDs []string
if environmentIDs, err = GetEnvironmentIDs(auth); err != nil {
return "", "", name, err
}
for _, environmentID := range environmentIDs {
if exists, name, err = CheckPolicyExists(auth, "environment", environmentID, uuid); err != nil {
return "", "", name, err
}
if exists {
return "environment", environmentID, name, nil
}
}
return "", "", name, fmt.Errorf("unable to resolve levelType and levelID of policy `%s`", uuid)
}
// ResolvePolicyLevel determines the `levelType` and `levelID` of a policy using different strategies
// - If it hasn't happened yet, all known policies are getting retrieved from the REST API
// - In case none of the results contains the given `policyUUID` the `levelType` and `levelID` are getting
// resolved using trial and error (see `fetchPolicyLevel`)
//
// This operation is guarded by a mutex
func ResolvePolicyLevel(auth iam.Authenticator, uuid string) (levelType string, levelID string, name string, err error) {
allPoliciesMutex.Lock()
defer allPoliciesMutex.Unlock()
return resolvePolicyLevel(auth, uuid)
}
// ResolvePolicyLevel determines the `levelType` and `levelID` of a policy using different strategies
// - If it hasn't happened yet, all known policies are getting retrieved from the REST API
// - In case none of the results contains the given `uuid` the `levelType` and `levelID` are getting
// resolved using trial and error (see `fetchPolicyLevel`)
//
// This operation is NOT guarded by a mutex. See `ResolvePolicyLevel` for a guarded version
func resolvePolicyLevel(auth iam.Authenticator, uuid string) (levelType string, levelID string, name string, err error) {
allPolicyLevels, err := fetchAllPolicyLevels(auth)
if err != nil {
return "", "", "", err
}
pl, found := allPolicyLevels[uuid]
if found {
return pl.LevelType, pl.LevelID, pl.Name, nil
}
if levelType, levelID, name, err = fetchPolicyLevel(auth, uuid); err == nil {
if err2 := registerPolicyLevel(auth, PolicyLevel{UUID: uuid, LevelType: levelType, LevelID: levelID, Name: name}); err2 != nil {
return levelType, levelID, name, err2
}
}
return levelType, levelID, name, err
}
type PolicyLevel struct {
UUID string
LevelType string
LevelID string
Name string
}
var globalAllPolicyLevels map[string]PolicyLevel
var allPoliciesMutex sync.Mutex
// RegisterPolicyLevel notes down the `levelType` and `levelID` of the policy identified by the given `uuid`.
// Prior to that, if it hasn't happened yet, all known polices are getting pulled from the REST API
// In other words: Registering the `levelType` and `levelID` avoids that just partial information about
// the policys is stored locally. It's all nor nothing.
//
// # An error will be returned in case loading all known polices from the REST API fails for some reason
//
// This operation is guarded by a mutex.
func RegisterPolicyLevel(auth iam.Authenticator, level PolicyLevel) error {
allPoliciesMutex.Lock()
defer allPoliciesMutex.Unlock()
return registerPolicyLevel(auth, level)
}
// registerPolicyLevel notes down the `levelType` and `levelID` of the policy identified by the given `uuid`.
// Prior to that, if it hasn't happened yet, all known polices are getting pulled from the REST API
// In other words: Registering the `levelType` and `levelID` avoids that just partial information about
// the policys is stored locally. It's all nor nothing.
//
// # An error will be returned in case loading all known polices from the REST API fails for some reason
//
// This operation is NOT guarded by a mutex. See `RegisterPolicyLevel` for a guarded version
func registerPolicyLevel(auth iam.Authenticator, level PolicyLevel) error {
// fmt.Println("[POLICY-LEVEL]", "[REGISTER]", "["+level.UUID+"]", "BEGIN")
// start := time.Now()
// defer func() {
// fmt.Println("[POLICY-LEVEL]", "[REGISTER]", "["+level.UUID+"]", fmt.Sprintf("... LASTED %v seconds", int64(time.Since(start).Seconds())))
// }()
if globalAllPolicyLevels == nil {
_, err := fetchAllPolicyLevels(auth)
if err != nil {
return err
}
}
globalAllPolicyLevels[level.UUID] = PolicyLevel{UUID: level.UUID, LevelType: level.LevelID, LevelID: level.LevelID, Name: level.Name}
return nil
}
// FetchAllPolicyLevels pulls all known polices reachable via the given IAM Client from the REST API
// and notes down the `levelType` and `levelID` for these polices (identified via a UUID only).
//
// # You should use `ResolvePolicyLevel` to look up the `levelType` and `levelID` of a policy identifed by a UUID only
//
// This operation is guarded by a mutext
func FetchAllPolicyLevels(auth iam.Authenticator) (map[string]PolicyLevel, error) {
allPoliciesMutex.Lock()
defer allPoliciesMutex.Unlock()
return fetchAllPolicyLevels(auth)
}
func fetchGlobalPolicies(auth iam.Authenticator) (results chan *api.Stub) {
client := iam.NewIAMClient(auth)
results = make(chan *api.Stub)
go func() {
defer func() {
defer close(results)
}()
var response ListPoliciesResponse
if err := iam.GET(client, "https://api.dynatrace.com/iam/v1/repo/global/global/policies", 200, false, &response); err != nil {
return
}
for _, policy := range response.Policies {
results <- &api.Stub{ID: fmt.Sprintf("%s#-#%s#-#%s", policy.UUID, "global", "global"), Name: policy.Name}
}
}()
return results
}
// fetchAllPolicyLevels pulls all known polices reachable via the given IAM Client from the REST API
// and notes down the `levelType` and `levelID` for these polices (identified via a UUID only).
//
// # You should use `ResolvePolicyLevel` to look up the `levelType` and `levelID` of a policy identifed by a UUID only
//
// This operation is NOT guarded by a mutext. See `FetchAllPolicyLevels` for a guarded version
func fetchAllPolicyLevels(auth iam.Authenticator) (m map[string]PolicyLevel, err error) {
if globalAllPolicyLevels != nil {
return globalAllPolicyLevels, nil
}
// start := time.Now()
// defer func() {
// fmt.Println("[POLICY-LEVEL]", "[FETCH-ALL]", fmt.Sprintf("... LASTED %v seconds", int64(time.Since(start).Seconds())))
// }()
nonGlobalStubs, err := list(auth)
if err != nil {
return nil, err
}
globalStubs := fetchGlobalPolicies(auth)
m = map[string]PolicyLevel{}
handleStub := func(stub *api.Stub) {
if stub == nil {
return
}
uuid, levelType, levelID, _ := SplitIDNoDefaults(stub.ID)
m[uuid] = PolicyLevel{LevelType: levelType, LevelID: levelID, Name: stub.Name}
}
for {
if nonGlobalStubs == nil && globalStubs == nil {
break
}
select {
case stub, more := <-nonGlobalStubs:
handleStub(stub)
if !more {
nonGlobalStubs = nil
if globalStubs == nil {
break
}
}
case stub, more := <-globalStubs:
handleStub(stub)
if !more {
globalStubs = nil
if nonGlobalStubs == nil {
break
}
}
}
if nonGlobalStubs == nil && globalStubs == nil {
break
}
}
globalAllPolicyLevels = m
return globalAllPolicyLevels, nil
}
// GetEnvironmentIDs retrieves all environmentIDs reachable via the given IAM Client
// The operation is NOT guarded by a mutex. See `GetEnvironmentIDs` for a guarded version
func getEnvironmentIDs(auth iam.Authenticator) ([]string, error) {
client := iam.NewIAMClient(auth)
accountID := strings.TrimPrefix(auth.AccountID(), "urn:dtaccount:")
var err error
var envResponse ListEnvResponse
if err = iam.GET(client, fmt.Sprintf("https://api.dynatrace.com/env/v2/accounts/%s/environments", accountID), 200, false, &envResponse); err != nil {
return nil, err
}
environmentIDs := []string{}
for _, dataStub := range envResponse.Data {
if len(dataStub.ID) > 0 { // we don't trust api.dynatrace.com
environmentIDs = append(environmentIDs, dataStub.ID)
}
}
cachedEnvironmentIDs = environmentIDs
return environmentIDs, nil
}