forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
1290 lines (1057 loc) · 31.7 KB
/
file.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
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"os"
"os/exec"
"os/signal"
"path"
"path/filepath"
"strconv"
"strings"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"github.com/lxc/lxd/client"
"github.com/lxc/lxd/lxc/utils"
"github.com/lxc/lxd/shared"
cli "github.com/lxc/lxd/shared/cmd"
"github.com/lxc/lxd/shared/i18n"
"github.com/lxc/lxd/shared/ioprogress"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/termios"
"github.com/lxc/lxd/shared/units"
)
// DirMode represents the file mode for creating dirs on `lxc file pull/push`.
const DirMode = 0755
type cmdFile struct {
global *cmdGlobal
flagUID int
flagGID int
flagMode string
flagMkdir bool
flagRecursive bool
}
func fileGetWrapper(server lxd.InstanceServer, inst string, path string) (buf io.ReadCloser, resp *lxd.InstanceFileResponse, err error) {
// Signal handling
chSignal := make(chan os.Signal, 1)
signal.Notify(chSignal, os.Interrupt)
// Operation handling
chDone := make(chan bool)
go func() {
buf, resp, err = server.GetInstanceFile(inst, path)
close(chDone)
}()
count := 0
for {
select {
case <-chDone:
return buf, resp, err
case <-chSignal:
count++
if count == 3 {
return nil, nil, fmt.Errorf(i18n.G("User signaled us three times, exiting. The remote operation will keep running"))
}
fmt.Println(i18n.G("Early server side processing of file transfer requests cannot be canceled (interrupt two more times to force)"))
}
}
}
func (c *cmdFile) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("file")
cmd.Short = i18n.G("Manage files in instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Manage files in instances`))
// Delete
fileDeleteCmd := cmdFileDelete{global: c.global, file: c}
cmd.AddCommand(fileDeleteCmd.Command())
// Pull
filePullCmd := cmdFilePull{global: c.global, file: c}
cmd.AddCommand(filePullCmd.Command())
// Push
filePushCmd := cmdFilePush{global: c.global, file: c}
cmd.AddCommand(filePushCmd.Command())
// Edit
fileEditCmd := cmdFileEdit{global: c.global, file: c, filePull: &filePullCmd, filePush: &filePushCmd}
cmd.AddCommand(fileEditCmd.Command())
// Mount
fileMountCmd := cmdFileMount{global: c.global, file: c}
cmd.AddCommand(fileMountCmd.Command())
// Workaround for subcommand usage errors. See: https://github.com/spf13/cobra/issues/706
cmd.Args = cobra.NoArgs
cmd.Run = func(cmd *cobra.Command, args []string) { _ = cmd.Usage() }
return cmd
}
// Delete.
type cmdFileDelete struct {
global *cmdGlobal
file *cmdFile
}
func (c *cmdFileDelete) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("delete", i18n.G("[<remote>:]<instance>/<path> [[<remote>:]<instance>/<path>...]"))
cmd.Aliases = []string{"rm"}
cmd.Short = i18n.G("Delete files in instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Delete files in instances`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdFileDelete) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, -1)
if exit {
return err
}
// Parse remote
resources, err := c.global.ParseServers(args...)
if err != nil {
return err
}
for _, resource := range resources {
pathSpec := strings.SplitN(resource.name, "/", 2)
if len(pathSpec) != 2 {
return fmt.Errorf(i18n.G("Invalid path %s"), resource.name)
}
// Delete the file
err = resource.server.DeleteInstanceFile(pathSpec[0], pathSpec[1])
if err != nil {
return err
}
}
return nil
}
// Edit.
type cmdFileEdit struct {
global *cmdGlobal
file *cmdFile
filePull *cmdFilePull
filePush *cmdFilePush
}
func (c *cmdFileEdit) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("edit", i18n.G("[<remote>:]<instance>/<path>"))
cmd.Short = i18n.G("Edit files in instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Edit files in instances`))
cmd.RunE = c.Run
return cmd
}
func (c *cmdFileEdit) Run(cmd *cobra.Command, args []string) error {
c.filePush.noModeChange = true
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
// If stdin isn't a terminal, read text from it
if !termios.IsTerminal(getStdinFd()) {
return c.filePush.Run(cmd, append([]string{os.Stdin.Name()}, args[0]))
}
// Create temp file
f, err := ioutil.TempFile("", "lxd_file_edit_")
if err != nil {
return fmt.Errorf(i18n.G("Unable to create a temporary file: %v"), err)
}
fname := f.Name()
_ = f.Close()
_ = os.Remove(fname)
// Tell pull/push that they're called from edit.
c.filePull.edit = true
c.filePush.edit = true
// Extract current value
defer func() { _ = os.Remove(fname) }()
err = c.filePull.Run(cmd, append([]string{args[0]}, fname))
if err != nil {
return err
}
// Spawn the editor
_, err = shared.TextEditor(fname, []byte{})
if err != nil {
return err
}
// Push the result
err = c.filePush.Run(cmd, append([]string{fname}, args[0]))
if err != nil {
return err
}
return nil
}
// Pull.
type cmdFilePull struct {
global *cmdGlobal
file *cmdFile
edit bool
}
func (c *cmdFilePull) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("pull", i18n.G("[<remote>:]<instance>/<path> [[<remote>:]<instance>/<path>...] <target path>"))
cmd.Short = i18n.G("Pull files from instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Pull files from instances`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc file pull foo/etc/hosts .
To pull /etc/hosts from the instance and write it to the current directory.`))
cmd.Flags().BoolVarP(&c.file.flagMkdir, "create-dirs", "p", false, i18n.G("Create any directories necessary"))
cmd.Flags().BoolVarP(&c.file.flagRecursive, "recursive", "r", false, i18n.G("Recursively transfer files"))
cmd.RunE = c.Run
return cmd
}
func (c *cmdFilePull) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, -1)
if exit {
return err
}
// Determine the target
target := filepath.Clean(args[len(args)-1])
if !c.edit {
target = shared.HostPathFollow(target)
}
targetIsDir := false
sb, err := os.Stat(target)
if err != nil && !os.IsNotExist(err) {
return err
}
/*
* If the path exists, just use it. If it doesn't exist, it might be a
* directory in one of three cases:
* 1. Someone explicitly put "/" at the end
* 2. Someone provided more than one source. In this case the target
* should be a directory so we can save all the files into it.
* 3. We are dealing with recursive copy
*/
if err == nil {
targetIsDir = sb.IsDir()
if !targetIsDir && len(args)-1 > 1 {
return fmt.Errorf(i18n.G("More than one file to download, but target is not a directory"))
}
} else if strings.HasSuffix(args[len(args)-1], string(os.PathSeparator)) || len(args)-1 > 1 {
err := os.MkdirAll(target, DirMode)
if err != nil {
return err
}
targetIsDir = true
} else if c.file.flagMkdir {
err := os.MkdirAll(filepath.Dir(target), DirMode)
if err != nil {
return err
}
}
// Parse remote
resources, err := c.global.ParseServers(args[:len(args)-1]...)
if err != nil {
return err
}
for _, resource := range resources {
pathSpec := strings.SplitN(resource.name, "/", 2)
if len(pathSpec) != 2 {
return fmt.Errorf(i18n.G("Invalid source %s"), resource.name)
}
buf, resp, err := fileGetWrapper(resource.server, pathSpec[0], pathSpec[1])
if err != nil {
return err
}
// Deal with recursion
if resp.Type == "directory" {
if c.file.flagRecursive {
if !shared.PathExists(target) {
err := os.MkdirAll(target, DirMode)
if err != nil {
return err
}
targetIsDir = true
}
err := c.file.recursivePullFile(resource.server, pathSpec[0], pathSpec[1], target)
if err != nil {
return err
}
continue
} else {
return fmt.Errorf(i18n.G("Can't pull a directory without --recursive"))
}
}
var targetPath string
if targetIsDir {
targetPath = path.Join(target, path.Base(pathSpec[1]))
} else {
targetPath = target
}
logger.Infof("Pulling %s from %s (%s)", targetPath, pathSpec[1], resp.Type)
if resp.Type == "symlink" {
linkTarget, err := ioutil.ReadAll(buf)
if err != nil {
return err
}
// Follow the symlink
if targetPath == "-" || c.file.flagRecursive {
for {
newPath := strings.TrimSuffix(string(linkTarget), "\n")
if !strings.HasPrefix(newPath, "/") {
newPath = filepath.Clean(filepath.Join(filepath.Dir(pathSpec[1]), newPath))
}
buf, resp, err = resource.server.GetInstanceFile(pathSpec[0], newPath)
if err != nil {
return err
}
if resp.Type != "symlink" {
break
}
}
} else {
err = os.Symlink(strings.TrimSpace(string(linkTarget)), targetPath)
if err != nil {
return err
}
continue
}
}
var f *os.File
if targetPath == "-" {
f = os.Stdout
} else {
f, err = os.Create(targetPath)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
err = os.Chmod(targetPath, os.FileMode(resp.Mode))
if err != nil {
return err
}
}
progress := utils.ProgressRenderer{
Format: fmt.Sprintf(i18n.G("Pulling %s from %s: %%s"), targetPath, pathSpec[1]),
Quiet: c.global.flagQuiet,
}
writer := &ioprogress.ProgressWriter{
WriteCloser: f,
Tracker: &ioprogress.ProgressTracker{
Handler: func(bytesReceived int64, speed int64) {
if targetPath == "-" {
return
}
progress.UpdateProgress(ioprogress.ProgressData{
Text: fmt.Sprintf("%s (%s/s)",
units.GetByteSizeString(bytesReceived, 2),
units.GetByteSizeString(speed, 2))})
},
},
}
_, err = io.Copy(writer, buf)
if err != nil {
progress.Done("")
return err
}
err = f.Close()
if err != nil {
progress.Done("")
return err
}
progress.Done("")
}
return nil
}
// Push.
type cmdFilePush struct {
global *cmdGlobal
file *cmdFile
edit bool
noModeChange bool
}
func (c *cmdFilePush) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("push", i18n.G("<source path>... [<remote>:]<instance>/<path>"))
cmd.Short = i18n.G("Push files into instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Push files into instances`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc file push /etc/hosts foo/etc/hosts
To push /etc/hosts into the instance "foo".`))
cmd.Flags().BoolVarP(&c.file.flagRecursive, "recursive", "r", false, i18n.G("Recursively transfer files"))
cmd.Flags().BoolVarP(&c.file.flagMkdir, "create-dirs", "p", false, i18n.G("Create any directories necessary"))
cmd.Flags().IntVar(&c.file.flagUID, "uid", -1, i18n.G("Set the file's uid on push")+"``")
cmd.Flags().IntVar(&c.file.flagGID, "gid", -1, i18n.G("Set the file's gid on push")+"``")
cmd.Flags().StringVar(&c.file.flagMode, "mode", "", i18n.G("Set the file's perms on push")+"``")
cmd.RunE = c.Run
return cmd
}
func (c *cmdFilePush) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 2, -1)
if exit {
return err
}
// Parse the destination
target := args[len(args)-1]
pathSpec := strings.SplitN(target, "/", 2)
if len(pathSpec) != 2 {
return fmt.Errorf(i18n.G("Invalid target %s"), target)
}
targetIsDir := strings.HasSuffix(target, "/")
// re-add leading / that got stripped by the SplitN
targetPath := "/" + pathSpec[1]
// clean various /./, /../, /////, etc. that users add (#2557)
targetPath = path.Clean(targetPath)
// normalization may reveal that path is still a dir, e.g. /.
if strings.HasSuffix(targetPath, "/") {
targetIsDir = true
}
// Parse remote
resources, err := c.global.ParseServers(pathSpec[0])
if err != nil {
return err
}
resource := resources[0]
// Make a list of paths to transfer
sourcefilenames := []string{}
for _, fname := range args[:len(args)-1] {
if !c.edit {
sourcefilenames = append(sourcefilenames, shared.HostPathFollow(filepath.Clean(fname)))
} else {
sourcefilenames = append(sourcefilenames, filepath.Clean(fname))
}
}
// Determine the target mode
mode := os.FileMode(DirMode)
if c.file.flagMode != "" {
if len(c.file.flagMode) == 3 {
c.file.flagMode = "0" + c.file.flagMode
}
m, err := strconv.ParseInt(c.file.flagMode, 0, 0)
if err != nil {
return err
}
mode = os.FileMode(m)
}
// Recursive calls
if c.file.flagRecursive {
// Quick checks.
if c.file.flagUID != -1 || c.file.flagGID != -1 || c.file.flagMode != "" {
return fmt.Errorf(i18n.G("Can't supply uid/gid/mode in recursive mode"))
}
// Create needed paths if requested
if c.file.flagMkdir {
f, err := os.Open(sourcefilenames[0])
if err != nil {
return err
}
finfo, err := f.Stat()
_ = f.Close()
if err != nil {
return err
}
mode, uid, gid := shared.GetOwnerMode(finfo)
err = c.file.recursiveMkdir(resource.server, resource.name, targetPath, &mode, int64(uid), int64(gid))
if err != nil {
return err
}
}
// Transfer the files
for _, fname := range sourcefilenames {
err := c.file.recursivePushFile(resource.server, resource.name, fname, targetPath)
if err != nil {
return err
}
}
return nil
}
// Determine the target uid
uid := 0
if c.file.flagUID >= 0 {
uid = c.file.flagUID
}
// Determine the target gid
gid := 0
if c.file.flagGID >= 0 {
gid = c.file.flagGID
}
if (len(sourcefilenames) > 1) && !targetIsDir {
return fmt.Errorf(i18n.G("Missing target directory"))
}
// Make sure all of the files are accessible by us before trying to push any of them
var files []*os.File
for _, f := range sourcefilenames {
var file *os.File
if f == "-" {
file = os.Stdin
} else {
file, err = os.Open(f)
if err != nil {
return err
}
}
defer func() { _ = file.Close() }()
files = append(files, file)
}
// Push the files
for _, f := range files {
fpath := targetPath
if targetIsDir {
fpath = path.Join(fpath, path.Base(f.Name()))
}
// Create needed paths if requested
if c.file.flagMkdir {
finfo, err := f.Stat()
if err != nil {
return err
}
_, dUID, dGID := shared.GetOwnerMode(finfo)
if c.file.flagUID == -1 || c.file.flagGID == -1 {
if c.file.flagUID == -1 {
uid = dUID
}
if c.file.flagGID == -1 {
gid = dGID
}
}
err = c.file.recursiveMkdir(resource.server, resource.name, path.Dir(fpath), nil, int64(uid), int64(gid))
if err != nil {
return err
}
}
// Transfer the files
args := lxd.InstanceFileArgs{
UID: -1,
GID: -1,
Mode: -1,
}
if !c.noModeChange {
if c.file.flagMode == "" || c.file.flagUID == -1 || c.file.flagGID == -1 {
finfo, err := f.Stat()
if err != nil {
return err
}
fMode, fUID, fGID := shared.GetOwnerMode(finfo)
if err != nil {
return err
}
if c.file.flagMode == "" {
mode = fMode
}
if c.file.flagUID == -1 {
uid = fUID
}
if c.file.flagGID == -1 {
gid = fGID
}
}
args.UID = int64(uid)
args.GID = int64(gid)
args.Mode = int(mode.Perm())
}
args.Type = "file"
fstat, err := f.Stat()
if err != nil {
return err
}
progress := utils.ProgressRenderer{
Format: fmt.Sprintf(i18n.G("Pushing %s to %s: %%s"), f.Name(), fpath),
Quiet: c.global.flagQuiet,
}
args.Content = shared.NewReadSeeker(&ioprogress.ProgressReader{
ReadCloser: f,
Tracker: &ioprogress.ProgressTracker{
Length: fstat.Size(),
Handler: func(percent int64, speed int64) {
progress.UpdateProgress(ioprogress.ProgressData{
Text: fmt.Sprintf("%d%% (%s/s)", percent, units.GetByteSizeString(speed, 2)),
})
},
},
}, f)
logger.Infof("Pushing %s to %s (%s)", f.Name(), fpath, args.Type)
err = resource.server.CreateInstanceFile(resource.name, fpath, args)
if err != nil {
progress.Done("")
return err
}
progress.Done("")
}
return nil
}
func (c *cmdFile) recursivePullFile(d lxd.InstanceServer, inst string, p string, targetDir string) error {
buf, resp, err := d.GetInstanceFile(inst, p)
if err != nil {
return err
}
target := filepath.Join(targetDir, filepath.Base(p))
logger.Infof("Pulling %s from %s (%s)", target, p, resp.Type)
if resp.Type == "directory" {
err := os.Mkdir(target, os.FileMode(resp.Mode))
if err != nil {
return err
}
for _, ent := range resp.Entries {
nextP := path.Join(p, ent)
err := c.recursivePullFile(d, inst, nextP, target)
if err != nil {
return err
}
}
} else if resp.Type == "file" {
f, err := os.Create(target)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
err = os.Chmod(target, os.FileMode(resp.Mode))
if err != nil {
return err
}
progress := utils.ProgressRenderer{
Format: fmt.Sprintf(i18n.G("Pulling %s from %s: %%s"), p, target),
Quiet: c.global.flagQuiet,
}
writer := &ioprogress.ProgressWriter{
WriteCloser: f,
Tracker: &ioprogress.ProgressTracker{
Handler: func(bytesReceived int64, speed int64) {
progress.UpdateProgress(ioprogress.ProgressData{
Text: fmt.Sprintf("%s (%s/s)",
units.GetByteSizeString(bytesReceived, 2),
units.GetByteSizeString(speed, 2))})
},
},
}
_, err = io.Copy(writer, buf)
if err != nil {
progress.Done("")
return err
}
err = f.Close()
if err != nil {
progress.Done("")
return err
}
progress.Done("")
} else if resp.Type == "symlink" {
linkTarget, err := ioutil.ReadAll(buf)
if err != nil {
return err
}
err = os.Symlink(strings.TrimSpace(string(linkTarget)), target)
if err != nil {
return err
}
} else {
return fmt.Errorf(i18n.G("Unknown file type '%s'"), resp.Type)
}
return nil
}
func (c *cmdFile) recursivePushFile(d lxd.InstanceServer, inst string, source string, target string) error {
source = filepath.Clean(source)
sourceDir, _ := filepath.Split(source)
sourceLen := len(sourceDir)
sendFile := func(p string, fInfo os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf(i18n.G("Failed to walk path for %s: %s"), p, err)
}
// Detect unsupported files
if !fInfo.Mode().IsRegular() && !fInfo.Mode().IsDir() && fInfo.Mode()&os.ModeSymlink != os.ModeSymlink {
return fmt.Errorf(i18n.G("'%s' isn't a supported file type"), p)
}
// Prepare for file transfer
targetPath := path.Join(target, filepath.ToSlash(p[sourceLen:]))
mode, uid, gid := shared.GetOwnerMode(fInfo)
args := lxd.InstanceFileArgs{
UID: int64(uid),
GID: int64(gid),
Mode: int(mode.Perm()),
}
var readCloser io.ReadCloser
if fInfo.IsDir() {
// Directory handling
args.Type = "directory"
} else if fInfo.Mode()&os.ModeSymlink == os.ModeSymlink {
// Symlink handling
symlinkTarget, err := os.Readlink(p)
if err != nil {
return err
}
args.Type = "symlink"
args.Content = bytes.NewReader([]byte(symlinkTarget))
readCloser = ioutil.NopCloser(args.Content)
} else {
// File handling
f, err := os.Open(p)
if err != nil {
return err
}
defer func() { _ = f.Close() }()
args.Type = "file"
args.Content = f
readCloser = f
}
progress := utils.ProgressRenderer{
Format: fmt.Sprintf(i18n.G("Pushing %s to %s: %%s"), p, targetPath),
Quiet: c.global.flagQuiet,
}
if args.Type != "directory" {
contentLength, err := args.Content.Seek(0, io.SeekEnd)
if err != nil {
return err
}
_, err = args.Content.Seek(0, io.SeekStart)
if err != nil {
return err
}
args.Content = shared.NewReadSeeker(&ioprogress.ProgressReader{
ReadCloser: readCloser,
Tracker: &ioprogress.ProgressTracker{
Length: contentLength,
Handler: func(percent int64, speed int64) {
progress.UpdateProgress(ioprogress.ProgressData{
Text: fmt.Sprintf("%d%% (%s/s)", percent,
units.GetByteSizeString(speed, 2))})
},
},
}, args.Content)
}
logger.Infof("Pushing %s to %s (%s)", p, targetPath, args.Type)
err = d.CreateInstanceFile(inst, targetPath, args)
if err != nil {
if args.Type != "directory" {
progress.Done("")
}
return err
}
if args.Type != "directory" {
progress.Done("")
}
return nil
}
return filepath.Walk(source, sendFile)
}
func (c *cmdFile) recursiveMkdir(d lxd.InstanceServer, inst string, p string, mode *os.FileMode, uid int64, gid int64) error {
/* special case, every instance has a /, we don't need to do anything */
if p == "/" {
return nil
}
// Remove trailing "/" e.g. /A/B/C/. Otherwise we will end up with an
// empty array entry "" which will confuse the Mkdir() loop below.
pclean := filepath.Clean(p)
parts := strings.Split(pclean, "/")
i := len(parts)
for ; i >= 1; i-- {
cur := filepath.Join(parts[:i]...)
_, resp, err := d.GetInstanceFile(inst, cur)
if err != nil {
continue
}
if resp.Type != "directory" {
return fmt.Errorf(i18n.G("%s is not a directory"), cur)
}
i++
break
}
for ; i <= len(parts); i++ {
cur := filepath.Join(parts[:i]...)
if cur == "" {
continue
}
cur = "/" + cur
modeArg := -1
if mode != nil {
modeArg = int(mode.Perm())
}
args := lxd.InstanceFileArgs{
UID: uid,
GID: gid,
Mode: modeArg,
Type: "directory",
}
logger.Infof("Creating %s (%s)", cur, args.Type)
err := d.CreateInstanceFile(inst, cur, args)
if err != nil {
return err
}
}
return nil
}
// Mount.
type cmdFileMount struct {
global *cmdGlobal
file *cmdFile
flagListen string
flagAuthNone bool
flagAuthUser string
}
func (c *cmdFileMount) Command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("mount", i18n.G("[<remote>:]<instance>[/<path>] [<target path>]"))
cmd.Short = i18n.G("Mount files from instances")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Mount files from instances`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc file mount foo/root fooroot
To mount /root from the instance foo onto the local fooroot directory.`))
cmd.RunE = c.Run
cmd.Flags().StringVar(&c.flagListen, "listen", "", i18n.G("Setup SSH SFTP listener on address:port instead of mounting"))
cmd.Flags().BoolVar(&c.flagAuthNone, "no-auth", false, i18n.G("Disable authentication when using SSH SFTP listener"))
cmd.Flags().StringVar(&c.flagAuthUser, "auth-user", "", i18n.G("Set authentication user when using SSH SFTP listener"))
return cmd
}
func (c *cmdFileMount) Run(cmd *cobra.Command, args []string) error {
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 2)
if exit {
return err
}
// Parse remote.
resources, err := c.global.ParseServers(args[0])
if err != nil {
return err
}
resource := resources[0]
var targetPath string
// Determine the target if specified.
if len(args) >= 2 {
targetPath = shared.HostPathFollow(filepath.Clean(args[len(args)-1]))
sb, err := os.Stat(targetPath)
if err != nil {
return err
}
if !sb.IsDir() {
return fmt.Errorf(i18n.G("Target path must be a directory"))
}
}