Merge pull request #4041 from lucasmichot/feat/try-catch

Remove some useless `catch` blocks
This commit is contained in:
Andras Bacsai
2024-10-28 21:15:08 +01:00
committed by GitHub
7 changed files with 230 additions and 263 deletions

View File

@@ -13,66 +13,63 @@ class StartProxy
public function handle(Server $server, bool $async = true, bool $force = false): string|Activity public function handle(Server $server, bool $async = true, bool $force = false): string|Activity
{ {
try { $proxyType = $server->proxyType();
$proxyType = $server->proxyType(); if ((is_null($proxyType) || $proxyType === 'NONE' || $server->proxy->force_stop || $server->isBuildServer()) && $force === false) {
if ((is_null($proxyType) || $proxyType === 'NONE' || $server->proxy->force_stop || $server->isBuildServer()) && $force === false) { return 'OK';
return 'OK';
}
$commands = collect([]);
$proxy_path = $server->proxyPath();
$configuration = CheckConfiguration::run($server);
if (! $configuration) {
throw new \Exception('Configuration is not synced');
}
SaveConfiguration::run($server, $configuration);
$docker_compose_yml_base64 = base64_encode($configuration);
$server->proxy->last_applied_settings = str($docker_compose_yml_base64)->pipe('md5')->value();
$server->save();
if ($server->isSwarm()) {
$commands = $commands->merge([
"mkdir -p $proxy_path/dynamic",
"cd $proxy_path",
"echo 'Creating required Docker Compose file.'",
"echo 'Starting coolify-proxy.'",
'docker stack deploy -c docker-compose.yml coolify-proxy',
"echo 'Successfully started coolify-proxy.'",
]);
} else {
$caddfile = 'import /dynamic/*.caddy';
$commands = $commands->merge([
"mkdir -p $proxy_path/dynamic",
"cd $proxy_path",
"echo '$caddfile' > $proxy_path/dynamic/Caddyfile",
"echo 'Creating required Docker Compose file.'",
"echo 'Pulling docker image.'",
'docker compose pull',
'if docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
" echo 'Stopping and removing existing coolify-proxy.'",
' docker rm -f coolify-proxy || true',
" echo 'Successfully stopped and removed existing coolify-proxy.'",
'fi',
"echo 'Starting coolify-proxy.'",
'docker compose up -d --remove-orphans',
"echo 'Successfully started coolify-proxy.'",
]);
$commands = $commands->merge(connectProxyToNetworks($server));
}
if ($async) {
$activity = remote_process($commands, $server, callEventOnFinish: 'ProxyStarted', callEventData: $server);
return $activity;
} else {
instant_remote_process($commands, $server);
$server->proxy->set('status', 'running');
$server->proxy->set('type', $proxyType);
$server->save();
ProxyStarted::dispatch($server);
return 'OK';
}
} catch (\Throwable $e) {
throw $e;
} }
$commands = collect([]);
$proxy_path = $server->proxyPath();
$configuration = CheckConfiguration::run($server);
if (! $configuration) {
throw new \Exception('Configuration is not synced');
}
SaveConfiguration::run($server, $configuration);
$docker_compose_yml_base64 = base64_encode($configuration);
$server->proxy->last_applied_settings = str($docker_compose_yml_base64)->pipe('md5')->value();
$server->save();
if ($server->isSwarm()) {
$commands = $commands->merge([
"mkdir -p $proxy_path/dynamic",
"cd $proxy_path",
"echo 'Creating required Docker Compose file.'",
"echo 'Starting coolify-proxy.'",
'docker stack deploy -c docker-compose.yml coolify-proxy',
"echo 'Successfully started coolify-proxy.'",
]);
} else {
$caddfile = 'import /dynamic/*.caddy';
$commands = $commands->merge([
"mkdir -p $proxy_path/dynamic",
"cd $proxy_path",
"echo '$caddfile' > $proxy_path/dynamic/Caddyfile",
"echo 'Creating required Docker Compose file.'",
"echo 'Pulling docker image.'",
'docker compose pull',
'if docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
" echo 'Stopping and removing existing coolify-proxy.'",
' docker rm -f coolify-proxy || true',
" echo 'Successfully stopped and removed existing coolify-proxy.'",
'fi',
"echo 'Starting coolify-proxy.'",
'docker compose up -d --remove-orphans',
"echo 'Successfully started coolify-proxy.'",
]);
$commands = $commands->merge(connectProxyToNetworks($server));
}
if ($async) {
$activity = remote_process($commands, $server, callEventOnFinish: 'ProxyStarted', callEventData: $server);
return $activity;
} else {
instant_remote_process($commands, $server);
$server->proxy->set('status', 'running');
$server->proxy->set('type', $proxyType);
$server->save();
ProxyStarted::dispatch($server);
return 'OK';
}
} }
} }

