// run executes a command within the cgroup's resource constraints
// Parameters:
// - ctx: Context for execution control (timeouts, cancellation)
// - command: The command string to execute
// - options: Configuration options for command execution
// Returns: Result containing execution outcome and any error encountered
func (s *cgroup1Sandbox) run(ctx context.Context, command string, options RunOptions) (*RunResult, error) {
// Parse the command string into program and arguments
cmdParts := strings.Fields(command)
if len(cmdParts) == 0 {
return nil, fmt.Errorf("empty command")
}
// Create a command with context for timeout/cancellation support
cmd := exec.CommandContext(ctx, cmdParts[0], cmdParts[1:]...)
// Set up pipes to capture command output
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// Apply run options (env vars, working directory, stdin, etc.)
if options.Dir != "" {
cmd.Dir = options.Dir
}
if options.Env != nil {
cmd.Env = append(os.Environ(), options.Env...)
}
if options.Stdin != nil {
cmd.Stdin = options.Stdin
}
// Start the command
startTime := time.Now()
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start command: %w", err)
}
// Add the process to the cgroup to enforce resource constraints
if err := s.cgroup.Add(cgroup1.Process{Pid: cmd.Process.Pid}); err != nil {
// Clean up if adding to cgroup fails
cmd.Process.Kill()
cmd.Wait() // Prevent zombie process
return nil, fmt.Errorf("failed to add process to cgroup: %w", err)
}
// Wait for the command to complete
waitErr := cmd.Wait()
endTime := time.Now()
// Determine the exit code
exitCode := 0
if waitErr != nil {
if exitErr, ok := waitErr.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
} else {
return nil, fmt.Errorf("error waiting for command: %w", waitErr)
}
}
// Collect resource usage statistics from the cgroup
var cpuUsage uint64
var memoryUsage uint64
if stats, err := s.cgroup.Stat(); err == nil {
if stats.CPU != nil && stats.CPU.Usage != nil {
cpuUsage = stats.CPU.Usage.Total
}
if stats.Memory != nil && stats.Memory.Usage != nil {
memoryUsage = stats.Memory.Usage.Usage
}
}
// Create and return the execution result
return &RunResult{
ExitCode: exitCode,
Stdout: stdout.String(),
Stderr: stderr.String(),
Duration: endTime.Sub(startTime),
CPUUsage: cpuUsage,
MemoryUsage: memoryUsage,
}, nil
}
User
My current RunResult and RunOptions:
go
type RunResult struct {
// Stdout of the run
Stdout []byte `json:"stdout"`
// Stderr of the run
Stderr []byte `json:"stderr"`
// ExitStatus of the run
ExitStatus int `json:"exit_status"`
// Time taken for the run
TimeUsed time.Duration `json:"time"`
// Memory used by the run
MemoryUsed int64 `json:"memory"`
// IsTimeLimitExceeded indicates if the time limit was exceeded
IsTimeLimitExceeded bool `json:"is_time_limit_exceeded"`
// IsMemoryLimitExceeded indicates if the memory limit was exceeded
IsMemoryLimitExceeded bool `json:"is_memory_limit_exceeded"`
}
type RunOptions struct {
// TimeLimit for the run
//
// If the value is not greater than 0, it means no time limit
TimeLimit time.Duration `json:"time_limit"`
// Stdin for the run
Stdin []byte `json:"stdin"`
// Environment variables for the run
Environment []string
}
Assistant
go
Would you like me to explain or break down this code?
// run executes a command within the cgroup's resource constraints
// Parameters:
// - ctx: Context for execution control (cancellation)
// - command: The command string to execute
// - options: Configuration options for command execution
// Returns: Result containing execution outcome and any error encountered
func (s *cgroup1Sandbox) run(ctx context.Context, command string, options RunOptions) (*RunResult, error) {
// Setup timeout if specified
var cancelFunc context.CancelFunc
if options.TimeLimit > 0 {
ctx, cancelFunc = context.WithTimeout(ctx, options.TimeLimit)
defer cancelFunc()
}
// Parse the command string into program and arguments
cmdParts := strings.Fields(command)
if len(cmdParts) == 0 {
return nil, fmt.Errorf("empty command")
}
// Create command with context for timeout/cancellation support
cmd := exec.CommandContext(ctx, cmdParts[0], cmdParts[1:]...)
// Set up pipes to capture command output
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// Apply environment variables if provided
if len(options.Environment) > 0 {
cmd.Env = options.Environment
}
// Set stdin if provided
if len(options.Stdin) > 0 {
cmd.Stdin = bytes.NewReader(options.Stdin)
}
// Start the command
startTime := time.Now()
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start command: %w", err)
}
// Add the process to the cgroup to enforce resource constraints
if err := s.cgroup.Add(cgroup1.Process{Pid: cmd.Process.Pid}); err != nil {
// Clean up if adding to cgroup fails
cmd.Process.Kill()
cmd.Wait() // Prevent zombie process
return nil, fmt.Errorf("failed to add process to cgroup: %w", err)
}
// Wait for the command to complete
waitErr := cmd.Wait()
endTime := time.Now()
// Prepare the result
result := &RunResult{
Stdout: stdout.Bytes(),
Stderr: stderr.Bytes(),
TimeUsed: endTime.Sub(startTime),
MemoryUsed: 0, // Will be populated from cgroup stats
}
// Determine if time limit was exceeded
if ctx.Err() == context.DeadlineExceeded {
result.IsTimeLimitExceeded = true
result.ExitStatus = -1 // Special status for timeout
} else if waitErr != nil {
// Check for normal process exit with non-zero code
if exitErr, ok := waitErr.(*exec.ExitError); ok {
result.ExitStatus = exitErr.ExitCode()
} else {
return nil, fmt.Errorf("error waiting for command: %w", waitErr)
}
}
// Collect resource usage statistics from the cgroup
if stats, err := s.cgroup.Stat(); err == nil {
if stats.Memory != nil && stats.Memory.Usage != nil {
result.MemoryUsed = int64(stats.Memory.Usage.Usage)
// Check if memory limit was exceeded
if stats.Memory.Usage.Limit > 0 && result.MemoryUsed >= int64(stats.Memory.Usage.Limit) {
result.IsMemoryLimitExceeded = true
}
}
}
return result, nil
}
Would you like me to explain or break down this code?