-
Notifications
You must be signed in to change notification settings - Fork 647
/
Copy pathcopy.go
247 lines (211 loc) · 6.72 KB
/
copy.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
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strings"
"github.com/coreos/go-semver/semver"
"github.com/lima-vm/lima/pkg/sshutil"
"github.com/lima-vm/lima/pkg/store"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
const copyHelp = `Copy files between host and guest
Prefix guest filenames with the instance name and a colon.
Example: limactl copy default:/etc/os-release .
`
type copyTool string
const (
rsync copyTool = "rsync"
scp copyTool = "scp"
)
func newCopyCommand() *cobra.Command {
copyCommand := &cobra.Command{
Use: "copy SOURCE ... TARGET",
Aliases: []string{"cp"},
Short: "Copy files between host and guest",
Long: copyHelp,
Args: WrapArgsError(cobra.MinimumNArgs(2)),
RunE: copyAction,
GroupID: advancedCommand,
}
copyCommand.Flags().BoolP("recursive", "r", false, "copy directories recursively")
copyCommand.Flags().BoolP("verbose", "v", false, "enable verbose output")
return copyCommand
}
func copyAction(cmd *cobra.Command, args []string) error {
recursive, err := cmd.Flags().GetBool("recursive")
if err != nil {
return err
}
verbose, err := cmd.Flags().GetBool("verbose")
if err != nil {
return err
}
debug, err := cmd.Flags().GetBool("debug")
if err != nil {
return err
}
if debug {
verbose = true
}
cpTool := rsync
arg0, err := exec.LookPath(string(cpTool))
if err != nil {
arg0, err = exec.LookPath(string(cpTool))
if err != nil {
return err
}
}
logrus.Infof("using copy tool %q", arg0)
var copyCmd *exec.Cmd
switch cpTool {
case scp:
copyCmd, err = scpCommand(arg0, args, verbose, recursive)
case rsync:
copyCmd, err = rsyncCommand(arg0, args, verbose, recursive)
default:
err = fmt.Errorf("invalid copy tool %q", cpTool)
}
if err != nil {
return err
}
copyCmd.Stdin = cmd.InOrStdin()
copyCmd.Stdout = cmd.OutOrStdout()
copyCmd.Stderr = cmd.ErrOrStderr()
logrus.Debugf("executing %v (may take a long time)", copyCmd)
// TODO: use syscall.Exec directly (results in losing tty?)
return copyCmd.Run()
}
func scpCommand(command string, args []string, verbose, recursive bool) (*exec.Cmd, error) {
instances := make(map[string]*store.Instance)
scpFlags := []string{}
scpArgs := []string{}
var err error
if verbose {
scpFlags = append(scpFlags, "-v")
} else {
scpFlags = append(scpFlags, "-q")
}
if recursive {
scpFlags = append(scpFlags, "-r")
}
// this assumes that ssh and scp come from the same place, but scp has no -V
legacySSH := sshutil.DetectOpenSSHVersion("ssh").LessThan(*semver.New("8.0.0"))
for _, arg := range args {
path := strings.Split(arg, ":")
switch len(path) {
case 1:
scpArgs = append(scpArgs, arg)
case 2:
instName := path[0]
inst, err := store.Inspect(instName)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("instance %q does not exist, run `limactl create %s` to create a new instance", instName, instName)
}
return nil, err
}
if inst.Status == store.StatusStopped {
return nil, fmt.Errorf("instance %q is stopped, run `limactl start %s` to start the instance", instName, instName)
}
if legacySSH {
scpFlags = append(scpFlags, "-P", fmt.Sprintf("%d", inst.SSHLocalPort))
scpArgs = append(scpArgs, fmt.Sprintf("%[email protected]:%s", *inst.Config.User.Name, path[1]))
} else {
scpArgs = append(scpArgs, fmt.Sprintf("scp://%[email protected]:%d/%s", *inst.Config.User.Name, inst.SSHLocalPort, path[1]))
}
instances[instName] = inst
default:
return nil, fmt.Errorf("path %q contains multiple colons", arg)
}
}
if legacySSH && len(instances) > 1 {
return nil, errors.New("more than one (instance) host is involved in this command, this is only supported for openSSH v8.0 or higher")
}
scpFlags = append(scpFlags, "-3", "--")
scpArgs = append(scpFlags, scpArgs...)
var sshOpts []string
if len(instances) == 1 {
// Only one (instance) host is involved; we can use the instance-specific
// arguments such as ControlPath. This is preferred as we can multiplex
// sessions without re-authenticating (MaxSessions permitting).
for _, inst := range instances {
sshOpts, err = sshutil.SSHOpts("ssh", inst.Dir, *inst.Config.User.Name, false, false, false, false)
if err != nil {
return nil, err
}
}
} else {
// Copying among multiple hosts; we can't pass in host-specific options.
sshOpts, err = sshutil.CommonOpts("ssh", false)
if err != nil {
return nil, err
}
}
sshArgs := sshutil.SSHArgsFromOpts(sshOpts)
return exec.Command(command, append(sshArgs, scpArgs...)...), nil
}
func rsyncCommand(command string, args []string, verbose, recursive bool) (*exec.Cmd, error) {
instances := make(map[string]*store.Instance)
var instName string
rsyncFlags := []string{}
rsyncArgs := []string{}
if verbose {
rsyncFlags = append(rsyncFlags, "-v", "--progress")
} else {
rsyncFlags = append(rsyncFlags, "-q")
}
if recursive {
rsyncFlags = append(rsyncFlags, "-r")
}
for _, arg := range args {
path := strings.Split(arg, ":")
switch len(path) {
case 1:
inst, ok := instances[instName]
if !ok {
return nil, fmt.Errorf("instance %q does not exist, run `limactl create %s` to create a new instance", instName, instName)
}
guestVM := fmt.Sprintf("%[email protected]:%s", *inst.Config.User.Name, path[0])
rsyncArgs = append(rsyncArgs, guestVM)
case 2:
instName = path[0]
inst, err := store.Inspect(instName)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("instance %q does not exist, run `limactl create %s` to create a new instance", instName, instName)
}
return nil, err
}
sshOpts, err := sshutil.SSHOpts("ssh", inst.Dir, *inst.Config.User.Name, false, false, false, false)
if err != nil {
return nil, err
}
sshArgs := sshutil.SSHArgsFromOpts(sshOpts)
sshStr := fmt.Sprintf("ssh -p %s %s", fmt.Sprintf("%d", inst.SSHLocalPort), strings.Join(sshArgs, " "))
destDir := args[1]
mkdirCmd := exec.Command(
"ssh",
"-p", fmt.Sprintf("%d", inst.SSHLocalPort),
)
mkdirCmd.Args = append(mkdirCmd.Args, sshArgs...)
mkdirCmd.Args = append(mkdirCmd.Args,
fmt.Sprintf("%s@%s", *inst.Config.User.Name, "127.0.0.1"),
fmt.Sprintf("sudo mkdir -p %q && sudo chown %s:%s %s", destDir, *inst.Config.User.Name, *inst.Config.User.Name, destDir),
)
mkdirCmd.Stdout = os.Stdout
mkdirCmd.Stderr = os.Stderr
if err := mkdirCmd.Run(); err != nil {
return nil, fmt.Errorf("failed to create directory %q on remote: %w", destDir, err)
}
rsyncArgs = append(rsyncArgs, "-avz", "-e", sshStr, path[1])
instances[instName] = inst
default:
return nil, fmt.Errorf("path %q contains multiple colons", arg)
}
}
rsyncArgs = append(rsyncFlags, rsyncArgs...)
return exec.Command(command, rsyncArgs...), nil
}