-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvolumes.go
More file actions
483 lines (428 loc) · 12.4 KB
/
volumes.go
File metadata and controls
483 lines (428 loc) · 12.4 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
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package cmd
import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strings"
"time"
drycc "github.com/drycc/controller-sdk-go"
"github.com/drycc/controller-sdk-go/api"
"github.com/drycc/controller-sdk-go/volumes"
"github.com/schollz/progressbar/v3"
"sigs.k8s.io/yaml"
)
// VolumesList list volumes in the application
func (d *DryccCmd) VolumesList(appID string, results int) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
if results == defaultLimit {
results = s.Limit
}
volumes, count, err := volumes.List(s.Client, appID, results)
if d.checkAPICompatibility(s.Client, err) != nil {
return err
}
if count == 0 {
d.Println("Could not find any volume.")
} else {
printVolumes(d, volumes)
}
return nil
}
// VolumesInfo get volume in the application
func (d *DryccCmd) VolumesInfo(appID, name string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
volume, err := volumes.Get(s.Client, appID, name)
if d.checkAPICompatibility(s.Client, err) != nil {
return err
}
table := d.getDefaultFormatTable([]string{})
table.Append([]string{"UUID:", volume.UUID})
table.Append([]string{"Name:", volume.Name})
table.Append([]string{"Owner:", volume.Owner})
table.Append([]string{"Type:", volume.Type})
// table append path
table.Append([]string{"Path:"})
path, err := yaml.Marshal(volume.Path)
if err != nil {
return err
}
table.Append([]string{"", string(path)})
// table append parameters
table.Append([]string{"Parameters:"})
parameters, err := yaml.Marshal(volume.Parameters)
if err != nil {
return err
}
table.Append([]string{"", string(parameters)})
table.Append([]string{"Created: ", d.formatTime(volume.Created)})
table.Append([]string{"Updated: ", d.formatTime(volume.Updated)})
table.Render()
return nil
}
// VolumesCreate create a volume for the application
func (d *DryccCmd) VolumesCreate(appID, name, vType, size string, parameters map[string]interface{}) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
regex := regexp.MustCompile("^([1-9][0-9]*[gG])$")
if !regex.MatchString(size) {
return fmt.Errorf(`%s doesn't fit format #unit
Examples: 2G 2g`, size)
}
d.Printf("Creating %s to %s... ", name, appID)
quit := progress(d.WOut)
volume := api.Volume{
Name: name,
Size: size,
Type: vType,
Parameters: parameters,
}
_, err = volumes.Create(s.Client, appID, volume)
quit <- true
<-quit
if d.checkAPICompatibility(s.Client, err) != nil {
return err
}
d.Println("done")
return nil
}
// VolumesExpand create a volume for the application
func (d *DryccCmd) VolumesExpand(appID, name, size string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
regex := regexp.MustCompile("^([1-9][0-9]*[gG])$")
if !regex.MatchString(size) {
return fmt.Errorf(`%s doesn't fit format #unit
Examples: 2G 2g`, size)
}
d.Printf("Expand %s to %s... ", name, appID)
quit := progress(d.WOut)
volume := api.Volume{
Name: name,
Size: size,
}
_, err = volumes.Expand(s.Client, appID, volume)
quit <- true
<-quit
if d.checkAPICompatibility(s.Client, err) != nil {
return err
}
d.Println("done")
return nil
}
// VolumesDelete delete a volume from the application
func (d *DryccCmd) VolumesDelete(appID, name string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
d.Printf("Deleting %s from %s... ", name, appID)
quit := progress(d.WOut)
err = volumes.Delete(s.Client, appID, name)
quit <- true
<-quit
if d.checkAPICompatibility(s.Client, err) != nil {
return err
}
d.Println("done")
return nil
}
// VolumesClient a client for manage volume file
func (d *DryccCmd) VolumesClient(appID, cmd string, args ...string) error {
switch cmd {
case "ls":
return d.volumesClientLs(appID, args[0])
case "cp":
return d.volumesClientCp(appID, args[0], args[1])
case "rm":
return d.volumesClientRm(appID, args[0])
default:
return fmt.Errorf("unknown command %s", cmd)
}
}
// VolumesMount mount a volume to process of the application
func (d *DryccCmd) VolumesMount(appID string, name string, volumeVars []string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
volumeMap, err := parseVolume(volumeVars)
if err != nil {
return err
}
d.Print("Mounting volume... ")
quit := progress(d.WOut)
volumeObj := api.Volume{Path: volumeMap}
_, err = volumes.Mount(s.Client, appID, name, volumeObj)
quit <- true
<-quit
if d.checkAPICompatibility(s.Client, err) != nil {
return err
}
d.Print("done\n")
d.Print("The pods should be restart, please check the pods up or not.\n")
return nil
}
// VolumesUnmount unmount a volume from process of the application
func (d *DryccCmd) VolumesUnmount(appID string, name string, volumeVars []string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
valuesMap := make(map[string]interface{})
for _, volumeVar := range volumeVars {
valuesMap[volumeVar] = nil
}
d.Print("Unmounting volume... ")
quit := progress(d.WOut)
volumeObj := api.Volume{Path: valuesMap}
_, err = volumes.Mount(s.Client, appID, name, volumeObj)
quit <- true
<-quit
if d.checkAPICompatibility(s.Client, err) != nil {
return err
}
d.Print("done\n")
d.Print("The pods should be restart, please check the pods up or not.\n")
return nil
}
// volumesClientLs get all directory entries sorted by filename.
func (d *DryccCmd) volumesClientLs(appID, vol string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
name, path, err := parseVol(vol)
if err != nil {
return err
}
dirs, _, err := volumes.ListDir(s.Client, appID, name, path, 3000)
if err != nil {
return err
}
table := d.getDefaultFormatTable([]string{})
for _, dir := range dirs {
if dir.Type == "dir" {
dir.Name = fmt.Sprintf("%s/", dir.Name)
}
table.Append([]string{fmt.Sprintf("[%s]", d.formatTime(dir.Timestamp)), dir.Size, dir.Name})
}
table.Render()
return nil
}
func (d *DryccCmd) volumesClientGetAll(client *drycc.Client, appID, volumeID, volumePath, localPath string) error {
if _, err := os.Stat(localPath); err != nil && os.IsNotExist(err) {
os.MkdirAll(localPath, os.ModePerm)
}
dirs, _, err := volumes.ListDir(client, appID, volumeID, volumePath, 3000)
if err != nil {
return err
}
for _, dir := range dirs {
_, subpath := path.Split(dir.Path)
filepath := path.Join(localPath, subpath)
if dir.Type == "file" {
res, err := volumes.GetFile(client, appID, volumeID, dir.Path)
if err != nil {
return err
}
w, err := os.OpenFile(filepath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
if err != nil {
return err
}
bar := d.newProgressbar(res.ContentLength, "↓", filepath)
defer w.Close()
if _, err = io.Copy(io.MultiWriter(w, bar), res.Body); err != nil {
return err
}
} else {
os.MkdirAll(filepath, os.ModePerm)
if err := d.volumesClientGetAll(client, appID, volumeID, dir.Path, filepath); err != nil {
return err
}
}
}
return nil
}
func (d *DryccCmd) volumesClientPostAll(client *drycc.Client, appID, volumeID, volumePath, localPath string) error {
if file, err := os.Stat(localPath); err != nil {
return err
} else if !file.IsDir() {
file, err := os.Open(localPath)
if err != nil {
return err
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return err
}
if stat.Size() > 0 { //ignore empty file
reader := progressbar.NewReader(file, d.newProgressbar(stat.Size(), "↑", localPath))
if _, err := volumes.PostFile(client, appID, volumeID, volumePath, file.Name(), stat.Size(), &reader); err != nil {
return err
}
} else {
d.newProgressbar(1, "?", localPath).Finish()
}
return nil
}
if entries, err := os.ReadDir(localPath); err == nil {
for _, entry := range entries {
var dstFilepath string
if entry.IsDir() {
dstFilepath = path.Join(volumePath, entry.Name())
} else {
dstFilepath = volumePath
}
if err := d.volumesClientPostAll(client, appID, volumeID, dstFilepath, path.Join(localPath, entry.Name())); err != nil {
return err
}
}
} else {
return err
}
return nil
}
// volumesClientCp copy files between volume and local file
func (d *DryccCmd) volumesClientCp(appID, src, dst string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
if strings.HasPrefix(src, "vol://") {
f, err := os.Stat(dst)
if err != nil {
return err
}
if !f.IsDir() {
return fmt.Errorf("the local path must be an existing dir")
}
volumeID, volumePath, err := parseVol(src)
if err != nil {
return err
}
if dirs, _, err := volumes.ListDir(s.Client, appID, volumeID, volumePath, 3000); err == nil && (len(dirs) != 1 || dirs[0].Type != "file") {
dst = mergeDestDir(dst, volumePath)
}
return d.volumesClientGetAll(s.Client, appID, volumeID, volumePath, dst)
} else if strings.HasPrefix(dst, "vol://") {
volumeID, volumePath, err := parseVol(dst)
if err != nil {
return err
}
if dirs, _, err := volumes.ListDir(s.Client, appID, volumeID, volumePath, 3000); err == nil {
names := strings.Split(strings.Trim(src, "/"), "/")
if len(dirs) == 1 && dirs[0].Type == "file" && strings.HasSuffix(strings.Trim(volumePath, "/"), names[len(names)-1]) {
return fmt.Errorf("the volume path cannot be an existing file")
}
}
if file, err := os.Stat(src); err == nil && file.IsDir() {
volumePath = mergeDestDir(volumePath, src)
}
return d.volumesClientPostAll(s.Client, appID, volumeID, volumePath, src)
}
return nil
}
// volumesClientRm delete a file from volume
func (d *DryccCmd) volumesClientRm(appID, vol string) error {
s, appID, err := load(d.ConfigFile, appID)
if err != nil {
return err
}
host, path, err := parseVol(vol)
if err != nil {
return err
}
res, err := volumes.DeleteFile(s.Client, appID, host, path)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("incorrect http status code %d", res.StatusCode)
}
return nil
}
func parseVolume(volumeVars []string) (map[string]interface{}, error) {
volumeMap := make(map[string]interface{})
regex := regexp.MustCompile(`^([a-z0-9]+(?:-[a-z0-9]+)*)=(\/([\w]+[\w-]*\/?)+)$`)
for _, volume := range volumeVars {
if regex.MatchString(volume) {
captures := regex.FindStringSubmatch(volume)
volumeMap[captures[1]] = captures[2]
} else {
return nil, fmt.Errorf("'%s' does not match the pattern 'key=var', ex: MODE=test", volume)
}
}
return volumeMap, nil
}
// parseVol format volume url
func parseVol(vol string) (string, string, error) {
u, err := url.Parse(vol)
if err != nil {
return "", "", err
}
if u.Scheme != "vol" || u.Host == "" {
return "", "", fmt.Errorf("vol %s format err", vol)
}
return u.Host, strings.TrimPrefix(u.Path, "/"), nil
}
// mergeDestDir merge dest dir
func mergeDestDir(prefix, dir string) string {
if !strings.HasSuffix(dir, "/") {
names := strings.Split(dir, "/")
return strings.Join([]string{prefix, names[len(names)-1]}, "/")
}
return prefix
}
// printVolumes format volume data
func printVolumes(d *DryccCmd, volumes api.Volumes) {
table := d.getDefaultFormatTable([]string{"NAME", "OWNER", "TYPE", "PTYPE", "PATH", "SIZE"})
for _, volume := range volumes {
if len(volume.Path) > 0 {
for _, key := range *sortKeys(volume.Path) {
table.Append([]string{volume.Name, volume.Owner, volume.Type, key, fmt.Sprintf("%v", volume.Path[key]), volume.Size})
}
} else {
table.Append([]string{volume.Name, volume.Owner, volume.Type, "", "", volume.Size})
}
}
table.Render()
}
func (d *DryccCmd) newProgressbar(maxBytes int64, icon, description string) *progressbar.ProgressBar {
return progressbar.NewOptions64(
maxBytes,
progressbar.OptionSetDescription(description),
progressbar.OptionSetWriter(os.Stderr),
progressbar.OptionShowBytes(true),
progressbar.OptionEnableColorCodes(true),
progressbar.OptionSetWidth(10),
progressbar.OptionThrottle(65*time.Millisecond),
progressbar.OptionShowCount(),
progressbar.OptionOnCompletion(func() { fmt.Fprint(os.Stderr, "\n") }),
progressbar.OptionSpinnerType(14),
progressbar.OptionFullWidth(),
progressbar.OptionSetRenderBlankState(true),
progressbar.OptionSetDescription(fmt.Sprintf("[cyan][%s][reset] %s", icon, d.fixateString(description, 32))),
progressbar.OptionSetTheme(progressbar.Theme{
Saucer: "[green]=[reset]",
SaucerHead: "[green]>[reset]",
SaucerPadding: " ",
BarStart: "[",
BarEnd: "]",
}),
)
}