INTEGRITY Dokumentace

Spouštění příkazů

Tato příručka ukazuje, jak v sandboxu spouštět příkazy, zpracovávat výstup a efektivně řešit chyby.

Vyberte správnou metodu

SDK nabízí několik způsobů spouštění příkazů:

Spouštění základních příkazů

Použijte exec() pro jednoduché příkazy, které se rychle dokončí:

import { getSandbox } from "@cloudflare/sandbox";

const sandbox = getSandbox(env.Sandbox, "my-sandbox");

// Execute a single command
const result = await sandbox.exec("python --version");

console.log(result.stdout); // "Python 3.11.0"
console.log(result.exitCode); // 0
console.log(result.success); // true
import { getSandbox } from '@cloudflare/sandbox';

const sandbox = getSandbox(env.Sandbox, 'my-sandbox');

// Execute a single command
const result = await sandbox.exec('python --version');

console.log(result.stdout);   // "Python 3.11.0"
console.log(result.exitCode); // 0
console.log(result.success);  // true

Předávejte argumenty bezpečně

Při předávání uživatelského vstupu nebo dynamických hodnot se vyhněte interpolaci řetězců, abyste předešli injekčním útokům:

// Unsafe - vulnerable to injection
const filename = userInput;
await sandbox.exec(`cat ${filename}`);

// Safe - use proper escaping or validation
const safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, "");
await sandbox.exec(`cat ${safeFilename}`);

// Better - write to file and execute
await sandbox.writeFile("/tmp/input.txt", userInput);
await sandbox.exec("python process.py /tmp/input.txt");
// Unsafe - vulnerable to injection
const filename = userInput;
await sandbox.exec(`cat ${filename}`);

// Safe - use proper escaping or validation
const safeFilename = filename.replace(/[^a-zA-Z0-9_.-]/g, '');
await sandbox.exec(`cat ${safeFilename}`);

// Better - write to file and execute
await sandbox.writeFile('/tmp/input.txt', userInput);
await sandbox.exec('python process.py /tmp/input.txt');

Zpracování chyb

Příkazy mohou selhat dvěma způsoby:

  1. Nenulový návratový kód - Příkaz proběhl, ale selhal (result.success === false)
  2. Chyba spuštění - Příkaz se nepodařilo spustit (vyvolá výjimku)
try {
	const result = await sandbox.exec("python analyze.py");

	if (!result.success) {
		// Command failed (non-zero exit code)
		console.error("Analysis failed:", result.stderr);
		console.log("Exit code:", result.exitCode);

		// Handle specific exit codes
		if (result.exitCode === 1) {
			throw new Error("Invalid input data");
		} else if (result.exitCode === 2) {
			throw new Error("Missing dependencies");
		}
	}

	// Success - process output
	return JSON.parse(result.stdout);
} catch (error) {
	// Execution error (couldn't start command)
	console.error("Execution failed:", error.message);
	throw error;
}
try {
  const result = await sandbox.exec('python analyze.py');

  if (!result.success) {
    // Command failed (non-zero exit code)
    console.error('Analysis failed:', result.stderr);
    console.log('Exit code:', result.exitCode);

    // Handle specific exit codes
    if (result.exitCode === 1) {
      throw new Error('Invalid input data');
    } else if (result.exitCode === 2) {
      throw new Error('Missing dependencies');
    }
  }

  // Success - process output
  return JSON.parse(result.stdout);

} catch (error) {
  // Execution error (couldn't start command)
  console.error('Execution failed:', error.message);
  throw error;
}

Spouštění shellových příkazů

Sandbox podporuje funkce shellu jako roury, přesměrování a řetězení příkazů:

// Pipes and filters
const result = await sandbox.exec('ls -la | grep ".py" | wc -l');
console.log("Python files:", result.stdout.trim());

// Output redirection
await sandbox.exec("python generate.py > output.txt 2> errors.txt");

// Multiple commands
await sandbox.exec("cd /workspace && npm install && npm test");
// Pipes and filters
const result = await sandbox.exec('ls -la | grep ".py" | wc -l');
console.log('Python files:', result.stdout.trim());

// Output redirection
await sandbox.exec('python generate.py > output.txt 2> errors.txt');

// Multiple commands
await sandbox.exec('cd /workspace && npm install && npm test');

Spouštění skriptů v Pythonu

// Run inline Python
const result = await sandbox.exec('python -c "print(sum([1, 2, 3, 4, 5]))"');
console.log("Sum:", result.stdout.trim()); // "15"

// Run a script file
await sandbox.writeFile(
	"/workspace/analyze.py",
	`
import sys
print(f"Argument: {sys.argv[1]}")
`,
);

await sandbox.exec("python /workspace/analyze.py data.csv");
// Run inline Python
const result = await sandbox.exec('python -c "print(sum([1, 2, 3, 4, 5]))"');
console.log('Sum:', result.stdout.trim()); // "15"

// Run a script file
await sandbox.writeFile('/workspace/analyze.py', `
import sys
print(f"Argument: {sys.argv[1]}")
`);

await sandbox.exec('python /workspace/analyze.py data.csv');

Časové limity

Nastavte maximální dobu spouštění příkazů, aby dlouho běžící operace neblokovaly systém donekonečna.

Časový limit pro jednotlivé příkazy

Předejte timeout v možnostech, kterými nastavíte časový limit pro jeden příkaz:

const result = await sandbox.exec("npm run build", {
	timeout: 30000, // 30 seconds
});
const result = await sandbox.exec('npm run build', {
  timeout: 30000 // 30 seconds
});

Časový limit na úrovni relace

Výchozí časový limit pro všechny příkazy v relaci nastavíte pomocí commandTimeoutMs:

const session = await sandbox.createSession({
	commandTimeoutMs: 10000, // 10s default for all commands
});

await session.exec("npm install"); // Times out after 10s
await session.exec("npm run build"); // Times out after 10s

// Per-command timeout overrides the session default
await session.exec("npm test", { timeout: 60000 }); // 60s for this command
const session = await sandbox.createSession({
  commandTimeoutMs: 10000 // 10s default for all commands
});

await session.exec('npm install');    // Times out after 10s
await session.exec('npm run build');  // Times out after 10s

// Per-command timeout overrides the session default
await session.exec('npm test', { timeout: 60000 }); // 60s for this command

Globální časový limit

Nastavte COMMAND_TIMEOUT_MS proměnná prostředí pro nastavení globálního výchozího časového limitu pro každé exec() volání napříč všemi relacemi.

Priorita časového limitu

Pokud je nastaveno více časových limitů, platí ten nejspecifičtější:

  1. Podle příkazu timeout na exec() (nejvyšší priorita)
  2. Na úrovni relace commandTimeoutMs na createSession()
  3. Globální COMMAND_TIMEOUT_MS proměnná prostředí (nejnižší priorita)

Pokud není nastaven žádný, příkazy běží bez časového limitu.

Časový limit proces neukončí

Osvědčené postupy

Řešení potíží

Příkaz nenalezen

Ověřte, že příkaz v kontejneru existuje:

const check = await sandbox.exec("which python3");
if (!check.success) {
	console.error("python3 not found");
}
const check = await sandbox.exec('which python3');
if (!check.success) {
  console.error('python3 not found');
}

Problémy s pracovním adresářem

Používejte absolutní cesty nebo změňte adresář:

// Use absolute path
await sandbox.exec("python /workspace/my-app/script.py");

// Or change directory
await sandbox.exec("cd /workspace/my-app && python script.py");
// Use absolute path
await sandbox.exec('python /workspace/my-app/script.py');

// Or change directory
await sandbox.exec('cd /workspace/my-app && python script.py');