-
Notifications
You must be signed in to change notification settings - Fork 3
/
resource_taikun_backup_policy.go
196 lines (170 loc) · 6.26 KB
/
resource_taikun_backup_policy.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
package taikun
import (
"context"
"fmt"
tk "github.com/itera-io/taikungoclient"
tkcore "github.com/itera-io/taikungoclient/client"
"regexp"
"strings"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceTaikunBackupPolicySchema() map[string]*schema.Schema {
return map[string]*schema.Schema{
"cron_period": {
Description: "Frequency of backups.",
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: stringIsCron,
},
"included_namespaces": {
Description: "Namespaces included in the backups.",
Type: schema.TypeList,
Optional: true,
Computed: true,
DefaultFunc: func() (interface{}, error) {
return []string{}, nil
},
Elem: &schema.Schema{Type: schema.TypeString},
},
"name": {
Description: "The name of the backup policy.",
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(3, 30),
},
"phase": {
Description: "The phase of the backup policy.",
Type: schema.TypeString,
Computed: true,
},
"project_id": {
Description: "The ID of the project.",
Type: schema.TypeString,
Required: true,
ForceNew: true,
ValidateDiagFunc: stringIsInt,
},
"retention_period": {
Description: "How long to store the backups.",
Type: schema.TypeString,
Optional: true,
Default: "720h",
ForceNew: true,
ValidateFunc: validation.StringMatch(
regexp.MustCompile(`^(((0*[1-9][0-9]*)h)?((0*[1-9][0-9]*)m)?((0*[1-9][0-9]*)s)|((0*[1-9][0-9]*)h)?((0*[1-9][0-9]*)m)((\\d+)s)?|((0*[1-9][0-9]*)h)((\\d+)m)?((\\d+)s)?)$`),
"The retention period must follow the HMS format, for example: `10h30m15s`, `48h5s` or `360h`.",
),
},
}
}
func resourceTaikunBackupPolicy() *schema.Resource {
return &schema.Resource{
Description: "Taikun Backup Policy",
CreateContext: resourceTaikunBackupPolicyCreate,
ReadContext: generateResourceTaikunBackupPolicyReadWithoutRetries(),
DeleteContext: resourceTaikunBackupPolicyDelete,
Schema: resourceTaikunBackupPolicySchema(),
CustomizeDiff: func(ctx context.Context, diff *schema.ResourceDiff, i interface{}) error {
if len(diff.Get("included_namespaces").([]interface{})) == 0 && len(diff.Get("excluded_namespaces").([]interface{})) == 0 {
return fmt.Errorf("please specify include or exclude namespace to create backup")
}
return nil
},
}
}
func resourceTaikunBackupPolicyCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
apiClient := meta.(*tk.Client)
projectId, _ := atoi32(d.Get("project_id").(string))
body := tkcore.CreateBackupPolicyCommand{}
body.SetCronPeriod(d.Get("cron_period").(string))
body.SetIncludeNamespaces(resourceGetStringList(d.Get("included_namespaces")))
body.SetName(d.Get("name").(string))
body.SetProjectId(projectId)
body.SetRetentionPeriod(d.Get("retention_period").(string))
res, err := apiClient.Client.BackupPolicyAPI.BackupCreate(ctx).CreateBackupPolicyCommand(body).Execute()
if err != nil {
return diag.FromErr(tk.CreateError(res, err))
}
d.SetId(fmt.Sprintf("%d/%s", projectId, d.Get("name").(string)))
return readAfterCreateWithRetries(generateResourceTaikunBackupPolicyReadWithRetries(), ctx, d, meta)
}
func generateResourceTaikunBackupPolicyReadWithRetries() schema.ReadContextFunc {
return generateResourceTaikunBackupPolicyRead(true)
}
func generateResourceTaikunBackupPolicyReadWithoutRetries() schema.ReadContextFunc {
return generateResourceTaikunBackupPolicyRead(false)
}
func generateResourceTaikunBackupPolicyRead(withRetries bool) schema.ReadContextFunc {
return func(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
apiClient := meta.(*tk.Client)
projectId, backupPolicyName, err := parseBackupPolicyId(d.Id())
if err != nil {
return diag.Errorf("Error while reading taikun_backup_policy : %s", err)
}
d.SetId("")
if err != nil {
return diag.FromErr(err)
}
// maybe add search?
response, res, err := apiClient.Client.BackupPolicyAPI.BackupListAllSchedules(context.TODO(), projectId).Limit(4000).Execute()
if err != nil {
return diag.FromErr(tk.CreateError(res, err))
}
for _, policy := range response.Data {
if policy.GetMetadataName() == backupPolicyName {
err = setResourceDataFromMap(d, flattenTaikunBackupPolicy(&policy))
if err != nil {
return diag.FromErr(err)
}
d.SetId(fmt.Sprintf("%d/%s", projectId, backupPolicyName))
return nil
}
}
if withRetries {
d.SetId(fmt.Sprintf("%d/%s", projectId, backupPolicyName))
return diag.Errorf(notFoundAfterCreateOrUpdateError)
}
return nil
}
}
func resourceTaikunBackupPolicyDelete(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
apiClient := meta.(*tk.Client)
projectId, backupPolicyName, err := parseBackupPolicyId(d.Id())
if err != nil {
return diag.Errorf("Error while deleting taikun_backup_policy : %s", err)
}
deleteBody := tkcore.DeleteScheduleCommand{}
deleteBody.SetName(backupPolicyName)
deleteBody.SetProjectId(projectId)
res, err := apiClient.Client.BackupPolicyAPI.BackupDeleteSchedule(context.TODO()).DeleteScheduleCommand(deleteBody).Execute()
if err != nil {
return diag.FromErr(tk.CreateError(res, err))
}
d.SetId("")
return nil
}
func flattenTaikunBackupPolicy(rawBackupPolicy *tkcore.CScheduleDto) map[string]interface{} {
return map[string]interface{}{
"cron_period": rawBackupPolicy.GetSchedule(),
"included_namespaces": rawBackupPolicy.GetIncludedNamespaces(),
"name": rawBackupPolicy.GetMetadataName(),
"phase": rawBackupPolicy.GetPhase(),
"retention_period": rawBackupPolicy.GetTtl(),
}
}
func parseBackupPolicyId(id string) (int32, string, error) {
list := strings.Split(id, "/")
if len(list) != 2 {
return 0, "", fmt.Errorf("unable to determine taikun_backup_policy ID")
}
projectId, err := atoi32(list[0])
if err != nil {
return 0, "", fmt.Errorf("unable to determine taikun_backup_policy ID")
}
backupPolicyName := list[1]
return projectId, backupPolicyName, nil
}