*/ public static function requirements(): array { $missing = []; if (! extension_loaded('pdo_sqlite')) { $missing[] = 'Die PHP-Erweiterung pdo_sqlite fehlt (eigene Testdatenbank je Lauf).'; } if (! is_file(storage_path('app/sandbox/template.sqlite'))) { $missing[] = 'Die Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).'; } $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions'))); if (! function_exists('proc_open') || in_array('proc_open', $disabled, true)) { $missing[] = 'Eigene Prozesse lassen sich nicht starten (proc_open gesperrt) – ohne eigenen Prozess ist keine sichere Trennung möglich.'; } if (str_contains(str_replace(DIRECTORY_SEPARATOR, '/', self::php()), '/') && ! is_file(self::php())) { $missing[] = 'Das PHP-Programm für den Testlauf wurde nicht gefunden.'; } return $missing; } /** * Plays a scenario with the (possibly unsaved) draft of a channel's process and returns the stored report. * * @param array $draft * @param array $inputs */ public function run(Channel $channel, IntakeKind $intake, array $draft, string $scenario, array $inputs, int $steps, User $user): ProcessTestRun { if (($missing = self::requirements()) !== []) { throw new RuntimeException('Der Prozess-Tester ist auf diesem Server gesperrt: '.implode(' ', $missing)); } if (ScenarioCatalogue::find($scenario) === null) { throw new RuntimeException('Unbekanntes Szenario.'); } if (($problems = app(ChannelProcessConfiguration::class)->problems($channel, $intake, $draft, sandbox: true)) !== []) { throw new RuntimeException('Die Konfiguration ist nicht zulässig: '.implode(' ', $problems)); } self::prune(); $locks = $this->slot($channel->tenant_id); $run = (string) Str::uuid(); $directory = SandboxBootstrapper::directory($run); try { File::ensureDirectoryExists($directory.'/files', 0700); $input = [ 'snapshot' => SandboxSnapshot::build($channel, $intake, $draft), 'scenario' => $scenario, 'inputs' => $inputs, 'steps' => $steps, 'start' => now()->startOfMinute()->toIso8601String(), ]; File::put($directory.'/input.json', (string) json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); $result = Process::path(base_path()) ->timeout(self::TIMEOUT_SECONDS) ->env([SandboxBootstrapper::ENV => $run, ...self::childEnvironment(), ...(app()->environment('testing') ? (array) config('fewo.sandbox.test_environment', []) : [])]) ->run([self::php(), 'artisan', 'process:sandbox-run', $run, '--no-interaction']); $report = is_file($directory.'/report.json') ? (array) json_decode((string) File::get($directory.'/report.json'), true) : []; if ($report === []) { $report = ['aborted' => 'Der Testlauf hat keinen Bericht geliefert'.($result->successful() ? '.' : ': '.mb_substr(trim($result->errorOutput() ?: $result->output()), 0, 300)), 'timeline' => [], 'violations' => []]; } return ProcessTestRun::query()->create([ 'tenant_id' => $channel->tenant_id, 'channel_id' => $channel->id, 'user_id' => $user->id, 'intake' => $intake->value, 'scenario' => $scenario, 'configuration' => $draft, 'inputs' => $inputs, 'steps' => $steps, 'report' => $report, 'outcome' => filled($report['aborted'] ?? null) ? ProcessTestRun::ABORTED : ProcessTestRun::COMPLETED, 'release' => self::release(), ]); } finally { File::deleteDirectory($directory); foreach ($locks as $lock) { flock($lock, LOCK_UN); fclose($lock); } } } /** * Removes directories of runs that ended abnormally (older than an hour). */ public static function prune(): void { foreach (glob(storage_path('app/sandbox/runs/*'), GLOB_ONLYDIR) ?: [] as $directory) { if (filemtime($directory) < time() - 3600) { File::deleteDirectory($directory); } } } /** * The release the report belongs to. */ public static function release(): ?string { // Releases on Strato live in releases/- (pipeline-manager, scripts/deploy.sh). $release = basename(base_path()); return preg_match('/^\d{14}-[0-9a-f]{7,40}$/', $release) === 1 ? $release : null; } /** * The PHP command line program for the run (Strato: php-cli next to the web PHP). */ public static function php(): string { $configured = (string) config('fewo.sandbox.php', ''); if ($configured !== '') { return $configured; } return PHP_SAPI === 'cli' ? PHP_BINARY : (is_file('/opt/RZphp84/bin/php-cli') ? '/opt/RZphp84/bin/php-cli' : 'php'); } /** * Environment of the run's process: what Laravel needs to boot – never database, mail or service credentials (the * run's configuration replaces them anyway, this keeps them out of its environment, too). * * @return array */ private static function childEnvironment(): array { $blank = []; foreach (array_keys(getenv()) as $key) { if (preg_match('/^(DB_|MAIL_|REDIS_|AWS_|MAILBOX_|FEWO_MAILBOX|OPENAI|ANTHROPIC|OPENROUTER|N8N_|PIPELINE_)/', (string) $key) === 1) { $blank[$key] = false; } } return $blank; } /** * One run per landlord and at most SLOTS on the server, as file locks (they end with the process). * * @return list the held locks (landlord, slot) */ private function slot(int $tenant): array { $directory = storage_path('app/sandbox/slots'); File::ensureDirectoryExists($directory, 0700); $tenantLock = fopen($directory.'/tenant-'.$tenant.'.lock', 'c'); if ($tenantLock === false || ! flock($tenantLock, LOCK_EX | LOCK_NB)) { throw new RuntimeException('Für diesen Vermieter läuft bereits ein Test. Bitte einen Moment warten.'); } for ($index = 1; $index <= self::SLOTS; $index++) { $slot = fopen($directory.'/slot-'.$index.'.lock', 'c'); if ($slot !== false && flock($slot, LOCK_EX | LOCK_NB)) { return [$tenantLock, $slot]; } if ($slot !== false) { fclose($slot); } } fclose($tenantLock); throw new RuntimeException('Der Prozess-Tester ist gerade belegt. Bitte gleich noch einmal versuchen.'); } }