-
Notifications
You must be signed in to change notification settings - Fork 386
/
main.go
300 lines (248 loc) · 6.74 KB
/
main.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
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"os/exec"
"time"
"github.com/earthly/earthly/conslogging"
"github.com/earthly/earthly/debugger/common"
"github.com/earthly/earthly/slog"
"github.com/alessio/shellescape"
"github.com/creack/pty"
"github.com/fatih/color"
multierror "github.com/hashicorp/go-multierror"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
var (
// Version is the version of the debugger
Version string
// GitSha is the git sha used to build the debugger
GitSha string
// ErrNoShellFound occurs when the container has no shell
ErrNoShellFound = errors.Errorf("no shell found")
)
func getShellPath() (string, bool) {
for _, sh := range []string{
"bash", "ksh", "zsh", "ash", "sh",
} {
if path, err := exec.LookPath(sh); err == nil {
return path, true
}
}
return "", false
}
func handlePtyData(ptmx *os.File, data []byte) error {
_, err := ptmx.Write(data)
if err != nil {
return errors.Wrap(err, "failed to write to ptmx")
}
return nil
}
func handleWinChangeData(ptmx *os.File, data []byte) error {
var size pty.Winsize
err := json.Unmarshal(data, &size)
if err != nil {
return errors.Wrap(err, "failed unmarshal data")
}
err = pty.Setsize(ptmx, &size)
if err != nil {
return errors.Wrap(err, "failed to set window size")
}
return nil
}
func populateShellHistory(cmd string) error {
var result error
for _, f := range []string{
"/root/.ash_history",
"/root/.bash_history",
} {
f, err := os.Create(f)
if err != nil {
result = multierror.Append(result, err)
}
defer f.Close()
f.Write([]byte(cmd + "\n"))
}
return result
}
func interactiveMode(ctx context.Context, remoteConsoleAddr string, cmdBuilder func() (*exec.Cmd, error)) error {
log := slog.GetLogger(ctx)
conn, err := net.Dial("tcp", remoteConsoleAddr)
if err != nil {
return errors.Wrap(err, "failed to connect to remote debugger")
}
defer func() {
err := conn.Close()
if err != nil {
log.Error(errors.Wrap(err, "error closing"))
}
}()
_, err = conn.Write([]byte{common.ShellID})
if err != nil {
return err
}
err = common.WriteDataPacket(conn, common.StartShellSession, nil)
if err != nil {
return err
}
c, err := cmdBuilder()
if err != nil {
return err
}
ptmx, err := pty.Start(c)
if err != nil {
log.Error(errors.Wrap(err, "failed to start pty"))
return err
}
defer func() { _ = ptmx.Close() }() // Best effort.
ctx, cancel := context.WithCancel(ctx)
go func() {
for {
connDataType, data, err := common.ReadDataPacket(conn)
if err != nil {
log.Error(errors.Wrap(err, "failed to read data from conn"))
break
}
switch connDataType {
case common.PtyData:
handlePtyData(ptmx, data)
case common.WinSizeData:
handleWinChangeData(ptmx, data)
default:
log.With("datatype", connDataType).Warning("unhandled data type")
}
}
cancel()
}()
go func() {
initialData := true
for {
buf := make([]byte, 100)
n, err := ptmx.Read(buf)
if err != nil {
log.Error(errors.Wrap(err, "failed to read from ptmx"))
break
}
buf = buf[:n]
if initialData {
buf = append([]byte("\r\n"), buf...)
initialData = false
}
common.WriteDataPacket(conn, common.PtyData, buf)
}
cancel()
}()
go func() {
c.Wait()
cancel()
}()
<-ctx.Done()
common.WriteDataPacket(conn, common.EndShellSession, nil)
return nil
}
func getSettings(path string) (*common.DebuggerSettings, error) {
s, err := ioutil.ReadFile(path)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to read %s", path))
}
var data common.DebuggerSettings
err = json.Unmarshal(s, &data)
if err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("failed to unmarshal %s", path))
}
return &data, nil
}
func main() {
args := os.Args[1:]
if args[0] == "--version" {
fmt.Printf("version: %v-%v\n", Version, GitSha)
return
}
forceInteractive := false
if args[0] == "--force" {
args = args[1:]
forceInteractive = true
}
conslogger := conslogging.Current(conslogging.ForceColor, conslogging.NoPadding, false)
color.NoColor = false
debuggerSettings, err := getSettings(fmt.Sprintf("/run/secrets/%s", common.DebuggerSettingsSecretsKey))
if err != nil {
conslogger.Warnf("failed to read settings: %v\n", debuggerSettings)
os.Exit(1)
}
if debuggerSettings.DebugLevelLogging {
logrus.SetLevel(logrus.DebugLevel)
conslogger = conslogger.WithVerbose(true)
}
ctx := context.Background()
log := slog.GetLogger(ctx)
if forceInteractive {
quotedCmd := shellescape.QuoteCommand(args)
conslogger.PrintBar(color.New(color.FgHiMagenta), " Start Interactive Session ", quotedCmd)
// Sometimes the interactive shell doesn't correctly get a newline
// Take a brief pause and issue a new line as a work around.
time.Sleep(time.Millisecond * 5)
err := os.Setenv("TERM", debuggerSettings.Term)
if err != nil {
conslogger.Warnf("Failed to set term: %v", err)
}
cmdBuilder := func() (*exec.Cmd, error) {
return exec.Command(args[0], args[1:]...), nil
}
err = interactiveMode(ctx, debuggerSettings.RepeaterAddr, cmdBuilder)
if err != nil {
log.Error(err)
}
conslogger.PrintBar(color.New(color.FgHiMagenta), " End Interactive Session ", "")
return
}
log.With("command", args).With("version", Version).Debug("running command")
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
quotedCmd := shellescape.QuoteCommand(args)
exitCode := 1
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
conslogger.Warnf("Command %s failed with exit code %d\n", quotedCmd, exitCode)
} else {
conslogger.Warnf("Command %s failed with unexpected execution error %v\n", quotedCmd, err)
}
if debuggerSettings.Enabled {
c := color.New(color.FgYellow)
c.Println("Entering interactive debugger (**Warning: only a single debugger per host is supported**)")
// Sometimes the interactive shell doesn't correctly get a newline
// Take a brief pause and issue a new line as a work around.
time.Sleep(time.Millisecond * 5)
err := os.Setenv("TERM", debuggerSettings.Term)
if err != nil {
conslogger.Warnf("Failed to set term: %v", err)
}
cmdBuilder := func() (*exec.Cmd, error) {
_ = populateShellHistory(quotedCmd) // best effort
shellPath, ok := getShellPath()
if !ok {
return nil, ErrNoShellFound
}
log.With("shell", shellPath).Debug("found shell")
return exec.Command(shellPath), nil
}
err = interactiveMode(ctx, debuggerSettings.RepeaterAddr, cmdBuilder)
if err != nil {
log.Error(err)
}
}
// ensure that this always exits with an error status; otherwise it will be cached by earthly
if exitCode == 0 {
exitCode = 1
}
os.Exit(exitCode)
}
}