feat: api api api api api api

This commit is contained in:
Andras Bacsai 2024-07-02 16:12:04 +02:00
parent 3c13f1ff61
commit 4459c9f73d
13 changed files with 636 additions and 85 deletions

View File

@ -0,0 +1,16 @@
<?php
namespace App\Actions\Application;
use App\Models\Application;
use Lorisleiva\Actions\Concerns\AsAction;
class LoadComposeFile
{
use AsAction;
public function handle(Application $application)
{
$application->loadComposeFile();
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace App\Actions\Service;
use App\Models\Service;
use Lorisleiva\Actions\Concerns\AsAction;
class RestartService
{
use AsAction;
public function handle(Service $service)
{
StopService::run($service);
return StartService::run($service);
}
}

View File

@ -7,5 +7,5 @@ enum BuildPackTypes: string
case NIXPACKS = 'nixpacks'; case NIXPACKS = 'nixpacks';
case STATIC = 'static'; case STATIC = 'static';
case DOCKERFILE = 'dockerfile'; case DOCKERFILE = 'dockerfile';
case DOCKER_COMPOSE = 'docker-compose'; case DOCKERCOMPOSE = 'dockercompose';
} }

View File

@ -8,7 +8,7 @@ enum NewResourceTypes: string
case PRIVATE_GH_APP = 'private-gh-app'; case PRIVATE_GH_APP = 'private-gh-app';
case PRIVATE_DEPLOY_KEY = 'private-deploy-key'; case PRIVATE_DEPLOY_KEY = 'private-deploy-key';
case DOCKERFILE = 'dockerfile'; case DOCKERFILE = 'dockerfile';
case DOCKER_COMPOSE_EMPTY = 'docker-compose-empty'; case DOCKERCOMPOSE = 'dockercompose';
case DOCKER_IMAGE = 'docker-image'; case DOCKER_IMAGE = 'docker-image';
case SERVICE = 'service'; case SERVICE = 'service';
case POSTGRESQL = 'postgresql'; case POSTGRESQL = 'postgresql';

View File

@ -12,7 +12,7 @@ class DatabaseStatusChanged implements ShouldBroadcast
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
public $userId; public ?string $userId = null;
public function __construct($userId = null) public function __construct($userId = null)
{ {
@ -20,15 +20,19 @@ public function __construct($userId = null)
$userId = auth()->user()->id ?? null; $userId = auth()->user()->id ?? null;
} }
if (is_null($userId)) { if (is_null($userId)) {
throw new \RuntimeException('User id is null'); return false;
} }
$this->userId = $userId; $this->userId = $userId;
} }
public function broadcastOn(): array public function broadcastOn(): ?array
{ {
if ($this->userId) {
return [ return [
new PrivateChannel("user.{$this->userId}"), new PrivateChannel("user.{$this->userId}"),
]; ];
} }
return null;
}
} }

View File

@ -12,7 +12,7 @@ class ServiceStatusChanged implements ShouldBroadcast
{ {
use Dispatchable, InteractsWithSockets, SerializesModels; use Dispatchable, InteractsWithSockets, SerializesModels;
public $userId; public ?string $userId = null;
public function __construct($userId = null) public function __construct($userId = null)
{ {
@ -20,15 +20,19 @@ public function __construct($userId = null)
$userId = auth()->user()->id ?? null; $userId = auth()->user()->id ?? null;
} }
if (is_null($userId)) { if (is_null($userId)) {
throw new \Exception('User id is null'); return false;
} }
$this->userId = $userId; $this->userId = $userId;
} }
public function broadcastOn(): array public function broadcastOn(): ?array
{ {
if ($this->userId) {
return [ return [
new PrivateChannel("user.{$this->userId}"), new PrivateChannel("user.{$this->userId}"),
]; ];
} }
return null;
}
} }

View File

