Repository navigation
[Feat] Add AWS Lightsail server provider #1252
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
451d30e
[Feat] Add AWS Lightsail server provider
saeedvaziry f90d7ae
Merge 4.x and address Lightsail review findings
saeedvaziry 4d6bf41
[Fix] Bound Lightsail catalog pagination
saeedvaziry 8443ade
[Docs] Add step-by-step Lightsail provider setup
saeedvaziry c619e0b
[Fix] Match versioned Lightsail Ubuntu blueprint groups
saeedvaziry 8e0fe60
[Fix] Handle Lightsail missing-resource error codes
saeedvaziry 52052e8
[Fix] Use distinct Lightsail key pair name and raw public key
saeedvaziry File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,291 @@ | ||
| <?php | ||
|
|
||
| namespace App\ServerProviders; | ||
|
|
||
| use App\Exceptions\ServerProviderError; | ||
| use Aws\Exception\AwsException; | ||
| use Aws\Lightsail\LightsailClient; | ||
| use Illuminate\Filesystem\FilesystemAdapter; | ||
| use Illuminate\Support\Facades\Storage; | ||
| use Illuminate\Support\Str; | ||
| use Illuminate\Validation\ValidationException; | ||
| use phpseclib3\Crypt\RSA; | ||
| use SensitiveParameter; | ||
|
|
||
| class Lightsail extends AbstractProvider | ||
| { | ||
| private const MAX_PAGES = 100; | ||
|
|
||
| public static function id(): string | ||
| { | ||
| return 'lightsail'; | ||
| } | ||
|
|
||
| public function createRules(array $input): array | ||
| { | ||
| return [ | ||
| 'plan' => ['required', 'string'], | ||
| 'region' => ['required', 'string', 'regex:/^[a-z]{2}(?:-[a-z]+)+-\d+$/'], | ||
| ]; | ||
| } | ||
|
|
||
| public function credentialValidationRules(array $input): array | ||
| { | ||
| return [ | ||
| 'key' => ['required', 'string'], | ||
| 'secret' => ['required', 'string'], | ||
| ]; | ||
| } | ||
|
|
||
| public function credentialData(array $input): array | ||
| { | ||
| return [ | ||
| 'key' => $input['key'], | ||
| 'secret' => $input['secret'], | ||
| ]; | ||
| } | ||
|
|
||
| public function data(array $input): array | ||
| { | ||
| return [ | ||
| 'plan' => $input['plan'], | ||
| 'region' => $input['region'], | ||
| ]; | ||
| } | ||
|
|
||
| public function connect(#[SensitiveParameter] array $credentials): bool | ||
| { | ||
| $this->request('GetRegions', credentials: $this->credentialData($credentials)); | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| public function regions(): array | ||
| { | ||
| return collect($this->request('GetRegions')['regions'] ?? []) | ||
| ->mapWithKeys(fn (array $region): array => [ | ||
| $region['name'] => $region['displayName'].' ('.$region['name'].')', | ||
| ]) | ||
| ->all(); | ||
| } | ||
|
|
||
| public function plans(?string $region): array | ||
| { | ||
| if (! $region) { | ||
| return []; | ||
| } | ||
|
|
||
| return collect($this->paginate('GetBundles', 'bundles', $region)) | ||
| ->filter(fn (array $bundle): bool => ($bundle['isActive'] ?? false) | ||
| && in_array('LINUX_UNIX', $bundle['supportedPlatforms'] ?? [], true) | ||
| && ($bundle['publicIpv4AddressCount'] ?? 0) > 0) | ||
| ->mapWithKeys(fn (array $bundle): array => [ | ||
| $bundle['bundleId'] => __('server_providers.plan', [ | ||
| 'name' => $bundle['name'], | ||
| 'cpu' => $bundle['cpuCount'], | ||
| 'memory' => $bundle['ramSizeInGb'] * 1024, | ||
| 'disk' => $bundle['diskSizeInGb'], | ||
| ]).' ('.number_format($bundle['price'], 2).'/mo)', | ||
| ]) | ||
| ->all(); | ||
| } | ||
|
|
||
| public function create(): void | ||
| { | ||
| $region = $this->server->provider_data['region']; | ||
| $regions = $this->request('GetRegions', ['includeAvailabilityZones' => true]); | ||
| $location = collect($regions['regions'] ?? [])->firstWhere('name', $region); | ||
| $zone = $location['availabilityZones'][0]['zoneName'] ?? null; | ||
|
|
||
| if (! $zone) { | ||
| throw new ServerProviderError('The selected AWS Lightsail region is unavailable.'); | ||
| } | ||
|
|
||
| if (! isset($this->plans($region)[$this->server->provider_data['plan']])) { | ||
| throw new ServerProviderError('The selected AWS Lightsail plan is unavailable.'); | ||
| } | ||
|
|
||
| $blueprint = collect($this->paginate('GetBlueprints', 'blueprints', $region)) | ||
| ->first(fn (array $blueprint): bool => ($blueprint['isActive'] ?? false) | ||
| && in_array($blueprint['group'] ?? '', ['ubuntu', $this->server->os->value], true) | ||
| && ($blueprint['type'] ?? '') === 'os' | ||
| && str_starts_with($blueprint['version'] ?? '', $this->server->os->getVersion())); | ||
|
|
||
| if (! $blueprint) { | ||
| throw new ServerProviderError('The selected Ubuntu version is unavailable on AWS Lightsail.'); | ||
| } | ||
|
|
||
| $name = 'vito-'.$this->server->id.'-'.Str::lower(Str::random(12)); | ||
| $keyName = $name.'-key'; | ||
| $this->generateKeyPair(); | ||
| $this->server->jsonUpdate('provider_data', 'ssh_key_name', $keyName); | ||
| $this->request('ImportKeyPair', [ | ||
| 'keyPairName' => $keyName, | ||
| 'publicKeyBase64' => $this->server->sshKey()['public_key'], | ||
| ]); | ||
|
|
||
| $this->server->jsonUpdate('provider_data', 'instance_name', $name); | ||
| $this->request('CreateInstances', [ | ||
| 'instanceNames' => [$name], | ||
| 'availabilityZone' => $zone, | ||
| 'blueprintId' => $blueprint['blueprintId'], | ||
| 'bundleId' => $this->server->provider_data['plan'], | ||
| 'keyPairName' => $keyName, | ||
| 'ipAddressType' => 'ipv4', | ||
| ]); | ||
| } | ||
|
|
||
| public function generateKeyPair(): void | ||
| { | ||
| $key = RSA::createKey(2048); | ||
| /** @var FilesystemAdapter $disk */ | ||
| $disk = Storage::disk(config('core.key_pairs_disk')); | ||
| $disk->put((string) $this->server->id, $key->toString('PKCS8')); | ||
| chmod($disk->path((string) $this->server->id), 0400); | ||
| $disk->put($this->server->id.'.pub', $key->getPublicKey()->toString('OpenSSH')); | ||
| } | ||
|
|
||
| public function isRunning(): bool | ||
| { | ||
| if (! isset($this->server->provider_data['instance_name'])) { | ||
| return false; | ||
| } | ||
|
|
||
| $result = $this->request('GetInstance', [ | ||
| 'instanceName' => $this->server->provider_data['instance_name'], | ||
| ]); | ||
| $instance = $result['instance'] ?? []; | ||
|
|
||
| if (($instance['state']['name'] ?? '') !== 'running' || empty($instance['publicIpAddress'])) { | ||
| return false; | ||
| } | ||
|
|
||
| if (! ($this->server->provider_data['ssh_access_configured'] ?? false) | ||
| && ! ($this->server->provider_data['firewall_configured'] ?? false)) { | ||
| $this->request('PutInstancePublicPorts', [ | ||
| 'instanceName' => $this->server->provider_data['instance_name'], | ||
| 'portInfos' => [[ | ||
| 'fromPort' => 22, | ||
| 'toPort' => 22, | ||
| 'protocol' => 'tcp', | ||
| 'cidrs' => ['0.0.0.0/0'], | ||
| ]], | ||
| ]); | ||
| $this->server->jsonUpdate('provider_data', 'ssh_access_configured', true, false); | ||
| } | ||
|
|
||
| $this->server->ip = $instance['publicIpAddress']; | ||
| $this->server->local_ip = $instance['privateIpAddress'] ?? null; | ||
| $this->server->save(); | ||
|
|
||
| return true; | ||
| } | ||
|
|
||
| public function configureFirewall(): void | ||
| { | ||
| if ($this->server->provider_data['firewall_configured'] ?? false) { | ||
| return; | ||
| } | ||
|
|
||
| $this->request('PutInstancePublicPorts', [ | ||
| 'instanceName' => $this->server->provider_data['instance_name'], | ||
| 'portInfos' => [[ | ||
| 'fromPort' => 0, | ||
| 'toPort' => 65535, | ||
| 'protocol' => 'all', | ||
| 'cidrs' => ['0.0.0.0/0'], | ||
| ]], | ||
| ]); | ||
| $this->server->jsonUpdate('provider_data', 'firewall_configured', true); | ||
| } | ||
|
|
||
| public function delete(): void | ||
| { | ||
| if (isset($this->server->provider_data['instance_name'])) { | ||
| $this->request('DeleteInstance', [ | ||
| 'instanceName' => $this->server->provider_data['instance_name'], | ||
| ]); | ||
| } | ||
|
|
||
| if (isset($this->server->provider_data['ssh_key_name'])) { | ||
| $this->request('DeleteKeyPair', [ | ||
| 'keyPairName' => $this->server->provider_data['ssh_key_name'], | ||
| ]); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * @return array<int, array<string, mixed>> | ||
| */ | ||
| private function paginate(string $operation, string $key, string $region): array | ||
| { | ||
| $items = []; | ||
| $parameters = ['includeInactive' => false]; | ||
| $page = 0; | ||
| $seenTokens = []; | ||
|
|
||
| do { | ||
| if (++$page > self::MAX_PAGES) { | ||
| throw new ServerProviderError('AWS Lightsail returned too many pages for '.$operation.'.'); | ||
| } | ||
|
|
||
| $result = $this->request($operation, $parameters, $region); | ||
| $items = array_merge($items, $result[$key] ?? []); | ||
| $parameters['pageToken'] = $result['nextPageToken'] ?? null; | ||
|
|
||
| if (isset($seenTokens[$parameters['pageToken']])) { | ||
| throw new ServerProviderError('AWS Lightsail returned an invalid page token for '.$operation.'.'); | ||
| } | ||
| if ($parameters['pageToken'] !== null) { | ||
| $seenTokens[$parameters['pageToken']] = true; | ||
| } | ||
| } while ($parameters['pageToken'] !== null && $parameters['pageToken'] !== ''); | ||
|
|
||
| return $items; | ||
| } | ||
|
|
||
| /** | ||
| * @param array<string, mixed> $parameters | ||
| * @param array{key: string, secret: string}|null $credentials | ||
| * @return array<string, mixed> | ||
| */ | ||
| private function request(string $operation, array $parameters = [], ?string $region = null, #[SensitiveParameter] ?array $credentials = null): array | ||
| { | ||
| $region ??= $this->server->provider_data['region'] ?? 'us-east-1'; | ||
|
|
||
| if (! preg_match('/^[a-z]{2}(?:-[a-z]+)+-\d+$/', $region)) { | ||
| throw ValidationException::withMessages(['region' => 'Invalid AWS Lightsail region.']); | ||
| } | ||
|
|
||
| try { | ||
| $client = app(LightsailClient::class, ['args' => [ | ||
| 'version' => '2016-11-28', | ||
| 'region' => $region, | ||
| 'credentials' => $credentials ?? $this->serverProvider->getCredentials(), | ||
| ]]); | ||
| $result = $client->execute($client->getCommand($operation, $parameters))->toArray(); | ||
| } catch (AwsException $exception) { | ||
| $code = $exception->getAwsErrorCode(); | ||
|
|
||
| if (in_array($code, ['NotFoundException', 'DoesNotExist'], true) | ||
| && in_array($operation, ['GetInstance', 'DeleteInstance', 'DeleteKeyPair'], true)) { | ||
| return []; | ||
| } | ||
|
|
||
| throw new ServerProviderError('AWS Lightsail could not complete '.$operation.($code ? ' ('.$code.')' : '').'.'); | ||
| } | ||
|
|
||
| foreach ($result['operations'] ?? (isset($result['operation']) ? [$result['operation']] : []) as $operationResult) { | ||
| if (($operationResult['status'] ?? '') === 'Failed') { | ||
| throw new ServerProviderError('AWS Lightsail could not complete '.$operation.'.'); | ||
| } | ||
|
|
||
| if (in_array($operation, ['DeleteInstance', 'DeleteKeyPair'], true) | ||
| && ! in_array($operationResult['status'] ?? '', ['Succeeded', 'Completed'], true)) { | ||
| throw new ServerProviderError('AWS Lightsail deletion is still in progress. Wait for it to finish, then retry deleting the server.'); | ||
| } | ||
| } | ||
|
|
||
| return $result; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.