View File

@@ -18,32 +18,28 @@ class UpdateCoolify
public function handle($manual_update = false) public function handle($manual_update = false)
{ {
try { $settings = instanceSettings();
$settings = instanceSettings(); $this->server = Server::find(0);
$this->server = Server::find(0); if (! $this->server) {
if (! $this->server) { return;
}
CleanupDocker::dispatch($this->server)->onQueue('high');
$this->latestVersion = get_latest_version_of_coolify();
$this->currentVersion = config('version');
if (! $manual_update) {
if (! $settings->is_auto_update_enabled) {
return; return;
} }
CleanupDocker::dispatch($this->server)->onQueue('high'); if ($this->latestVersion === $this->currentVersion) {
$this->latestVersion = get_latest_version_of_coolify(); return;
$this->currentVersion = config('version'); }
if (! $manual_update) { if (version_compare($this->latestVersion, $this->currentVersion, '<')) {
if (! $settings->is_auto_update_enabled) { return;
return;
}
if ($this->latestVersion === $this->currentVersion) {
return;
}
if (version_compare($this->latestVersion, $this->currentVersion, '<')) {
return;
}
} }
$this->update();
$settings->new_version_available = false;
$settings->save();
} catch (\Throwable $e) {
throw $e;
} }
$this->update();
$settings->new_version_available = false;
$settings->save();
} }
private function update() private function update()

View File

@@ -112,56 +112,48 @@ class Controller extends BaseController
public function accept_invitation() public function accept_invitation()
{ {
try { $resetPassword = request()->query('reset-password');
$resetPassword = request()->query('reset-password'); $invitationUuid = request()->route('uuid');
$invitationUuid = request()->route('uuid'); $invitation = TeamInvitation::whereUuid($invitationUuid)->firstOrFail();
$invitation = TeamInvitation::whereUuid($invitationUuid)->firstOrFail(); $user = User::whereEmail($invitation->email)->firstOrFail();
$user = User::whereEmail($invitation->email)->firstOrFail(); $invitationValid = $invitation->isValid();
$invitationValid = $invitation->isValid(); if ($invitationValid) {
if ($invitationValid) { if ($resetPassword) {
if ($resetPassword) { $user->update([
$user->update([ 'password' => Hash::make($invitationUuid),
'password' => Hash::make($invitationUuid), 'force_password_reset' => true,
'force_password_reset' => true, ]);
]); }
} if ($user->teams()->where('team_id', $invitation->team->id)->exists()) {
if ($user->teams()->where('team_id', $invitation->team->id)->exists()) {
$invitation->delete();
return redirect()->route('team.index');
}
$user->teams()->attach($invitation->team->id, ['role' => $invitation->role]);
$invitation->delete(); $invitation->delete();
if (auth()->user()?->id !== $user->id) {
return redirect()->route('login');
}
refreshSession($invitation->team);
return redirect()->route('team.index'); return redirect()->route('team.index');
} else {
abort(401);
} }
} catch (\Throwable $e) { $user->teams()->attach($invitation->team->id, ['role' => $invitation->role]);
throw $e; $invitation->delete();
if (auth()->user()?->id !== $user->id) {
return redirect()->route('login');
}
refreshSession($invitation->team);
return redirect()->route('team.index');
} else {
abort(401);
} }
} }
public function revoke_invitation() public function revoke_invitation()
{ {
try { $invitation = TeamInvitation::whereUuid(request()->route('uuid'))->firstOrFail();
$invitation = TeamInvitation::whereUuid(request()->route('uuid'))->firstOrFail(); $user = User::whereEmail($invitation->email)->firstOrFail();
$user = User::whereEmail($invitation->email)->firstOrFail(); if (is_null(auth()->user())) {
if (is_null(auth()->user())) { return redirect()->route('login');
return redirect()->route('login');
}
if (auth()->user()->id !== $user->id) {
abort(401);
}
$invitation->delete();
return redirect()->route('team.index');
} catch (\Throwable $e) {
throw $e;
} }
if (auth()->user()->id !== $user->id) {
abort(401);
}
$invitation->delete();
return redirect()->route('team.index');
} }
} }

