-
Notifications
You must be signed in to change notification settings - Fork 3
/
helper.go
388 lines (321 loc) · 9.3 KB
/
helper.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
package taikun
import (
"context"
"fmt"
tk "github.com/itera-io/taikungoclient"
tkcore "github.com/itera-io/taikungoclient/client"
tkshowback "github.com/itera-io/taikungoclient/showbackclient"
"math/rand"
"net/mail"
"os"
"strconv"
"strings"
"time"
"github.com/hashicorp/go-uuid"
"github.com/robfig/cron/v3"
"github.com/go-openapi/strfmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
)
const testNamePrefix = "tf-acc-test-"
//func init() {
// rand.Seed(time.Now().UnixNano())
//}
func setResourceDataFromMap(d *schema.ResourceData, m map[string]interface{}) error {
for key, value := range m {
if err := d.Set(key, value); err != nil {
return fmt.Errorf("unable to set `%s` attribute: %s", key, err)
}
}
return nil
}
func atoi32(str string) (int32, error) {
res, err := strconv.ParseInt(str, 10, 32)
if err != nil {
return 0, err
}
return int32(res), nil
}
func i32toa(x int32) string {
return strconv.FormatInt(int64(x), 10)
}
func gibiByteToMebiByte(x int32) int32 {
return x * 1024
}
func mebiByteToGibiByte(x int64) int32 {
var kibi int64 = 1024
return int32(x / kibi)
}
func gibiByteToByte(x int) int64 {
return int64(1073741824 * x)
}
func byteToGibiByte(x int64) int64 {
return x / 1073741824
}
func stringIsInt(i interface{}, path cty.Path) diag.Diagnostics {
v, ok := i.(string)
if !ok {
return diag.FromErr(path.NewErrorf("expected type to be string"))
}
_, err := strconv.Atoi(v)
if err != nil {
return diag.FromErr(path.NewErrorf("expected an int inside a string"))
}
return nil
}
func stringIsEmail(i interface{}, path cty.Path) diag.Diagnostics {
v, ok := i.(string)
if !ok {
return diag.FromErr(path.NewErrorf("expected type to be string"))
}
_, err := mail.ParseAddress(v)
if err != nil {
return diag.FromErr(path.NewErrorf("expected an email"))
}
return nil
}
func stringIsFilePath(i interface{}, path cty.Path) diag.Diagnostics {
filePath, ok := i.(string)
if !ok {
return diag.FromErr(path.NewErrorf("expected type to be string"))
}
fileInfo, err := os.Stat(filePath)
if err != nil {
return diag.FromErr(path.NewError(err))
}
if fileInfo.IsDir() {
return diag.FromErr(path.NewErrorf("expected a file, not a directory"))
}
return nil
}
func stringIsCron(i interface{}, path cty.Path) diag.Diagnostics {
v, ok := i.(string)
if !ok {
return diag.FromErr(path.NewErrorf("expected type to be string"))
}
parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
if _, err := parser.Parse(v); err != nil {
return diag.FromErr(path.NewErrorf("expected a valid cron period"))
}
return nil
}
func dateToDateTime(date string) strfmt.DateTime {
time, _ := time.Parse(time.RFC3339, dateToRfc3339DateTime(date))
return strfmt.DateTime(time)
}
func dateToRfc3339DateTime(date string) string {
return date[6:10] + "-" + date[3:5] + "-" + date[0:2] + "T00:00:00Z"
}
func rfc3339DateTimeToDate(date string) string {
if date == "" {
return date
}
return date[8:10] + "/" + date[5:7] + "/" + date[0:4]
}
func stringIsDate(i interface{}, path cty.Path) diag.Diagnostics {
v, ok := i.(string)
if !ok {
return diag.FromErr(path.NewErrorf("expected type to be string"))
}
if len(v) != 10 {
return diag.FromErr(path.NewErrorf("expected a valid date in the format: 'dd/mm/yyyy'"))
}
if _, err := time.Parse(time.RFC3339, dateToRfc3339DateTime(v)); len(v) != 10 || err != nil {
return diag.FromErr(path.NewErrorf("expected a valid date in the format: 'dd/mm/yyyy'"))
}
return nil
}
func stringIsUUID(i interface{}, path cty.Path) diag.Diagnostics {
v, ok := i.(string)
if !ok {
return diag.FromErr(path.NewErrorf("expected type to be string"))
}
if _, err := uuid.ParseUUID(v); err != nil {
return diag.FromErr(path.NewErrorf("expected a valid UUID, got %v", v))
}
return nil
}
func resourceGetStringList(data interface{}) []string {
rawList := data.([]interface{})
result := make([]string, 0)
for _, e := range rawList {
result = append(result, e.(string))
}
return result
}
func randomTestName() string {
return randomName(testNamePrefix, 15)
}
func shortRandomTestName() string {
return randomName(testNamePrefix, 5)
}
func randomName(prefix string, length int) string {
return fmt.Sprintf("%s%s", prefix, acctest.RandString(length))
}
func randomString() string {
return fmt.Sprintf("%s%s", "tf", acctest.RandString(rand.Int()%6+7)) // Taikun can have problems with strings starting with numbers
}
func randomURL() string {
return fmt.Sprintf("https://%s.%s.example", randomString(), randomString())
}
func randomEmail() string {
return fmt.Sprintf("%s@mailinator.com", randomString())
}
func randomBool() bool {
return rand.Int()%2 == 0
}
// Return an integer in the range [0; maxInt[
func randomInt(maxInt int) int {
return rand.Int() % maxInt
}
func getLockMode(locked bool) string {
if locked {
return "lock"
}
return "unlock"
}
func getEPrometheusType(prometheusType string) tkshowback.EPrometheusType {
return getPrometheusTypeInt(prometheusType)
}
func getPrometheusType(prometheusType string) tkcore.PrometheusType {
if prometheusType == "Count" {
return tkcore.PROMETHEUSTYPE_COUNT
}
return tkcore.PROMETHEUSTYPE_SUM
}
func getPrometheusTypeInt(prometheusType string) tkshowback.EPrometheusType {
if prometheusType == "Count" {
return tkshowback.EPROMETHEUSTYPE_COUNT
}
return tkshowback.EPROMETHEUSTYPE_SUM // Sum
}
func getShowbackType(showbackType string) tkshowback.EShowbackType {
if showbackType == "General" {
return tkshowback.ESHOWBACKTYPE_GENERAL
}
return tkshowback.ESHOWBACKTYPE_EXTERNAL // External
}
const (
loadBalancerOctavia = "Octavia"
loadBalancerTaikun = "Taikun"
loadBalancerNone = "None"
)
func getLoadBalancingSolution(octaviaEnabled bool, taikunLBEnabled bool) string {
if octaviaEnabled {
return loadBalancerOctavia
} else if taikunLBEnabled {
return loadBalancerTaikun
}
return loadBalancerNone
}
func parseLoadBalancingSolution(loadBalancingSolution string) (octaviaEnabled bool, taikunLBEnabled bool) {
if loadBalancingSolution == loadBalancerOctavia {
return true, false
} else if loadBalancingSolution == loadBalancerTaikun {
return false, true
}
return false, false
}
func getAlertingIntegrationType(integrationType string) tkcore.AlertingIntegrationType {
switch integrationType {
case "Opsgenie":
return tkcore.ALERTINGINTEGRATIONTYPE_OPSGENIE
case "Pagerduty":
return tkcore.ALERTINGINTEGRATIONTYPE_PAGERDUTY
case "Splunk":
return tkcore.ALERTINGINTEGRATIONTYPE_SPLUNK
default: // "MicrosoftTeams"
return tkcore.ALERTINGINTEGRATIONTYPE_MICROSOFT_TEAMS
}
}
func getKubeconfigRoleID(role string) int32 {
switch role {
case "cluster-admin":
return 1
case "admin":
return 2
case "edit":
return 3
default: // view
return 4
}
}
const (
cloudTypeAWS = "AWS"
cloudTypeAzure = "Azure"
cloudTypeOpenStack = "OpenStack"
cloudTypeGCP = "GCP"
cloudTypeProxmox = "Proxmox"
)
func getSecurityGroupProtocol(protocol string) tkcore.SecurityGroupProtocol {
switch strings.ToUpper(protocol) {
case "ICMP":
return tkcore.SECURITYGROUPPROTOCOL_ICMP
case "TCP":
return tkcore.SECURITYGROUPPROTOCOL_TCP
default: // UDP
return tkcore.SECURITYGROUPPROTOCOL_UDP
}
}
func setResourceDataId(d *schema.ResourceData, id int32) {
idAsString := strconv.FormatInt(int64(id), 10)
d.SetId(idAsString)
}
func continentShorthand(continent string) string {
continent = strings.ToLower(continent)
if continent == "europe" {
return "eu"
}
if continent == "asia" {
return "as"
}
if continent == "america" {
return "us"
}
return ""
}
// This function is used when we have an API parameter PARAM with the following behavior
// - We set PARAM to "x" and API returns PARAM with "x" (there is no change)
// - We do not set PARAM. API figures out some value "y" and returns PARAM with value "y" (Terraform must ignore the change)
func ignoreChangeFromEmpty(k string, old string, new string, d *schema.ResourceData) bool {
// First apply, we did not specify the PARAM. Don't supress diff.
if old == "" && new == "" {
return false
}
// Second apply, we did not specify a PARAM. Supress diff.
// There used to be a PARAM, but now we specified none. Supress diff.
if old != "" && new == "" {
return true
}
// The PARAM was changed in .tf file. Don't supress diff.
if old != "" && new != "" {
return false
}
// Else, Don't supress diff.
return false
}
func getLastCharacter(zoneString string) string {
if len(zoneString) == 0 {
return ""
}
return zoneString[len(zoneString)-1:]
}
// Proxmox storage options in kubernetes profile and Project are different from what we send while creating k8s servers
func getProxmoxStorageStringForServer(projectID int32, apiClient *tk.Client) (string, error) {
data, response, err := apiClient.Client.ServersAPI.ServersDetails(context.TODO(), projectID).Execute()
if err != nil {
return "", tk.CreateError(response, err)
}
kubernetesProfile := data.GetProject()
proxmoxStorageString := kubernetesProfile.GetProxmoxStorage()
switch proxmoxStorageString {
case "NFS":
return "NFS", nil
case "OpenEBS":
return "STORAGE", nil
default:
return "", fmt.Errorf("Parsed an unrecognised Proxmox Storage type from Kubernetes Profile for this project.")
}
}