forked from mtusi2026/mtusi2026lab5
lab5 na4
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package images
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"mtusi2026/internal/config"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid_image")
|
||||
var ErrLimit = errors.New("image_resource_limit")
|
||||
|
||||
func Run(ctx context.Context, mode, source, dir string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 25*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, config.GetEnv("PYTHON", "python3"), config.GetEnv("IMAGE_SCRIPT", "scripts/process_image.py"), mode, source, dir)
|
||||
out, err := cmd.Output()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
var ex *exec.ExitError
|
||||
if errors.As(err, &ex) {
|
||||
switch ex.ExitCode() {
|
||||
case 2:
|
||||
return nil, ErrInvalid
|
||||
case 3:
|
||||
return nil, ErrLimit
|
||||
}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package images
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestImageSubprocessDeadlineKillsChild(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("python3 is required for subprocess test")
|
||||
}
|
||||
script := filepath.Join(t.TempDir(), "slow.py")
|
||||
if err := os.WriteFile(script, []byte("import time\ntime.sleep(60)\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("IMAGE_SCRIPT", script)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
_, err := Run(ctx, "process", "unused", "unused")
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if time.Since(start) > 3*time.Second {
|
||||
t.Fatal("child was not killed within deadline")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user