View File

@@ -21,36 +21,32 @@ class CheckAndStartSentinelJob implements ShouldBeEncrypted, ShouldQueue
public function handle(): void public function handle(): void
{ {
try { $latestVersion = get_latest_sentinel_version();
$latestVersion = get_latest_sentinel_version();
// Check if sentinel is running // Check if sentinel is running
$sentinelFound = instant_remote_process(['docker inspect coolify-sentinel'], $this->server, false); $sentinelFound = instant_remote_process(['docker inspect coolify-sentinel'], $this->server, false);
$sentinelFoundJson = json_decode($sentinelFound, true); $sentinelFoundJson = json_decode($sentinelFound, true);
$sentinelStatus = data_get($sentinelFoundJson, '0.State.Status', 'exited'); $sentinelStatus = data_get($sentinelFoundJson, '0.State.Status', 'exited');
if ($sentinelStatus !== 'running') { if ($sentinelStatus !== 'running') {
StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion);
return;
}
// If sentinel is running, check if it needs an update
$runningVersion = instant_remote_process(['docker exec coolify-sentinel sh -c "curl http://127.0.0.1:8888/api/version"'], $this->server, false);
if (empty($runningVersion)) {
$runningVersion = '0.0.0';
}
if ($latestVersion === '0.0.0' && $runningVersion === '0.0.0') {
StartSentinel::run(server: $this->server, restart: true, latestVersion: 'latest');
return;
} else {
if (version_compare($runningVersion, $latestVersion, '<')) {
StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion); StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion);
return; return;
} }
// If sentinel is running, check if it needs an update
$runningVersion = instant_remote_process(['docker exec coolify-sentinel sh -c "curl http://127.0.0.1:8888/api/version"'], $this->server, false);
if (empty($runningVersion)) {
$runningVersion = '0.0.0';
}
if ($latestVersion === '0.0.0' && $runningVersion === '0.0.0') {
StartSentinel::run(server: $this->server, restart: true, latestVersion: 'latest');
return;
} else {
if (version_compare($runningVersion, $latestVersion, '<')) {
StartSentinel::run(server: $this->server, restart: true, latestVersion: $latestVersion);
return;
}
}
} catch (\Throwable $e) {
throw $e;
} }
} }
} }

View File

@@ -20,12 +20,8 @@ class PullHelperImageJob implements ShouldBeEncrypted, ShouldQueue
public function handle(): void public function handle(): void
{ {
try { $helperImage = config('coolify.helper_image');
$helperImage = config('coolify.helper_image'); $latest_version = instanceSettings()->helper_version;
$latest_version = instanceSettings()->helper_version; instant_remote_process(["docker pull -q {$helperImage}:{$latest_version}"], $this->server, false);
instant_remote_process(["docker pull -q {$helperImage}:{$latest_version}"], $this->server, false);
} catch (\Throwable $e) {
throw $e;
}
} }
} }

View File

@@ -21,18 +21,14 @@ class PullVersionsFromCDN implements ShouldBeEncrypted, ShouldQueue
public function handle(): void public function handle(): void
{ {
try { if (! isDev() && ! isCloud()) {
if (! isDev() && ! isCloud()) { $response = Http::retry(3, 1000)->get('https://cdn.coollabs.io/coolify/versions.json');
$response = Http::retry(3, 1000)->get('https://cdn.coollabs.io/coolify/versions.json'); if ($response->successful()) {
if ($response->successful()) { $versions = $response->json();
$versions = $response->json(); File::put(base_path('versions.json'), json_encode($versions, JSON_PRETTY_PRINT));
File::put(base_path('versions.json'), json_encode($versions, JSON_PRETTY_PRINT)); } else {
} else { send_internal_notification('PullTemplatesAndVersions failed with: '.$response->status().' '.$response->body());
send_internal_notification('PullTemplatesAndVersions failed with: '.$response->status().' '.$response->body());
}
} }
} catch (\Throwable $e) {
throw $e;
} }
} }
} }

View File

