-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathclone.go
234 lines (202 loc) · 8.24 KB
/
clone.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
package clone
import (
"context"
"encoding/json"
"fmt"
"github.com/goccy/go-yaml"
"github.com/stackitcloud/stackit-cli/internal/pkg/args"
cliErr "github.com/stackitcloud/stackit-cli/internal/pkg/errors"
"github.com/stackitcloud/stackit-cli/internal/pkg/examples"
"github.com/stackitcloud/stackit-cli/internal/pkg/flags"
"github.com/stackitcloud/stackit-cli/internal/pkg/globalflags"
"github.com/stackitcloud/stackit-cli/internal/pkg/print"
"github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresflex/client"
postgresflexUtils "github.com/stackitcloud/stackit-cli/internal/pkg/services/postgresflex/utils"
"github.com/stackitcloud/stackit-cli/internal/pkg/spinner"
"github.com/stackitcloud/stackit-cli/internal/pkg/utils"
"github.com/spf13/cobra"
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex"
"github.com/stackitcloud/stackit-sdk-go/services/postgresflex/wait"
)
const (
instanceIdArg = "INSTANCE_ID"
storageClassFlag = "storage-class"
storageSizeFlag = "storage-size"
recoveryTimestampFlag = "recovery-timestamp"
recoveryDateFormat = "2006-01-02T15:04:05-07:00"
)
type inputModel struct {
*globalflags.GlobalFlagModel
InstanceId string
StorageClass *string
StorageSize *int64
RecoveryDate *string
}
func NewCmd(p *print.Printer) *cobra.Command {
cmd := &cobra.Command{
Use: fmt.Sprintf("clone %s", instanceIdArg),
Short: "Clones a PostgreSQL Flex instance",
Long: "Clones a PostgreSQL Flex instance from a selected point in time. " +
"The new cloned instance will be an independent instance with the same settings as the original instance unless the flags are specified.",
Example: examples.Build(
examples.NewExample(
`Clone a PostgreSQL Flex instance with ID "xxx" from a selected recovery timestamp.`,
`$ stackit postgresflex instance clone xxx --recovery-timestamp 2023-04-17T09:28:00+00:00`),
examples.NewExample(
`Clone a PostgreSQL Flex instance with ID "xxx" from a selected recovery timestamp and specify storage class.`,
`$ stackit postgresflex instance clone xxx --recovery-timestamp 2023-04-17T09:28:00+00:00 --storage-class premium-perf6-stackit`),
examples.NewExample(
`Clone a PostgreSQL Flex instance with ID "xxx" from a selected recovery timestamp and specify storage size.`,
`$ stackit postgresflex instance clone xxx --recovery-timestamp 2023-04-17T09:28:00+00:00 --storage-size 10`),
),
Args: args.SingleArg(instanceIdArg, utils.ValidateUUID),
RunE: func(cmd *cobra.Command, args []string) error {
ctx := context.Background()
model, err := parseInput(p, cmd, args)
if err != nil {
return err
}
// Configure API client
apiClient, err := client.ConfigureClient(p)
if err != nil {
return err
}
instanceLabel, err := postgresflexUtils.GetInstanceName(ctx, apiClient, model.ProjectId, model.InstanceId)
if err != nil {
p.Debug(print.ErrorLevel, "get instance name: %v", err)
instanceLabel = model.InstanceId
}
if !model.AssumeYes {
prompt := fmt.Sprintf("Are you sure you want to clone instance %q?", instanceLabel)
err = p.PromptForConfirmation(prompt)
if err != nil {
return err
}
}
// Call API
req, err := buildRequest(ctx, model, apiClient)
if err != nil {
return err
}
resp, err := req.Execute()
if err != nil {
return fmt.Errorf("clone PostgreSQL Flex instance: %w", err)
}
instanceId := *resp.InstanceId
// Wait for async operation, if async mode not enabled
if !model.Async {
s := spinner.New(p)
s.Start("Cloning instance")
_, err = wait.CreateInstanceWaitHandler(ctx, apiClient, model.ProjectId, instanceId).WaitWithContext(ctx)
if err != nil {
return fmt.Errorf("wait for PostgreSQL Flex instance cloning: %w", err)
}
s.Stop()
}
return outputResult(p, model, instanceLabel, instanceId, resp)
},
}
configureFlags(cmd)
return cmd
}
func configureFlags(cmd *cobra.Command) {
cmd.Flags().String(recoveryTimestampFlag, "", "Recovery timestamp for the instance, in a date-time with the layout format YYYY-MM-DDTHH:mm:ss±HH:mm, e.g. 2006-01-02T15:04:05-07:00")
cmd.Flags().String(storageClassFlag, "", "Storage class. If not specified, storage class from the existing instance will be used.")
cmd.Flags().Int64(storageSizeFlag, 0, "Storage size (in GB). If not specified, storage size from the existing instance will be used.")
err := flags.MarkFlagsRequired(cmd, recoveryTimestampFlag)
cobra.CheckErr(err)
}
func parseInput(p *print.Printer, cmd *cobra.Command, inputArgs []string) (*inputModel, error) {
instanceId := inputArgs[0]
globalFlags := globalflags.Parse(p, cmd)
if globalFlags.ProjectId == "" {
return nil, &cliErr.ProjectIdError{}
}
recoveryTimestamp, err := flags.FlagToDateTimePointer(p, cmd, recoveryTimestampFlag, recoveryDateFormat)
if err != nil {
return nil, &cliErr.FlagValidationError{
Flag: recoveryTimestampFlag,
Details: err.Error(),
}
}
recoveryTimestampString := recoveryTimestamp.Format(recoveryDateFormat)
model := inputModel{
GlobalFlagModel: globalFlags,
InstanceId: instanceId,
StorageClass: flags.FlagToStringPointer(p, cmd, storageClassFlag),
StorageSize: flags.FlagToInt64Pointer(p, cmd, storageSizeFlag),
RecoveryDate: utils.Ptr(recoveryTimestampString),
}
if p.IsVerbosityDebug() {
modelStr, err := print.BuildDebugStrFromInputModel(model)
if err != nil {
p.Debug(print.ErrorLevel, "convert model to string for debugging: %v", err)
} else {
p.Debug(print.DebugLevel, "parsed input values: %s", modelStr)
}
}
return &model, nil
}
type PostgreSQLFlexClient interface {
CloneInstance(ctx context.Context, projectId, instanceId string) postgresflex.ApiCloneInstanceRequest
GetInstanceExecute(ctx context.Context, projectId, instanceId string) (*postgresflex.InstanceResponse, error)
ListStoragesExecute(ctx context.Context, projectId, flavorId string) (*postgresflex.ListStoragesResponse, error)
}
func buildRequest(ctx context.Context, model *inputModel, apiClient PostgreSQLFlexClient) (postgresflex.ApiCloneInstanceRequest, error) {
req := apiClient.CloneInstance(ctx, model.ProjectId, model.InstanceId)
var storages *postgresflex.ListStoragesResponse
if model.StorageClass != nil || model.StorageSize != nil {
currentInstance, err := apiClient.GetInstanceExecute(ctx, model.ProjectId, model.InstanceId)
if err != nil {
return req, fmt.Errorf("get PostgreSQL Flex instance: %w", err)
}
validationFlavorId := currentInstance.Item.Flavor.Id
currentInstanceStorageClass := currentInstance.Item.Storage.Class
currentInstanceStorageSize := currentInstance.Item.Storage.Size
storages, err = apiClient.ListStoragesExecute(ctx, model.ProjectId, *validationFlavorId)
if err != nil {
return req, fmt.Errorf("get PostgreSQL Flex storages: %w", err)
}
if model.StorageClass == nil {
err = postgresflexUtils.ValidateStorage(currentInstanceStorageClass, model.StorageSize, storages, *validationFlavorId)
} else if model.StorageSize == nil {
err = postgresflexUtils.ValidateStorage(model.StorageClass, currentInstanceStorageSize, storages, *validationFlavorId)
} else {
err = postgresflexUtils.ValidateStorage(model.StorageClass, model.StorageSize, storages, *validationFlavorId)
}
if err != nil {
return req, err
}
}
req = req.CloneInstancePayload(postgresflex.CloneInstancePayload{
Class: model.StorageClass,
Size: model.StorageSize,
Timestamp: model.RecoveryDate,
})
return req, nil
}
func outputResult(p *print.Printer, model *inputModel, instanceLabel, instanceId string, resp *postgresflex.CloneInstanceResponse) error {
switch model.OutputFormat {
case print.JSONOutputFormat:
details, err := json.MarshalIndent(resp, "", " ")
if err != nil {
return fmt.Errorf("marshal PostgresFlex instance clone: %w", err)
}
p.Outputln(string(details))
return nil
case print.YAMLOutputFormat:
details, err := yaml.MarshalWithOptions(resp, yaml.IndentSequence(true))
if err != nil {
return fmt.Errorf("marshal PostgresFlex instance clone: %w", err)
}
p.Outputln(string(details))
return nil
default:
operationState := "Cloned"
if model.Async {
operationState = "Triggered cloning of"
}
p.Info("%s instance from instance %q. New Instance ID: %s\n", operationState, instanceLabel, instanceId)
return nil
}
}