misc_pterodactyl-panel/app/Services/Servers/SuspensionService.php

62 lines
2 KiB
PHP
Raw Permalink Normal View History

<?php
namespace Pterodactyl\Services\Servers;
use Webmozart\Assert\Assert;
2017-08-05 22:26:30 +00:00
use Pterodactyl\Models\Server;
use Pterodactyl\Repositories\Wings\DaemonServerRepository;
use Symfony\Component\HttpKernel\Exception\ConflictHttpException;
class SuspensionService
{
2021-01-23 20:33:34 +00:00
public const ACTION_SUSPEND = 'suspend';
public const ACTION_UNSUSPEND = 'unsuspend';
2018-01-20 19:48:02 +00:00
/**
* SuspensionService constructor.
*/
public function __construct(
private DaemonServerRepository $daemonServerRepository
) {
}
/**
* Suspends a server on the system.
*
* @throws \Throwable
*/
public function toggle(Server $server, string $action = self::ACTION_SUSPEND): void
{
Assert::oneOf($action, [self::ACTION_SUSPEND, self::ACTION_UNSUSPEND]);
$isSuspending = $action === self::ACTION_SUSPEND;
// 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
// is not suspended, and we try to un-suspend the instance.
if ($isSuspending === $server->isSuspended()) {
return;
}
2020-12-16 23:55:44 +00:00
// Check if the server is currently being transferred.
2021-01-23 20:33:34 +00:00
if (!is_null($server->transfer)) {
throw new ConflictHttpException('Cannot toggle suspension status on a server that is currently being transferred.');
2020-12-16 23:55:44 +00: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;
}
}
}