-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathpolicy_utils.go
277 lines (236 loc) · 7.22 KB
/
policy_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
/* Copyright © 2019 VMware, Inc. All Rights Reserved.
SPDX-License-Identifier: MPL-2.0 */
package nsxt
import (
"fmt"
"log"
"strings"
"time"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/vmware/vsphere-automation-sdk-go/runtime/bindings"
"github.com/vmware/vsphere-automation-sdk-go/runtime/protocol/client"
"github.com/vmware/vsphere-automation-sdk-go/services/nsxt/infra/realized_state"
"github.com/vmware/vsphere-automation-sdk-go/services/nsxt/model"
)
func getOrGenerateID(d *schema.ResourceData, m interface{}, presenceChecker func(string, *client.RestConnector, bool) (bool, error)) (string, error) {
connector := getPolicyConnector(m)
isGlobalManager := isPolicyGlobalManager(m)
id := d.Get("nsx_id").(string)
if id == "" {
return newUUID(), nil
}
exists, err := presenceChecker(id, connector, isGlobalManager)
if err != nil {
return "", err
}
if exists {
return "", fmt.Errorf("Resource with id %s already exists", id)
}
return id, nil
}
func newUUID() string {
uuid, _ := uuid.NewRandom()
return uuid.String()
}
func getPolicyTagsFromSet(tagSet *schema.Set) []model.Tag {
tags := tagSet.List()
var tagList []model.Tag
for _, tag := range tags {
data := tag.(map[string]interface{})
tagScope := data["scope"].(string)
tagTag := data["tag"].(string)
elem := model.Tag{
Scope: &tagScope,
Tag: &tagTag}
tagList = append(tagList, elem)
}
return tagList
}
func initPolicyTagsSet(tags []model.Tag) []map[string]interface{} {
var tagList []map[string]interface{}
for _, tag := range tags {
elem := make(map[string]interface{})
elem["scope"] = tag.Scope
elem["tag"] = tag.Tag
tagList = append(tagList, elem)
}
return tagList
}
func getCustomizedPolicyTagsFromSchema(d *schema.ResourceData, schemaName string) []model.Tag {
tags := d.Get(schemaName).(*schema.Set).List()
tagList := make([]model.Tag, 0)
for _, tag := range tags {
data := tag.(map[string]interface{})
tagScope := data["scope"].(string)
tagTag := data["tag"].(string)
elem := model.Tag{
Scope: &tagScope,
Tag: &tagTag}
tagList = append(tagList, elem)
}
return tagList
}
func setCustomizedPolicyTagsInSchema(d *schema.ResourceData, tags []model.Tag, schemaName string) {
var tagList []map[string]interface{}
for _, tag := range tags {
elem := make(map[string]interface{})
elem["scope"] = tag.Scope
elem["tag"] = tag.Tag
tagList = append(tagList, elem)
}
err := d.Set(schemaName, tagList)
if err != nil {
log.Printf("[WARNING] Failed to set tag in schema: %v", err)
}
}
func getPolicyTagsFromSchema(d *schema.ResourceData) []model.Tag {
return getCustomizedPolicyTagsFromSchema(d, "tag")
}
func setPolicyTagsInSchema(d *schema.ResourceData, tags []model.Tag) {
setCustomizedPolicyTagsInSchema(d, tags, "tag")
}
func getPathListFromMap(data map[string]interface{}, attrName string) []string {
pathList := interface2StringList(data[attrName].(*schema.Set).List())
if len(pathList) == 0 {
// Convert empty value to "ANY"
pathList = append(pathList, "ANY")
}
return pathList
}
func setPathListInMap(data map[string]interface{}, attrName string, pathList []string) {
if len(pathList) == 1 && pathList[0] == "ANY" {
data[attrName] = nil
} else {
data[attrName] = pathList
}
}
func getDomainFromResourcePath(rPath string) string {
return getResourceIDFromResourcePath(rPath, "domains")
}
func getResourceIDFromResourcePath(rPath string, rType string) string {
segments := strings.Split(rPath, "/")
for i, seg := range segments {
if seg == rType && i+1 < len(segments) {
return segments[i+1]
}
}
return ""
}
func nsxtDomainResourceImporter(d *schema.ResourceData, m interface{}) ([]*schema.ResourceData, error) {
importDomain := defaultDomain
importID := d.Id()
s := strings.Split(importID, "/")
if len(s) == 2 {
importDomain = s[0]
d.SetId(s[1])
} else {
d.SetId(s[0])
}
d.Set("domain", importDomain)
return []*schema.ResourceData{d}, nil
}
func isPolicyPath(policyPath string) bool {
pathSegs := strings.Split(policyPath, "/")
if len(pathSegs) < 4 {
return false
} else if pathSegs[0] != "" || pathSegs[len(pathSegs)-1] == "" {
return false
} else if !strings.Contains(pathSegs[1], "infra") {
// must be infra or global-infra as of now
return false
}
return true
}
func getPolicyIDFromPath(path string) string {
tokens := strings.Split(path, "/")
return tokens[len(tokens)-1]
}
func interfaceListToStringList(interfaces []interface{}) []string {
var strList []string
for _, elem := range interfaces {
strList = append(strList, elem.(string))
}
return strList
}
func policyResourceNotSupportedError() error {
return fmt.Errorf("This NSX policy resource is not supported with given provider settings")
}
func collectSeparatedStringListToMap(stringList []string, separator string) map[string]string {
strMap := make(map[string]string)
for _, elem := range stringList {
segs := strings.Split(elem, separator)
if len(segs) > 1 {
strMap[segs[0]] = segs[1]
}
}
return strMap
}
func stringListToCommaSeparatedString(stringList []string) string {
var str string
if len(stringList) > 0 {
for i, seg := range stringList {
str += seg
if i < len(stringList)-1 {
str += ","
}
}
}
return str
}
func commaSeparatedStringToStringList(commaString string) []string {
var strList []string
for _, seg := range strings.Split(commaString, ",") {
if seg != "" {
strList = append(strList, seg)
}
}
return strList
}
func nsxtPolicyWaitForRealizationStateConf(connector *client.RestConnector, d *schema.ResourceData, realizedEntityPath string) *resource.StateChangeConf {
client := realized_state.NewDefaultRealizedEntitiesClient(connector)
pendingStates := []string{"UNKNOWN", "UNREALIZED"}
targetStates := []string{"REALIZED", "ERROR"}
stateConf := &resource.StateChangeConf{
Pending: pendingStates,
Target: targetStates,
Refresh: func() (interface{}, string, error) {
realizationResult, realizationError := client.List(realizedEntityPath, nil)
if realizationError == nil {
// Find the right entry
for _, objInList := range realizationResult.Results {
if objInList.State != nil {
return objInList, *objInList.State, nil
}
}
// Realization info not found yet
return nil, "UNKNOWN", nil
}
return nil, "", realizationError
},
Timeout: d.Timeout(schema.TimeoutCreate),
MinTimeout: 1 * time.Second,
Delay: 1 * time.Second,
}
return stateConf
}
func getPolicyEnforcementPointPath(m interface{}) string {
return "/infra/sites/default/enforcement-points/" + getPolicyEnforcementPoint(m)
}
func getGlobalPolicyEnforcementPointPathWithLocation(m interface{}, location string) string {
return "/global-infra/sites/" + location + "/enforcement-points/" + getPolicyEnforcementPoint(m)
}
func convertModelBindingType(obj interface{}, sourceType bindings.BindingType, destType bindings.BindingType) (interface{}, error) {
converter := bindings.NewTypeConverter()
converter.SetMode(bindings.REST)
dataValue, err := converter.ConvertToVapi(obj, sourceType)
if err != nil {
return nil, err[0]
}
gmObj, err := converter.ConvertToGolang(dataValue, destType)
if err != nil {
return nil, err[0]
}
return gmObj, nil
}