@ -2,7 +2,9 @@
namespace App\Http\Controllers\Api; namespace App\Http\Controllers\Api;
use App\Actions\Application\LoadComposeFile;
use App\Actions\Application\StopApplication; use App\Actions\Application\StopApplication;
use App\Actions\Service\StartService;
use App\Enums\BuildPackTypes; use App\Enums\BuildPackTypes;
use App\Enums\NewResourceTypes; use App\Enums\NewResourceTypes;
use App\Http\Controllers\Controller; use App\Http\Controllers\Controller;
@ -64,7 +66,7 @@ public function applications(Request $request)
public function create_application(Request $request) public function create_application(Request $request)
{ {
$allowedFields = ['project_uuid', 'environment_name', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'is_static', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'redirect', 'github_app_uuid', 'instant_deploy', 'dockerfile']; $allowedFields = ['project_uuid', 'environment_name', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'is_static', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'redirect', 'github_app_uuid', 'instant_deploy', 'dockerfile', 'docker_compose_location', 'docker_compose', 'docker_compose_raw', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'watch_paths'];
$teamId = getTeamIdFromToken(); $teamId = getTeamIdFromToken();
if (is_null($teamId)) { if (is_null($teamId)) {
return invalidTokenResponse(); return invalidTokenResponse();
@ -136,6 +138,12 @@ public function create_application(Request $request)
'git_branch' => 'string|required', 'git_branch' => 'string|required',
'build_pack' => [Rule::enum(BuildPackTypes::class)], 'build_pack' => [Rule::enum(BuildPackTypes::class)],
'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|required', 'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|required',
'docker_compose_location' => 'string',
'docker_compose' => 'string|nullable',
'docker_compose_raw' => 'string|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_custom_start_command' => 'string|nullable',
'docker_compose_custom_build_command' => 'string|nullable',
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return response()->json([ return response()->json([
@ -152,6 +160,19 @@ public function create_application(Request $request)
removeUnnecessaryFieldsFromRequest($request); removeUnnecessaryFieldsFromRequest($request);
$application->fill($request->all()); $application->fill($request->all());
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
$dockerComposeDomains = collect($request->docker_compose_domains);
if ($dockerComposeDomains->count() > 0) {
$dockerComposeDomains->each(function ($domain, $key) use ($dockerComposeDomainsJson) {
$dockerComposeDomainsJson->put(data_get($domain, 'name'), ['domain' => data_get($domain, 'domain')]);
});
}
$request->offsetUnset('docker_compose_domains');
}
if ($dockerComposeDomainsJson->count() > 0) {
$application->docker_compose_domains = $dockerComposeDomainsJson;
}
$application->fqdn = $fqdn; $application->fqdn = $fqdn;
$application->destination_id = $destination->id; $application->destination_id = $destination->id;
@ -168,6 +189,10 @@ public function create_application(Request $request)
no_questions_asked: true, no_questions_asked: true,
is_api: true, is_api: true,
); );
} else {
if ($application->build_pack === 'dockercompose') {
LoadComposeFile::dispatch($application);
}
} }
return response()->json([ return response()->json([
@ -185,6 +210,13 @@ public function create_application(Request $request)
'build_pack' => ['required', Rule::enum(BuildPackTypes::class)], 'build_pack' => ['required', Rule::enum(BuildPackTypes::class)],
'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|required', 'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|required',
'github_app_uuid' => 'string|required', 'github_app_uuid' => 'string|required',
'watch_paths' => 'string|nullable',
'docker_compose_location' => 'string',
'docker_compose' => 'string|nullable',
'docker_compose_raw' => 'string|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_custom_start_command' => 'string|nullable',
'docker_compose_custom_build_command' => 'string|nullable',
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return response()->json([ return response()->json([
@ -210,6 +242,24 @@ public function create_application(Request $request)
$application->fill($request->all()); $application->fill($request->all());
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
$yaml = Yaml::parse($application->docker_compose_raw);
$services = data_get($yaml, 'services');
$dockerComposeDomains = collect($request->docker_compose_domains);
if ($dockerComposeDomains->count() > 0) {
$dockerComposeDomains->each(function ($domain, $key) use ($services, $dockerComposeDomainsJson) {
$name = data_get($domain, 'name');
if (data_get($services, $name)) {
$dockerComposeDomainsJson->put($name, ['domain' => data_get($domain, 'domain')]);
}
});
}
$request->offsetUnset('docker_compose_domains');
}
if ($dockerComposeDomainsJson->count() > 0) {
$application->docker_compose_domains = $dockerComposeDomainsJson;
}
$application->fqdn = $fqdn; $application->fqdn = $fqdn;
$application->git_repository = $gitRepository; $application->git_repository = $gitRepository;
$application->destination_id = $destination->id; $application->destination_id = $destination->id;
@ -228,6 +278,10 @@ public function create_application(Request $request)
no_questions_asked: true, no_questions_asked: true,
is_api: true, is_api: true,
); );
} else {
if ($application->build_pack === 'dockercompose') {
LoadComposeFile::dispatch($application);
}
} }
return response()->json([ return response()->json([
@ -245,7 +299,15 @@ public function create_application(Request $request)
'build_pack' => ['required', Rule::enum(BuildPackTypes::class)], 'build_pack' => ['required', Rule::enum(BuildPackTypes::class)],
'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|required', 'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|required',
'private_key_uuid' => 'string|required', 'private_key_uuid' => 'string|required',
'watch_paths' => 'string|nullable',
'docker_compose_location' => 'string',
'docker_compose' => 'string|nullable',
'docker_compose_raw' => 'string|nullable',
'docker_compose_domains' => 'array|nullable',
'docker_compose_custom_start_command' => 'string|nullable',
'docker_compose_custom_build_command' => 'string|nullable',
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return response()->json([ return response()->json([
'message' => 'Validation failed.', 'message' => 'Validation failed.',
@ -265,6 +327,25 @@ public function create_application(Request $request)
removeUnnecessaryFieldsFromRequest($request); removeUnnecessaryFieldsFromRequest($request);
$application->fill($request->all()); $application->fill($request->all());
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
$yaml = Yaml::parse($application->docker_compose_raw);
$services = data_get($yaml, 'services');
$dockerComposeDomains = collect($request->docker_compose_domains);
if ($dockerComposeDomains->count() > 0) {
$dockerComposeDomains->each(function ($domain, $key) use ($services, $dockerComposeDomainsJson) {
$name = data_get($domain, 'name');
if (data_get($services, $name)) {
$dockerComposeDomainsJson->put($name, ['domain' => data_get($domain, 'domain')]);
}
});
}
$request->offsetUnset('docker_compose_domains');
}
if ($dockerComposeDomainsJson->count() > 0) {
$application->docker_compose_domains = $dockerComposeDomainsJson;
}
$application->fqdn = $fqdn; $application->fqdn = $fqdn;
$application->private_key_id = $privateKey->id; $application->private_key_id = $privateKey->id;
$application->destination_id = $destination->id; $application->destination_id = $destination->id;
@ -281,6 +362,10 @@ public function create_application(Request $request)
no_questions_asked: true, no_questions_asked: true,
is_api: true, is_api: true,
); );
} else {
if ($application->build_pack === 'dockercompose') {
LoadComposeFile::dispatch($application);
}
} }
return response()->json([ return response()->json([
@ -415,14 +500,30 @@ public function create_application(Request $request)
'success' => true, 'success' => true,
'data' => serializeApiResponse($application), 'data' => serializeApiResponse($application),
]); ]);
} elseif ($type === 'docker-compose-empty') { } elseif ($type === 'dockercompose') {
$allowedFields = ['project_uuid', 'environment_name', 'server_uuid', 'destination_uuid', 'type', 'name', 'description', 'instant_deploy', 'docker_compose_raw'];
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'success' => false,
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
if (! $request->has('name')) { if (! $request->has('name')) {
$request->offsetSet('name', 'service'.new Cuid2(7)); $request->offsetSet('name', 'service'.new Cuid2(7));
} }
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
sharedDataApplications(), sharedDataApplications(),
'docker_compose' => 'string|required', 'docker_compose_raw' => 'string|required',
'ports_exposes' => 'string|regex:/^(\d+)(,\d+)*$/|required',
]); ]);
if ($validator->fails()) { if ($validator->fails()) {
return response()->json([ return response()->json([
@ -435,25 +536,25 @@ public function create_application(Request $request)
if ($return instanceof \Illuminate\Http\JsonResponse) { if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return; return $return;
} }
if (! isBase64Encoded($request->docker_compose)) { if (! isBase64Encoded($request->docker_compose_raw)) {
return response()->json([ return response()->json([
'success' => false, 'success' => false,
'message' => 'Validation failed.', 'message' => 'Validation failed.',
'errors' => [ 'errors' => [
'docker_compose' => 'The docker_compose should be base64 encoded.', 'docker_compose_raw' => 'The docker_compose_raw should be base64 encoded.',
], ],
], 422); ], 422);
} }
$dockerCompose = base64_decode($request->docker_compose); $dockerComposeRaw = base64_decode($request->docker_compose_raw);
if (mb_detect_encoding($dockerCompose, 'ASCII', true) === false) { if (mb_detect_encoding($dockerComposeRaw, 'ASCII', true) === false) {
return response()->json([ return response()->json([
'message' => 'Validation failed.', 'message' => 'Validation failed.',
'errors' => [ 'errors' => [
'docker_compose' => 'The docker_compose should be base64 encoded.', 'docker_compose_raw' => 'The docker_compose_raw should be base64 encoded.',
], ],
], 422); ], 422);
} }
$dockerCompose = base64_decode($request->docker_compose); $dockerCompose = base64_decode($request->docker_compose_raw);
$dockerComposeRaw = Yaml::dump(Yaml::parse($dockerCompose), 10, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK); $dockerComposeRaw = Yaml::dump(Yaml::parse($dockerCompose), 10, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
// $isValid = validateComposeFile($dockerComposeRaw, $server_id); // $isValid = validateComposeFile($dockerComposeRaw, $server_id);
@ -463,8 +564,8 @@ public function create_application(Request $request)
$service = new Service(); $service = new Service();
removeUnnecessaryFieldsFromRequest($request); removeUnnecessaryFieldsFromRequest($request);
$service->name = $request->name; $service->fill($request->all());
$service->description = $request->description;
$service->docker_compose_raw = $dockerComposeRaw; $service->docker_compose_raw = $dockerComposeRaw;
$service->environment_id = $environment->id; $service->environment_id = $environment->id;
$service->server_id = $server->id; $service->server_id = $server->id;
@ -474,16 +575,7 @@ public function create_application(Request $request)
$service->name = "service-$service->uuid"; $service->name = "service-$service->uuid";
$service->parse(isNew: true); $service->parse(isNew: true);
// if ($instantDeploy) { StartService::dispatch($service);
// $deployment_uuid = new Cuid2(7);
// queue_application_deployment(
// application: $application,
// deployment_uuid: $deployment_uuid,
// no_questions_asked: true,
// is_api: true,
// );
// }
return response()->json([ return response()->json([
'success' => true, 'success' => true,
@ -572,7 +664,7 @@ public function update_by_uuid(Request $request)
], 404); ], 404);
} }
$server = $application->destination->server; $server = $application->destination->server;
$allowedFields = ['name', 'description', 'is_static', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'static_image', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'watch_paths', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'docker_compose_location', 'docker_compose', 'docker_compose_raw', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'redirect']; $allowedFields = ['name', 'description', 'is_static', 'domains', 'git_repository', 'git_branch', 'git_commit_sha', 'docker_registry_image_name', 'docker_registry_image_tag', 'build_pack', 'static_image', 'install_command', 'build_command', 'start_command', 'ports_exposes', 'ports_mappings', 'base_directory', 'publish_directory', 'health_check_enabled', 'health_check_path', 'health_check_port', 'health_check_host', 'health_check_method', 'health_check_return_code', 'health_check_scheme', 'health_check_response_text', 'health_check_interval', 'health_check_timeout', 'health_check_retries', 'health_check_start_period', 'limits_memory', 'limits_memory_swap', 'limits_memory_swappiness', 'limits_memory_reservation', 'limits_cpus', 'limits_cpuset', 'limits_cpu_shares', 'custom_labels', 'custom_docker_run_options', 'post_deployment_command', 'post_deployment_command_container', 'pre_deployment_command', 'pre_deployment_command_container', 'watch_paths', 'manual_webhook_secret_github', 'manual_webhook_secret_gitlab', 'manual_webhook_secret_bitbucket', 'manual_webhook_secret_gitea', 'docker_compose_location', 'docker_compose', 'docker_compose_raw', 'docker_compose_custom_start_command', 'docker_compose_custom_build_command', 'docker_compose_domains', 'redirect'];
$validator = customApiValidator($request->all(), [ $validator = customApiValidator($request->all(), [
sharedDataApplications(), sharedDataApplications(),
@ -583,7 +675,7 @@ public function update_by_uuid(Request $request)
'docker_compose_location' => 'string', 'docker_compose_location' => 'string',
'docker_compose' => 'string|nullable', 'docker_compose' => 'string|nullable',
'docker_compose_raw' => 'string|nullable', 'docker_compose_raw' => 'string|nullable',
// 'docker_compose_domains' => 'string|nullable', // must be like: "{\"api\":{\"domain\":\"http:\\/\\/b8sos8k.127.0.0.1.sslip.io\"}}" 'docker_compose_domains' => 'array|nullable',
'docker_compose_custom_start_command' => 'string|nullable', 'docker_compose_custom_start_command' => 'string|nullable',
'docker_compose_custom_build_command' => 'string|nullable', 'docker_compose_custom_build_command' => 'string|nullable',
]); ]);
@ -635,8 +727,26 @@ public function update_by_uuid(Request $request)
$request->offsetUnset('domains'); $request->offsetUnset('domains');
} }
$dockerComposeDomainsJson = collect();
if ($request->has('docker_compose_domains')) {
$yaml = Yaml::parse($application->docker_compose_raw);
$services = data_get($yaml, 'services');
$dockerComposeDomains = collect($request->docker_compose_domains);
if ($dockerComposeDomains->count() > 0) {
$dockerComposeDomains->each(function ($domain, $key) use ($services, $dockerComposeDomainsJson) {
$name = data_get($domain, 'name');
if (data_get($services, $name)) {
$dockerComposeDomainsJson->put($name, ['domain' => data_get($domain, 'domain')]);
}
});
}
$request->offsetUnset('docker_compose_domains');
}
$data = $request->all(); $data = $request->all();
data_set($data, 'fqdn', $domains); data_set($data, 'fqdn', $domains);
if ($dockerComposeDomainsJson->count() > 0) {
data_set($data, 'docker_compose_domains', json_encode($dockerComposeDomainsJson));
}
$application->fill($data); $application->fill($data);
$application->save(); $application->save();
@ -983,7 +1093,7 @@ public function delete_env_by_uuid(Request $request)
'message' => 'Environment variable not found.', 'message' => 'Environment variable not found.',
], 404); ], 404);
} }
$found_env->delete(); $found_env->forceDelete();
return response()->json([ return response()->json([
'success' => true, 'success' => true,
@ -1038,7 +1148,6 @@ public function action_stop(Request $request)
return invalidTokenResponse(); return invalidTokenResponse();
} }
$uuid = $request->route('uuid'); $uuid = $request->route('uuid');
$sync = $request->query->get('sync') ?? false;
if (! $uuid) { if (! $uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 400); return response()->json(['success' => false, 'message' => 'UUID is required.'], 400);
} }
@ -1046,26 +1155,15 @@ public function action_stop(Request $request)
if (! $application) { if (! $application) {
return response()->json(['success' => false, 'message' => 'Application not found.'], 404); return response()->json(['success' => false, 'message' => 'Application not found.'], 404);
} }
if ($sync) {
StopApplication::run($application);
return response()->json(
[
'success' => true,
'message' => 'Stopped the application.',
],
);
} else {
StopApplication::dispatch($application); StopApplication::dispatch($application);
return response()->json( return response()->json(
[ [
'success' => true, 'success' => true,
'message' => 'Stopping request queued.', 'message' => 'Application stopping request queued.',
], ],
); );
} }
}
public function action_restart(Request $request) public function action_restart(Request $request)
{ {
@ -1108,11 +1206,6 @@ private function validateDataApplications(Request $request, Server $server)
{ {
$teamId = getTeamIdFromToken(); $teamId = getTeamIdFromToken();
// Default build pack is nixpacks
if (! $request->has('build_pack')) {
$request->offsetSet('build_pack', 'nixpacks');
}
// Validate ports_mappings // Validate ports_mappings
if ($request->has('ports_mappings')) { if ($request->has('ports_mappings')) {
$ports = []; $ports = [];

View File

@ -2,6 +2,7 @@
namespace App\Http\Controllers\Api; namespace App\Http\Controllers\Api;
use App\Actions\Database\RestartDatabase;
use App\Actions\Database\StartDatabase; use App\Actions\Database\StartDatabase;
use App\Actions\Database\StartDatabaseProxy; use App\Actions\Database\StartDatabaseProxy;
use App\Actions\Database\StopDatabase; use App\Actions\Database\StopDatabase;
@ -557,11 +558,93 @@ public function delete_by_uuid(Request $request)
return response()->json(['success' => false, 'message' => 'Database not found.'], 404); return response()->json(['success' => false, 'message' => 'Database not found.'], 404);
} }
StopDatabase::dispatch($database); StopDatabase::dispatch($database);
$database->delete(); $database->forceDelete();
return response()->json([ return response()->json([
'success' => true, 'success' => true,
'message' => 'Database deletion request queued.', 'message' => 'Database deletion request queued.',
]); ]);
} }
public function action_deploy(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 400);
}
$database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId);
if (! $database) {
return response()->json(['success' => false, 'message' => 'Database not found.'], 404);
}
if (str($database->status)->contains('running')) {
return response()->json(['success' => false, 'message' => 'Database is already running.'], 400);
}
StartDatabase::dispatch($database);
return response()->json(
[
'success' => true,
'message' => 'Database starting request queued.',
],
200
);
}
public function action_stop(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 400);
}
$database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId);
if (! $database) {
return response()->json(['success' => false, 'message' => 'Database not found.'], 404);
}
if (str($database->status)->contains('stopped') || str($database->status)->contains('exited')) {
return response()->json(['success' => false, 'message' => 'Database is already stopped.'], 400);
}
StopDatabase::dispatch($database);
return response()->json(
[
'success' => true,
'message' => 'Database stopping request queued.',
],
200
);
}
public function action_restart(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 400);
}
$database = queryDatabaseByUuidWithinTeam($request->uuid, $teamId);
if (! $database) {
return response()->json(['success' => false, 'message' => 'Database not found.'], 404);
}
RestartDatabase::dispatch($database);
return response()->json(
[
'success' => true,
'message' => 'Database restarting request queued.',
],
200
);
}
} }

