-
Notifications
You must be signed in to change notification settings - Fork 4
/
shell.go
206 lines (184 loc) · 4.72 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
package main
import (
"context"
_ "embed"
"errors"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/moby/term"
)
const (
ExitCodeOnError = 66
)
func shell(args []string) (int, error) {
if len(args) < 1 {
return ExitCodeOnError, errors.New("shell needs at least one argument to run")
}
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return ExitCodeOnError, err
}
var sshSock string
if activeProfile.SSH {
if runtime.GOOS == "darwin" {
// Docker has magic paths for this on Mac
sshSock = "/run/host-services/ssh-auth.sock"
} else {
sshSock, _ = os.LookupEnv("SSH_AUTH_SOCK")
}
}
printIfErr(checkUpdate(activeProfile, false, false))
var containerID string
if activeProfile.Persistent {
containerID, err = getPersistentContainer(ctx, cli, activeProfile)
if err != nil {
return ExitCodeOnError, err
}
}
if containerID != "" {
needsUpdate, err := checkContainerImageVersion(ctx, cli, containerID)
if err != nil {
return ExitCodeOnError, err
}
if needsUpdate {
fmt.Print(
"WARNING: Persistent container is using an out of date image.\n" +
"WARNING: Please terminate and restart to use the new version.\n\n",
)
}
} else {
containerID, err = startContainer(ctx, cli, activeProfile, sshSock)
if err != nil {
return ExitCodeOnError, err
}
}
wd, err := getWorkingDir(activeProfile)
if err != nil {
return ExitCodeOnError, err
}
execCfg := container.ExecOptions{
User: fmt.Sprintf("%s:%s", activeProfile.User, activeProfile.Group),
WorkingDir: wd,
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Tty: true,
Cmd: args,
}
if sshSock != "" {
execCfg.Env = []string{"SSH_AUTH_SOCK=" + sshSock}
}
execResp, err := cli.ContainerExecCreate(ctx, containerID, execCfg)
if err != nil {
return ExitCodeOnError, err
}
execID := execResp.ID
hijack, err := cli.ContainerExecAttach(ctx, execID, container.ExecAttachOptions{Tty: execCfg.Tty})
if err != nil {
return ExitCodeOnError, err
}
defer hijack.Close()
// keep the TTY the same size in the container as on the host
err = resizeTty(ctx, cli, execID)
if err != nil {
// for very fast commands, the resize may happen too early or too late
if !strings.Contains(err.Error(), "cannot resize a stopped container") &&
!strings.Contains(err.Error(), "no such exec") {
return ExitCodeOnError, err
}
}
monitorTtySize(ctx, cli, execID)
termState, err := term.SetRawTerminal(os.Stdin.Fd())
if err != nil {
return ExitCodeOnError, err
}
defer func() {
err = errors.Join(err, term.RestoreTerminal(os.Stdin.Fd(), termState))
}()
outErr := make(chan (error))
inErr := make(chan (error))
go func() {
_, err := io.Copy(os.Stdout, hijack.Reader)
outErr <- err
}()
go func() {
_, err := io.Copy(hijack.Conn, os.Stdin)
inErr <- err
}()
err = cli.ContainerExecStart(ctx, execID, container.ExecStartOptions{})
if err != nil {
return ExitCodeOnError, err
}
select {
case err := <-outErr:
if err != nil {
return ExitCodeOnError, err
}
break
case err := <-inErr:
if err != nil {
return ExitCodeOnError, err
}
select {
case err := <-outErr:
if err != nil {
return ExitCodeOnError, err
}
case <-ctx.Done():
return ExitCodeOnError, ctx.Err()
}
}
details, err := cli.ContainerExecInspect(ctx, execID)
if err != nil {
return ExitCodeOnError, err
}
if !activeProfile.Persistent {
err = removeContainer(ctx, cli, containerID)
if err != nil {
return ExitCodeOnError, err
}
}
return details.ExitCode, nil
}
func resizeTty(ctx context.Context, cli *client.Client, execID string) error {
termSize, err := term.GetWinsize(os.Stdout.Fd())
if err != nil {
return err
}
resizeOpts := container.ResizeOptions{
Height: uint(termSize.Height),
Width: uint(termSize.Width),
}
return cli.ContainerExecResize(ctx, execID, resizeOpts)
}
func monitorTtySize(ctx context.Context, cli *client.Client, execID string) {
sigchan := make(chan os.Signal, 1)
signal.Notify(sigchan, syscall.SIGWINCH)
go func() {
for range sigchan {
//nolint:errcheck // no way to salvage error, and we DO want it to try again on the next resize
resizeTty(ctx, cli, execID)
}
}()
}
func getWorkingDir(profile *Profile) (string, error) {
// start in the right workdir
cwd, err := os.Getwd()
if err != nil {
return "", err
}
if !strings.HasPrefix(cwd, profile.Path) {
return "", errors.New("current directory is not within the current profile's path")
}
cwd = strings.TrimPrefix(cwd, profile.Path)
return filepath.Join(canonMountPoint, cwd), nil
}