feat: add runRemoteCommandSync

This commit is contained in:
Andras Bacsai 2023-03-31 09:42:05 +02:00
parent 00ae88b6b6
commit 47d3ac3ef5
2 changed files with 19 additions and 6 deletions

View File

@ -32,10 +32,7 @@ public function handle(): void
$not_found_applications = $applications;
$containers = collect();
foreach ($servers as $server) {
$private_key_location = savePrivateKey($server);
$ssh_command = generateSshCommand($private_key_location, $server->ip, $server->user, $server->port, 'docker ps -a -q --format \'{{json .}}\'');
$process = Process::run($ssh_command);
$output = trim($process->output());
$output = runRemoteCommandSync($server, ['docker ps -a -q --format \'{{json .}}\'']);
$containers = $containers->concat(formatDockerCmdOutputToJson($output));
}
foreach ($containers as $container) {
@ -48,13 +45,13 @@ public function handle(): void
});
$found_application->status = $container['State'];
$found_application->save();
Log::info('Found application: ' . $found_application->uuid . '.Set status to: ' . $found_application->status);
Log::info('Found application: ' . $found_application->uuid . '. Set status to: ' . $found_application->status);
}
}
foreach ($not_found_applications as $not_found_application) {
$not_found_application->status = 'exited';
$not_found_application->save();
Log::info('Not found application: ' . $not_found_application->uuid . '.Set status to: ' . $not_found_application->status);
Log::info('Not found application: ' . $not_found_application->uuid . '. Set status to: ' . $not_found_application->status);
}
} catch (\Exception $e) {
Log::error($e->getMessage());

View File

@ -7,6 +7,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Storage;
use Spatie\Activitylog\Contracts\Activity;
@ -113,3 +114,18 @@ function formatDockerLabelsToJson($rawOutput): Collection
})[0];
}
}
if (!function_exists('runRemoteCommandSync')) {
function runRemoteCommandSync($server, array $command) {
$command_string = implode("\n", $command);
$private_key_location = savePrivateKey($server);
$ssh_command = generateSshCommand($private_key_location, $server->ip, $server->user, $server->port, $command_string);
$process = Process::run($ssh_command);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
Log::error($output);
throw new \RuntimeException('There was an error running the command.');
}
return $output;
}
}