View File

@ -150,7 +150,7 @@ public function delete_key(Request $request)
if (is_null($key)) { if (is_null($key)) {
return response()->json(['success' => false, 'message' => 'Key not found.'], 404); return response()->json(['success' => false, 'message' => 'Key not found.'], 404);
} }
$key->delete(); $key->forceDelete();
return response()->json([ return response()->json([
'success' => true, 'success' => true,

View File

@ -0,0 +1,314 @@
<?php
namespace App\Http\Controllers\Api;
use App\Actions\Service\RestartService;
use App\Actions\Service\StartService;
use App\Actions\Service\StopService;
use App\Http\Controllers\Controller;
use App\Jobs\DeleteResourceJob;
use App\Models\EnvironmentVariable;
use App\Models\Project;
use App\Models\Server;
use App\Models\Service;
use Illuminate\Http\Request;
class ServicesController extends Controller
{
private function removeSensitiveData($service)
{
$token = auth()->user()->currentAccessToken();
if ($token->can('view:sensitive')) {
return serializeApiResponse($service);
}
$service->makeHidden([
'docker_compose_raw',
'docker_compose',
]);
return serializeApiResponse($service);
}
public function services(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$projects = Project::where('team_id', $teamId)->get();
$services = collect();
foreach ($projects as $project) {
$services->push($project->services()->get());
}
foreach ($services as $service) {
$service = $this->removeSensitiveData($service);
}
return response()->json([
'success' => true,
'data' => $services,
]);
}
public function create_service(Request $request)
{
$allowedFields = ['type', 'name', 'description', 'project_uuid', 'environment_name', 'server_uuid', 'destination_uuid', 'instant_deploy'];
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$return = validateIncomingRequest($request);
if ($return instanceof \Illuminate\Http\JsonResponse) {
return $return;
}
$validator = customApiValidator($request->all(), [
'type' => 'string|required',
'project_uuid' => 'string|required',
'environment_name' => 'string|required',
'server_uuid' => 'string|required',
'destination_uuid' => 'string',
'name' => 'string|max:255',
'description' => 'string|nullable',
'instant_deploy' => 'boolean',
]);
$extraFields = array_diff(array_keys($request->all()), $allowedFields);
if ($validator->fails() || ! empty($extraFields)) {
$errors = $validator->errors();
if (! empty($extraFields)) {
foreach ($extraFields as $field) {
$errors->add($field, 'This field is not allowed.');
}
}
return response()->json([
'success' => false,
'message' => 'Validation failed.',
'errors' => $errors,
], 422);
}
$serverUuid = $request->server_uuid;
$instantDeploy = $request->instant_deploy ?? false;
if ($request->is_public && ! $request->public_port) {
$request->offsetSet('is_public', false);
}
$project = Project::whereTeamId($teamId)->whereUuid($request->project_uuid)->first();
if (! $project) {
return response()->json(['succes' => false, 'message' => 'Project not found.'], 404);
}
$environment = $project->environments()->where('name', $request->environment_name)->first();
if (! $environment) {
return response()->json(['success' => false, 'message' => 'Environment not found.'], 404);
}
$server = Server::whereTeamId($teamId)->whereUuid($serverUuid)->first();
if (! $server) {
return response()->json(['success' => false, 'message' => 'Server not found.'], 404);
}
$destinations = $server->destinations();
if ($destinations->count() == 0) {
return response()->json(['success' => false, 'message' => 'Server has no destinations.'], 400);
}
if ($destinations->count() > 1 && ! $request->has('destination_uuid')) {
return response()->json(['success' => false, 'message' => 'Server has multiple destinations and you do not set destination_uuid.'], 400);
}
$destination = $destinations->first();
$services = get_service_templates();
$serviceKeys = $services->keys();
if ($serviceKeys->contains($request->type)) {
$oneClickServiceName = $request->type;
$oneClickService = data_get($services, "$oneClickServiceName.compose");
$oneClickDotEnvs = data_get($services, "$oneClickServiceName.envs", null);
if ($oneClickDotEnvs) {
$oneClickDotEnvs = str(base64_decode($oneClickDotEnvs))->split('/\r\n|\r|\n/')->filter(function ($value) {
return ! empty($value);
});
}
if ($oneClickService) {
$service_payload = [
'name' => "$oneClickServiceName-".str()->random(10),
'docker_compose_raw' => base64_decode($oneClickService),
'environment_id' => $environment->id,
'service_type' => $oneClickServiceName,
'server_id' => $server->id,
'destination_id' => $destination->id,
'destination_type' => $destination->getMorphClass(),
];
if ($oneClickServiceName === 'cloudflared') {
data_set($service_payload, 'connect_to_docker_network', true);
}
$service = Service::create($service_payload);
$service->name = "$oneClickServiceName-".$service->uuid;
$service->save();
if ($oneClickDotEnvs?->count() > 0) {
$oneClickDotEnvs->each(function ($value) use ($service) {
$key = str()->before($value, '=');
$value = str(str()->after($value, '='));
$generatedValue = $value;
if ($value->contains('SERVICE_')) {
$command = $value->after('SERVICE_')->beforeLast('_');
$generatedValue = generateEnvValue($command->value(), $service);
}
EnvironmentVariable::create([
'key' => $key,
'value' => $generatedValue,
'service_id' => $service->id,
'is_build_time' => false,
'is_preview' => false,
]);
});
}
$service->parse(isNew: true);
if ($instantDeploy) {
StartService::dispatch($service);
}
$domains = $service->applications()->get()->pluck('fqdn')->sort();
$domains = $domains->map(function ($domain) {
return str($domain)->beforeLast(':')->value();
});
return response()->json([
'success' => true,
'message' => 'Service created.',
'data' => $this->removeSensitiveData([
'id' => $service->id,
'uuid' => $service->uuid,
'name' => $service->name,
'domains' => $domains,
]),
]);
}
return response()->json(['success' => false, 'message' => 'Service not found.'], 404);
} else {
return response()->json(['success' => false, 'message' => 'Invalid service type.', 'valid_service_types' => $serviceKeys], 400);
}
return response()->json(['success' => false, 'message' => 'Invalid service type.'], 400);
}
public function service_by_uuid(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
if (! $request->uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 404);
}
$service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['success' => false, 'message' => 'Service not found.'], 404);
}
return response()->json([
'success' => true,
'data' => $this->removeSensitiveData($service),
]);
}
public function delete_by_uuid(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
if (! $request->uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 404);
}
$service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['success' => false, 'message' => 'Service not found.'], 404);
}
DeleteResourceJob::dispatch($service);
return response()->json([
'success' => true,
'message' => 'Service deletion request queued.',
]);
}
public function action_deploy(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 400);
}
$service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['success' => false, 'message' => 'Service not found.'], 404);
}
if (str($service->status())->contains('running')) {
return response()->json(['success' => false, 'message' => 'Service is already running.'], 400);
}
StartService::dispatch($service);
return response()->json(
[
'success' => true,
'message' => 'Service starting request queued.',
],
200
);
}
public function action_stop(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 400);
}
$service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['success' => false, 'message' => 'Service not found.'], 404);
}
if (str($service->status())->contains('stopped') || str($service->status())->contains('exited')) {
return response()->json(['success' => false, 'message' => 'Service is already stopped.'], 400);
}
StopService::dispatch($service);
return response()->json(
[
'success' => true,
'message' => 'Service stopping request queued.',
],
200
);
}
public function action_restart(Request $request)
{
$teamId = getTeamIdFromToken();
if (is_null($teamId)) {
return invalidTokenResponse();
}
$uuid = $request->route('uuid');
if (! $uuid) {
return response()->json(['success' => false, 'message' => 'UUID is required.'], 400);
}
$service = Service::whereRelation('environment.project.team', 'id', $teamId)->whereUuid($request->uuid)->first();
if (! $service) {
return response()->json(['success' => false, 'message' => 'Service not found.'], 404);
}
RestartService::dispatch($service);
return response()->json(
[
'success' => true,
'message' => 'Service restarting request queued.',
],
200
);
}
}