@@ -91,119 +91,113 @@ class PushServerUpdateJob implements ShouldBeEncrypted, ShouldQueue
public function handle() public function handle()
{ {
// TODO: Swarm is not supported yet // TODO: Swarm is not supported yet
try { if (! $this->data) {
if (! $this->data) { throw new \Exception('No data provided');
throw new \Exception('No data provided'); }
} $data = collect($this->data);
$data = collect($this->data);
$this->server->sentinelHeartbeat(); $this->server->sentinelHeartbeat();
$this->containers = collect(data_get($data, 'containers')); $this->containers = collect(data_get($data, 'containers'));
$filesystemUsageRoot = data_get($data, 'filesystem_usage_root.used_percentage'); $filesystemUsageRoot = data_get($data, 'filesystem_usage_root.used_percentage');
ServerStorageCheckJob::dispatch($this->server, $filesystemUsageRoot); ServerStorageCheckJob::dispatch($this->server, $filesystemUsageRoot);
if ($this->containers->isEmpty()) { if ($this->containers->isEmpty()) {
return; return;
} }
$this->applications = $this->server->applications(); $this->applications = $this->server->applications();
$this->databases = $this->server->databases(); $this->databases = $this->server->databases();
$this->previews = $this->server->previews(); $this->previews = $this->server->previews();
$this->services = $this->server->services()->get(); $this->services = $this->server->services()->get();
$this->allApplicationIds = $this->applications->filter(function ($application) { $this->allApplicationIds = $this->applications->filter(function ($application) {
return $application->additional_servers->count() === 0; return $application->additional_servers->count() === 0;
})->pluck('id'); })->pluck('id');
$this->allApplicationsWithAdditionalServers = $this->applications->filter(function ($application) { $this->allApplicationsWithAdditionalServers = $this->applications->filter(function ($application) {
return $application->additional_servers->count() > 0; return $application->additional_servers->count() > 0;
});
$this->allApplicationPreviewsIds = $this->previews->pluck('id');
$this->allDatabaseUuids = $this->databases->pluck('uuid');
$this->allTcpProxyUuids = $this->databases->where('is_public', true)->pluck('uuid');
$this->services->each(function ($service) {
$service->applications()->pluck('id')->each(function ($applicationId) {
$this->allServiceApplicationIds->push($applicationId);
}); });
$this->allApplicationPreviewsIds = $this->previews->pluck('id'); $service->databases()->pluck('id')->each(function ($databaseId) {
$this->allDatabaseUuids = $this->databases->pluck('uuid'); $this->allServiceDatabaseIds->push($databaseId);
$this->allTcpProxyUuids = $this->databases->where('is_public', true)->pluck('uuid');
$this->services->each(function ($service) {
$service->applications()->pluck('id')->each(function ($applicationId) {
$this->allServiceApplicationIds->push($applicationId);
});
$service->databases()->pluck('id')->each(function ($databaseId) {
$this->allServiceDatabaseIds->push($databaseId);
});
}); });
});
foreach ($this->containers as $container) { foreach ($this->containers as $container) {
$containerStatus = data_get($container, 'state', 'exited'); $containerStatus = data_get($container, 'state', 'exited');
$containerHealth = data_get($container, 'health_status', 'unhealthy'); $containerHealth = data_get($container, 'health_status', 'unhealthy');
$containerStatus = "$containerStatus ($containerHealth)"; $containerStatus = "$containerStatus ($containerHealth)";
$labels = collect(data_get($container, 'labels')); $labels = collect(data_get($container, 'labels'));
$coolify_managed = $labels->has('coolify.managed'); $coolify_managed = $labels->has('coolify.managed');
if ($coolify_managed) { if ($coolify_managed) {
$name = data_get($container, 'name'); $name = data_get($container, 'name');
if ($name === 'coolify-log-drain' && $this->isRunning($containerStatus)) { if ($name === 'coolify-log-drain' && $this->isRunning($containerStatus)) {
$this->foundLogDrainContainer = true; $this->foundLogDrainContainer = true;
} }
if ($labels->has('coolify.applicationId')) { if ($labels->has('coolify.applicationId')) {
$applicationId = $labels->get('coolify.applicationId'); $applicationId = $labels->get('coolify.applicationId');
$pullRequestId = data_get($labels, 'coolify.pullRequestId', '0'); $pullRequestId = data_get($labels, 'coolify.pullRequestId', '0');
try { try {
if ($pullRequestId === '0') { if ($pullRequestId === '0') {
if ($this->allApplicationIds->contains($applicationId) && $this->isRunning($containerStatus)) { if ($this->allApplicationIds->contains($applicationId) && $this->isRunning($containerStatus)) {
$this->foundApplicationIds->push($applicationId); $this->foundApplicationIds->push($applicationId);
}
$this->updateApplicationStatus($applicationId, $containerStatus);
} else {
if ($this->allApplicationPreviewsIds->contains($applicationId) && $this->isRunning($containerStatus)) {
$this->foundApplicationPreviewsIds->push($applicationId);
}
$this->updateApplicationPreviewStatus($applicationId, $containerStatus);
} }
} catch (\Exception $e) { $this->updateApplicationStatus($applicationId, $containerStatus);
}
} elseif ($labels->has('coolify.serviceId')) {
$serviceId = $labels->get('coolify.serviceId');
$subType = $labels->get('coolify.service.subType');
$subId = $labels->get('coolify.service.subId');
if ($subType === 'application' && $this->isRunning($containerStatus)) {
$this->foundServiceApplicationIds->push($subId);
$this->updateServiceSubStatus($serviceId, $subType, $subId, $containerStatus);
} elseif ($subType === 'database' && $this->isRunning($containerStatus)) {
$this->foundServiceDatabaseIds->push($subId);
$this->updateServiceSubStatus($serviceId, $subType, $subId, $containerStatus);
}
} else {
$uuid = $labels->get('com.docker.compose.service');
$type = $labels->get('coolify.type');
if ($name === 'coolify-proxy' && $this->isRunning($containerStatus)) {
$this->foundProxy = true;
} elseif ($type === 'service' && $this->isRunning($containerStatus)) {
} else { } else {
if ($this->allDatabaseUuids->contains($uuid) && $this->isRunning($containerStatus)) { if ($this->allApplicationPreviewsIds->contains($applicationId) && $this->isRunning($containerStatus)) {
$this->foundDatabaseUuids->push($uuid); $this->foundApplicationPreviewsIds->push($applicationId);
if ($this->allTcpProxyUuids->contains($uuid) && $this->isRunning($containerStatus)) { }
$this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: true); $this->updateApplicationPreviewStatus($applicationId, $containerStatus);
} else { }
$this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: false); } catch (\Exception $e) {
} }
} elseif ($labels->has('coolify.serviceId')) {
$serviceId = $labels->get('coolify.serviceId');
$subType = $labels->get('coolify.service.subType');
$subId = $labels->get('coolify.service.subId');
if ($subType === 'application' && $this->isRunning($containerStatus)) {
$this->foundServiceApplicationIds->push($subId);
$this->updateServiceSubStatus($serviceId, $subType, $subId, $containerStatus);
} elseif ($subType === 'database' && $this->isRunning($containerStatus)) {
$this->foundServiceDatabaseIds->push($subId);
$this->updateServiceSubStatus($serviceId, $subType, $subId, $containerStatus);
}
} else {
$uuid = $labels->get('com.docker.compose.service');
$type = $labels->get('coolify.type');
if ($name === 'coolify-proxy' && $this->isRunning($containerStatus)) {
$this->foundProxy = true;
} elseif ($type === 'service' && $this->isRunning($containerStatus)) {
} else {
if ($this->allDatabaseUuids->contains($uuid) && $this->isRunning($containerStatus)) {
$this->foundDatabaseUuids->push($uuid);
if ($this->allTcpProxyUuids->contains($uuid) && $this->isRunning($containerStatus)) {
$this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: true);
} else {
$this->updateDatabaseStatus($uuid, $containerStatus, tcpProxy: false);
} }
} }
} }
} }
} }
$this->updateProxyStatus();
$this->updateNotFoundApplicationStatus();
$this->updateNotFoundApplicationPreviewStatus();
$this->updateNotFoundDatabaseStatus();
$this->updateNotFoundServiceStatus();
$this->updateAdditionalServersStatus();
$this->checkLogDrainContainer();
} catch (\Exception $e) {
throw $e;
} }
$this->updateProxyStatus();
$this->updateNotFoundApplicationStatus();
$this->updateNotFoundApplicationPreviewStatus();
$this->updateNotFoundDatabaseStatus();
$this->updateNotFoundServiceStatus();
$this->updateAdditionalServersStatus();
$this->checkLogDrainContainer();
} }
private function updateApplicationStatus(string $applicationId, string $containerStatus) private function updateApplicationStatus(string $applicationId, string $containerStatus)