-
Notifications
You must be signed in to change notification settings - Fork 644
/
Copy pathshell.go
238 lines (214 loc) · 6.75 KB
/
shell.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
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"al.essio.dev/pkg/shellescape"
"github.com/lima-vm/lima/pkg/sshutil"
"github.com/lima-vm/lima/pkg/store"
"github.com/mattn/go-isatty"
"github.com/mattn/go-shellwords"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// Environment variable that allows configuring the command (alias) to execute
// in place of the 'ssh' executable.
const envShellSSH = "SSH"
const shellHelp = `Execute shell in Lima
lima command is provided as an alias for limactl shell $LIMA_INSTANCE. $LIMA_INSTANCE defaults to "` + DefaultInstanceName + `".
By default, the first 'ssh' executable found in the host's PATH is used to connect to the Lima instance.
A custom ssh alias can be used instead by setting the $` + envShellSSH + ` environment variable.
Hint: try --debug to show the detailed logs, if it seems hanging (mostly due to some SSH issue).
`
func newShellCommand() *cobra.Command {
shellCmd := &cobra.Command{
Use: "shell [flags] INSTANCE [COMMAND...]",
Short: "Execute shell in Lima",
Long: shellHelp,
Args: WrapArgsError(cobra.MinimumNArgs(1)),
RunE: shellAction,
ValidArgsFunction: shellBashComplete,
SilenceErrors: true,
GroupID: basicCommand,
}
shellCmd.Flags().SetInterspersed(false)
shellCmd.Flags().String("shell", "", "shell interpreter, e.g. /bin/bash")
shellCmd.Flags().String("workdir", "", "working directory")
return shellCmd
}
func shellAction(cmd *cobra.Command, args []string) error {
_ = os.Setenv("_LIMACTL_SHELL_IN_ACTION", "")
// simulate the behavior of double dash
newArg := []string{}
if len(args) >= 2 && args[1] == "--" {
newArg = append(newArg, args[:1]...)
newArg = append(newArg, args[2:]...)
args = newArg
}
instName := args[0]
if len(args) >= 2 {
switch args[1] {
case "create", "start", "delete", "shell":
// `lima start` (alias of `limactl $LIMA_INSTANCE start`) is probably a typo of `limactl start`
logrus.Warnf("Perhaps you meant `limactl %s`?", strings.Join(args[1:], " "))
}
}
tty, err := interactive(cmd)
if err != nil {
return err
}
inst, err := store.Inspect(instName)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return err
}
if !tty {
return fmt.Errorf("instance %q does not exist, run `limactl create %s` to create a new instance", instName, instName)
}
if err := askToStart(cmd, instName, true); err != nil {
return err
}
inst, err = store.Inspect(instName)
} else if inst.Status == store.StatusStopped {
if !tty {
return fmt.Errorf("instance %q is stopped, run `limactl start %s` to start the instance", instName, instName)
}
if err := askToStart(cmd, instName, false); err != nil {
return err
}
inst, err = store.Inspect(instName)
}
if err != nil {
return err
}
if inst.Status != store.StatusRunning {
return fmt.Errorf("instance %q status is not %q but %q", inst.Name, store.StatusRunning, inst.Status)
}
// When workDir is explicitly set, the shell MUST have workDir as the cwd, or exit with an error.
//
// changeDirCmd := "cd workDir || exit 1" if workDir != ""
// := "cd hostCurrentDir || cd hostHomeDir" if workDir == ""
var changeDirCmd string
workDir, err := cmd.Flags().GetString("workdir")
if err != nil {
return err
}
if workDir != "" {
changeDirCmd = fmt.Sprintf("cd %s || exit 1", shellescape.Quote(workDir))
// FIXME: check whether y.Mounts contains the home, not just len > 0
} else if len(inst.Config.Mounts) > 0 {
hostCurrentDir, err := os.Getwd()
if err == nil {
changeDirCmd = fmt.Sprintf("cd %s", shellescape.Quote(hostCurrentDir))
} else {
changeDirCmd = "false"
logrus.WithError(err).Warn("failed to get the current directory")
}
hostHomeDir, err := os.UserHomeDir()
if err == nil {
changeDirCmd = fmt.Sprintf("%s || cd %s", changeDirCmd, shellescape.Quote(hostHomeDir))
} else {
logrus.WithError(err).Warn("failed to get the home directory")
}
} else {
logrus.Debug("the host home does not seem mounted, so the guest shell will have a different cwd")
}
if changeDirCmd == "" {
changeDirCmd = "false"
}
logrus.Debugf("changeDirCmd=%q", changeDirCmd)
shell, err := cmd.Flags().GetString("shell")
if err != nil {
return err
}
if shell == "" {
shell = `"$SHELL"`
} else {
shell = shellescape.Quote(shell)
}
script := fmt.Sprintf("%s ; exec %s --login", changeDirCmd, shell)
if len(args) > 1 {
quotedArgs := make([]string, len(args[1:]))
parsingEnv := true
for i, arg := range args[1:] {
if parsingEnv && isEnv(arg) {
quotedArgs[i] = quoteEnv(arg)
} else {
parsingEnv = false
quotedArgs[i] = shellescape.Quote(arg)
}
}
script += fmt.Sprintf(
" -c %s",
shellescape.Quote(strings.Join(quotedArgs, " ")),
)
}
var arg0 string
var arg0Args []string
if sshShell := os.Getenv(envShellSSH); sshShell != "" {
sshShellFields, err := shellwords.Parse(sshShell)
switch {
case err != nil:
logrus.WithError(err).Warnf("Failed to split %s variable into shell tokens. "+
"Falling back to 'ssh' command", envShellSSH)
case len(sshShellFields) > 0:
arg0 = sshShellFields[0]
if len(sshShellFields) > 1 {
arg0Args = sshShellFields[1:]
}
}
}
if arg0 == "" {
arg0, err = exec.LookPath("ssh")
if err != nil {
return err
}
}
sshOpts, err := sshutil.SSHOpts(
inst.Dir,
*inst.Config.User.Name,
*inst.Config.SSH.LoadDotSSHPubKeys,
*inst.Config.SSH.ForwardAgent,
*inst.Config.SSH.ForwardX11,
*inst.Config.SSH.ForwardX11Trusted)
if err != nil {
return err
}
sshArgs := sshutil.SSHArgsFromOpts(sshOpts)
if isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()) {
// required for showing the shell prompt: https://stackoverflow.com/a/626574
sshArgs = append(sshArgs, "-t")
}
if _, present := os.LookupEnv("COLORTERM"); present {
// SendEnv config is cumulative, with already existing options in ssh_config
sshArgs = append(sshArgs, "-o", "SendEnv=COLORTERM")
}
sshArgs = append(sshArgs, []string{
"-q",
"-p", strconv.Itoa(inst.SSHLocalPort),
inst.SSHAddress,
"--",
script,
}...)
sshCmd := exec.Command(arg0, append(arg0Args, sshArgs...)...)
sshCmd.Stdin = os.Stdin
sshCmd.Stdout = os.Stdout
sshCmd.Stderr = os.Stderr
logrus.Debugf("executing ssh (may take a long)): %+v", sshCmd.Args)
// TODO: use syscall.Exec directly (results in losing tty?)
return sshCmd.Run()
}
func shellBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return bashCompleteInstanceNames(cmd)
}
func isEnv(arg string) bool {
return len(strings.Split(arg, "=")) > 1
}
func quoteEnv(arg string) string {
env := strings.SplitN(arg, "=", 2)
env[1] = shellescape.Quote(env[1])
return strings.Join(env, "=")
}