-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathutil.go
More file actions
359 lines (313 loc) · 10.2 KB
/
util.go
File metadata and controls
359 lines (313 loc) · 10.2 KB
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
/*
Copyright 2024 Flant JSC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"bufio"
"context"
"encoding/base64"
"errors"
"fmt"
"log/slog"
neturl "net/url"
"os"
"slices"
"strings"
"time"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
ctrlrtclient "sigs.k8s.io/controller-runtime/pkg/client"
"github.com/deckhouse/deckhouse-cli/internal/dataexport/api/v1alpha1"
safeClient "github.com/deckhouse/deckhouse-cli/pkg/libsaferequest/client"
)
const (
defaultTTL = "2m"
PersistentVolumeClaimKind = "PersistentVolumeClaim"
VolumeSnapshotKind = "VolumeSnapshot"
VirtualDiskKind = "VirtualDisk"
VirtualDiskSnapshotKind = "VirtualDiskSnapshot"
)
var (
ErrUnsupportedVolumeMode = errors.New("invalid volume mode")
)
// Function pointers for test stubbing
var (
PrepareDownloadFunc = PrepareDownload
CreateDataExporterIfNeededFunc = CreateDataExporterIfNeeded
)
func GetDataExport(ctx context.Context, deName, namespace string, rtClient ctrlrtclient.Client) (*v1alpha1.DataExport, error) {
deObj := &v1alpha1.DataExport{}
err := rtClient.Get(ctx, ctrlrtclient.ObjectKey{Namespace: namespace, Name: deName}, deObj)
if err != nil {
return nil, fmt.Errorf("kube Get dataexport: %s", err.Error())
}
// check DataExport is Ready. No status in new version of dataexport
for _, condition := range deObj.Status.Conditions {
if condition.Type == "Ready" {
if condition.Status != "True" {
return nil, fmt.Errorf("DataExport %s/%s is not Ready", deObj.ObjectMeta.Namespace, deObj.ObjectMeta.Name)
}
break
}
}
return deObj, nil
}
func GetDataExportWithRestart(ctx context.Context, deName, namespace string, rtClient ctrlrtclient.Client) (*v1alpha1.DataExport, error) {
deObj := &v1alpha1.DataExport{}
for i := 0; ; i++ {
var returnErr error = nil
// get DataExport from k8s by name
err := rtClient.Get(ctx, ctrlrtclient.ObjectKey{Namespace: namespace, Name: deName}, deObj)
if err != nil {
return nil, fmt.Errorf("kube Get dataexport with restart: %s", err.Error())
}
for _, condition := range deObj.Status.Conditions {
// restart DataExport if Expired
if condition.Type == "Expired" {
if condition.Status == "True" {
if err := DeleteDataExport(ctx, deName, namespace, rtClient); err != nil {
return nil, err
}
if err := CreateDataExport(
ctx,
deName, namespace, "",
deObj.Spec.TargetRef.Kind,
deObj.Spec.TargetRef.Name,
deObj.Spec.Publish, rtClient,
); err != nil {
return nil, err
}
}
}
// check DataExport is Ready
if condition.Type == "Ready" {
if condition.Status != "True" {
returnErr = fmt.Errorf("DataExport %s/%s is not Ready", deObj.ObjectMeta.Namespace, deObj.ObjectMeta.Name)
}
}
}
// check DataExport Url
if returnErr == nil && deObj.Status.Url == "" {
returnErr = fmt.Errorf("DataExport %s/%s has no URL", deObj.ObjectMeta.Namespace, deObj.ObjectMeta.Name)
} else if deObj.Spec.Publish && deObj.Status.PublicURL == "" {
returnErr = fmt.Errorf("DataExport %s/%s has empty PublicURL", deObj.ObjectMeta.Namespace, deObj.ObjectMeta.Name)
}
if returnErr == nil {
break
}
if i > 60 {
return nil, returnErr
}
time.Sleep(time.Second * 3)
}
return deObj, nil
}
func CreateDataExporterIfNeeded(ctx context.Context, log *slog.Logger, dataName, namespace string, publish bool, ttl string, rtClient ctrlrtclient.Client) (string, string, error) {
deName := dataName
var volumeKind, volumeName string
lowerCaseDeName := strings.ToLower(dataName)
switch {
// PVC / PersistentVolumeClaim
case strings.HasPrefix(lowerCaseDeName, "pvc/"):
volumeKind = PersistentVolumeClaimKind
volumeName = dataName[4:]
deName = "de-pvc-" + volumeName
case strings.HasPrefix(lowerCaseDeName, "persistentvolumeclaim/"):
volumeKind = PersistentVolumeClaimKind
volumeName = dataName[len("persistentvolumeclaim/"):]
deName = "de-pvc-" + volumeName
// VS / VolumeSnapshot
case strings.HasPrefix(lowerCaseDeName, "vs/"):
volumeKind = VolumeSnapshotKind
volumeName = dataName[3:]
deName = "de-vs-" + volumeName
case strings.HasPrefix(lowerCaseDeName, "volumesnapshot/"):
volumeKind = VolumeSnapshotKind
volumeName = dataName[len("volumesnapshot/"):]
deName = "de-vs-" + volumeName
// VD / VirtualDisk
case strings.HasPrefix(lowerCaseDeName, "vd/"):
volumeKind = VirtualDiskKind
volumeName = dataName[3:]
deName = "de-vd-" + volumeName
case strings.HasPrefix(lowerCaseDeName, "virtualdisk/"):
volumeKind = VirtualDiskKind
volumeName = dataName[len("virtualdisk/"):]
deName = "de-vd-" + volumeName
// VDS / VirtualDiskSnapshot
case strings.HasPrefix(lowerCaseDeName, "vds/"):
volumeKind = VirtualDiskSnapshotKind
volumeName = dataName[4:]
deName = "de-vds-" + volumeName
case strings.HasPrefix(lowerCaseDeName, "virtualdisksnapshot/"):
volumeKind = VirtualDiskSnapshotKind
volumeName = dataName[len("virtualdisksnapshot/"):]
deName = "de-vds-" + volumeName
default:
// Assume user provided existing DataExport name; don't validate kind here.
return deName, "", nil
}
if err := CreateDataExport(ctx, deName, namespace, ttl, volumeKind, volumeName, publish, rtClient); err != nil {
return deName, "", err
}
log.Info("DataExport creating", slog.String("name", deName), slog.String("namespace", namespace))
// Build minimal object to propagate kind information further.
return deName, volumeKind, nil
}
func CreateDataExport(ctx context.Context, deName, namespace, ttl, volumeKind, volumeName string, publish bool, rtClient ctrlrtclient.Client) error {
if ttl == "" {
ttl = defaultTTL
}
// Create dataexport object
deCfg := &v1alpha1.DataExport{
TypeMeta: metav1.TypeMeta{
APIVersion: "deckhouse.io/v1alpha1",
Kind: "DataExport",
},
ObjectMeta: metav1.ObjectMeta{
Name: deName,
Namespace: namespace,
},
Spec: v1alpha1.DataexportSpec{
Ttl: ttl,
TargetRef: v1alpha1.TargetRefSpec{
Kind: volumeKind,
Name: volumeName,
},
Publish: publish,
},
}
err := rtClient.Create(ctx, deCfg)
if err != nil && !apierrors.IsAlreadyExists(err) {
return fmt.Errorf("DataExporter create error: %s", err.Error())
}
return nil
}
func DeleteDataExport(ctx context.Context, deName, namespace string, rtClient ctrlrtclient.Client) error {
deObj := &v1alpha1.DataExport{
ObjectMeta: metav1.ObjectMeta{
Name: deName,
Namespace: namespace,
},
}
err := rtClient.Delete(ctx, deObj)
if err != nil {
return err
}
return nil
}
func AskYesNoWithTimeout(prompt string, timeout time.Duration) bool {
inputChan := make(chan string)
defer close(inputChan)
go func() {
reader := bufio.NewReader(os.Stdin)
for {
fmt.Printf("%s: ", prompt)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("Error reading input, please try again.")
continue
}
input = strings.ToLower(strings.TrimSpace(input))
if slices.Contains([]string{"y", "n"}, input) {
inputChan <- strings.TrimSpace(input)
return
} else {
fmt.Println("Invalid input. Please press 'y' or 'n'.")
}
}
}()
select {
case input := <-inputChan:
if input == "n" || input == "no" {
return false
}
return true
case <-time.After(timeout):
fmt.Printf("\n")
return true
}
}
func getExportStatus(ctx context.Context, log *slog.Logger, deName, namespace string, public bool, rtClient ctrlrtclient.Client) (podUrl, volumeMode, internalCAData string, err error) {
log.Info("Waiting for DataExport to be ready", slog.String("name", deName), slog.String("namespace", namespace))
deObj, err := GetDataExportWithRestart(ctx, deName, namespace, rtClient)
if err != nil {
return
}
if public {
if deObj.Status.PublicURL == "" {
err = fmt.Errorf("empty PublicURL")
return
}
podUrl = deObj.Status.PublicURL
if !strings.HasPrefix(podUrl, "http") {
podUrl += "https://"
}
} else if deObj.Status.Url != "" {
podUrl = deObj.Status.Url
internalCAData = deObj.Status.CA
} else {
err = fmt.Errorf("invalid URL")
return
}
volumeKind := deObj.Spec.TargetRef.Kind
if !slices.Contains([]string{PersistentVolumeClaimKind, VolumeSnapshotKind, VirtualDiskKind, VirtualDiskSnapshotKind}, volumeKind) {
err = fmt.Errorf("invalid volume kind: %s", volumeKind)
return
}
volumeMode = deObj.Status.VolumeMode
log.Info("DataExport is ready", slog.String("name", deName), slog.String("namespace", namespace), slog.String("url", podUrl), slog.String("volumeMode", volumeMode))
return
}
func PrepareDownload(ctx context.Context, log *slog.Logger, deName, namespace string, publish bool, sClient *safeClient.SafeClient) (url, volumeMode string, subClient *safeClient.SafeClient, finErr error) {
rtClient, err := sClient.NewRTClient(v1alpha1.AddToScheme)
if err != nil {
finErr = err
return
}
podUrl, volumeMode, intrenalCAData, err := getExportStatus(ctx, log, deName, namespace, publish, rtClient)
if err != nil {
finErr = err
return
}
// Validate srcPath, dstPath params
switch volumeMode {
case "Filesystem":
url, err = neturl.JoinPath(podUrl, "api/v1/files")
if err != nil {
finErr = err
return
}
case "Block":
url, err = neturl.JoinPath(podUrl, "api/v1/block")
if err != nil {
finErr = err
return
}
default:
finErr = fmt.Errorf("%w: '%s'", ErrUnsupportedVolumeMode, volumeMode)
return
}
// Reuse the original SafeClient unless we need to inject additional CA.
subClient = sClient
if !publish && len(intrenalCAData) > 0 {
// Create an isolated copy to avoid mutating the original client
subClient = sClient.Copy()
decodedBytes, err := base64.StdEncoding.DecodeString(intrenalCAData)
if err != nil {
finErr = fmt.Errorf("CA decoding error: %s", err.Error())
return
}
subClient.SetTLSCAData(decodedBytes)
}
return
}