Great! With the definitions of RunResult and RunOptions, we can enhance the run method to capture the detailed results and respect the options provided. Below is the updated implementation:
package main
import (
"context"
"fmt"
"io/ioutil"
"strings"
"syscall"
"time"
"github.com/containerd/cgroups/v3/cgroup1"
"github.com/opencontainers/runtime-tools/specs"
)
type cgroupResources struct {
cpuQuota int64
cpuPeriod uint64
memoryLimit int64
}
type cgroup1Sandbox struct {
cgroup cgroup1.Cgroup
}
// RunOptions represents options for running a command.
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
}
// RunResult represents the result of running a command.
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"`
}
// newCgroup1Sandbox creates a new cgroup v1 sandbox with the specified name and resources.
func newCgroup1Sandbox(cgroupName string, resources cgroupResources) (*cgroup1Sandbox, error) {
// Define cgroup v1 resources
v1Resources := &specs.LinuxResources{
CPU: &specs.LinuxCPU{
Quota: ptr(resources.cpuQuota), // 100ms CPU quota
Period: ptr(resources.cpuPeriod), // 1s CPU period
},
Memory: &specs.LinuxMemory{
Limit: ptr(resources.memoryLimit), // 100MB memory limit
},
}
control, err := cgroup1.New(cgroup1.StaticPath("/"+cgroupName), v1Resources)
if err != nil {
return nil, fmt.Errorf("failed to create cgroup v1: %w", err)
}
return &cgroup1Sandbox{
cgroup: control,
}, nil
}
// run executes a command within the cgroup sandbox.
func (s *cgroup1Sandbox) run(ctx context.Context, command string, options RunOptions) (*RunResult, error) {
// Parse the command and arguments
args := splitCommand(command)
// Create a new process with the specified command
cmd := exec.CommandContext(ctx, args[0], args[1:]...)
cmd.Env = options.Environment
cmd.Stdin = strings.NewReader(string(options.Stdin))
// Set the cgroup for the process
if err := s.cgroup.Add(cgroup1.Process{Pid: cmd.Process}); err != nil {
return nil, fmt.Errorf("failed to add process to cgroup: %w", err)
}
// Capture stdout and stderr
stdout, stderr := &bytes.Buffer{}, &bytes.Buffer{}
cmd.Stdout, cmd.Stderr = stdout, stderr
// Start the timer
startTime := time.Now()
// Start the process
if err := cmd.Start(); err != nil {
return nil, fmt.Errorf("failed to start process: %w", err)
}
// Set up a context with a timeout if a time limit is specified
var cancel context.CancelFunc
if options.TimeLimit > 0 {
ctx, cancel = context.WithTimeout(ctx, options.TimeLimit)
defer cancel()
}
// Wait for the process to finish
err := cmd.WaitWithContext(ctx)
duration := time.Since(startTime)
// Check if the time limit was exceeded
var isTimeLimitExceeded bool
if options.TimeLimit > 0 && err == context.DeadlineExceeded {
isTimeLimitExceeded = true
err = nil // Reset error since it was due to timeout
}
// Capture the exit status
var exitStatus int
if exitErr, ok := err.(*exec.ExitError); ok {
ws := exitErr.Sys().(syscall.WaitStatus)
exitStatus = ws.ExitStatus()
} else if err == nil {
exitStatus = 0
} else {
return nil, fmt.Errorf("failed to wait for process: %w", err)
}
// Capture memory usage
memoryUsed, err := s.cgroup.MemoryUsageInBytes()
if err != nil {
return nil, fmt.Errorf("failed to get memory usage: %w", err)
}
// Check if the memory limit was exceeded
var isMemoryLimitExceeded bool
if memoryUsed > s.cgroup.MemoryLimitInBytes() {
isMemoryLimitExceeded = true
}
// Return the result
return &RunResult{
Stdout: stdout.Bytes(),
Stderr: stderr.Bytes(),
ExitStatus: exitStatus,
TimeUsed: duration,
MemoryUsed: memoryUsed,
IsTimeLimitExceeded: isTimeLimitExceeded,
IsMemoryLimitExceeded: isMemoryLimitExceeded,
}, nil
}
// ptr converts a value to a pointer.
func ptr[T any](v T) *T {
return &v
}
// splitCommand splits a command string into an array of arguments.
func splitCommand(command string) []string {
// Simple split by spaces; in a real-world scenario, use a more robust parser
return strings.Fields(command)
}