This repository has been archived by the owner on Nov 14, 2020. It is now read-only.
/
util.go
333 lines (277 loc) · 8.56 KB
/
util.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
package openstack
import (
"encoding/json"
"fmt"
"net/http"
"sort"
"strconv"
"strings"
"time"
"github.com/gophercloud/gophercloud"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
)
// BuildRequest takes an opts struct and builds a request body for
// Gophercloud to execute
func BuildRequest(opts interface{}, parent string) (map[string]interface{}, error) {
b, err := gophercloud.BuildRequestBody(opts, "")
if err != nil {
return nil, err
}
b = AddValueSpecs(b)
return map[string]interface{}{parent: b}, nil
}
// CheckDeleted checks the error to see if it's a 404 (Not Found) and, if so,
// sets the resource ID to the empty string instead of throwing an error.
func CheckDeleted(d *schema.ResourceData, err error, msg string) error {
if _, ok := err.(gophercloud.ErrDefault404); ok {
d.SetId("")
return nil
}
return fmt.Errorf("%s %s: %s", msg, d.Id(), err)
}
// GetRegion returns the region that was specified in the resource. If a
// region was not set, the provider-level region is checked. The provider-level
// region can either be set by the region argument or by OS_REGION_NAME.
func GetRegion(d *schema.ResourceData, config *Config) string {
if v, ok := d.GetOk("region"); ok {
return v.(string)
}
return config.Region
}
// AddValueSpecs expands the 'value_specs' object and removes 'value_specs'
// from the reqeust body.
func AddValueSpecs(body map[string]interface{}) map[string]interface{} {
if body["value_specs"] != nil {
for k, v := range body["value_specs"].(map[string]interface{}) {
body[k] = v
}
delete(body, "value_specs")
}
return body
}
// MapValueSpecs converts ResourceData into a map
func MapValueSpecs(d *schema.ResourceData) map[string]string {
m := make(map[string]string)
for key, val := range d.Get("value_specs").(map[string]interface{}) {
m[key] = val.(string)
}
return m
}
// List of headers that contain sensitive data.
var sensitiveHeaders = map[string]struct{}{
"x-auth-token": {},
"x-auth-key": {},
"x-service-token": {},
"x-storage-token": {},
"x-account-meta-temp-url-key": {},
"x-account-meta-temp-url-key-2": {},
"x-container-meta-temp-url-key": {},
"x-container-meta-temp-url-key-2": {},
"set-cookie": {},
"x-subject-token": {},
}
func hideSensitiveHeadersData(headers http.Header) []string {
result := make([]string, len(headers))
headerIdx := 0
for header, data := range headers {
if _, ok := sensitiveHeaders[strings.ToLower(header)]; ok {
result[headerIdx] = fmt.Sprintf("%s: %s", header, "***")
} else {
result[headerIdx] = fmt.Sprintf("%s: %s", header, strings.Join(data, " "))
}
headerIdx++
}
return result
}
// formatHeaders converts standard http.Header type to a string with separated headers.
// It will hide data of sensitive headers.
func formatHeaders(headers http.Header, separator string) string {
redactedHeaders := hideSensitiveHeadersData(headers)
sort.Strings(redactedHeaders)
return strings.Join(redactedHeaders, separator)
}
func checkForRetryableError(err error) *resource.RetryError {
switch err.(type) {
case gophercloud.ErrDefault500:
return resource.RetryableError(err)
case gophercloud.ErrDefault409:
return resource.RetryableError(err)
case gophercloud.ErrDefault503:
return resource.RetryableError(err)
default:
return resource.NonRetryableError(err)
}
}
func suppressEquivilentTimeDiffs(k, old, new string, d *schema.ResourceData) bool {
oldTime, err := time.Parse(time.RFC3339, old)
if err != nil {
return false
}
newTime, err := time.Parse(time.RFC3339, new)
if err != nil {
return false
}
return oldTime.Equal(newTime)
}
func validateSubnetV2IPv6Mode(v interface{}, k string) (ws []string, errors []error) {
value := v.(string)
if value != "slaac" && value != "dhcpv6-stateful" && value != "dhcpv6-stateless" {
err := fmt.Errorf("%s must be one of slaac, dhcpv6-stateful or dhcpv6-stateless", k)
errors = append(errors, err)
}
return
}
func resourceNetworkingAvailabilityZoneHintsV2(d *schema.ResourceData) []string {
rawAZH := d.Get("availability_zone_hints").([]interface{})
azh := make([]string, len(rawAZH))
for i, raw := range rawAZH {
azh[i] = raw.(string)
}
return azh
}
func expandVendorOptions(vendOptsRaw []interface{}) map[string]interface{} {
vendorOptions := make(map[string]interface{})
for _, option := range vendOptsRaw {
for optKey, optValue := range option.(map[string]interface{}) {
vendorOptions[optKey] = optValue
}
}
return vendorOptions
}
func networkV2ReadAttributesTags(d *schema.ResourceData, tags []string) {
d.Set("all_tags", tags)
allTags := d.Get("all_tags").(*schema.Set)
desiredTags := d.Get("tags").(*schema.Set)
actualTags := allTags.Intersection(desiredTags)
if !actualTags.Equal(desiredTags) {
d.Set("tags", expandToStringSlice(actualTags.List()))
}
}
func networkV2UpdateAttributesTags(d *schema.ResourceData) (tags []string) {
allTags := d.Get("all_tags").(*schema.Set)
oldTagsRaw, newTagsRaw := d.GetChange("tags")
oldTags, newTags := oldTagsRaw.(*schema.Set), newTagsRaw.(*schema.Set)
allWithoutOld := allTags.Difference(oldTags)
return expandToStringSlice(allWithoutOld.Union(newTags).List())
}
func networkV2AttributesTags(d *schema.ResourceData) (tags []string) {
rawTags := d.Get("tags").(*schema.Set).List()
tags = make([]string, len(rawTags))
for i, raw := range rawTags {
tags[i] = raw.(string)
}
return
}
func expandToMapStringString(v map[string]interface{}) map[string]string {
m := make(map[string]string)
for key, val := range v {
if strVal, ok := val.(string); ok {
m[key] = strVal
}
}
return m
}
func expandToStringSlice(v []interface{}) []string {
s := make([]string, len(v))
for i, val := range v {
if strVal, ok := val.(string); ok {
s[i] = strVal
}
}
return s
}
// strSliceContains checks if a given string is contained in a slice
// When anybody asks why Go needs generics, here you go.
func strSliceContains(haystack []string, needle string) bool {
for _, s := range haystack {
if s == needle {
return true
}
}
return false
}
func sliceUnion(a, b []string) []string {
var res []string
for _, i := range a {
if !strSliceContains(res, i) {
res = append(res, i)
}
}
for _, k := range b {
if !strSliceContains(res, k) {
res = append(res, k)
}
}
return res
}
// compatibleMicroversion will determine if an obtained microversion is
// compatible with a given microversion.
func compatibleMicroversion(direction, required, given string) (bool, error) {
if direction != "min" && direction != "max" {
return false, fmt.Errorf("Invalid microversion direction %s. Must be min or max", direction)
}
if required == "" || given == "" {
return false, nil
}
requiredParts := strings.Split(required, ".")
if len(requiredParts) != 2 {
return false, fmt.Errorf("Not a valid microversion: %s", required)
}
givenParts := strings.Split(given, ".")
if len(givenParts) != 2 {
return false, fmt.Errorf("Not a valid microversion: %s", given)
}
requiredMajor, requiredMinor := requiredParts[0], requiredParts[1]
givenMajor, givenMinor := givenParts[0], givenParts[1]
requiredMajorInt, err := strconv.Atoi(requiredMajor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", required)
}
requiredMinorInt, err := strconv.Atoi(requiredMinor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", required)
}
givenMajorInt, err := strconv.Atoi(givenMajor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", given)
}
givenMinorInt, err := strconv.Atoi(givenMinor)
if err != nil {
return false, fmt.Errorf("Unable to parse microversion: %s", given)
}
switch direction {
case "min":
if requiredMajorInt == givenMajorInt {
if requiredMinorInt <= givenMinorInt {
return true, nil
}
}
case "max":
if requiredMajorInt == givenMajorInt {
if requiredMinorInt >= givenMinorInt {
return true, nil
}
}
}
return false, nil
}
func validateJsonObject(v interface{}, k string) ([]string, []error) {
if v == nil || v.(string) == "" {
return nil, []error{fmt.Errorf("%q value must not be empty", k)}
}
var j map[string]interface{}
s := v.(string)
err := json.Unmarshal([]byte(s), &j)
if err != nil {
return nil, []error{fmt.Errorf("%q must be a JSON object: %s", k, err)}
}
return nil, nil
}
func diffSuppressJsonObject(k, old, new string, d *schema.ResourceData) bool {
if strSliceContains([]string{"{}", ""}, old) &&
strSliceContains([]string{"{}", ""}, new) {
return true
}
return false
}