forked from opensandbox-group/OpenSandbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommand.go
More file actions
351 lines (313 loc) · 9.11 KB
/
command.go
File metadata and controls
351 lines (313 loc) · 9.11 KB
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
// Copyright 2025 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build !windows
// +build !windows
package runtime
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"os/user"
"strconv"
"sync"
"syscall"
"time"
"github.com/alibaba/opensandbox/internal/safego"
"github.com/alibaba/opensandbox/execd/pkg/jupyter/execute"
"github.com/alibaba/opensandbox/execd/pkg/log"
"github.com/alibaba/opensandbox/execd/pkg/util/pathutil"
)
// getShell returns the preferred shell, falling back to sh if bash is not available.
// This is needed for Alpine-based Docker images that only have sh by default.
func getShell() string {
if _, err := exec.LookPath("bash"); err == nil {
return "bash"
}
return "sh"
}
func buildCredential(uid, gid *uint32) (*syscall.Credential, error) {
if uid == nil && gid == nil {
return nil, nil //nolint:nilnil
}
cred := &syscall.Credential{}
if uid != nil {
cred.Uid = *uid
// Load user info to get primary GID and supplemental groups
u, err := user.LookupId(strconv.FormatUint(uint64(*uid), 10))
if err == nil {
// Set primary GID if not explicitly provided
if gid == nil {
primaryGid, err := strconv.ParseUint(u.Gid, 10, 32)
if err == nil {
cred.Gid = uint32(primaryGid)
}
}
// Load supplemental groups
gids, err := u.GroupIds()
if err == nil {
for _, g := range gids {
id, err := strconv.ParseUint(g, 10, 32)
if err == nil {
cred.Groups = append(cred.Groups, uint32(id))
}
}
}
}
}
// Override Gid if explicitly provided
if gid != nil {
cred.Gid = *gid
}
return cred, nil
}
// runCommand executes shell commands and streams their output.
func (c *Controller) runCommand(ctx context.Context, request *ExecuteCodeRequest) error {
session := c.newContextID()
signals := make(chan os.Signal, 1)
defer close(signals)
signal.Notify(signals)
defer signal.Reset()
stdout, stderr, err := c.stdLogDescriptor(session)
if err != nil {
return fmt.Errorf("failed to get stdlog descriptor: %w", err)
}
defer stdout.Close()
defer stderr.Close()
stdoutPath := c.stdoutFileName(session)
stderrPath := c.stderrFileName(session)
startAt := time.Now()
log.Info("received command: %v", log.SanitizeCommand(request.Code))
shell := getShell()
cmd := exec.CommandContext(ctx, shell, "-c", request.Code)
extraEnv := mergeExtraEnvs(loadExtraEnvFromFile(), request.Envs)
cwd, err := pathutil.ExpandPathWithEnv(request.Cwd, extraEnv)
if err != nil {
return fmt.Errorf("resolve request cwd %s: %w", request.Cwd, err)
}
// Configure credentials and process group
cred, err := buildCredential(request.Uid, request.Gid)
if err != nil {
return fmt.Errorf("failed to build credential: %w", err)
}
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Credential: cred,
}
cmd.Stdout = stdout
cmd.Stderr = stderr
cmd.Env = mergeEnvs(os.Environ(), extraEnv)
cmd.Dir = cwd
done := make(chan struct{}, 1)
var wg sync.WaitGroup
wg.Add(2)
safego.Go(func() {
defer wg.Done()
c.tailStdPipe(stdoutPath, request.Hooks.OnExecuteStdout, done)
})
safego.Go(func() {
defer wg.Done()
c.tailStdPipe(stderrPath, request.Hooks.OnExecuteStderr, done)
})
err = cmd.Start()
if err != nil {
close(done)
wg.Wait()
request.Hooks.OnExecuteInit(session)
request.Hooks.OnExecuteError(&execute.ErrorOutput{
EName: "CommandExecError",
EValue: err.Error(),
Traceback: []string{err.Error()},
})
log.Error("CommandExecError: error starting commands: %v", err)
return nil
}
kernel := &commandKernel{
pid: cmd.Process.Pid,
stdoutPath: stdoutPath,
stderrPath: stderrPath,
startedAt: startAt,
running: true,
content: request.Code,
isBackground: false,
}
c.storeCommandKernel(session, kernel)
request.Hooks.OnExecuteInit(session)
safego.Go(func() {
for {
select {
case <-done:
// cmd.Wait() has returned (or start failed). The pid is
// about to be — or already has been — reaped, so we
// must not signal it. Execute()'s defer cancel() fires
// after every foreground command, including successful
// ones, so without this gate the SIGKILL below would
// run on a recycled pid/pgid and could kill an
// unrelated process group.
return
case <-ctx.Done():
// Re-check `done` to avoid a race with cmd.Wait()
// returning concurrently. If cmd.Wait() has just
// finished, the leader pid may be reaped and recycled
// at any moment; signaling -pid would then target a
// foreign process group.
select {
case <-done:
return
default:
}
// Genuine cancellation (timeout, client disconnect,
// Interrupt). Kill the whole process group so children
// don't outlive the cancelled context.
if cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
}
return
case sig := <-signals:
if sig == nil {
continue
}
// DO NOT forward syscall.SIGURG to children processes.
if sig != syscall.SIGCHLD && sig != syscall.SIGURG {
_ = syscall.Kill(-cmd.Process.Pid, sig.(syscall.Signal))
}
}
}
})
err = cmd.Wait()
close(done)
wg.Wait()
if err != nil {
var eName, eValue string
var eCode int
var traceback []string
var exitError *exec.ExitError
if errors.As(err, &exitError) {
exitCode := exitError.ExitCode()
eName = "CommandExecError"
eValue = strconv.Itoa(exitCode)
eCode = exitCode
} else {
eName = "CommandExecError"
eValue = err.Error()
eCode = 1
}
traceback = []string{err.Error()}
request.Hooks.OnExecuteError(&execute.ErrorOutput{
EName: eName,
EValue: eValue,
Traceback: traceback,
})
log.Error("CommandExecError: error running commands: %v", err)
c.markCommandFinished(session, eCode, err.Error())
return nil
}
c.markCommandFinished(session, 0, "")
request.Hooks.OnExecuteComplete(time.Since(startAt))
return nil
}
// runBackgroundCommand executes shell commands in detached mode.
func (c *Controller) runBackgroundCommand(ctx context.Context, cancel context.CancelFunc, request *ExecuteCodeRequest) error {
session := c.newContextID()
request.Hooks.OnExecuteInit(session)
pipe, err := c.combinedOutputDescriptor(session)
if err != nil {
cancel()
return fmt.Errorf("failed to get combined output descriptor: %w", err)
}
stdoutPath := c.combinedOutputFileName(session)
stderrPath := c.combinedOutputFileName(session)
signals := make(chan os.Signal, 1)
defer close(signals)
signal.Notify(signals)
defer signal.Reset()
startAt := time.Now()
log.Info("received command: %v", log.SanitizeCommand(request.Code))
shell := getShell()
cmd := exec.CommandContext(ctx, shell, "-c", request.Code)
extraEnv := mergeExtraEnvs(loadExtraEnvFromFile(), request.Envs)
cwd, err := pathutil.ExpandPathWithEnv(request.Cwd, extraEnv)
if err != nil {
cancel()
return fmt.Errorf("resolve cwd: %w", err)
}
cmd.Dir = cwd
// Configure credentials and process group
cred, err := buildCredential(request.Uid, request.Gid)
if err != nil {
cancel()
return fmt.Errorf("build credential: %w", err)
}
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Credential: cred,
}
cmd.Stdout = pipe
cmd.Stderr = pipe
cmd.Env = mergeEnvs(os.Environ(), extraEnv)
// use DevNull as stdin so interactive programs exit immediately.
devNull, err := os.Open(os.DevNull)
if err == nil {
cmd.Stdin = devNull
defer devNull.Close()
}
err = cmd.Start()
kernel := &commandKernel{
pid: -1,
stdoutPath: stdoutPath,
stderrPath: stderrPath,
startedAt: startAt,
running: true,
content: request.Code,
isBackground: true,
}
if err != nil {
cancel()
log.Error("CommandExecError: error starting commands: %v", err)
kernel.running = false
c.storeCommandKernel(session, kernel)
c.markCommandFinished(session, 255, err.Error())
return fmt.Errorf("failed to start commands: %w", err)
}
safego.Go(func() {
defer pipe.Close()
kernel.running = true
kernel.pid = cmd.Process.Pid
c.storeCommandKernel(session, kernel)
err = cmd.Wait()
cancel()
if err != nil {
log.Error("CommandExecError: error running commands: %v", err)
exitCode := 1
var exitError *exec.ExitError
if errors.As(err, &exitError) {
exitCode = exitError.ExitCode()
}
c.markCommandFinished(session, exitCode, err.Error())
return
}
c.markCommandFinished(session, 0, "")
})
// ensure we kill the whole process group if the context is cancelled (e.g., timeout).
safego.Go(func() {
<-ctx.Done()
if cmd.Process != nil {
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) // best-effort
}
})
request.Hooks.OnExecuteComplete(time.Since(startAt))
return nil
}