Files

62 lines
2.0 KiB
PHP
Raw Permalink Normal View History

2017-07-23 14:51:18 -05:00
<?php
namespace Pterodactyl\Services\Servers;
use Webmozart\Assert\Assert;
2017-08-05 17:26:30 -05:00
use Pterodactyl\Models\Server;
use Pterodactyl\Repositories\Wings\DaemonServerRepository;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
2017-07-23 14:51:18 -05:00
class SuspensionService
{
2021-01-23 12:33:34 -08:00
public const ACTION_SUSPEND = 'suspend';
public const ACTION_UNSUSPEND = 'unsuspend';
2018-01-20 13:48:02 -06:00
2017-07-23 14:51:18 -05:00
/**
* SuspensionService constructor.
*/
public function __construct(
2024-10-21 19:18:20 -06:00
private DaemonServerRepository $daemonServerRepository,
2017-07-23 14:51:18 -05:00
) {
}
/**
* Suspends a server on the system.
*
* @throws \Throwable
2017-07-23 14:51:18 -05:00
*/
2022-10-14 10:59:20 -06:00
public function toggle(Server $server, string $action = self::ACTION_SUSPEND): void
2017-07-23 14:51:18 -05:00
{
Assert::oneOf($action, [self::ACTION_SUSPEND, self::ACTION_UNSUSPEND]);
2017-07-23 14:51:18 -05:00
$isSuspending = $action === self::ACTION_SUSPEND;
2022-10-14 10:59:20 -06:00
// Nothing needs to happen if we're suspending the server, and it is already
// suspended in the database. Additionally, nothing needs to happen if the server
2022-10-14 10:59:20 -06:00
// is not suspended, and we try to un-suspend the instance.
if ($isSuspending === $server->isSuspended()) {
return;
2017-07-23 14:51:18 -05:00
}
2020-12-16 16:55:44 -07:00
// Check if the server is currently being transferred.
2021-01-23 12:33:34 -08:00
if (!is_null($server->transfer)) {
throw new ConflictHttpException('Cannot toggle suspension status on a server that is currently being transferred.');
2020-12-16 16:55:44 -07:00
}
// Update the server's suspension status.
$server->update([
'status' => $isSuspending ? Server::STATUS_SUSPENDED : null,
]);
try {
// Tell wings to re-sync the server state.
$this->daemonServerRepository->setServer($server)->sync();
} catch (\Exception $exception) {
// Rollback the server's suspension status if wings fails to sync the server.
$server->update([
'status' => $isSuspending ? null : Server::STATUS_SUSPENDED,
]);
throw $exception;
}
2017-07-23 14:51:18 -05:00
}
}