View File

@ -6,7 +6,7 @@
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
class ReadOnlyApiToken class IgnoreReadOnlyApiToken
{ {
/** /**
* Handle an incoming request. * Handle an incoming request.

View File

@ -127,7 +127,7 @@ class ApplicationDeploymentJob implements ShouldBeEncrypted, ShouldQueue
private string $dockerfile_location = '/Dockerfile'; private string $dockerfile_location = '/Dockerfile';
private string $docker_compose_location = '/docker-compose.yml'; private string $docker_compose_location = '/docker-compose.yaml';
private ?string $docker_compose_custom_start_command = null; private ?string $docker_compose_custom_start_command = null;

View File

@ -8,10 +8,11 @@
use App\Http\Controllers\Api\ResourcesController; use App\Http\Controllers\Api\ResourcesController;
use App\Http\Controllers\Api\SecurityController; use App\Http\Controllers\Api\SecurityController;
use App\Http\Controllers\Api\ServersController; use App\Http\Controllers\Api\ServersController;
use App\Http\Controllers\Api\ServicesController;
use App\Http\Controllers\Api\TeamController; use App\Http\Controllers\Api\TeamController;
use App\Http\Middleware\ApiAllowed; use App\Http\Middleware\ApiAllowed;
use App\Http\Middleware\IgnoreReadOnlyApiToken;
use App\Http\Middleware\OnlyRootApiToken; use App\Http\Middleware\OnlyRootApiToken;
use App\Http\Middleware\ReadOnlyApiToken;
use App\Models\InstanceSettings; use App\Models\InstanceSettings;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Http;
@ -83,13 +84,13 @@
Route::get('/projects/{uuid}/{environment_name}', [ProjectController::class, 'environment_details']); Route::get('/projects/{uuid}/{environment_name}', [ProjectController::class, 'environment_details']);
Route::get('/security/keys', [SecurityController::class, 'keys']); Route::get('/security/keys', [SecurityController::class, 'keys']);
Route::post('/security/keys', [SecurityController::class, 'create_key'])->middleware([ReadOnlyApiToken::class]); Route::post('/security/keys', [SecurityController::class, 'create_key'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::get('/security/keys/{uuid}', [SecurityController::class, 'key_by_uuid']); Route::get('/security/keys/{uuid}', [SecurityController::class, 'key_by_uuid']);
Route::patch('/security/keys/{uuid}', [SecurityController::class, 'update_key'])->middleware([ReadOnlyApiToken::class]); Route::patch('/security/keys/{uuid}', [SecurityController::class, 'update_key'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::delete('/security/keys/{uuid}', [SecurityController::class, 'delete_key'])->middleware([ReadOnlyApiToken::class]); Route::delete('/security/keys/{uuid}', [SecurityController::class, 'delete_key'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/deploy', [DeployController::class, 'deploy'])->middleware([ReadOnlyApiToken::class]); Route::match(['get', 'post'], '/deploy', [DeployController::class, 'deploy'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::get('/deployments', [DeployController::class, 'deployments']); Route::get('/deployments', [DeployController::class, 'deployments']);
Route::get('/deployments/{uuid}', [DeployController::class, 'deployment_by_uuid']); Route::get('/deployments/{uuid}', [DeployController::class, 'deployment_by_uuid']);
@ -101,30 +102,48 @@
Route::get('/resources', [ResourcesController::class, 'resources']); Route::get('/resources', [ResourcesController::class, 'resources']);
Route::get('/applications', [ApplicationsController::class, 'applications']); Route::get('/applications', [ApplicationsController::class, 'applications']);
Route::post('/applications', [ApplicationsController::class, 'create_application'])->middleware([ReadOnlyApiToken::class]); Route::post('/applications', [ApplicationsController::class, 'create_application'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::get('/applications/{uuid}', [ApplicationsController::class, 'application_by_uuid']); Route::get('/applications/{uuid}', [ApplicationsController::class, 'application_by_uuid']);
Route::patch('/applications/{uuid}', [ApplicationsController::class, 'update_by_uuid'])->middleware([ReadOnlyApiToken::class]); Route::patch('/applications/{uuid}', [ApplicationsController::class, 'update_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::delete('/applications/{uuid}', [ApplicationsController::class, 'delete_by_uuid'])->middleware([ReadOnlyApiToken::class]); Route::delete('/applications/{uuid}', [ApplicationsController::class, 'delete_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::get('/applications/{uuid}/envs', [ApplicationsController::class, 'envs_by_uuid']); Route::get('/applications/{uuid}/envs', [ApplicationsController::class, 'envs_by_uuid']);
Route::post('/applications/{uuid}/envs', [ApplicationsController::class, 'create_env'])->middleware([ReadOnlyApiToken::class]); Route::post('/applications/{uuid}/envs', [ApplicationsController::class, 'create_env'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::post('/applications/{uuid}/envs/bulk', [ApplicationsController::class, 'create_bulk_envs'])->middleware([ReadOnlyApiToken::class]); Route::post('/applications/{uuid}/envs/bulk', [ApplicationsController::class, 'create_bulk_envs'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::patch('/applications/{uuid}/envs', [ApplicationsController::class, 'update_env_by_uuid']); Route::patch('/applications/{uuid}/envs', [ApplicationsController::class, 'update_env_by_uuid']);
Route::delete('/applications/{uuid}/envs/{env_uuid}', [ApplicationsController::class, 'delete_env_by_uuid'])->middleware([ReadOnlyApiToken::class]); Route::delete('/applications/{uuid}/envs/{env_uuid}', [ApplicationsController::class, 'delete_env_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/applications/{uuid}/action/deploy', [ApplicationsController::class, 'action_deploy'])->middleware([ReadOnlyApiToken::class]); Route::match(['get', 'post'], '/applications/{uuid}/start', [ApplicationsController::class, 'action_deploy'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/applications/{uuid}/action/restart', [ApplicationsController::class, 'action_restart'])->middleware([ReadOnlyApiToken::class]); Route::match(['get', 'post'], '/applications/{uuid}/deploy', [ApplicationsController::class, 'action_deploy'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/applications/{uuid}/action/stop', [ApplicationsController::class, 'action_stop'])->middleware([ReadOnlyApiToken::class]); Route::match(['get', 'post'], '/applications/{uuid}/restart', [ApplicationsController::class, 'action_restart'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/applications/{uuid}/stop', [ApplicationsController::class, 'action_stop'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::get('/databases', [DatabasesController::class, 'databases']); Route::get('/databases', [DatabasesController::class, 'databases']);
Route::post('/databases', [DatabasesController::class, 'create_database'])->middleware([ReadOnlyApiToken::class]); Route::post('/databases', [DatabasesController::class, 'create_database'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::get('/databases/{uuid}', [DatabasesController::class, 'database_by_uuid']); Route::get('/databases/{uuid}', [DatabasesController::class, 'database_by_uuid']);
Route::patch('/databases/{uuid}', [DatabasesController::class, 'update_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::delete('/databases/{uuid}', [DatabasesController::class, 'delete_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::patch('/databases/{uuid}', [DatabasesController::class, 'update_by_uuid'])->middleware([ReadOnlyApiToken::class]); Route::match(['get', 'post'], '/databases/{uuid}/start', [DatabasesController::class, 'action_deploy'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::delete('/databases/{uuid}', [DatabasesController::class, 'delete_by_uuid'])->middleware([ReadOnlyApiToken::class]); Route::match(['get', 'post'], '/databases/{uuid}/deploy', [DatabasesController::class, 'action_deploy'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/databases/{uuid}/restart', [DatabasesController::class, 'action_restart'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/databases/{uuid}/stop', [DatabasesController::class, 'action_stop'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::delete('/envs/{env_uuid}', [EnvironmentVariablesController::class, 'delete_env_by_uuid'])->middleware([ReadOnlyApiToken::class]); Route::get('/services', [ServicesController::class, 'services']);
Route::post('/services', [ServicesController::class, 'create_service'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::get('/services/{uuid}', [ServicesController::class, 'service_by_uuid']);
// Route::patch('/services/{uuid}', [ServicesController::class, 'update_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::delete('/services/{uuid}', [ServicesController::class, 'delete_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/services/{uuid}/start', [ServicesController::class, 'action_deploy'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/services/{uuid}/deploy', [ServicesController::class, 'action_deploy'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/services/{uuid}/restart', [ServicesController::class, 'action_restart'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::match(['get', 'post'], '/services/{uuid}/stop', [ServicesController::class, 'action_stop'])->middleware([IgnoreReadOnlyApiToken::class]);
Route::delete('/envs/{env_uuid}', [EnvironmentVariablesController::class, 'delete_env_by_uuid'])->middleware([IgnoreReadOnlyApiToken::class]);
}); });