Merge pull request #1095 from coollabsio/v4-next

Just merging v4-next to v4 so I can finalize everything to the release
This commit is contained in:
Andras Bacsai 2023-06-07 17:36:32 +02:00 committed by GitHub
commit 5abe308a97
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
345 changed files with 14358 additions and 3282 deletions

View File

@ -19,4 +19,4 @@ yarn-error.log
/.vscode
/.npm
/.bash_history
/_volumes
/_data

View File

@ -5,6 +5,12 @@
# Run in your terminal: `id -u` and `id -g` and that's the results
USERID=
GROUPID=
PROJECT_PATH_ON_HOST=/Users/your-username-here/code/coollabsio/coolify
SERVEO_URL=<for receiving webhooks locally https://serveo.net/>
MUX_ENABLED=false
# If you are using the included Buggregator
RAY_HOST=ray@host.docker.internal
RAY_PORT=8001
############################################################################################################
APP_NAME=Coolify
@ -15,6 +21,10 @@ APP_DEBUG=true
APP_URL=http://localhost
APP_PORT=8000
MAIL_MAILER=smtp
MAIL_HOST=coolify-mail
MAIL_PORT=1025
SESSION_DRIVER=database
DUSK_DRIVER_URL=http://selenium:4444
@ -25,4 +35,5 @@ DB_DATABASE=coolify
DB_USERNAME=coolify
DB_PASSWORD=password
QUEUE_CONNECTION=database
QUEUE_CONNECTION=redis
REDIS_HOST=coolify-redis

View File

@ -1,6 +1,12 @@
COOLIFY_DEFAULT_PROXY=traefik
COOLIFY_DEFAULT_NETWORK=coolify
SENTRY_LARAVEL_DSN=https://fc21c062604d4526a4a9f263a0addeac@o1082494.ingest.sentry.io/4504672605372416
SENTRY_TRACES_SAMPLE_RATE=0.2
APP_NAME=Coolify
APP_SERVICE=php
APP_ENV=local
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=http://localhost
@ -15,4 +21,8 @@ DB_DATABASE=coolify
DB_USERNAME=coolify
DB_PASSWORD=
QUEUE_CONNECTION=database
QUEUE_CONNECTION=redis
REDIS_HOST=coolify-redis
REDIS_PASSWORD=
CACHE_DRIVER=redis

View File

@ -1,4 +1,4 @@
# Secrets related to pushing to GH, Sync files to BunnyCDN etc.
# Secrets related to pushing to GH, Sync files to BunnyCDN etc. Only for maintainers.
# Not related to Coolify, but to how we publish new versions.
GITHUB_TOKEN=

View File

@ -24,7 +24,7 @@ jobs:
with:
no-cache: true
context: .
file: docker/builder/Dockerfile
file: docker/coolify-builder/Dockerfile
platforms: linux/amd64
push: true
tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest

View File

@ -1,10 +1,14 @@
name: Docker Image CI
on:
# push:
# branches: [ "main" ]
# pull_request:
# branches: [ "*" ]
push:
branches: [ "main" ]
branches: ["this-does-not-exist"]
pull_request:
branches: [ "*" ]
branches: ["this-does-not-exist"]
jobs:
build:

View File

@ -2,7 +2,7 @@ name: Production Build (v4)
on:
push:
branches: ["v4"]
branches: ["v4", "v4-next"]
env:
REGISTRY: ghcr.io

10
.gitignore vendored
View File

@ -19,7 +19,13 @@ yarn-error.log
/.vscode
/.npm
/.bash_history
/_volumes
/_data
_testing_hosts/
_volumes/
.lesshst
psysh_history
.psql_history
_ide_helper.php
.gitignore
.phpstorm.meta.php
_ide_helper_models.php

View File

@ -8,13 +8,19 @@ # v4
Thinks will be added here incrementally through PR's.
# Installation
```bash
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash
```
## Support
- Mastodon: [@andrasbacsai@fosstodon.org](https://fosstodon.org/@andrasbacsai)
- Telegram: [@andrasbacsai](https://t.me/andrasbacsai)
- Twitter: [@andrasbacsai](https://twitter.com/heyandras)
- Twitter: [@heyandras](https://twitter.com/heyandras)
- Email: [andras@coollabs.io](mailto:andras@coollabs.io)
- Discord: [Invitation](https://coollabs.io/discord)
- Telegram: [@andrasbacsai](https://t.me/andrasbacsai)
---

View File

@ -1,17 +1,24 @@
<?php
namespace App\Actions\RemoteProcess;
namespace App\Actions\CoolifyTask;
use App\Data\RemoteProcessArgs;
use App\Jobs\ExecuteRemoteProcess;
use App\Data\CoolifyTaskArgs;
use App\Jobs\CoolifyTask;
use Spatie\Activitylog\Models\Activity;
class DispatchRemoteProcess
/**
* The initial step to run a `CoolifyTask`: a remote SSH process
* with monitoring/tracking/trace feature. Such thing is made
* possible using an Activity model and some attributes.
*/
class PrepareCoolifyTask
{
protected Activity $activity;
public function __construct(RemoteProcessArgs $remoteProcessArgs)
protected CoolifyTaskArgs $remoteProcessArgs;
public function __construct(CoolifyTaskArgs $remoteProcessArgs)
{
$this->remoteProcessArgs = $remoteProcessArgs;
if ($remoteProcessArgs->model) {
$properties = $remoteProcessArgs->toArray();
unset($properties['model']);
@ -31,7 +38,7 @@ public function __construct(RemoteProcessArgs $remoteProcessArgs)
public function __invoke(): Activity
{
$job = new ExecuteRemoteProcess($this->activity);
$job = new CoolifyTask($this->activity, ignore_errors: $this->remoteProcessArgs->ignore_errors);
dispatch($job);
$this->activity->refresh();
return $this->activity;

View File

@ -1,66 +1,69 @@
<?php
namespace App\Actions\RemoteProcess;
namespace App\Actions\CoolifyTask;
use App\Enums\ActivityTypes;
use App\Enums\ProcessStatus;
use App\Jobs\DeployApplicationJob;
use App\Jobs\ApplicationDeploymentJob;
use Illuminate\Process\ProcessResult;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Process;
use Spatie\Activitylog\Models\Activity;
const TIMEOUT = 3600;
const IDLE_TIMEOUT = 3600;
class RunRemoteProcess
{
public Activity $activity;
public bool $hideFromOutput;
public bool $hide_from_output;
public bool $isFinished;
public bool $is_finished;
public bool $ignoreErrors;
public bool $ignore_errors;
protected $timeStart;
protected $time_start;
protected $currentTime;
protected $current_time;
protected $lastWriteAt = 0;
protected $last_write_at = 0;
protected $throttleIntervalMS = 500;
protected $throttle_interval_ms = 500;
protected int $counter = 1;
/**
* Create a new job instance.
*/
public function __construct(Activity $activity, bool $hideFromOutput = false, bool $isFinished = false, bool $ignoreErrors = false)
public function __construct(Activity $activity, bool $hide_from_output = false, bool $is_finished = false, bool $ignore_errors = false)
{
if ($activity->getExtraProperty('type') !== ActivityTypes::REMOTE_PROCESS->value && $activity->getExtraProperty('type') !== ActivityTypes::DEPLOYMENT->value) {
if ($activity->getExtraProperty('type') !== ActivityTypes::INLINE->value && $activity->getExtraProperty('type') !== ActivityTypes::DEPLOYMENT->value) {
throw new \RuntimeException('Incompatible Activity to run a remote command.');
}
$this->activity = $activity;
$this->hideFromOutput = $hideFromOutput;
$this->isFinished = $isFinished;
$this->ignoreErrors = $ignoreErrors;
$this->hide_from_output = $hide_from_output;
$this->is_finished = $is_finished;
$this->ignore_errors = $ignore_errors;
}
public function __invoke(): ProcessResult
{
$this->timeStart = hrtime(true);
$this->time_start = hrtime(true);
$status = ProcessStatus::IN_PROGRESS;
$processResult = Process::run($this->getCommand(), $this->handleOutput(...));
$processResult = Process::timeout(TIMEOUT)->idleTimeout(IDLE_TIMEOUT)->run($this->getCommand(), $this->handleOutput(...));
if ($this->activity->properties->get('status') === ProcessStatus::ERROR->value) {
$status = ProcessStatus::ERROR;
} else {
if (($processResult->exitCode() == 0 && $this->isFinished) || $this->activity->properties->get('status') === ProcessStatus::FINISHED->value) {
if (($processResult->exitCode() == 0 && $this->is_finished) || $this->activity->properties->get('status') === ProcessStatus::FINISHED->value) {
$status = ProcessStatus::FINISHED;
}
if ($processResult->exitCode() != 0 && !$this->ignoreErrors) {
if ($processResult->exitCode() != 0 && !$this->ignore_errors) {
$status = ProcessStatus::ERROR;
}
}
@ -73,7 +76,7 @@ public function __invoke(): ProcessResult
]);
$this->activity->save();
if ($processResult->exitCode() != 0 && !$this->ignoreErrors) {
if ($processResult->exitCode() != 0 && !$this->ignore_errors) {
throw new \RuntimeException($processResult->errorOutput());
}
@ -97,22 +100,22 @@ protected function getCommand(): string
$port = $this->activity->getExtraProperty('port');
$command = $this->activity->getExtraProperty('command');
return generateSshCommand($private_key_location, $server_ip, $user, $port, $command);
return generate_ssh_command($private_key_location, $server_ip, $user, $port, $command);
}
protected function handleOutput(string $type, string $output)
{
if ($this->hideFromOutput) {
if ($this->hide_from_output) {
return;
}
$this->currentTime = $this->elapsedTime();
$this->current_time = $this->elapsedTime();
$this->activity->description = $this->encodeOutput($type, $output);
if ($this->isAfterLastThrottle()) {
// Let's write to database.
DB::transaction(function () {
$this->activity->save();
$this->lastWriteAt = $this->currentTime;
$this->last_write_at = $this->current_time;
});
}
}
@ -125,7 +128,7 @@ public function encodeOutput($type, $output)
'type' => $type,
'output' => $output,
'timestamp' => hrtime(true),
'batch' => DeployApplicationJob::$batch_counter,
'batch' => ApplicationDeploymentJob::$batch_counter,
'order' => $this->getLatestCounter(),
];
@ -162,16 +165,16 @@ public static function decodeOutput(?Activity $activity = null): string
protected function isAfterLastThrottle()
{
// If DB was never written, then we immediately decide we have to write.
if ($this->lastWriteAt === 0) {
if ($this->last_write_at === 0) {
return true;
}
return ($this->currentTime - $this->throttleIntervalMS) > $this->lastWriteAt;
return ($this->current_time - $this->throttle_interval_ms) > $this->last_write_at;
}
protected function elapsedTime(): int
{
$timeMs = (hrtime(true) - $this->timeStart) / 1_000_000;
$timeMs = (hrtime(true) - $this->time_start) / 1_000_000;
return intval($timeMs);
}

View File

@ -23,7 +23,7 @@ class CreateNewUser implements CreatesNewUsers
*/
public function create(array $input): User
{
$settings = InstanceSettings::find(0);
$settings = InstanceSettings::get();
if (!$settings->is_registration_enabled) {
Log::info('Registration is disabled');
abort(403);

View File

@ -0,0 +1,33 @@
<?php
namespace App\Actions\Proxy;
use App\Enums\ProxyTypes;
use App\Models\Server;
use Illuminate\Support\Str;
class CheckProxySettingsInSync
{
public function __invoke(Server $server, bool $reset = false)
{
$proxy_path = config('coolify.proxy_config_path');
$output = instant_remote_process([
"cat $proxy_path/docker-compose.yml",
], $server, false);
if (is_null($output) || $reset) {
$final_output = Str::of(getProxyConfiguration($server))->trim()->value;
} else {
$final_output = Str::of($output)->trim()->value;
}
$docker_compose_yml_base64 = base64_encode($final_output);
$server->extra_attributes->proxy_last_saved_settings = Str::of($docker_compose_yml_base64)->pipe('md5')->value;
$server->save();
if (is_null($output) || $reset) {
instant_remote_process([
"mkdir -p $proxy_path",
"echo '$docker_compose_yml_base64' | base64 -d > $proxy_path/docker-compose.yml",
], $server);
}
return $final_output;
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Actions\Proxy;
use App\Models\Server;
use Spatie\Activitylog\Models\Activity;
use Illuminate\Support\Str;
class InstallProxy
{
public function __invoke(Server $server): Activity
{
$proxy_path = config('coolify.proxy_config_path');
$networks = collect($server->standaloneDockers)->map(function ($docker) {
return $docker['network'];
})->unique();
if ($networks->count() === 0) {
$networks = collect(['coolify']);
}
$create_networks_command = $networks->map(function ($network) {
return "docker network ls --format '{{.Name}}' | grep '^$network$' >/dev/null 2>&1 || docker network create --attachable $network > /dev/null 2>&1";
});
$configuration = instant_remote_process([
"cat $proxy_path/docker-compose.yml",
], $server, false);
if (is_null($configuration)) {
$configuration = Str::of(getProxyConfiguration($server))->trim()->value;
} else {
$configuration = Str::of($configuration)->trim()->value;
}
$docker_compose_yml_base64 = base64_encode($configuration);
$server->extra_attributes->proxy_last_applied_settings = Str::of($docker_compose_yml_base64)->pipe('md5')->value;
$server->save();
$activity = remote_process([
"echo 'Creating required Docker networks...'",
...$create_networks_command,
"mkdir -p $proxy_path",
"cd $proxy_path",
"echo '$docker_compose_yml_base64' | base64 -d > $proxy_path/docker-compose.yml",
"echo 'Creating Docker Compose file...'",
"echo 'Pulling docker image...'",
'docker compose pull -q',
"echo 'Stopping old proxy...'",
'docker compose down -v --remove-orphans',
"echo 'Starting new proxy...'",
'docker compose up -d --remove-orphans',
"echo 'Proxy installed successfully...'"
], $server);
return $activity;
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace App\Actions\Server;
use App\Enums\ActivityTypes;
use App\Models\Server;
class InstallDocker
{
public function __invoke(Server $server)
{
$config = base64_encode('{ "live-restore": true }');
$activity = remote_process([
"echo Installing Docker...",
"curl https://releases.rancher.com/install-docker/23.0.sh | sh",
"echo Configuring Docker...",
"echo '{$config}' | base64 -d > /etc/docker/daemon.json",
"echo Restarting Docker...",
"systemctl restart docker"
], $server);
return $activity;
}
}

View File

@ -0,0 +1,75 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use function Termwind\ask;
use function Termwind\render;
use function Termwind\style;
class NotifyDemo extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:demo-notify {channel?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send a demo notification, to a given channel. Run to see options.';
/**
* Execute the console command.
*/
public function handle()
{
$channel = $this->argument('channel');
if (blank($channel)) {
$this->showHelp();
return;
}
ray($channel);
}
private function showHelp()
{
style('coolify')->color('#9333EA');
style('title-box')->apply('mt-1 px-2 py-1 bg-coolify');
render(<<<'HTML'
<div>
<div class="title-box">
Coolify
</div>
<p class="ml-1 mt-1 ">
Demo Notify <strong class="text-coolify">=></strong> Send a demo notification to a given channel.
</p>
<p class="ml-1 mt-1 bg-coolify px-1">
php artisan app:demo-notify {channel}
</p>
<div class="my-1">
<div class="text-yellow-500"> Channels: </div>
<ul class="text-coolify">
<li>email</li>
<li>slack</li>
<li>discord</li>
<li>telegram</li>
</ul>
</div>
</div>
HTML);
ask(<<<'HTML'
<div class="mr-1">
In which manner you wish a <strong class="text-coolify">coolified</strong> notification?
</div>
HTML, ['email', 'slack', 'discord', 'telegram']);
}
}

View File

@ -28,17 +28,21 @@ class SyncBunny extends Command
*/
public function handle()
{
$bunny_cdn = "https://coolify-cdn.b-cdn.net/";
$bunny_cdn_path = "files";
$bunny_cdn_storage_name = "coolify-cdn";
$bunny_cdn = "https://cdn.coollabs.io";
$bunny_cdn_path = "coolify";
$bunny_cdn_storage_name = "coolcdn";
$parent_dir = realpath(dirname(__FILE__) . '/../../..');
$compose_file = "docker-compose.yml";
$compose_file_prod = "docker-compose.prod.yml";
$install_script = "install.sh";
$upgrade_script = "upgrade.sh";
$docker_install_script = "install-docker.sh";
$production_env = ".env.production";
$versions = "versions.json";
PendingRequest::macro('storage', function ($file) {
$headers = [
'AccessKey' => env('BUNNY_STORAGE_API_KEY'),
@ -49,28 +53,39 @@ public function handle()
$file = fread($fileStream, filesize($file));
return PendingRequest::baseUrl('https://storage.bunnycdn.com')->withHeaders($headers)->withBody($file)->throw();
});
PendingRequest::macro('purge', function ($url) {
$headers = [
'AccessKey' => env('BUNNY_API_KEY'),
'Accept' => 'application/json',
];
ray('Purging: ' . $url);
return PendingRequest::withHeaders($headers)->get('https://api.bunny.net/purge', [
"url" => $url,
"async" => false
]);
});
try {
Http::pool(fn (Pool $pool) => [
$pool->storage(file: "$parent_dir/$compose_file")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$compose_file"),
$pool->storage(file: "$parent_dir/$compose_file_prod")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$compose_file_prod"),
$pool->storage(file: "$parent_dir/scripts/$upgrade_script")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$upgrade_script"),
$pool->storage(file: "$parent_dir/$production_env")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$production_env"),
$pool->storage(file: "$parent_dir/scripts/$upgrade_script")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$upgrade_script"),
$pool->storage(file: "$parent_dir/scripts/$install_script")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$install_script"),
$pool->storage(file: "$parent_dir/scripts/$docker_install_script")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$docker_install_script"),
$pool->storage(file: "$parent_dir/$versions")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$versions"),
]);
$res = Http::withHeaders([
'AccessKey' => env('BUNNY_API_KEY'),
'Accept' => 'application/json',
])->get('https://api.bunny.net/purge', [
"url" => "$bunny_cdn/$bunny_cdn_path/$compose_file",
"url" => "$bunny_cdn/$bunny_cdn_path/$compose_file_prod",
"url" => "$bunny_cdn/$bunny_cdn_path/$upgrade_script",
"url" => "$bunny_cdn/$bunny_cdn_path/$production_env"
ray("{$bunny_cdn}/{$bunny_cdn_path}");
Http::pool(fn (Pool $pool) => [
$pool->purge("$bunny_cdn/$bunny_cdn_path/$compose_file"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$compose_file_prod"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$production_env"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$upgrade_script"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$install_script"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$docker_install_script"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$versions"),
]);
if ($res->ok()) {
echo "All files uploaded & purged...\n";
}
echo "All files uploaded & purged...\n";
} catch (\Exception $e) {
echo "Something went wrong.\n";
echo $e->getMessage();
}
}

View File

@ -2,25 +2,26 @@
namespace App\Console;
use App\Jobs\ContainerStatusJob;
use App\Jobs\DockerCleanupDanglingImagesJob;
use App\Jobs\InstanceAutoUpdateJob;
use App\Jobs\InstanceProxyCheckJob;
use App\Jobs\InstanceDockerCleanupJob;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
$schedule->job(new ContainerStatusJob)->everyMinute();
$schedule->job(new DockerCleanupDanglingImagesJob)->everyMinute();
if (config('app.env') === 'local') {
$schedule->command('horizon:snapshot')->everyMinute();
$schedule->job(new InstanceDockerCleanupJob)->everyMinute();
$schedule->job(new InstanceAutoUpdateJob(true))->everyMinute();
} else {
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->job(new InstanceDockerCleanupJob)->everyFiveMinutes();
$schedule->job(new InstanceAutoUpdateJob)->everyFifteenMinutes();
}
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__ . '/Commands');

View File

@ -0,0 +1,27 @@
<?php
namespace App\Data;
use App\Enums\ProcessStatus;
use Illuminate\Database\Eloquent\Model;
use Spatie\LaravelData\Data;
/**
* The parameters to execute a CoolifyTask, organized in a DTO.
*/
class CoolifyTaskArgs extends Data
{
public function __construct(
public string $server_ip,
public string $private_key_location,
public string $command,
public int $port,
public string $user,
public string $type,
public ?string $type_uuid = null,
public ?Model $model = null,
public string $status = ProcessStatus::QUEUED->value,
public bool $ignore_errors = false,
) {
}
}

View File

@ -1,24 +0,0 @@
<?php
namespace App\Data;
use App\Enums\ActivityTypes;
use App\Enums\ProcessStatus;
use Illuminate\Database\Eloquent\Model;
use Spatie\LaravelData\Data;
class RemoteProcessArgs extends Data
{
public function __construct(
public string $server_ip,
public string $private_key_location,
public string|null $deployment_uuid,
public string $command,
public int $port,
public string $user,
public string $type = ActivityTypes::REMOTE_PROCESS->value,
public string $status = ProcessStatus::HOLDING->value,
public ?Model $model = null,
) {
}
}

View File

@ -0,0 +1,16 @@
<?php
namespace App\Data;
use App\Enums\ProxyStatus;
use App\Enums\ProxyTypes;
use Spatie\LaravelData\Data;
class ServerMetadata extends Data
{
public function __construct(
public ?ProxyTypes $proxy_type,
public ?ProxyStatus $proxy_status
) {
}
}

View File

@ -4,6 +4,6 @@
enum ActivityTypes: string
{
case REMOTE_PROCESS = 'remote_process';
case INLINE = 'inline';
case DEPLOYMENT = 'deployment';
}

View File

@ -4,8 +4,9 @@
enum ProcessStatus: string
{
case HOLDING = 'holding';
case QUEUED = 'queued';
case IN_PROGRESS = 'in_progress';
case FINISHED = 'finished';
case ERROR = 'error';
case CANCELLED = 'cancelled';
}

15
app/Enums/ProxyTypes.php Normal file
View File

@ -0,0 +1,15 @@
<?php
namespace App\Enums;
enum ProxyTypes: string
{
case TRAEFIK_V2 = 'TRAEFIK_V2';
case NGINX = 'NGINX';
case CADDY = 'CADDY';
}
enum ProxyStatus: string
{
case EXITED = 'exited';
case RUNNING = 'running';
}

View File

@ -4,6 +4,7 @@
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
use Sentry\Laravel\Integration;
class Handler extends ExceptionHandler
{
@ -42,7 +43,7 @@ class Handler extends ExceptionHandler
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
Integration::captureUnhandledException($e);
});
}
}

View File

@ -2,11 +2,15 @@
namespace App\Http\Controllers;
use App\Models\ApplicationDeploymentQueue;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\Request;
use Spatie\Activitylog\Models\Activity;
class ApplicationController extends Controller
{
use AuthorizesRequests, ValidatesRequests;
public function configuration()
{
$project = session('currentTeam')->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first();
@ -37,7 +41,7 @@ public function deployments()
if (!$application) {
return redirect()->route('dashboard');
}
return view('project.application.deployments', ['application' => $application, 'deployments' => $application->deployments()]);
return view('project.application.deployments', ['application' => $application]);
}
public function deployment()
@ -56,11 +60,26 @@ public function deployment()
if (!$application) {
return redirect()->route('dashboard');
}
$activity = Activity::where('properties->deployment_uuid', '=', $deployment_uuid)->first();
$activity = Activity::where('properties->type_uuid', '=', $deployment_uuid)->first();
if (!$activity) {
return redirect()->route('project.application.deployments', [
'project_uuid' => $project->uuid,
'environment_name' => $environment->name,
'application_uuid' => $application->uuid,
]);
}
$deployment = ApplicationDeploymentQueue::where('deployment_uuid', $deployment_uuid)->first();
if (!$deployment) {
return redirect()->route('project.application.deployments', [
'project_uuid' => $project->uuid,
'environment_name' => $environment->name,
'application_uuid' => $application->uuid,
]);
}
return view('project.application.deployment', [
'application' => $application,
'activity' => $activity,
'deployment' => $deployment,
'deployment_uuid' => $deployment_uuid,
]);
}

View File

@ -2,6 +2,9 @@
namespace App\Http\Controllers;
use App\Models\InstanceSettings;
use App\Models\Project;
use App\Models\Server;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
@ -9,4 +12,32 @@
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
public function dashboard()
{
$projects = Project::ownedByCurrentTeam()->get();
$servers = Server::ownedByCurrentTeam()->get();
$resources = 0;
foreach ($projects as $project) {
$resources += $project->applications->count();
}
return view('dashboard', [
'servers' => $servers->count(),
'projects' => $projects->count(),
'resources' => $resources,
]);
}
public function settings()
{
if (auth()->user()->isAdmin()) {
$settings = InstanceSettings::get();
return view('settings', [
'settings' => $settings
]);
} else {
return redirect()->route('dashboard');
}
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Http\Controllers;
use App\Http\Livewire\Server\PrivateKey;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Server;
class MagicController extends Controller
{
public function servers()
{
return response()->json([
'servers' => Server::validated()->get()
]);
}
public function destinations()
{
return response()->json([
'destinations' => Server::destinationsByServer(request()->query('server_id'))->sortBy('name')
]);
}
public function projects()
{
return response()->json([
'projects' => Project::ownedByCurrentTeam()->get()
]);
}
public function environments()
{
return response()->json([
'environments' => Project::ownedByCurrentTeam()->whereUuid(request()->query('project_uuid'))->first()->environments
]);
}
public function new_project()
{
$project = Project::firstOrCreate(
['name' => request()->query('name') ?? generate_random_name()],
['team_id' => session('currentTeam')->id]
);
ray($project);
return response()->json([
'project_uuid' => $project->uuid
]);
}
public function new_environment()
{
$environment = Environment::firstOrCreate(
['name' => request()->query('name') ?? generate_random_name()],
['project_id' => Project::ownedByCurrentTeam()->whereUuid(request()->query('project_uuid'))->firstOrFail()->id]
);
return response()->json([
'environment_name' => $environment->name,
]);
}
}

View File

@ -2,13 +2,24 @@
namespace App\Http\Controllers;
use Spatie\Activitylog\Models\Activity;
use App\Models\Project;
class ProjectController extends Controller
{
public function environments()
public function all()
{
$project = session('currentTeam')->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first();
$team_id = session('currentTeam')->id;
$projects = Project::where('team_id', $team_id)->get();
return view('projects', ['projects' => $projects]);
}
public function show()
{
$project_uuid = request()->route('project_uuid');
$team_id = session('currentTeam')->id;
$project = Project::where('team_id', $team_id)->where('uuid', $project_uuid)->first();
if (!$project) {
return redirect()->route('dashboard');
}
@ -16,10 +27,10 @@ public function environments()
if (count($project->environments) == 1) {
return redirect()->route('project.resources', ['project_uuid' => $project->uuid, 'environment_name' => $project->environments->first()->name]);
}
return view('project.environments', ['project' => $project]);
return view('project.show', ['project' => $project]);
}
public function resources_new()
public function new()
{
$project = session('currentTeam')->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first();
if (!$project) {
@ -29,7 +40,12 @@ public function resources_new()
if (!$environment) {
return redirect()->route('dashboard');
}
return view('project.new', ['project' => $project, 'environment' => $environment, 'type' => 'resource']);
$type = request()->query('type');
return view('project.new', [
'type' => $type
]);
}
public function resources()
{
@ -41,64 +57,9 @@ public function resources()
if (!$environment) {
return redirect()->route('dashboard');
}
return view('project.resources', ['project' => $project, 'environment' => $environment]);
}
public function application_configuration()
{
$project = session('currentTeam')->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first();
if (!$project) {
return redirect()->route('dashboard');
}
$environment = $project->load(['environments'])->environments->where('name', request()->route('environment_name'))->first()->load(['applications']);
if (!$environment) {
return redirect()->route('dashboard');
}
$application = $environment->applications->where('uuid', request()->route('application_uuid'))->first();
if (!$application) {
return redirect()->route('dashboard');
}
return view('project.application.configuration', ['application' => $application]);
}
public function application_deployments()
{
$project = session('currentTeam')->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first();
if (!$project) {
return redirect()->route('dashboard');
}
$environment = $project->load(['environments'])->environments->where('name', request()->route('environment_name'))->first()->load(['applications']);
if (!$environment) {
return redirect()->route('dashboard');
}
$application = $environment->applications->where('uuid', request()->route('application_uuid'))->first();
if (!$application) {
return redirect()->route('dashboard');
}
return view('project.application.deployments', ['application' => $application, 'deployments' => $application->deployments()]);
}
public function application_deployment()
{
$deployment_uuid = request()->route('deployment_uuid');
$project = session('currentTeam')->load(['projects'])->projects->where('uuid', request()->route('project_uuid'))->first();
if (!$project) {
return redirect()->route('dashboard');
}
$environment = $project->load(['environments'])->environments->where('name', request()->route('environment_name'))->first()->load(['applications']);
if (!$environment) {
return redirect()->route('dashboard');
}
$application = $environment->applications->where('uuid', request()->route('application_uuid'))->first();
if (!$application) {
return redirect()->route('dashboard');
}
$activity = Activity::where('properties->deployment_uuid', '=', $deployment_uuid)->first();
return view('project.application.deployment', [
'application' => $application,
'activity' => $activity,
'deployment_uuid' => $deployment_uuid,
return view('project.resources', [
'project' => $project,
'environment' => $environment
]);
}
}

View File

@ -0,0 +1,34 @@
<?php
namespace App\Http\Controllers;
use App\Models\PrivateKey;
use App\Models\Server;
class ServerController extends Controller
{
public function all()
{
return view('server.all', [
'servers' => Server::ownedByCurrentTeam()->get()
]);
}
public function create()
{
return view('server.create', [
'private_keys' => PrivateKey::ownedByCurrentTeam()->get(),
]);
}
public function show()
{
return view('server.show', [
'server' => Server::ownedByCurrentTeam()->whereUuid(request()->server_uuid)->firstOrFail(),
]);
}
public function proxy()
{
return view('server.proxy', [
'server' => Server::ownedByCurrentTeam()->whereUuid(request()->server_uuid)->firstOrFail(),
]);
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace App\Http\Livewire;
use App\Enums\ProcessStatus;
use Livewire\Component;
use Spatie\Activitylog\Models\Activity;
class ActivityMonitor extends Component
{
public bool $header = false;
public $activityId;
public $isPollingActive = false;
protected $activity;
protected $listeners = ['newMonitorActivity'];
public function hydrateActivity()
{
$this->activity = Activity::query()
->find($this->activityId);
}
public function newMonitorActivity($activityId)
{
$this->activityId = $activityId;
$this->hydrateActivity();
$this->isPollingActive = true;
}
public function polling()
{
$this->hydrateActivity();
$this->setStatus(ProcessStatus::IN_PROGRESS);
$exit_code = data_get($this->activity, 'properties.exitCode');
if ($exit_code !== null) {
if ($exit_code === 0) {
$this->setStatus(ProcessStatus::FINISHED);
} else {
$this->setStatus(ProcessStatus::ERROR);
}
$this->isPollingActive = false;
}
}
protected function setStatus($status)
{
$this->activity->properties = $this->activity->properties->merge([
'status' => $status,
]);
$this->activity->save();
}
}

View File

@ -2,8 +2,6 @@
namespace App\Http\Livewire;
use App\Models\Server;
use Illuminate\Support\Facades\Http;
use Livewire\Component;
class CheckUpdate extends Component
@ -15,8 +13,8 @@ class CheckUpdate extends Component
public function checkUpdate()
{
$this->latestVersion = getLatestVersionOfCoolify();
$this->currentVersion = config('coolify.version');
$this->latestVersion = get_latest_version_of_coolify();
$this->currentVersion = config('version');
if ($this->latestVersion === 'latest') {
$this->updateAvailable = true;
return;

View File

@ -0,0 +1,37 @@
<?php
namespace App\Http\Livewire\Destination;
use Livewire\Component;
class Form extends Component
{
public mixed $destination;
protected $rules = [
'destination.name' => 'required',
'destination.network' => 'required',
'destination.server.ip' => 'required',
];
public function submit()
{
$this->validate();
$this->destination->save();
}
public function delete()
{
try {
if ($this->destination->getMorphClass() === 'App\Models\StandaloneDocker') {
if ($this->destination->attachedTo()) {
return $this->emit('error', 'You must delete all resources before deleting this destination.');
}
instant_remote_process(["docker network disconnect {$this->destination->network} coolify-proxy"], $this->destination->server, throwError: false);
instant_remote_process(['docker network rm -f ' . $this->destination->network], $this->destination->server);
}
$this->destination->delete();
return redirect()->route('dashboard');
} catch (\Exception $e) {
return general_error_handler($e);
}
}
}

View File

@ -4,14 +4,16 @@
use App\Models\Server;
use App\Models\StandaloneDocker as ModelsStandaloneDocker;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
class StandaloneDocker extends Component
{
public string $name;
public string $network;
public $servers;
public Collection $servers;
public int|null $server_id = null;
protected $rules = [
@ -21,13 +23,19 @@ class StandaloneDocker extends Component
];
public function mount()
{
$this->name = generateRandomName();
$this->servers = Server::where('team_id', session('currentTeam')->id)->get();
}
public function setServerId($server_id)
{
$this->server_id = $server_id;
if (!$this->server_id) {
if (request()->query('server_id')) {
$this->server_id = request()->query('server_id');
} else {
if ($this->servers->count() > 0) {
$this->server_id = $this->servers->first()->id;
}
}
}
$this->network = new Cuid2(7);
$this->name = generate_random_name();
}
public function submit()
{
$this->validate();
@ -36,6 +44,10 @@ public function submit()
$this->addError('network', 'Network already added to this server.');
return;
}
$server = Server::find($this->server_id);
instant_remote_process(['docker network create --attachable ' . $this->network], $server, throwError: false);
instant_remote_process(["docker network connect $this->network coolify-proxy"], $server, throwError: false);
$docker = ModelsStandaloneDocker::create([
'name' => $this->name,
'network' => $this->network,
@ -43,9 +55,7 @@ public function submit()
'team_id' => session('currentTeam')->id
]);
$server = Server::find($this->server_id);
runRemoteCommandSync($server, ['docker network create --attachable ' . $this->network], throwError: false);
return redirect()->route('destination.show', $docker->uuid);
}
}

View File

@ -2,50 +2,19 @@
namespace App\Http\Livewire;
use App\Models\Server;
use Illuminate\Support\Facades\Http;
use App\Jobs\InstanceAutoUpdateJob;
use Livewire\Component;
class ForceUpgrade extends Component
{
public bool $visible = false;
public function upgrade()
{
if (env('APP_ENV') === 'local') {
$server = Server::where('ip', 'coolify-testing-host')->first();
if (!$server) {
return;
}
runRemoteCommandSync($server, [
"sleep 2"
]);
remoteProcess([
"sleep 10"
], $server);
$this->emit('updateInitiated');
} else {
$latestVersion = getLatestVersionOfCoolify();
$cdn = "https://coolify-cdn.b-cdn.net/files";
$server = Server::where('ip', 'host.docker.internal')->first();
if (!$server) {
return;
}
runRemoteCommandSync($server, [
"curl -fsSL $cdn/docker-compose.yml -o /data/coolify/source/docker-compose.yml",
"curl -fsSL $cdn/docker-compose.prod.yml -o /data/coolify/source/docker-compose.prod.yml",
"curl -fsSL $cdn/.env.production -o /data/coolify/source/.env.production",
"curl -fsSL $cdn/upgrade.sh -o /data/coolify/source/upgrade.sh",
]);
runRemoteCommandSync($server, [
"docker compose -f /data/coolify/source/docker-compose.yml -f /data/coolify/source/docker-compose.prod.yml pull",
]);
remoteProcess([
"bash /data/coolify/source/upgrade.sh $latestVersion"
], $server);
$this->emit('updateInitiated');
try {
$this->visible = true;
dispatch(new InstanceAutoUpdateJob(force: true));
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Http\Livewire\Notifications;
use App\Models\Server;
use App\Models\Team;
use App\Notifications\TestNotification;
use Illuminate\Support\Facades\Notification;
use Livewire\Component;
class DiscordSettings extends Component
{
public Team $model;
protected $rules = [
'model.extra_attributes.discord_active' => 'nullable|boolean',
'model.extra_attributes.discord_webhook' => 'required|url',
];
protected $validationAttributes = [
'model.extra_attributes.discord_webhook' => 'Discord Webhook',
];
public function instantSave()
{
try {
$this->submit();
} catch (\Exception $e) {
$this->model->extra_attributes->discord_active = false;
$this->validate();
}
}
private function saveModel()
{
$this->model->save();
if (is_a($this->model, Team::class)) {
session(['currentTeam' => $this->model]);
}
}
public function submit()
{
$this->resetErrorBag();
$this->validate();
$this->saveModel();
}
public function sendTestNotification()
{
Notification::send($this->model, new TestNotification);
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace App\Http\Livewire\Notifications;
use App\Models\InstanceSettings;
use App\Models\Team;
use App\Notifications\TestNotification;
use Illuminate\Support\Facades\Notification;
use Livewire\Component;
class EmailSettings extends Component
{
public Team $model;
protected $rules = [
'model.extra_attributes.smtp_active' => 'nullable|boolean',
'model.extra_attributes.smtp_from_address' => 'required|email',
'model.extra_attributes.smtp_from_name' => 'required',
'model.extra_attributes.smtp_recipients' => 'required',
'model.extra_attributes.smtp_host' => 'required',
'model.extra_attributes.smtp_port' => 'required',
'model.extra_attributes.smtp_encryption' => 'nullable',
'model.extra_attributes.smtp_username' => 'nullable',
'model.extra_attributes.smtp_password' => 'nullable',
'model.extra_attributes.smtp_timeout' => 'nullable',
'model.extra_attributes.smtp_test_recipients' => 'nullable',
];
protected $validationAttributes = [
'model.extra_attributes.smtp_from_address' => '',
'model.extra_attributes.smtp_from_name' => '',
'model.extra_attributes.smtp_recipients' => '',
'model.extra_attributes.smtp_host' => '',
'model.extra_attributes.smtp_port' => '',
'model.extra_attributes.smtp_encryption' => '',
'model.extra_attributes.smtp_username' => '',
'model.extra_attributes.smtp_password' => '',
'model.extra_attributes.smtp_test_recipients' => '',
];
public function copySMTP()
{
$settings = InstanceSettings::get();
$this->model->extra_attributes->smtp_active = true;
$this->model->extra_attributes->smtp_from_address = $settings->extra_attributes->smtp_from_address;
$this->model->extra_attributes->smtp_from_name = $settings->extra_attributes->smtp_from_name;
$this->model->extra_attributes->smtp_recipients = $settings->extra_attributes->smtp_recipients;
$this->model->extra_attributes->smtp_host = $settings->extra_attributes->smtp_host;
$this->model->extra_attributes->smtp_port = $settings->extra_attributes->smtp_port;
$this->model->extra_attributes->smtp_encryption = $settings->extra_attributes->smtp_encryption;
$this->model->extra_attributes->smtp_username = $settings->extra_attributes->smtp_username;
$this->model->extra_attributes->smtp_password = $settings->extra_attributes->smtp_password;
$this->model->extra_attributes->smtp_timeout = $settings->extra_attributes->smtp_timeout;
$this->model->extra_attributes->smtp_test_recipients = $settings->extra_attributes->smtp_test_recipients;
$this->saveModel();
}
public function submit()
{
$this->resetErrorBag();
$this->validate();
$this->model->extra_attributes->smtp_recipients = str_replace(' ', '', $this->model->extra_attributes->smtp_recipients);
$this->model->extra_attributes->smtp_test_recipients = str_replace(' ', '', $this->model->extra_attributes->smtp_test_recipients);
$this->saveModel();
}
private function saveModel()
{
$this->model->save();
if (is_a($this->model, Team::class)) {
session(['currentTeam' => $this->model]);
}
}
public function sendTestNotification()
{
Notification::send($this->model, new TestNotification);
}
public function instantSave()
{
try {
$this->submit();
} catch (\Exception $e) {
$this->model->extra_attributes->smtp_active = false;
$this->validate();
}
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Livewire\PrivateKey;
use App\Models\PrivateKey;
use Livewire\Component;
class Change extends Component
{
public string $private_key_uuid;
public PrivateKey $private_key;
protected $rules = [
'private_key.name' => 'required|string',
'private_key.description' => 'nullable|string',
'private_key.private_key' => 'required|string'
];
public function mount()
{
$this->private_key = PrivateKey::where('uuid', $this->private_key_uuid)->first();
}
public function delete()
{
PrivateKey::where('uuid', $this->private_key_uuid)->delete();
session('currentTeam')->privateKeys = PrivateKey::where('team_id', session('currentTeam')->id)->get();
redirect()->route('dashboard');
}
public function changePrivateKey()
{
try {
$this->private_key->private_key = trim($this->private_key->private_key);
if (!str_ends_with($this->private_key->private_key, "\n")) {
$this->private_key->private_key .= "\n";
}
$this->private_key->save();
session('currentTeam')->privateKeys = PrivateKey::where('team_id', session('currentTeam')->id)->get();
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Http\Livewire\PrivateKey;
use App\Models\PrivateKey;
use Livewire\Component;
class Create extends Component
{
protected string|null $from = null;
public string $name;
public string|null $description = null;
public string $value;
protected $rules = [
'name' => 'required|string',
'value' => 'required|string',
];
protected $validationAttributes = [
'name' => 'Name',
'value' => 'Private Key',
];
public function createPrivateKey()
{
$this->validate();
try {
$this->value = trim($this->value);
if (!str_ends_with($this->value, "\n")) {
$this->value .= "\n";
}
$private_key = PrivateKey::create([
'name' => $this->name,
'description' => $this->description,
'private_key' => $this->value,
'team_id' => session('currentTeam')->id
]);
if ($this->from === 'server') {
return redirect()->route('server.create');
}
return redirect()->route('private-key.show', ['private_key_uuid' => $private_key->uuid]);
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace App\Http\Livewire\Profile;
use App\Models\User;
use Livewire\Component;
class Form extends Component
{
public int $userId;
public string $name;
public string $email;
protected $rules = [
'name' => 'required',
];
public function mount()
{
$this->userId = auth()->user()->id;
$this->name = auth()->user()->name;
$this->email = auth()->user()->email;
}
public function submit()
{
try {
$this->validate();
User::where('id', $this->userId)->update([
'name' => $this->name,
]);
} catch (\Throwable $error) {
return general_error_handler($error, $this);
}
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Livewire\Project\Application;
use App\Models\Application;
use Livewire\Component;
class Danger extends Component
{
public Application $application;
public array $parameters;
public function mount()
{
$this->parameters = get_parameters();
}
public function delete()
{
$destination = $this->application->destination->getMorphClass()::where('id', $this->application->destination->id)->first();
instant_remote_process(["docker rm -f {$this->application->uuid}"], $destination->server);
$this->application->delete();
return redirect()->route('project.resources', [
'project_uuid' => $this->parameters['project_uuid'],
'environment_name' => $this->parameters['environment_name']
]);
}
}

View File

@ -2,9 +2,8 @@
namespace App\Http\Livewire\Project\Application;
use App\Jobs\DeployApplicationJob;
use App\Jobs\ContainerStopJob;
use App\Models\Application;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
@ -21,67 +20,52 @@ class Deploy extends Component
protected array $command = [];
protected $source;
protected $listeners = [
'applicationStatusChanged',
];
public function mount()
{
$this->parameters = Route::current()->parameters();
$this->parameters = get_parameters();
$this->application = Application::where('id', $this->applicationId)->first();
$this->destination = $this->application->destination->getMorphClass()::where('id', $this->application->destination->id)->first();
}
protected function setDeploymentUuid()
public function applicationStatusChanged()
{
$this->application->refresh();
}
protected function set_deployment_uuid()
{
// Create Deployment ID
$this->deployment_uuid = new Cuid2(7);
$this->parameters['deployment_uuid'] = $this->deployment_uuid;
}
protected function redirectToDeployment()
public function deploy(bool $force = false, bool|null $debug = null)
{
return redirect()->route('project.application.deployment', $this->parameters);
}
public function start()
{
$this->setDeploymentUuid();
if ($debug && !$this->application->settings->is_debug_enabled) {
$this->application->settings->is_debug_enabled = true;
$this->application->settings->save();
}
$this->set_deployment_uuid();
dispatch(new DeployApplicationJob(
queue_application_deployment(
application_id: $this->application->id,
deployment_uuid: $this->deployment_uuid,
application_uuid: $this->application->uuid,
force_rebuild: false,
));
return $this->redirectToDeployment();
}
public function forceRebuild()
{
$this->setDeploymentUuid();
dispatch(new DeployApplicationJob(
deployment_uuid: $this->deployment_uuid,
application_uuid: $this->application->uuid,
force_rebuild: true,
));
return $this->redirectToDeployment();
}
public function delete()
{
$this->stop();
Application::find($this->applicationId)->delete();
return redirect()->route('project.resources', [
force_rebuild: $force,
);
return redirect()->route('project.application.deployment', [
'project_uuid' => $this->parameters['project_uuid'],
'environment_name' => $this->parameters['environment_name']
'application_uuid' => $this->parameters['application_uuid'],
'deployment_uuid' => $this->deployment_uuid,
'environment_name' => $this->parameters['environment_name'],
]);
}
public function stop()
{
runRemoteCommandSync($this->destination->server, ["docker rm -f {$this->application->uuid}"]);
if ($this->application->status != 'exited') {
$this->application->status = 'exited';
$this->application->save();
}
}
public function pollingStatus()
{
$this->application->refresh();
instant_remote_process(["docker rm -f {$this->application->uuid}"], $this->application->destination->server);
$this->application->status = get_container_status(server: $this->application->destination->server, container_id: $this->application->uuid);
$this->application->save();
$this->emit('applicationStatusChanged');
}
}

View File

@ -2,25 +2,31 @@
namespace App\Http\Livewire\Project\Application;
use App\Enums\ActivityTypes;
use App\Models\Application;
use Illuminate\Support\Facades\Redis;
use Livewire\Component;
use Spatie\Activitylog\Models\Activity;
class PollDeployment extends Component
class DeploymentLogs extends Component
{
public Application $application;
public $activity;
public $isKeepAliveOn = true;
public $deployment_uuid;
public function polling()
{
if ( is_null($this->activity) && isset($this->deployment_uuid)) {
$this->activity = Activity::where('properties->deployment_uuid', '=', $this->deployment_uuid)
$this->emit('deploymentFinished');
if (is_null($this->activity) && isset($this->deployment_uuid)) {
$this->activity = Activity::query()
->where('properties->type', '=', ActivityTypes::DEPLOYMENT->value)
->where('properties->type_uuid', '=', $this->deployment_uuid)
->first();
} else {
$this->activity?->refresh();
}
if (data_get($this->activity, 'properties.status') == 'finished' || data_get($this->activity, 'properties.status') == 'failed' ) {
if (data_get($this->activity, 'properties.status') == 'finished' || data_get($this->activity, 'properties.status') == 'failed') {
$this->isKeepAliveOn = false;
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Http\Livewire\Project\Application;
use App\Enums\ProcessStatus;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use Livewire\Component;
class DeploymentNavbar extends Component
{
public Application $application;
public $activity;
public string $deployment_uuid;
protected $listeners = ['deploymentFinished'];
public function deploymentFinished()
{
$this->activity->refresh();
}
public function cancel()
{
try {
ray('Cancelling deployment: ' . $this->deployment_uuid . ' of application: ' . $this->application->uuid);
// Update deployment queue
$deployment = ApplicationDeploymentQueue::where('deployment_uuid', $this->deployment_uuid)->first();
$deployment->status = 'cancelled by user';
$deployment->save();
// Update activity
$this->activity->properties = $this->activity->properties->merge([
'exitCode' => 1,
'status' => ProcessStatus::CANCELLED->value,
]);
$this->activity->save();
// Remove builder container
instant_remote_process(["docker rm -f {$this->deployment_uuid}"], $this->application->destination->server, throwError: false, repeat: 25);
queue_next_deployment($this->application);
} catch (\Throwable $th) {
return general_error_handler($th, $this);
}
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace App\Http\Livewire\Project\Application;
use App\Models\Application;
use Livewire\Component;
class Deployments extends Component
{
public int $application_id;
public $deployments = [];
public int $deployments_count = 0;
public string $current_url;
public int $skip = 0;
public int $default_take = 8;
public bool $show_next = false;
public function mount()
{
$this->current_url = url()->current();
}
public function reload_deployments()
{
$this->load_deployments();
}
public function load_deployments(int|null $take = null)
{
if ($take) {
$this->skip = $this->skip + $take;
}
$take = $this->default_take;
['deployments' => $deployments, 'count' => $count] = Application::find($this->application_id)->deployments($this->skip, $take);
$this->deployments = $deployments;
$this->deployments_count = $count;
if (count($this->deployments) !== 0) {
$this->show_next = true;
if (count($this->deployments) < $take) {
$this->show_next = false;
}
return;
}
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace App\Http\Livewire\Project\Application\EnvironmentVariable;
use Livewire\Component;
class Add extends Component
{
public $parameters;
public bool $is_preview = false;
public string $key;
public string $value;
public bool $is_build_time = false;
protected $listeners = ['clearAddEnv' => 'clear'];
protected $rules = [
'key' => 'required|string',
'value' => 'required|string',
'is_build_time' => 'required|boolean',
];
public function mount()
{
$this->parameters = get_parameters();
}
public function submit()
{
$this->validate();
$this->emitUp('submit', [
'key' => $this->key,
'value' => $this->value,
'is_build_time' => $this->is_build_time,
'is_preview' => $this->is_preview,
]);
}
public function clear()
{
$this->key = '';
$this->value = '';
$this->is_build_time = false;
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Http\Livewire\Project\Application\EnvironmentVariable;
use App\Models\Application;
use App\Models\EnvironmentVariable;
use Livewire\Component;
class All extends Component
{
public Application $application;
protected $listeners = ['refreshEnvs', 'submit'];
public function refreshEnvs()
{
$this->application->refresh();
}
public function submit($data)
{
try {
EnvironmentVariable::create([
'key' => $data['key'],
'value' => $data['value'],
'is_build_time' => $data['is_build_time'],
'is_preview' => $data['is_preview'],
'application_id' => $this->application->id,
]);
$this->application->refresh();
$this->emit('clearAddEnv');
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Http\Livewire\Project\Application\EnvironmentVariable;
use App\Models\EnvironmentVariable as ModelsEnvironmentVariable;
use Livewire\Component;
class Show extends Component
{
public $parameters;
public ModelsEnvironmentVariable $env;
protected $rules = [
'env.key' => 'required|string',
'env.value' => 'required|string',
'env.is_build_time' => 'required|boolean',
];
public function mount()
{
$this->parameters = get_parameters();
}
public function submit()
{
$this->validate();
$this->env->save();
}
public function delete()
{
$this->env->delete();
$this->emit('refreshEnvs');
}
}

View File

@ -1,10 +0,0 @@
<?php
namespace App\Http\Livewire\Project\Application;
use Livewire\Component;
class EnvironmentVariables extends Component
{
public array $envs = [];
}

View File

@ -3,7 +3,10 @@
namespace App\Http\Livewire\Project\Application;
use App\Models\Application;
use App\Models\InstanceSettings;
use Livewire\Component;
use Illuminate\Support\Str;
use Spatie\Url\Url;
class General extends Component
{
@ -16,16 +19,17 @@ class General extends Component
public string $git_branch;
public string|null $git_commit_sha;
public string $build_pack;
public string|null $wildcard_domain = null;
public string|null $project_wildcard_domain = null;
public string|null $global_wildcard_domain = null;
public bool $is_static;
public bool $is_git_submodules_allowed;
public bool $is_git_lfs_allowed;
public bool $is_debug;
public bool $is_previews;
public bool $is_custom_ssl;
public bool $is_http2;
public bool $is_auto_deploy;
public bool $is_dual_cert;
public bool $is_git_submodules_enabled;
public bool $is_git_lfs_enabled;
public bool $is_debug_enabled;
public bool $is_preview_deployments_enabled;
public bool $is_auto_deploy_enabled;
public bool $is_force_https_enabled;
protected $rules = [
'application.name' => 'required|min:6',
@ -33,6 +37,9 @@ class General extends Component
'application.git_repository' => 'required',
'application.git_branch' => 'required',
'application.git_commit_sha' => 'nullable',
'application.install_command' => 'nullable',
'application.build_command' => 'nullable',
'application.start_command' => 'nullable',
'application.build_pack' => 'required',
'application.static_image' => 'required',
'application.base_directory' => 'required',
@ -42,35 +49,70 @@ class General extends Component
];
public function instantSave()
{
// @TODO: find another way
// @TODO: find another way - if possible
$this->application->settings->is_static = $this->is_static;
$this->application->settings->is_git_submodules_allowed = $this->is_git_submodules_allowed;
$this->application->settings->is_git_lfs_allowed = $this->is_git_lfs_allowed;
$this->application->settings->is_debug = $this->is_debug;
$this->application->settings->is_previews = $this->is_previews;
$this->application->settings->is_custom_ssl = $this->is_custom_ssl;
$this->application->settings->is_http2 = $this->is_http2;
$this->application->settings->is_auto_deploy = $this->is_auto_deploy;
$this->application->settings->is_dual_cert = $this->is_dual_cert;
$this->application->settings->is_git_submodules_enabled = $this->is_git_submodules_enabled;
$this->application->settings->is_git_lfs_enabled = $this->is_git_lfs_enabled;
$this->application->settings->is_debug_enabled = $this->is_debug_enabled;
$this->application->settings->is_preview_deployments_enabled = $this->is_preview_deployments_enabled;
$this->application->settings->is_auto_deploy_enabled = $this->is_auto_deploy_enabled;
$this->application->settings->is_force_https_enabled = $this->is_force_https_enabled;
$this->application->settings->save();
$this->application->refresh();
$this->emit('saved', 'Application settings updated!');
$this->checkWildCardDomain();
}
protected function checkWildCardDomain()
{
$coolify_instance_settings = InstanceSettings::get();
$this->project_wildcard_domain = data_get($this->application, 'environment.project.settings.wildcard_domain');
$this->global_wildcard_domain = data_get($coolify_instance_settings, 'wildcard_domain');
$this->wildcard_domain = $this->project_wildcard_domain ?? $this->global_wildcard_domain ?? null;
}
public function mount()
{
$this->application = Application::where('id', $this->applicationId)->with('destination', 'settings')->firstOrFail();
$this->is_static = $this->application->settings->is_static;
$this->is_git_submodules_allowed = $this->application->settings->is_git_submodules_allowed;
$this->is_git_lfs_allowed = $this->application->settings->is_git_lfs_allowed;
$this->is_debug = $this->application->settings->is_debug;
$this->is_previews = $this->application->settings->is_previews;
$this->is_custom_ssl = $this->application->settings->is_custom_ssl;
$this->is_http2 = $this->application->settings->is_http2;
$this->is_auto_deploy = $this->application->settings->is_auto_deploy;
$this->is_dual_cert = $this->application->settings->is_dual_cert;
$this->is_git_submodules_enabled = $this->application->settings->is_git_submodules_enabled;
$this->is_git_lfs_enabled = $this->application->settings->is_git_lfs_enabled;
$this->is_debug_enabled = $this->application->settings->is_debug_enabled;
$this->is_preview_deployments_enabled = $this->application->settings->is_preview_deployments_enabled;
$this->is_auto_deploy_enabled = $this->application->settings->is_auto_deploy_enabled;
$this->is_force_https_enabled = $this->application->settings->is_force_https_enabled;
$this->checkWildCardDomain();
}
public function generateGlobalRandomDomain()
{
// Set wildcard domain based on Global wildcard domain
$url = Url::fromString($this->global_wildcard_domain);
$host = $url->getHost();
$path = $url->getPath() === '/' ? '' : $url->getPath();
$scheme = $url->getScheme();
$this->application->fqdn = $scheme . '://' . $this->application->uuid . '.' . $host . $path;
$this->application->save();
}
public function generateProjectRandomDomain()
{
// Set wildcard domain based on Project wildcard domain
$url = Url::fromString($this->project_wildcard_domain);
$host = $url->getHost();
$path = $url->getPath() === '/' ? '' : $url->getPath();
$scheme = $url->getScheme();
$this->application->fqdn = $scheme . '://' . $this->application->uuid . '.' . $host . $path;
$this->application->save();
}
public function submit()
{
$this->validate();
$this->application->save();
try {
$this->validate();
$domains = Str::of($this->application->fqdn)->trim()->explode(',')->map(function ($domain) {
return Str::of($domain)->trim()->lower();
});
$this->application->fqdn = $domains->implode(',');
$this->application->save();
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -1,19 +0,0 @@
<?php
namespace App\Http\Livewire\Project\Application;
use Livewire\Component;
use Spatie\Activitylog\Models\Activity;
class GetDeployments extends Component
{
public string $deployment_uuid;
public string $created_at;
public string $status;
public function polling()
{
$activity = Activity::where('properties->deployment_uuid', '=', $this->deployment_uuid)->first();
$this->created_at = $activity->created_at;
$this->status = data_get($activity, 'properties.status');
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace App\Http\Livewire\Project\Application\Preview;
use App\Models\Application;
use Illuminate\Support\Str;
use Livewire\Component;
use Spatie\Url\Url;
class Form extends Component
{
public Application $application;
public string $preview_url_template;
protected $rules = [
'application.preview_url_template' => 'required',
];
public function resetToDefault()
{
$this->application->preview_url_template = '{{pr_id}}.{{domain}}';
$this->preview_url_template = $this->application->preview_url_template;
$this->application->save();
$this->generate_real_url();
}
public function generate_real_url()
{
if (data_get($this->application, 'fqdn')) {
$url = Url::fromString($this->application->fqdn);
$host = $url->getHost();
$this->preview_url_template = Str::of($this->application->preview_url_template)->replace('{{domain}}', $host);
}
}
public function mount()
{
$this->generate_real_url();
}
public function submit()
{
$this->validate();
$this->application->preview_url_template = str_replace(' ', '', $this->application->preview_url_template);
$this->application->save();
$this->generate_real_url();
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace App\Http\Livewire\Project\Application;
use App\Jobs\ApplicationContainerStatusJob;
use App\Models\Application;
use App\Models\ApplicationPreview;
use Illuminate\Support\Collection;
use Livewire\Component;
use Visus\Cuid2\Cuid2;
class Previews extends Component
{
public Application $application;
public string $deployment_uuid;
public array $parameters;
public Collection $pull_requests;
public int $rate_limit_remaining;
public function mount()
{
$this->pull_requests = collect();
$this->parameters = get_parameters();
}
public function loadStatus($pull_request_id)
{
dispatch(new ApplicationContainerStatusJob(
application: $this->application,
container_name: generate_container_name($this->application->uuid, $pull_request_id),
pull_request_id: $pull_request_id
));
}
protected function set_deployment_uuid()
{
$this->deployment_uuid = new Cuid2(7);
$this->parameters['deployment_uuid'] = $this->deployment_uuid;
}
public function load_prs()
{
try {
['rate_limit_remaining' => $rate_limit_remaining, 'data' => $data] = get_from_git_api($this->application->source, "/repos/{$this->application->git_repository}/pulls");
$this->rate_limit_remaining = $rate_limit_remaining;
$this->pull_requests = $data->sortBy('number')->values();
} catch (\Throwable $th) {
$this->rate_limit_remaining = 0;
return general_error_handler($th, $this);
}
}
public function deploy(int $pull_request_id, string|null $pull_request_html_url = null)
{
try {
$this->set_deployment_uuid();
$found = ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->first();
if (!$found && !is_null($pull_request_html_url)) {
ApplicationPreview::create([
'application_id' => $this->application->id,
'pull_request_id' => $pull_request_id,
'pull_request_html_url' => $pull_request_html_url
]);
}
queue_application_deployment(
application_id: $this->application->id,
deployment_uuid: $this->deployment_uuid,
force_rebuild: true,
pull_request_id: $pull_request_id,
);
return redirect()->route('project.application.deployment', [
'project_uuid' => $this->parameters['project_uuid'],
'application_uuid' => $this->parameters['application_uuid'],
'deployment_uuid' => $this->deployment_uuid,
'environment_name' => $this->parameters['environment_name'],
]);
} catch (\Throwable $th) {
return general_error_handler($th, $this);
}
}
public function stop(int $pull_request_id)
{
try {
$container_name = generate_container_name($this->application->uuid, $pull_request_id);
ray('Stopping container: ' . $container_name);
instant_remote_process(["docker rm -f $container_name"], $this->application->destination->server, throwError: false);
ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', $pull_request_id)->delete();
$this->application->refresh();
} catch (\Throwable $th) {
return general_error_handler($th, $this);
}
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Http\Livewire\Project\Application;
use App\Models\Application;
use Livewire\Component;
class ResourceLimits extends Component
{
public Application $application;
protected $rules = [
'application.limits_memory' => 'required|string',
'application.limits_memory_swap' => 'required|string',
'application.limits_memory_swappiness' => 'required|integer|min:0|max:100',
'application.limits_memory_reservation' => 'required|string',
'application.limits_cpus' => 'nullable',
'application.limits_cpuset' => 'nullable',
'application.limits_cpu_shares' => 'nullable',
];
public function submit()
{
try {
if (!$this->application->limits_memory) {
$this->application->limits_memory = "0";
}
if (!$this->application->limits_memory_swap) {
$this->application->limits_memory_swap = "0";
}
if (!$this->application->limits_memory_swappiness) {
$this->application->limits_memory_swappiness = "60";
}
if (!$this->application->limits_memory_reservation) {
$this->application->limits_memory_reservation = "0";
}
if (!$this->application->limits_cpus) {
$this->application->limits_cpus = "0";
}
if (!$this->application->limits_cpuset) {
$this->application->limits_cpuset = "0";
}
if (!$this->application->limits_cpu_shares) {
$this->application->limits_cpu_shares = 1024;
}
$this->validate();
$this->application->save();
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace App\Http\Livewire\Project\Application;
use App\Models\Application;
use Livewire\Component;
use Illuminate\Support\Str;
use Visus\Cuid2\Cuid2;
class Rollback extends Component
{
public Application $application;
public $images = [];
public string|null $current;
public array $parameters;
public function mount()
{
$this->parameters = get_parameters();
}
public function rollbackImage($commit)
{
$deployment_uuid = new Cuid2(7);
queue_application_deployment(
application_id: $this->application->id,
deployment_uuid: $deployment_uuid,
commit: $commit,
force_rebuild: false,
);
return redirect()->route('project.application.deployment', [
'project_uuid' => $this->parameters['project_uuid'],
'application_uuid' => $this->parameters['application_uuid'],
'deployment_uuid' => $deployment_uuid,
'environment_name' => $this->parameters['environment_name'],
]);
}
public function loadImages()
{
try {
$image = $this->application->uuid;
$output = instant_remote_process([
"docker inspect --format='{{.Config.Image}}' {$this->application->uuid}",
], $this->application->destination->server, throwError: false);
$current_tag = Str::of($output)->trim()->explode(":");
$this->current = data_get($current_tag, 1);
$output = instant_remote_process([
"docker images --format '{{.Repository}}#{{.Tag}}#{{.CreatedAt}}'",
], $this->application->destination->server);
$this->images = Str::of($output)->trim()->explode("\n")->filter(function ($item) use ($image) {
return Str::of($item)->contains($image);
})->map(function ($item) {
$item = Str::of($item)->explode('#');
if ($item[1] === $this->current) {
// $is_current = true;
}
return [
'tag' => $item[1],
'created_at' => $item[2],
'is_current' => $is_current ?? null,
];
})->toArray();
} catch (\Throwable $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -15,8 +15,14 @@ class Source extends Component
'application.git_branch' => 'required',
'application.git_commit_sha' => 'nullable',
];
public function mount()
public function submit()
{
$this->application = Application::where('id', $this->applicationId)->first();
$this->validate();
if (!$this->application->git_commit_sha) {
$this->application->git_commit_sha = 'HEAD';
}
$this->application->save();
$this->emit('saved', 'Application source updated!');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Livewire\Project\Application;
use App\Models\Application;
use Livewire\Component;
class Status extends Component
{
public Application $application;
public function applicationStatusChanged()
{
$this->application->refresh();
$this->emit('applicationStatusChanged');
}
}

View File

@ -1,11 +0,0 @@
<?php
namespace App\Http\Livewire\Project\Application;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Component;
class Storages extends Component
{
public Collection $storages;
}

View File

@ -0,0 +1,43 @@
<?php
namespace App\Http\Livewire\Project\Application\Storages;
use App\Models\Application;
use App\Models\LocalPersistentVolume;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
class Add extends Component
{
public $parameters;
public string $name;
public string $mount_path;
public string|null $host_path = null;
protected $listeners = ['clearAddStorage' => 'clear'];
protected $rules = [
'name' => 'required|string',
'mount_path' => 'required|string',
'host_path' => 'string|nullable',
];
public function mount()
{
$this->parameters = get_parameters();
}
public function submit()
{
$this->validate();
$this->emitUp('submit', [
'name' => $this->name,
'mount_path' => $this->mount_path,
'host_path' => $this->host_path,
]);
}
public function clear()
{
$this->name = '';
$this->mount_path = '';
$this->host_path = null;
}
}

View File

@ -0,0 +1,33 @@
<?php
namespace App\Http\Livewire\Project\Application\Storages;
use App\Models\Application;
use App\Models\LocalPersistentVolume;
use Livewire\Component;
class All extends Component
{
public Application $application;
protected $listeners = ['refreshStorages', 'submit'];
public function refreshStorages()
{
$this->application->refresh();
}
public function submit($data)
{
try {
LocalPersistentVolume::create([
'name' => $data['name'],
'mount_path' => $data['mount_path'],
'host_path' => $data['host_path'],
'resource_id' => $this->application->id,
'resource_type' => Application::class,
]);
$this->application->refresh();
$this->emit('clearAddStorage');
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Http\Livewire\Project\Application\Storages;
use Livewire\Component;
class Show extends Component
{
public $storage;
protected $rules = [
'storage.name' => 'required|string',
'storage.mount_path' => 'required|string',
'storage.host_path' => 'string|nullable',
];
public function submit()
{
$this->validate();
$this->storage->save();
}
public function delete()
{
$this->storage->delete();
$this->emit('refreshStorages');
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Http\Livewire\Project;
use App\Models\Environment;
use App\Models\Project;
use Livewire\Component;
class DeleteEnvironment extends Component
{
public array $parameters;
public int $environment_id;
public int $resource_count = 0;
public function mount()
{
$this->parameters = get_parameters();
}
public function delete()
{
$this->validate([
'environment_id' => 'required|int',
]);
$environment = Environment::findOrFail($this->environment_id);
if ($environment->applications->count() > 0) {
return $this->emit('error', 'Environment has resources defined, please delete them first.');
}
$environment->delete();
return redirect()->route('project.show', ['project_uuid' => $this->parameters['project_uuid']]);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Livewire\Project;
use App\Models\Project;
use Livewire\Component;
class DeleteProject extends Component
{
public array $parameters;
public int $project_id;
public int $resource_count = 0;
public function mount()
{
$this->parameters = get_parameters();
}
public function delete()
{
$this->validate([
'project_id' => 'required|int',
]);
$project = Project::findOrFail($this->project_id);
if ($project->applications->count() > 0) {
return $this->emit('error', 'Project has resources defined, please delete them first.');
}
$project->delete();
return redirect()->route('projects');
}
}

View File

@ -10,9 +10,9 @@ class EmptyProject extends Component
public function createEmptyProject()
{
$project = Project::create([
'name' => generateRandomName(),
'name' => generate_random_name(),
'team_id' => session('currentTeam')->id,
]);
return redirect()->route('project.environments', ['project_uuid' => $project->uuid, 'environment_name' => 'production']);
return redirect()->route('project.show', ['project_uuid' => $project->uuid, 'environment_name' => 'production']);
}
}

View File

@ -0,0 +1,162 @@
<?php
namespace App\Http\Livewire\Project\New;
use App\Models\Application;
use App\Models\GithubApp;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Livewire\Component;
class GithubPrivateRepository extends Component
{
public $github_apps;
public GithubApp $github_app;
public $parameters;
public $query;
public $type;
public int $selected_repository_id;
public int $selected_github_app_id;
public string $selected_repository_owner;
public string $selected_repository_repo;
public string $selected_branch_name = 'main';
public string $token;
protected int $page = 1;
public $repositories;
public int $total_repositories_count = 0;
public $branches;
public int $total_branches_count = 0;
public int $port = 3000;
public bool $is_static = false;
public string|null $publish_directory = null;
protected function loadRepositoryByPage()
{
$response = Http::withToken($this->token)->get("{$this->github_app->api_url}/installation/repositories?per_page=100&page={$this->page}");
$json = $response->json();
if ($response->status() !== 200) {
return $this->emit('error', $json['message']);
}
if ($json['total_count'] === 0) {
return;
}
$this->total_repositories_count = $json['total_count'];
$this->repositories = $this->repositories->concat(collect($json['repositories']));
}
protected function loadBranchByPage()
{
Log::info('Loading page ' . $this->page);
$response = Http::withToken($this->token)->get("{$this->github_app->api_url}/repos/{$this->selected_repository_owner}/{$this->selected_repository_repo}/branches?per_page=100&page={$this->page}");
$json = $response->json();
if ($response->status() !== 200) {
return $this->emit('error', $json['message']);
}
$this->total_branches_count = count($json);
$this->branches = $this->branches->concat(collect($json));
}
public function loadRepositories($github_app_id)
{
$this->repositories = collect();
$this->page = 1;
$this->selected_github_app_id = $github_app_id;
$this->github_app = GithubApp::where('id', $github_app_id)->first();
$this->token = generate_github_installation_token($this->github_app);
$this->loadRepositoryByPage();
if ($this->repositories->count() < $this->total_repositories_count) {
while ($this->repositories->count() < $this->total_repositories_count) {
$this->page++;
$this->loadRepositoryByPage();
}
}
$this->selected_repository_id = $this->repositories[0]['id'];
}
public function loadBranches()
{
$this->selected_repository_owner = $this->repositories->where('id', $this->selected_repository_id)->first()['owner']['login'];
$this->selected_repository_repo = $this->repositories->where('id', $this->selected_repository_id)->first()['name'];
$this->branches = collect();
$this->page = 1;
$this->loadBranchByPage();
if ($this->total_branches_count === 100) {
while ($this->total_branches_count === 100) {
$this->page++;
$this->loadBranchByPage();
}
}
}
public function submit()
{
try {
$destination_uuid = $this->query['destination'];
$destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (!$destination) {
$destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (!$destination) {
throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
$project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('name', $this->parameters['environment_name'])->first();
$application = Application::create([
'name' => generate_application_name($this->selected_repository_owner . '/' . $this->selected_repository_repo, $this->selected_branch_name),
'repository_project_id' => $this->selected_repository_id,
'git_repository' => "{$this->selected_repository_owner}/{$this->selected_repository_repo}",
'git_branch' => $this->selected_branch_name,
'build_pack' => 'nixpacks',
'ports_exposes' => $this->port,
'publish_directory' => $this->publish_directory,
'environment_id' => $environment->id,
'destination_id' => $destination->id,
'destination_type' => $destination_class,
'source_id' => $this->github_app->id,
'source_type' => $this->github_app->getMorphClass()
]);
$application->settings->is_static = $this->is_static;
$application->settings->save();
redirect()->route('project.application.configuration', [
'application_uuid' => $application->uuid,
'environment_name' => $environment->name,
'project_uuid' => $project->uuid,
]);
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
public function instantSave()
{
if ($this->is_static) {
$this->port = 80;
$this->publish_directory = '/dist';
} else {
$this->port = 3000;
$this->publish_directory = null;
}
$this->emit('saved', 'Application settings updated!');
}
public function mount()
{
$this->parameters = get_parameters();
$this->query = request()->query();
$this->repositories = $this->branches = collect();
$this->github_apps = GithubApp::private();
}
}

View File

@ -0,0 +1,102 @@
<?php
namespace App\Http\Livewire\Project\New;
use App\Models\Application;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use Livewire\Component;
use Spatie\Url\Url;
class GithubPrivateRepositoryDeployKey extends Component
{
public $parameters;
public $query;
public $private_keys;
public int $private_key_id;
public string $repository_url;
public int $port = 3000;
public string $type;
public bool $is_static = false;
public null|string $publish_directory = null;
protected $rules = [
'repository_url' => 'required|url',
'port' => 'required|numeric',
'is_static' => 'required|boolean',
'publish_directory' => 'nullable|string',
];
public function mount()
{
if (config('app.env') === 'local') {
$this->repository_url = 'https://github.com/coollabsio/coolify-examples/tree/nodejs-fastify';
}
$this->parameters = get_parameters();
$this->query = request()->query();
$this->private_keys = PrivateKey::where('team_id', session('currentTeam')->id)->get();
}
public function instantSave()
{
if ($this->is_static) {
$this->port = 80;
$this->publish_directory = '/dist';
} else {
$this->port = 3000;
$this->publish_directory = null;
}
}
public function setPrivateKey($private_key_id)
{
$this->private_key_id = $private_key_id;
}
public function submit()
{
try {
$this->validate();
$url = Url::fromString($this->repository_url);
$git_host = $url->getHost();
$git_repository = $url->getSegment(1) . '/' . $url->getSegment(2);
$git_branch = $url->getSegment(4) ?? 'main';
$destination_uuid = $this->query['destination'];
$destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (!$destination) {
$destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (!$destination) {
throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
$project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('name', $this->parameters['environment_name'])->first();
$application_init = [
'name' => generate_random_name(),
'git_repository' => $git_repository,
'git_branch' => $git_branch,
'git_full_url' => "git@$git_host:$git_repository.git",
'build_pack' => 'nixpacks',
'ports_exposes' => $this->port,
'publish_directory' => $this->publish_directory,
'environment_id' => $environment->id,
'destination_id' => $destination->id,
'destination_type' => $destination_class,
'private_key_id' => $this->private_key_id,
];
$application = Application::create($application_init);
$application->settings->is_static = $this->is_static;
$application->settings->save();
return redirect()->route('project.application.configuration', [
'project_uuid' => $project->uuid,
'environment_name' => $environment->name,
'application_uuid' => $application->uuid,
]);
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -8,54 +8,43 @@
use App\Models\Project;
use App\Models\StandaloneDocker;
use App\Models\SwarmDocker;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
use Spatie\Url\Url;
class PublicGitRepository extends Component
{
public string $public_repository_url;
public int $port;
public string $repository_url;
private object $repository_url_parsed;
public int $port = 3000;
public string $type;
public $parameters;
public $query;
public $servers;
public $standalone_docker;
public $swarm_docker;
public $chosenServer;
public $chosenDestination;
public $github_apps;
public $gitlab_apps;
public $branches = [];
public string $selected_branch = 'main';
public bool $is_static = false;
public null|string $publish_directory = null;
public string|null $publish_directory = null;
private GithubApp|GitlabApp $git_source;
private string $git_host;
private string $git_repository;
private string $git_branch;
protected $rules = [
'public_repository_url' => 'required|url',
'repository_url' => 'required|url',
'port' => 'required|numeric',
'is_static' => 'required|boolean',
'publish_directory' => 'nullable|string',
];
public function mount()
{
if (env('APP_ENV') === 'local') {
$this->public_repository_url = 'https://github.com/coollabsio/coolify-examples/tree/nodejs-fastify';
if (config('app.env') === 'local') {
$this->repository_url = 'https://github.com/coollabsio/coolify-examples';
$this->port = 3000;
}
$this->parameters = Route::current()->parameters();
$this->servers = session('currentTeam')->load(['servers'])->servers;
}
public function chooseServer($server_id)
{
$this->chosenServer = $server_id;
$this->standalone_docker = StandaloneDocker::where('server_id', $server_id)->get();
$this->swarm_docker = SwarmDocker::where('server_id', $server_id)->get();
}
public function setDestination($destination_uuid, $destination_type)
{
$class = "App\Models\\{$destination_type}";
$instance = new $class;
$this->chosenDestination = $instance::where('uuid', $destination_uuid)->first();
$this->parameters = get_parameters();
$this->query = request()->query();
}
public function instantSave()
@ -67,53 +56,86 @@ public function instantSave()
$this->port = 3000;
$this->publish_directory = null;
}
$this->emit('saved', 'Application settings updated!');
}
public function load_branches()
{
$this->validate([
'repository_url' => 'required|url'
]);
$this->get_git_source();
try {
['data' => $data] = get_from_git_api($this->git_source, "/repos/{$this->git_repository}/branches");
$this->branches = collect($data)->pluck('name')->toArray();
} catch (\Throwable $th) {
return general_error_handler($th, $this);
}
}
private function get_git_source()
{
$this->repository_url_parsed = Url::fromString($this->repository_url);
$this->git_host = $this->repository_url_parsed->getHost();
$this->git_repository = $this->repository_url_parsed->getSegment(1) . '/' . $this->repository_url_parsed->getSegment(2);
$this->git_branch = $this->repository_url_parsed->getSegment(4) ?? 'main';
if ($this->git_host == 'github.com') {
$this->git_source = GithubApp::where('name', 'Public GitHub')->first();
} elseif ($this->git_host == 'gitlab.com') {
$this->git_source = GitlabApp::where('name', 'Public GitLab')->first();
} elseif ($this->git_host == 'bitbucket.org') {
// Not supported yet
}
}
public function submit()
{
$this->validate();
$url = Url::fromString($this->public_repository_url);
$git_host = $url->getHost();
$git_repository = $url->getSegment(1) . '/' . $url->getSegment(2);
$git_branch = $url->getSegment(4) ?? 'main';
try {
$this->validate();
$destination_uuid = $this->query['destination'];
$project_uuid = $this->parameters['project_uuid'];
$environment_name = $this->parameters['environment_name'];
if ($this->type === 'project') {
$project = Project::create([
'name' => generateRandomName(),
'team_id' => session('currentTeam')->id,
$this->get_git_source();
$this->git_branch = $this->selected_branch ?? $this->git_branch;
$destination = StandaloneDocker::where('uuid', $destination_uuid)->first();
if (!$destination) {
$destination = SwarmDocker::where('uuid', $destination_uuid)->first();
}
if (!$destination) {
throw new \Exception('Destination not found. What?!');
}
$destination_class = $destination->getMorphClass();
$project = Project::where('uuid', $project_uuid)->first();
$environment = $project->load(['environments'])->environments->where('name', $environment_name)->first();
$application_init = [
'name' => generate_application_name($this->git_repository, $this->git_branch),
'git_repository' => $this->git_repository,
'git_branch' => $this->git_branch,
'build_pack' => 'nixpacks',
'ports_exposes' => $this->port,
'publish_directory' => $this->publish_directory,
'environment_id' => $environment->id,
'destination_id' => $destination->id,
'destination_type' => $destination_class,
'source_id' => $this->git_source->id,
'source_type' => $this->git_source->getMorphClass()
];
$application = Application::create($application_init);
$application->settings->is_static = $this->is_static;
$application->settings->save();
return redirect()->route('project.application.configuration', [
'project_uuid' => $project->uuid,
'environment_name' => $environment->name,
'application_uuid' => $application->uuid,
]);
$environment = $project->environments->first();
} else {
$project = Project::where('uuid', $this->parameters['project_uuid'])->firstOrFail();
$environment = $project->environments->where('name', $this->parameters['environment_name'])->firstOrFail();
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
$application_init = [
'name' => generateRandomName(),
'git_repository' => $git_repository,
'git_branch' => $git_branch,
'build_pack' => 'nixpacks',
'ports_exposes' => $this->port,
'publish_directory' => $this->publish_directory,
'environment_id' => $environment->id,
'destination_id' => $this->chosenDestination->id,
'destination_type' => $this->chosenDestination->getMorphClass(),
];
if ($git_host == 'github.com') {
$application_init['source_id'] = GithubApp::where('name', 'Public GitHub')->first()->id;
$application_init['source_type'] = GithubApp::class;
} elseif ($git_host == 'gitlab.com') {
$application_init['source_id'] = GitlabApp::where('name', 'Public GitLab')->first()->id;
$application_init['source_type'] = GitlabApp::class;
} elseif ($git_host == 'bitbucket.org') {
}
$application = Application::create($application_init);
$application->settings->is_static = $this->is_static;
$application->settings->save();
return redirect()->route('project.application.configuration', [
'project_uuid' => $project->uuid,
'environment_name' => $environment->name,
'application_uuid' => $application->uuid,
]);
}
}

View File

@ -2,56 +2,34 @@
namespace App\Http\Livewire;
use App\Enums\ActivityTypes;
use App\Models\Server;
use Livewire\Component;
class RunCommand extends Component
{
public $activity;
public $isKeepAliveOn = false;
public $manualKeepAlive = false;
public $command = 'ls';
public string $command;
public $server;
public $servers = [];
protected $rules = [
'server' => 'required',
'command' => 'required',
];
public function mount()
public function mount($servers)
{
$this->servers = Server::all();
$this->server = $this->servers[0]->uuid;
$this->servers = $servers;
$this->server = $servers[0]->uuid;
}
public function runCommand()
{
$this->isKeepAliveOn = true;
$this->activity = remoteProcess([$this->command], Server::where('uuid', $this->server)->first());
}
public function runSleepingBeauty()
{
$this->isKeepAliveOn = true;
$this->activity = remoteProcess(['x=1; while [ $x -le 40 ]; do sleep 0.1 && echo "Welcome $x times" $(( x++ )); done'], Server::where('uuid', $this->server)->first());
}
public function runDummyProjectBuild()
{
$this->isKeepAliveOn = true;
$this->activity = remoteProcess([' cd projects/dummy-project', 'docker-compose build --no-cache'], Server::where('uuid', $this->server)->first());
}
public function polling()
{
$this->activity?->refresh();
if (data_get($this->activity, 'properties.exitCode') !== null) {
$this->isKeepAliveOn = false;
try {
$this->validate();
$activity = remote_process([$this->command], Server::where('uuid', $this->server)->first(), ignore_errors: true);
$this->emit('newMonitorActivity', $activity->id);
} catch (\Exception $e) {
return general_error_handler($e);
}
}
}

View File

@ -2,8 +2,8 @@
namespace App\Http\Livewire\Server;
use App\Actions\Server\InstallDocker;
use App\Models\Server;
use Illuminate\Support\Facades\Validator;
use Livewire\Component;
class Form extends Component
@ -11,6 +11,8 @@ class Form extends Component
public $server_id;
public Server $server;
public $uptime;
public $dockerVersion;
public $dockerComposeVersion;
protected $rules = [
'server.name' => 'required|min:6',
@ -18,14 +20,48 @@ class Form extends Component
'server.ip' => 'required',
'server.user' => 'required',
'server.port' => 'required',
'server.settings.is_validated' => 'required',
'server.settings.is_part_of_swarm' => 'required'
];
public function mount()
{
$this->server = Server::find($this->server_id);
$this->server = Server::find($this->server_id)->load(['settings']);
}
public function checkConnection()
public function installDocker()
{
$this->uptime = runRemoteCommandSync($this->server, ['uptime']);
$activity = resolve(InstallDocker::class)($this->server);
$this->emit('newMonitorActivity', $activity->id);
}
public function validateServer()
{
try {
$this->uptime = instant_remote_process(['uptime'], $this->server, false);
if (!$this->uptime) {
$this->uptime = 'Server not reachable.';
throw new \Exception('Server not reachable.');
} else {
if (!$this->server->settings->is_validated) {
$this->server->settings->is_validated = true;
$this->server->settings->save();
$this->emit('serverValidated');
}
}
$this->dockerVersion = instant_remote_process(['docker version|head -2|grep -i version'], $this->server, false);
if (!$this->dockerVersion) {
$this->dockerVersion = 'Not installed.';
}
$this->dockerComposeVersion = instant_remote_process(['docker compose version|head -2|grep -i version'], $this->server, false);
if (!$this->dockerComposeVersion) {
$this->dockerComposeVersion = 'Not installed.';
}
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
public function delete()
{
$this->server->delete();
redirect()->route('dashboard');
}
public function submit()
{

View File

@ -9,51 +9,59 @@
class ByIp extends Component
{
public $private_keys;
public int $private_key_id;
public int|null $private_key_id = null;
public $new_private_key_name;
public $new_private_key_description;
public $new_private_key_value;
public string $name;
public string $description;
public string|null $description = null;
public string $ip;
public string $user = 'root';
public int $port = 22;
public bool $is_part_of_swarm = false;
protected $rules = [
'name' => 'required',
'ip' => 'required',
'user' => 'required',
'port' => 'required|integer',
'is_part_of_swarm' => 'required|boolean',
];
public function mount()
{
$this->name = generateRandomName();
$this->private_keys = PrivateKey::where('team_id', session('currentTeam')->id)->get();
$this->name = generate_random_name();
$this->private_key_id = $this->private_keys->first()->id;
}
public function setPrivateKey($private_key_id)
public function setPrivateKey(string $private_key_id)
{
$this->private_key_id = $private_key_id;
}
public function addPrivateKey()
public function instantSave()
{
$this->new_private_key_value = trim($this->new_private_key_value);
if (!str_ends_with($this->new_private_key_value, "\n")) {
$this->new_private_key_value .= "\n";
}
PrivateKey::create([
'name' => $this->new_private_key_name,
'description' => $this->new_private_key_description,
'private_key' => $this->new_private_key_value,
'team_id' => session('currentTeam')->id
]);
session('currentTeam')->privateKeys = $this->private_keys = PrivateKey::where('team_id', session('currentTeam')->id)->get();
$this->emit('saved', 'Application settings updated!');
}
public function submit()
{
$server = Server::create([
'name' => $this->name,
'description' => $this->description,
'ip' => $this->ip,
'user' => $this->user,
'port' => $this->port,
'team_id' => session('currentTeam')->id,
'private_key_id' => $this->private_key_id
]);
return redirect()->route('server.show', $server->uuid);
try {
if (!$this->private_key_id) {
return $this->emit('error', 'You must select a private key');
}
$this->validate();
$server = Server::create([
'name' => $this->name,
'description' => $this->description,
'ip' => $this->ip,
'user' => $this->user,
'port' => $this->port,
'team_id' => session('currentTeam')->id,
'private_key_id' => $this->private_key_id,
]);
$server->settings->is_part_of_swarm = $this->is_part_of_swarm;
$server->settings->save();
return redirect()->route('server.show', $server->uuid);
} catch (\Exception $e) {
return general_error_handler($e);
}
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Http\Livewire\Server;
use App\Models\PrivateKey as ModelsPrivateKey;
use App\Models\Server;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
class PrivateKey extends Component
{
public $private_keys;
public $parameters;
public function setPrivateKey($private_key_id)
{
$server = Server::where('uuid', $this->parameters['server_uuid']);
$server->update([
'private_key_id' => $private_key_id
]);
// Delete the old ssh mux file to force a new one to be created
Storage::disk('ssh-mux')->delete("{$server->first()->ip}_{$server->first()->port}_{$server->first()->user}");
return redirect()->route('server.show', $this->parameters['server_uuid']);
}
public function mount()
{
$this->parameters = get_parameters();
$this->private_keys = ModelsPrivateKey::where('team_id', session('currentTeam')->id)->get();
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace App\Http\Livewire\Server;
use App\Actions\Proxy\CheckProxySettingsInSync;
use App\Actions\Proxy\InstallProxy;
use App\Enums\ProxyTypes;
use Illuminate\Support\Str;
use App\Models\Server;
use Livewire\Component;
class Proxy extends Component
{
public Server $server;
public ProxyTypes $selectedProxy = ProxyTypes::TRAEFIK_V2;
public $proxy_settings = null;
protected $listeners = ['serverValidated', 'saveConfiguration'];
public function serverValidated()
{
$this->server->refresh();
}
public function installProxy()
{
if (
$this->server->extra_attributes->proxy_last_applied_settings &&
$this->server->extra_attributes->proxy_last_saved_settings !== $this->server->extra_attributes->proxy_last_applied_settings
) {
$this->saveConfiguration($this->server);
}
$activity = resolve(InstallProxy::class)($this->server);
$this->emit('newMonitorActivity', $activity->id);
}
public function setProxy(string $proxy_type)
{
$this->server->extra_attributes->proxy_type = $proxy_type;
$this->server->extra_attributes->proxy_status = 'exited';
$this->server->save();
}
public function stopProxy()
{
instant_remote_process([
"docker rm -f coolify-proxy",
], $this->server);
$this->server->extra_attributes->proxy_status = 'exited';
$this->server->save();
}
public function saveConfiguration(Server $server)
{
try {
$proxy_path = config('coolify.proxy_config_path');
$this->proxy_settings = Str::of($this->proxy_settings)->trim()->value;
$docker_compose_yml_base64 = base64_encode($this->proxy_settings);
$server->extra_attributes->proxy_last_saved_settings = Str::of($docker_compose_yml_base64)->pipe('md5')->value;
$server->save();
instant_remote_process([
"echo '$docker_compose_yml_base64' | base64 -d > $proxy_path/docker-compose.yml",
], $server);
} catch (\Exception $e) {
return general_error_handler($e);
}
}
public function resetProxy()
{
try {
$this->proxy_settings = resolve(CheckProxySettingsInSync::class)($this->server, true);
} catch (\Exception $e) {
return general_error_handler($e);
}
}
public function checkProxySettingsInSync()
{
try {
$this->proxy_settings = resolve(CheckProxySettingsInSync::class)($this->server);
} catch (\Exception $e) {
return general_error_handler($e);
}
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace App\Http\Livewire\Server\Proxy;
use App\Actions\Proxy\InstallProxy;
use App\Models\Server;
use Livewire\Component;
use Str;
class Deploy extends Component
{
public Server $server;
public $proxy_settings = null;
protected $listeners = ['proxyStatusUpdated', 'serverValidated' => 'proxyStatusUpdated'];
public function proxyStatusUpdated()
{
$this->server->refresh();
}
public function deploy()
{
if (
$this->server->extra_attributes->proxy_last_applied_settings &&
$this->server->extra_attributes->proxy_last_saved_settings !== $this->server->extra_attributes->proxy_last_applied_settings
) {
$this->saveConfiguration($this->server);
}
$activity = resolve(InstallProxy::class)($this->server);
$this->emit('newMonitorActivity', $activity->id);
}
public function stop()
{
instant_remote_process([
"docker rm -f coolify-proxy",
], $this->server);
$this->server->extra_attributes->proxy_status = 'exited';
$this->server->save();
$this->emit('proxyStatusUpdated');
}
private function saveConfiguration(Server $server)
{
$this->emit('saveConfiguration', $server);
}
}

View File

@ -0,0 +1,29 @@
<?php
namespace App\Http\Livewire\Server\Proxy;
use App\Jobs\ProxyContainerStatusJob;
use App\Models\Server;
use Livewire\Component;
class Status extends Component
{
public Server $server;
protected $listeners = ['proxyStatusUpdated', 'serverValidated' => 'proxyStatusUpdated'];
public function proxyStatusUpdated()
{
ray('Status: ' . $this->server->extra_attributes->proxy_status);
$this->server->refresh();
}
public function proxyStatus()
{
try {
dispatch(new ProxyContainerStatusJob(
server: $this->server
));
$this->emit('proxyStatusUpdated');
} catch (\Exception $e) {
ray($e->getMessage());
}
}
}

View File

@ -0,0 +1,66 @@
<?php
namespace App\Http\Livewire\Settings;
use App\Mail\TestTransactionalEmail;
use App\Models\InstanceSettings;
use App\Notifications\TestTransactionEmail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use Livewire\Component;
class Email extends Component
{
public InstanceSettings $settings;
protected $rules = [
'settings.extra_attributes.smtp_host' => 'required',
'settings.extra_attributes.smtp_port' => 'required|numeric',
'settings.extra_attributes.smtp_encryption' => 'nullable',
'settings.extra_attributes.smtp_username' => 'nullable',
'settings.extra_attributes.smtp_password' => 'nullable',
'settings.extra_attributes.smtp_timeout' => 'nullable',
'settings.extra_attributes.smtp_recipients' => 'required',
'settings.extra_attributes.smtp_test_recipients' => 'nullable',
'settings.extra_attributes.smtp_from_address' => 'required|email',
'settings.extra_attributes.smtp_from_name' => 'required',
];
public function test_email()
{
Notification::send($this->settings, new TestTransactionEmail);
}
// public function test_email()
// {
// config()->set('mail.default', 'smtp');
// config()->set('mail.mailers.smtp', [
// "transport" => "smtp",
// "host" => $this->settings->smtp_host,
// "port" => $this->settings->smtp_port,
// "encryption" => $this->settings->smtp_encryption,
// "username" => $this->settings->smtp_username,
// "password" => $this->settings->smtp_password,
// ]);
// $this->send_email();
// }
// public function test_email_local()
// {
// config()->set('mail.default', 'smtp');
// config()->set('mail.mailers.smtp', [
// "transport" => "smtp",
// "host" => 'coolify-mail',
// "port" => 1025,
// ]);
// $this->send_email();
// }
// private function send_email()
// {
// }
public function submit()
{
$this->validate();
$this->settings->extra_attributes->smtp_recipients = str_replace(' ', '', $this->settings->extra_attributes->smtp_recipients);
$this->settings->extra_attributes->smtp_test_recipients = str_replace(' ', '', $this->settings->extra_attributes->smtp_test_recipients);
$this->settings->save();
}
}

View File

@ -3,7 +3,10 @@
namespace App\Http\Livewire\Settings;
use App\Models\InstanceSettings as ModelsInstanceSettings;
use App\Models\Server;
use Livewire\Component;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
class Form extends Component
{
@ -11,28 +14,173 @@ class Form extends Component
public $do_not_track;
public $is_auto_update_enabled;
public $is_registration_enabled;
public $is_https_forced;
protected string $dynamic_config_path;
protected Server $server;
protected $rules = [
'settings.fqdn' => 'nullable',
'settings.wildcard_domain' => 'nullable',
'settings.public_port_min' => 'required',
'settings.public_port_max' => 'required',
'settings.default_redirect_404' => 'nullable',
];
public function mount()
{
$this->do_not_track = $this->settings->do_not_track;
$this->is_auto_update_enabled = $this->settings->is_auto_update_enabled;
$this->is_registration_enabled = $this->settings->is_registration_enabled;
$this->is_https_forced = $this->settings->is_https_forced;
}
public function instantSave()
{
$this->settings->do_not_track = $this->do_not_track;
$this->settings->is_auto_update_enabled = $this->is_auto_update_enabled;
$this->settings->is_registration_enabled = $this->is_registration_enabled;
$this->settings->is_https_forced = $this->is_https_forced;
$this->settings->save();
$this->emit('saved', 'Settings updated!');
}
private function setup_instance_fqdn()
{
$file = "$this->dynamic_config_path/coolify.yaml";
if (empty($this->settings->fqdn)) {
remote_process([
"rm -f $file",
], $this->server);
} else {
$url = Url::fromString($this->settings->fqdn);
$host = $url->getHost();
$schema = $url->getScheme();
$traefik_dynamic_conf = [
'http' =>
[
'routers' =>
[
'coolify-http' =>
[
'entryPoints' => [
0 => 'http',
],
'service' => 'coolify',
'rule' => "Host(`{$host}`)",
],
],
'services' =>
[
'coolify' =>
[
'loadBalancer' =>
[
'servers' =>
[
0 =>
[
'url' => 'http://coolify:80',
],
],
],
],
],
],
];
if ($schema === 'https') {
$traefik_dynamic_conf['http']['routers']['coolify-http']['middlewares'] = [
0 => 'redirect-to-https@docker',
];
$traefik_dynamic_conf['http']['routers']['coolify-https'] = [
'entryPoints' => [
0 => 'https',
],
'service' => 'coolify',
'rule' => "Host(`{$host}`)",
'tls' => [
'certresolver' => 'letsencrypt',
],
];
}
$this->save_configuration_to_disk($traefik_dynamic_conf, $file);
}
}
private function setup_default_redirect_404()
{
$file = "$this->dynamic_config_path/default_redirect_404.yaml";
if (empty($this->settings->default_redirect_404)) {
remote_process([
"rm -f $file",
], $this->server);
} else {
$url = Url::fromString($this->settings->default_redirect_404);
$host = $url->getHost();
$schema = $url->getScheme();
$traefik_dynamic_conf = [
'http' =>
[
'routers' =>
[
'catchall' =>
[
'entryPoints' => [
0 => 'http',
1 => 'https',
],
'service' => 'noop',
'rule' => "HostRegexp(`{catchall:.*}`)",
'priority' => 1,
'middlewares' => [
0 => 'redirect-regexp@file',
],
],
],
'services' =>
[
'noop' =>
[
'loadBalancer' =>
[
'servers' =>
[
0 =>
[
'url' => '',
],
],
],
],
],
'middlewares' =>
[
'redirect-regexp' =>
[
'redirectRegex' =>
[
'regex' => '(.*)',
'replacement' => $this->settings->default_redirect_404,
'permanent' => false,
],
],
],
],
];
$this->save_configuration_to_disk($traefik_dynamic_conf, $file);
}
}
private function save_configuration_to_disk(array $traefik_dynamic_conf, string $file)
{
$yaml = Yaml::dump($traefik_dynamic_conf, 12, 2);
$yaml =
"# This file is automatically generated by Coolify.\n" .
"# Do not edit it manually (only if you know what are you doing).\n\n" .
$yaml;
$base64 = base64_encode($yaml);
remote_process([
"mkdir -p $this->dynamic_config_path",
"echo '$base64' | base64 -d > $file",
], $this->server);
if (config('app.env') == 'local') {
ray($yaml);
}
}
public function submit()
{
@ -43,5 +191,14 @@ public function submit()
}
$this->validate();
$this->settings->save();
$this->dynamic_config_path = '/data/coolify/proxy/dynamic';
if (config('app.env') == 'local') {
$this->server = Server::findOrFail(1);
} else {
$this->server = Server::findOrFail(0);
}
$this->setup_instance_fqdn();
$this->setup_default_redirect_404();
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace App\Http\Livewire\Source\Github;
use App\Models\GithubApp;
use App\Models\InstanceSettings;
use Livewire\Component;
class Change extends Component
{
public string $host;
public $parameters;
public GithubApp $github_app;
public string $installation_url;
public string $name;
public bool $is_system_wide;
protected $rules = [
'github_app.name' => 'required|string',
'github_app.organization' => 'nullable|string',
'github_app.api_url' => 'required|string',
'github_app.html_url' => 'required|string',
'github_app.custom_user' => 'required|string',
'github_app.custom_port' => 'required|int',
'github_app.app_id' => 'required|int',
'github_app.installation_id' => 'required|int',
'github_app.client_id' => 'required|string',
'github_app.client_secret' => 'required|string',
'github_app.webhook_secret' => 'required|string',
'github_app.is_system_wide' => 'required|bool',
];
public function submit()
{
try {
$this->validate();
$this->github_app->save();
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
public function instantSave()
{
try {
$this->github_app->is_system_wide = $this->is_system_wide;
$this->github_app->save();
$this->emit('saved', 'GitHub settings updated!');
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
public function mount()
{
$settings = InstanceSettings::get();
if ($settings->fqdn) {
$this->host = $settings->fqdn;
}
$this->parameters = get_parameters();
$this->is_system_wide = $this->github_app->is_system_wide;
}
public function delete()
{
try {
$this->github_app->delete();
redirect()->route('dashboard');
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Http\Livewire\Source\Github;
use App\Models\GithubApp;
use Livewire\Component;
class Create extends Component
{
public string $name;
public string|null $organization = null;
public string $api_url = 'https://api.github.com';
public string $html_url = 'https://github.com';
public string $custom_user = 'git';
public int $custom_port = 22;
public bool $is_system_wide = false;
public function mount()
{
$this->name = generate_random_name();
}
public function createGitHubApp()
{
try {
$this->validate([
"name" => 'required|string',
"organization" => 'nullable|string',
"api_url" => 'required|string',
"html_url" => 'required|string',
"custom_user" => 'required|string',
"custom_port" => 'required|int',
"is_system_wide" => 'required|bool',
]);
$github_app = GithubApp::create([
'name' => $this->name,
'organization' => $this->organization,
'api_url' => $this->api_url,
'html_url' => $this->html_url,
'custom_user' => $this->custom_user,
'custom_port' => $this->custom_port,
'is_system_wide' => $this->is_system_wide,
'team_id' => session('currentTeam')->id,
]);
redirect()->route('source.github.show', ['github_app_uuid' => $github_app->uuid]);
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -7,6 +7,11 @@
class SwitchTeam extends Component
{
public string $selectedTeamId = 'default';
public function updatedSelectedTeamId()
{
$this->switch_to($this->selectedTeamId);
}
public function switch_to($team_id)
{
if (!auth()->user()->teams->contains($team_id)) {

View File

@ -0,0 +1,15 @@
<?php
namespace App\Http\Livewire\Team;
use App\Models\User;
use Livewire\Component;
class Member extends Component
{
public User $member;
public function render()
{
return view('livewire.team.member');
}
}

View File

@ -0,0 +1,15 @@
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Upgrading extends Component
{
public bool $visible = false;
protected $listeners = ['updateInitiated'];
public function updateInitiated()
{
$this->visible = true;
}
}

View File

@ -12,7 +12,7 @@ class TrustProxies extends Middleware
*
* @var array<int, string>|string|null
*/
protected $proxies;
protected $proxies = '*';
/**
* The headers that should be used to detect proxies.
@ -20,7 +20,7 @@ class TrustProxies extends Middleware
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |

View File

@ -0,0 +1,57 @@
<?php
namespace App\Jobs;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class ApplicationContainerStatusJob implements ShouldQueue, ShouldBeUnique
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public string $container_name;
public string|null $pull_request_id;
public Application $application;
public function __construct($application, string $container_name, string|null $pull_request_id = null)
{
$this->application = $application;
$this->container_name = $container_name;
$this->pull_request_id = $pull_request_id;
}
public function uniqueId(): string
{
return $this->container_name;
}
public function handle(): void
{
try {
$status = get_container_status(server: $this->application->destination->server, container_id: $this->container_name, throwError: false);
if ($this->pull_request_id) {
$preview = ApplicationPreview::findPreviewByApplicationAndPullId($this->application->id, $this->pull_request_id);
$preview->status = $status;
$preview->save();
} else {
$this->application->status = $status;
$this->application->save();
}
} catch (\Exception $e) {
Log::error($e->getMessage());
}
}
protected function check_container_status()
{
if ($this->application->destination->server) {
$this->application->status = get_container_status(server: $this->application->destination->server, container_id: $this->application->uuid);
$this->application->save();
}
}
}

View File

@ -0,0 +1,688 @@
<?php
namespace App\Jobs;
use App\Actions\CoolifyTask\RunRemoteProcess;
use App\Data\CoolifyTaskArgs;
use App\Enums\ActivityTypes;
use App\Enums\ProcessStatus;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\ApplicationPreview;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Spatie\Activitylog\Models\Activity;
use Symfony\Component\Yaml\Yaml;
use Illuminate\Support\Str;
use Spatie\Url\Url;
use Visus\Cuid2\Cuid2;
class ApplicationDeploymentJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
private Application $application;
private ApplicationDeploymentQueue $application_deployment_queue;
private $destination;
private $source;
private Activity $activity;
private string|null $git_commit = null;
private string $workdir;
private string $docker_compose;
private $build_args;
private $env_args;
private string $build_image_name;
private string $production_image_name;
private string $container_name;
private ApplicationPreview|null $preview;
public static int $batch_counter = 0;
public $timeout = 10200;
public function __construct(
public int $application_deployment_queue_id,
public string $deployment_uuid,
public string $application_id,
public bool $force_rebuild = false,
public string $rollback_commit = 'HEAD',
public int $pull_request_id = 0,
) {
$this->application_deployment_queue = ApplicationDeploymentQueue::find($this->application_deployment_queue_id);
$this->application_deployment_queue->update([
'status' => ProcessStatus::IN_PROGRESS->value,
]);
if ($this->rollback_commit) {
$this->git_commit = $this->rollback_commit;
}
$this->application = Application::find($this->application_id);
if ($this->pull_request_id !== 0) {
$this->preview = ApplicationPreview::findPreviewByApplicationAndPullId($this->application->id, $this->pull_request_id);
}
$this->destination = $this->application->destination->getMorphClass()::where('id', $this->application->destination->id)->first();
$server = $this->destination->server;
$private_key_location = save_private_key_for_server($server);
$remoteProcessArgs = new CoolifyTaskArgs(
server_ip: $server->ip,
private_key_location: $private_key_location,
command: 'overwritten-later',
port: $server->port,
user: $server->user,
type: ActivityTypes::DEPLOYMENT->value,
type_uuid: $this->deployment_uuid,
);
$this->activity = activity()
->performedOn($this->application)
->withProperties($remoteProcessArgs->toArray())
->event(ActivityTypes::DEPLOYMENT->value)
->log("[]");
}
public function handle(): void
{
try {
if ($this->application->deploymentType() === 'source') {
$this->source = $this->application->source->getMorphClass()::where('id', $this->application->source->id)->first();
}
$this->workdir = "/artifacts/{$this->deployment_uuid}";
if ($this->pull_request_id !== 0) {
ray('Deploying pull/' . $this->pull_request_id . '/head for application: ' . $this->application->name);
$this->deploy_pull_request();
} else {
$this->deploy();
}
} catch (\Exception $e) {
$this->execute_now([
"echo '\nOops something is not okay, are you okay? 😢'",
"echo '\n\n{$e->getMessage()}'",
]);
$this->fail();
} finally {
if (isset($this->docker_compose)) {
Storage::disk('deployments')->put(Str::kebab($this->application->name) . '/docker-compose.yml', $this->docker_compose);
}
$this->execute_now(["docker rm -f {$this->deployment_uuid} >/dev/null 2>&1"], hideFromOutput: true);
}
}
private function start_builder_image()
{
$this->execute_now([
"echo -n 'Pulling latest version of the builder image (ghcr.io/coollabsio/coolify-builder)... '",
]);
$this->execute_now([
"docker run --pull=always -d --name {$this->deployment_uuid} --rm -v /var/run/docker.sock:/var/run/docker.sock ghcr.io/coollabsio/coolify-builder",
], isDebuggable: true);
$this->execute_now([
"echo 'Done.'"
]);
$this->execute_now([
$this->execute_in_builder("mkdir -p {$this->workdir}"),
]);
}
private function clone_repository()
{
$this->execute_now([
"echo -n 'Importing {$this->application->git_repository}:{$this->application->git_branch} to {$this->workdir}... '"
]);
$this->execute_now([
...$this->importing_git_repository(),
], 'importing_git_repository');
$this->execute_now([
"echo 'Done.'"
]);
// Get git commit
$this->execute_now([$this->execute_in_builder("cd {$this->workdir} && git rev-parse HEAD")], 'commit_sha', hideFromOutput: true);
$this->git_commit = $this->activity->properties->get('commit_sha');
}
private function cleanup_git()
{
$this->execute_now([
$this->execute_in_builder("rm -fr {$this->workdir}/.git")
], hideFromOutput: true);
}
private function generate_buildpack()
{
$this->execute_now([
"echo -n 'Generating nixpacks configuration... '",
]);
$this->execute_now([
$this->nixpacks_build_cmd(),
$this->execute_in_builder("cp {$this->workdir}/.nixpacks/Dockerfile {$this->workdir}/Dockerfile"),
$this->execute_in_builder("rm -f {$this->workdir}/.nixpacks/Dockerfile"),
], isDebuggable: true);
$this->execute_now([
"echo 'Done... '",
]);
}
private function build_image()
{
$this->execute_now([
"echo -n 'Building image... '",
]);
if ($this->application->settings->is_static && isset($this->application->build_command)) {
$this->execute_now([
$this->execute_in_builder("docker build -f {$this->workdir}/Dockerfile {$this->build_args} --progress plain -t { $this->build_image_name {$this->workdir}"),
], isDebuggable: true);
$dockerfile = "FROM {$this->application->static_image}
WORKDIR /usr/share/nginx/html/
LABEL coolify.deploymentId={$this->deployment_uuid}
COPY --from=$this->build_image_name /app/{$this->application->publish_directory} .";
$docker_file = base64_encode($dockerfile);
$this->execute_now([
$this->execute_in_builder("echo '{$docker_file}' | base64 -d > {$this->workdir}/Dockerfile-prod"),
$this->execute_in_builder("docker build -f {$this->workdir}/Dockerfile-prod {$this->build_args} --progress plain -t $this->production_image_name {$this->workdir}"),
], hideFromOutput: true);
} else {
$this->execute_now([
$this->execute_in_builder("docker build -f {$this->workdir}/Dockerfile {$this->build_args} --progress plain -t $this->production_image_name {$this->workdir}"),
], isDebuggable: true);
}
$this->execute_now([
"echo 'Done.'",
]);
}
private function deploy_pull_request()
{
$this->build_image_name = "{$this->application->uuid}:pr-{$this->pull_request_id}-build";
$this->production_image_name = "{$this->application->uuid}:pr-{$this->pull_request_id}";
$this->container_name = generate_container_name($this->application->uuid, $this->pull_request_id);
// Deploy pull request
$this->execute_now([
"echo 'Starting deployment of {$this->application->git_repository}:{$this->application->git_branch} PR#{$this->pull_request_id}...'",
]);
$this->start_builder_image();
$this->clone_repository();
$this->cleanup_git();
$this->generate_buildpack();
$this->generate_compose_file();
// Needs separate preview variables
// $this->generate_build_env_variables();
// $this->add_build_env_variables_to_dockerfile();
$this->build_image();
$this->stop_running_container();
$this->start_by_compose_file();
$this->next(ProcessStatus::FINISHED->value);
}
private function deploy()
{
$this->container_name = generate_container_name($this->application->uuid);
// Deploy normal commit
$this->execute_now([
"echo 'Starting deployment of {$this->application->git_repository}:{$this->application->git_branch}...'",
]);
$this->start_builder_image();
ray('Rollback Commit: ' . $this->rollback_commit);
if ($this->rollback_commit === 'HEAD') {
$this->clone_repository();
}
$this->build_image_name = "{$this->application->uuid}:{$this->git_commit}-build";
$this->production_image_name = "{$this->application->uuid}:{$this->git_commit}";
ray('Build Image Name: ' . $this->build_image_name . ' & Production Image Name:' . $this->production_image_name);
if (!$this->force_rebuild) {
$this->execute_now([
"docker images -q {$this->application->uuid}:{$this->git_commit} 2>/dev/null",
], 'local_image_found', hideFromOutput: true, ignoreErrors: true);
$image_found = Str::of($this->activity->properties->get('local_image_found'))->trim()->isNotEmpty();
if ($image_found) {
$this->execute_now([
"echo 'Docker Image found locally with the same Git Commit SHA. Build skipped...'"
]);
$this->generate_compose_file();
$this->stop_running_container();
$this->start_by_compose_file();
$this->next(ProcessStatus::FINISHED->value);
return;
}
}
$this->cleanup_git();
$this->generate_buildpack();
$this->generate_compose_file();
$this->generate_build_env_variables();
$this->add_build_env_variables_to_dockerfile();
$this->build_image();
$this->stop_running_container();
$this->start_by_compose_file();
$this->next(ProcessStatus::FINISHED->value);
}
public function failed(): void
{
$this->next(ProcessStatus::ERROR->value);
}
private function next(string $status)
{
if (!Str::of($this->application_deployment_queue->status)->startsWith('cancelled')) {
$this->application_deployment_queue->update([
'status' => $status,
]);
}
dispatch(new ApplicationContainerStatusJob(
application: $this->application,
container_name: $this->container_name,
pull_request_id: $this->pull_request_id
));
queue_next_deployment($this->application);
}
private function execute_in_builder(string $command)
{
return "docker exec {$this->deployment_uuid} bash -c '{$command}'";
}
private function generate_environment_variables($ports)
{
$environment_variables = collect();
ray('Generate Environment Variables');
if ($this->pull_request_id === 0) {
ray($this->application->runtime_environment_variables);
foreach ($this->application->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->value");
}
} else {
ray($this->application->runtime_environment_variables_preview);
foreach ($this->application->runtime_environment_variables_preview as $env) {
$environment_variables->push("$env->key=$env->value");
}
}
// Add PORT if not exists, use the first port as default
if ($environment_variables->filter(fn ($env) => Str::of($env)->contains('PORT'))->isEmpty()) {
$environment_variables->push("PORT={$ports[0]}");
}
return $environment_variables->all();
}
private function generate_env_variables()
{
$this->env_args = collect([]);
if ($this->pull_request_id === 0) {
foreach ($this->application->nixpacks_environment_variables as $env) {
$this->env_args->push("--env {$env->key}={$env->value}");
}
} else {
foreach ($this->application->nixpacks_environment_variables_preview as $env) {
$this->env_args->push("--env {$env->key}={$env->value}");
}
}
$this->env_args = $this->env_args->implode(' ');
}
private function generate_build_env_variables()
{
$this->build_args = collect(["--build-arg SOURCE_COMMIT={$this->git_commit}"]);
if ($this->pull_request_id === 0) {
foreach ($this->application->build_environment_variables as $env) {
$this->build_args->push("--build-arg {$env->key}={$env->value}");
}
} else {
foreach ($this->application->build_environment_variables_preview as $env) {
$this->build_args->push("--build-arg {$env->key}={$env->value}");
}
}
$this->build_args = $this->build_args->implode(' ');
}
private function add_build_env_variables_to_dockerfile()
{
$this->execute_now([
$this->execute_in_builder("cat {$this->workdir}/Dockerfile")
], propertyName: 'dockerfile', hideFromOutput: true);
$dockerfile = collect(Str::of($this->activity->properties->get('dockerfile'))->trim()->explode("\n"));
foreach ($this->application->build_environment_variables as $env) {
$dockerfile->splice(1, 0, "ARG {$env->key}={$env->value}");
}
$dockerfile_base64 = base64_encode($dockerfile->implode("\n"));
$this->execute_now([
$this->execute_in_builder("echo '{$dockerfile_base64}' | base64 -d > {$this->workdir}/Dockerfile")
], hideFromOutput: true);
}
private function generate_docker_compose()
{
$ports = $this->application->settings->is_static ? [80] : $this->application->ports_exposes_array;
$persistent_storages = $this->generate_local_persistent_volumes();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables($ports);
$docker_compose = [
'version' => '3.8',
'services' => [
$this->container_name => [
'image' => $this->production_image_name,
'container_name' => $this->container_name,
'restart' => 'always',
'environment' => $environment_variables,
'labels' => $this->set_labels_for_applications(),
'expose' => $ports,
'networks' => [
$this->destination->network,
],
'healthcheck' => [
'test' => [
'CMD-SHELL',
$this->generate_healthcheck_commands()
],
'interval' => $this->application->health_check_interval . 's',
'timeout' => $this->application->health_check_timeout . 's',
'retries' => $this->application->health_check_retries,
'start_period' => $this->application->health_check_start_period . 's'
],
'mem_limit' => $this->application->limits_memory,
'memswap_limit' => $this->application->limits_memory_swap,
'mem_swappiness' => $this->application->limits_memory_swappiness,
'mem_reservation' => $this->application->limits_memory_reservation,
'cpus' => $this->application->limits_cpus,
'cpuset' => $this->application->limits_cpuset,
'cpu_shares' => $this->application->limits_cpu_shares,
]
],
'networks' => [
$this->destination->network => [
'external' => false,
'name' => $this->destination->network,
'attachable' => true,
]
]
];
if (count($this->application->ports_mappings_array) > 0 && $this->pull_request_id === 0) {
$docker_compose['services'][$this->container_name]['ports'] = $this->application->ports_mappings_array;
}
if (count($persistent_storages) > 0) {
$docker_compose['services'][$this->container_name]['volumes'] = $persistent_storages;
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
return Yaml::dump($docker_compose, 10);
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->application->persistentStorages as $persistentStorage) {
$volume_name = $persistentStorage->host_path ?? $persistentStorage->name;
if ($this->pull_request_id !== 0) {
$volume_name = $volume_name . '-pr-' . $this->pull_request_id;
}
$local_persistent_volumes[] = $volume_name . ':' . $persistentStorage->mount_path;
}
ray('local_persistent_volumes', $local_persistent_volumes);
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->application->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
if ($this->pull_request_id !== 0) {
$name = $name . '-pr-' . $this->pull_request_id;
}
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_healthcheck_commands()
{
if (!$this->application->health_check_port) {
$this->application->health_check_port = $this->application->ports_exposes_array[0];
}
if ($this->application->health_check_path) {
$generated_healthchecks_commands = [
"curl -s -X {$this->application->health_check_method} -f {$this->application->health_check_scheme}://{$this->application->health_check_host}:{$this->application->health_check_port}{$this->application->health_check_path} > /dev/null"
];
} else {
$generated_healthchecks_commands = [
"curl -s -X {$this->application->health_check_method} -f {$this->application->health_check_scheme}://{$this->application->health_check_host}:{$this->application->health_check_port}/"
];
}
return implode(' ', $generated_healthchecks_commands);
}
private function set_labels_for_applications()
{
$labels = [];
$labels[] = 'coolify.managed=true';
$labels[] = 'coolify.version=' . config('version');
$labels[] = 'coolify.applicationId=' . $this->application->id;
$labels[] = 'coolify.type=application';
$labels[] = 'coolify.name=' . $this->application->name;
if ($this->pull_request_id !== 0) {
$labels[] = 'coolify.pullRequestId=' . $this->pull_request_id;
}
if ($this->application->fqdn) {
if ($this->pull_request_id !== 0) {
$preview_fqdn = data_get($this->preview, 'fqdn');
$template = $this->application->preview_url_template;
$url = Url::fromString($this->application->fqdn);
$host = $url->getHost();
$schema = $url->getScheme();
$random = new Cuid2(7);
$preview_fqdn = str_replace('{{random}}', $random, $template);
$preview_fqdn = str_replace('{{domain}}', $host, $preview_fqdn);
$preview_fqdn = str_replace('{{pr_id}}', $this->pull_request_id, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn";
$this->preview->fqdn = $preview_fqdn;
$this->preview->save();
$domains = Str::of($preview_fqdn)->explode(',');
} else {
$domains = Str::of($this->application->fqdn)->explode(',');
}
$labels[] = 'traefik.enable=true';
foreach ($domains as $domain) {
$url = Url::fromString($domain);
$host = $url->getHost();
$path = $url->getPath();
$schema = $url->getScheme();
$slug = Str::slug($host . $path);
$http_label = "{$this->application->uuid}-{$slug}-http";
$https_label = "{$this->application->uuid}-{$slug}-https";
if ($schema === 'https') {
// Set labels for https
$labels[] = "traefik.http.routers.{$https_label}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)";
$labels[] = "traefik.http.routers.{$https_label}.entryPoints=https";
$labels[] = "traefik.http.routers.{$https_label}.middlewares=gzip";
if ($path !== '/') {
$labels[] = "traefik.http.routers.{$https_label}.middlewares={$https_label}-stripprefix";
$labels[] = "traefik.http.middlewares.{$https_label}-stripprefix.stripprefix.prefixes={$path}";
}
$labels[] = "traefik.http.routers.{$https_label}.tls=true";
$labels[] = "traefik.http.routers.{$https_label}.tls.certresolver=letsencrypt";
// Set labels for http (redirect to https)
$labels[] = "traefik.http.routers.{$http_label}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)";
$labels[] = "traefik.http.routers.{$http_label}.entryPoints=http";
if ($this->application->settings->is_force_https_enabled) {
$labels[] = "traefik.http.routers.{$http_label}.middlewares=redirect-to-https";
}
} else {
// Set labels for http
$labels[] = "traefik.http.routers.{$http_label}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)";
$labels[] = "traefik.http.routers.{$http_label}.entryPoints=http";
$labels[] = "traefik.http.routers.{$http_label}.middlewares=gzip";
if ($path !== '/') {
$labels[] = "traefik.http.routers.{$http_label}.middlewares={$http_label}-stripprefix";
$labels[] = "traefik.http.middlewares.{$http_label}-stripprefix.stripprefix.prefixes={$path}";
}
}
}
}
return $labels;
}
private function execute_now(
array|Collection $command,
string $propertyName = null,
bool $isFinished = false,
bool $hideFromOutput = false,
bool $isDebuggable = false,
bool $ignoreErrors = false
) {
static::$batch_counter++;
if ($command instanceof Collection) {
$commandText = $command->implode("\n");
} else {
$commandText = collect($command)->implode("\n");
}
ray('Executing command: ' . $commandText);
$this->activity->properties = $this->activity->properties->merge([
'command' => $commandText,
]);
$this->activity->save();
if ($isDebuggable && !$this->application->settings->is_debug_enabled) {
$hideFromOutput = true;
}
$remote_process = resolve(RunRemoteProcess::class, [
'activity' => $this->activity,
'hideFromOutput' => $hideFromOutput,
'isFinished' => $isFinished,
'ignoreErrors' => $ignoreErrors,
]);
$result = $remote_process();
if ($propertyName) {
$this->activity->properties = $this->activity->properties->merge([
$propertyName => trim($result->output()),
]);
$this->activity->save();
}
if ($result->exitCode() != 0 && $result->errorOutput() && !$ignoreErrors) {
throw new \RuntimeException($result->errorOutput());
}
}
private function set_git_import_settings($git_clone_command)
{
if ($this->application->git_commit_sha !== 'HEAD') {
$git_clone_command = "{$git_clone_command} && cd {$this->workdir} && git -c advice.detachedHead=false checkout {$this->application->git_commit_sha} >/dev/null 2>&1";
}
if ($this->application->settings->is_git_submodules_enabled) {
$git_clone_command = "{$git_clone_command} && cd {$this->workdir} && git submodule update --init --recursive";
}
if ($this->application->settings->is_git_lfs_enabled) {
$git_clone_command = "{$git_clone_command} && cd {$this->workdir} && git lfs pull";
}
return $git_clone_command;
}
private function importing_git_repository()
{
$git_clone_command = "git clone -q -b {$this->application->git_branch}";
if ($this->pull_request_id !== 0) {
$pr_branch_name = "pr-{$this->pull_request_id}-coolify";
}
if ($this->application->deploymentType() === 'source') {
$source_html_url = data_get($this->application, 'source.html_url');
$url = parse_url(filter_var($source_html_url, FILTER_SANITIZE_URL));
$source_html_url_host = $url['host'];
$source_html_url_scheme = $url['scheme'];
if ($this->source->getMorphClass() == 'App\Models\GithubApp') {
if ($this->source->is_public) {
$git_clone_command = "{$git_clone_command} {$this->source->html_url}/{$this->application->git_repository} {$this->workdir}";
$git_clone_command = $this->set_git_import_settings($git_clone_command);
$commands = [$this->execute_in_builder($git_clone_command)];
if ($this->pull_request_id !== 0) {
$commands[] = $this->execute_in_builder("cd {$this->workdir} && git fetch origin pull/{$this->pull_request_id}/head:$pr_branch_name >/dev/null 2>&1 && git checkout $pr_branch_name >/dev/null 2>&1");
}
return $commands;
} else {
$github_access_token = generate_github_installation_token($this->source);
$commands = [
$this->execute_in_builder("git clone -q -b {$this->application->git_branch} $source_html_url_scheme://x-access-token:$github_access_token@$source_html_url_host/{$this->application->git_repository}.git {$this->workdir}")
];
if ($this->pull_request_id !== 0) {
$commands[] = $this->execute_in_builder("cd {$this->workdir} && git fetch origin pull/{$this->pull_request_id}/head:$pr_branch_name && git checkout $pr_branch_name");
}
return $commands;
}
}
}
if ($this->application->deploymentType() === 'deploy_key') {
$private_key = base64_encode($this->application->private_key->private_key);
$git_clone_command = "GIT_SSH_COMMAND=\"ssh -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /root/.ssh/id_rsa\" {$git_clone_command} {$this->application->git_full_url} {$this->workdir}";
$git_clone_command = $this->set_git_import_settings($git_clone_command);
return [
$this->execute_in_builder("mkdir -p /root/.ssh"),
$this->execute_in_builder("echo '{$private_key}' | base64 -d > /root/.ssh/id_rsa"),
$this->execute_in_builder("chmod 600 /root/.ssh/id_rsa"),
$this->execute_in_builder($git_clone_command)
];
}
}
private function nixpacks_build_cmd()
{
$this->generate_env_variables();
$nixpacks_command = "nixpacks build -o {$this->workdir} {$this->env_args} --no-error-without-start";
if ($this->application->build_command) {
$nixpacks_command .= " --build-cmd \"{$this->application->build_command}\"";
}
if ($this->application->start_command) {
$nixpacks_command .= " --start-cmd \"{$this->application->start_command}\"";
}
if ($this->application->install_command) {
$nixpacks_command .= " --install-cmd \"{$this->application->install_command}\"";
}
$nixpacks_command .= " {$this->workdir}";
return $this->execute_in_builder($nixpacks_command);
}
private function stop_running_container()
{
$this->execute_now([
"echo -n 'Removing old instance... '",
$this->execute_in_builder("docker rm -f $this->container_name >/dev/null 2>&1"),
"echo 'Done.'",
]);
}
private function start_by_compose_file()
{
$this->execute_now([
"echo -n 'Starting your application... '",
]);
$this->execute_now([
$this->execute_in_builder("docker compose --project-directory {$this->workdir} up -d >/dev/null"),
], isDebuggable: true);
$this->execute_now([
"echo 'Done. 🎉'",
], isFinished: true);
}
private function generate_compose_file()
{
$this->docker_compose = $this->generate_docker_compose();
$docker_compose_base64 = base64_encode($this->docker_compose);
$this->execute_now([
$this->execute_in_builder("echo '{$docker_compose_base64}' | base64 -d > {$this->workdir}/docker-compose.yml")
], hideFromOutput: true);
}
}

View File

@ -1,76 +0,0 @@
<?php
namespace App\Jobs;
use App\Models\Application;
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class ContainerStatusJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public string|null $container_id = null,
) {
}
public function handle(): void
{
try {
if ($this->container_id) {
$this->checkContainerStatus();
} else {
$this->checkAllServers();
}
} catch (\Exception $e) {
Log::error($e->getMessage());
}
}
protected function checkAllServers()
{
$servers = Server::all()->reject(fn (Server $server) => $server->settings->is_build_server);
$applications = Application::all();
$not_found_applications = $applications;
$containers = collect();
foreach ($servers as $server) {
$output = runRemoteCommandSync($server, ['docker ps -a -q --format \'{{json .}}\'']);
$containers = $containers->concat(formatDockerCmdOutputToJson($output));
}
foreach ($containers as $container) {
$found_application = $applications->filter(function ($value, $key) use ($container) {
return $value->uuid == $container['Names'];
})->first();
if ($found_application) {
$not_found_applications = $not_found_applications->filter(function ($value, $key) use ($found_application) {
return $value->uuid != $found_application->uuid;
});
$found_application->status = $container['State'];
$found_application->save();
Log::info('Found application: ' . $found_application->uuid . '. Set status to: ' . $found_application->status);
}
}
foreach ($not_found_applications as $not_found_application) {
$not_found_application->status = 'exited';
$not_found_application->save();
Log::info('Not found application: ' . $not_found_application->uuid . '. Set status to: ' . $not_found_application->status);
}
}
protected function checkContainerStatus()
{
$application = Application::where('uuid', $this->container_id)->firstOrFail();
if (!$application) {
return;
}
if ($application->destination->server) {
$container = runRemoteCommandSync($application->destination->server, ["docker inspect --format '{{json .State}}' {$this->container_id}"]);
$container = formatDockerCmdOutputToJson($container);
$application->status = $container[0]['Status'];
$application->save();
}
}
}

View File

@ -2,7 +2,7 @@
namespace App\Jobs;
use App\Actions\RemoteProcess\RunRemoteProcess;
use App\Actions\CoolifyTask\RunRemoteProcess;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
@ -10,7 +10,7 @@
use Illuminate\Queue\SerializesModels;
use Spatie\Activitylog\Models\Activity;
class ExecuteRemoteProcess implements ShouldQueue
class CoolifyTask implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
@ -19,18 +19,22 @@ class ExecuteRemoteProcess implements ShouldQueue
*/
public function __construct(
public Activity $activity,
){}
public bool $ignore_errors = false,
) {
}
/**
* Execute the job.
*/
public function handle(): void
{
$remoteProcess = resolve(RunRemoteProcess::class, [
$remote_process = resolve(RunRemoteProcess::class, [
'activity' => $this->activity,
'ignore_errors' => $this->ignore_errors,
]);
$remoteProcess();
$remote_process();
// @TODO: Remove file at $this->activity->getExtraProperty('private_key_location') after process is finished
}
}

View File

@ -1,471 +0,0 @@
<?php
namespace App\Jobs;
use App\Actions\RemoteProcess\RunRemoteProcess;
use App\Data\RemoteProcessArgs;
use App\Enums\ActivityTypes;
use App\Models\Application;
use App\Models\InstanceSettings;
use DateTimeImmutable;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Signer\Rsa\Sha256;
use Lcobucci\JWT\Token\Builder;
use Spatie\Activitylog\Models\Activity;
use Symfony\Component\Yaml\Yaml;
use Illuminate\Support\Str;
class DeployApplicationJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $application;
protected $destination;
protected $source;
protected Activity $activity;
protected string $git_commit;
protected string $workdir;
protected string $docker_compose;
public static int $batch_counter = 0;
/**
* Create a new job instance.
*/
public function __construct(
public string $deployment_uuid,
public string $application_uuid,
public bool $force_rebuild = false,
) {
$this->application = Application::query()
->where('uuid', $this->application_uuid)
->firstOrFail();
$this->destination = $this->application->destination->getMorphClass()::where('id', $this->application->destination->id)->first();
$server = $this->destination->server;
$private_key_location = savePrivateKeyForServer($server);
$remoteProcessArgs = new RemoteProcessArgs(
server_ip: $server->ip,
private_key_location: $private_key_location,
deployment_uuid: $this->deployment_uuid,
command: 'overwritten-later',
port: $server->port,
user: $server->user,
type: ActivityTypes::DEPLOYMENT->value,
);
$this->activity = activity()
->performedOn($this->application)
->withProperties($remoteProcessArgs->toArray())
->event(ActivityTypes::DEPLOYMENT->value)
->log("[]");
}
protected function stopRunningContainer()
{
$this->executeNow([
"echo -n 'Removing old instance... '",
$this->execute_in_builder("docker rm -f {$this->application->uuid} >/dev/null 2>&1"),
"echo 'Done.'",
"echo -n 'Starting your application... '",
]);
}
protected function startByComposeFile()
{
$this->executeNow([
$this->execute_in_builder("docker compose --project-directory {$this->workdir} up -d >/dev/null"),
], isDebuggable: true);
$this->executeNow([
"echo 'Done. 🎉'",
], isFinished: true);
}
protected function generateComposeFile()
{
$this->docker_compose = $this->generate_docker_compose();
$docker_compose_base64 = base64_encode($this->docker_compose);
$this->executeNow([
$this->execute_in_builder("echo '{$docker_compose_base64}' | base64 -d > {$this->workdir}/docker-compose.yml")
], hideFromOutput: true);
}
/**
* Execute the job.
*/
public function handle(): void
{
try {
$coolify_instance_settings = InstanceSettings::find(0);
$this->source = $this->application->source->getMorphClass()::where('id', $this->application->source->id)->first();
// Get Wildcard Domain
$project_wildcard_domain = data_get($this->application, 'environment.project.settings.wildcard_domain');
$global_wildcard_domain = data_get($coolify_instance_settings, 'wildcard_domain');
$wildcard_domain = $project_wildcard_domain ?? $global_wildcard_domain ?? null;
// Set wildcard domain
if (!$this->application->fqdn && $wildcard_domain) {
$this->application->fqdn = 'http://' . $this->application->uuid . '.' . $wildcard_domain;
$this->application->save();
}
$this->workdir = "/artifacts/{$this->deployment_uuid}";
// Pull builder image
$this->executeNow([
"echo 'Starting deployment of {$this->application->git_repository}:{$this->application->git_branch}...'",
"echo -n 'Pulling latest version of the builder image (ghcr.io/coollabsio/coolify-builder)... '",
"docker run --pull=always -d --name {$this->deployment_uuid} --rm -v /var/run/docker.sock:/var/run/docker.sock ghcr.io/coollabsio/coolify-builder >/dev/null 2>&1",
"echo 'Done.'",
]);
// Import git repository
$this->executeNow([
"echo -n 'Importing {$this->application->git_repository}:{$this->application->git_branch} to {$this->workdir}... '"
]);
$this->executeNow([
...$this->gitImport(),
], 'importing_git_repository');
$this->executeNow([
"echo 'Done.'"
]);
// Get git commit
$this->executeNow([$this->execute_in_builder("cd {$this->workdir} && git rev-parse HEAD")], 'commit_sha', hideFromOutput: true);
$this->git_commit = $this->activity->properties->get('commit_sha');
if (!$this->force_rebuild) {
$this->executeNow([
"docker images -q {$this->application->uuid}:{$this->git_commit} 2>/dev/null",
], 'local_image_found', hideFromOutput: true, ignoreErrors: true);
$image_found = Str::of($this->activity->properties->get('local_image_found'))->trim()->isNotEmpty();
if ($image_found) {
$this->executeNow([
"echo 'Docker Image found locally with the same Git Commit SHA. Build skipped...'"
]);
// Generate docker-compose.yml
$this->generateComposeFile();
// Stop running container
$this->stopRunningContainer();
// Start application
$this->startByComposeFile();
return;
}
}
$this->executeNow([
$this->execute_in_builder("rm -fr {$this->workdir}/.git")
], hideFromOutput: true);
// Generate docker-compose.yml
$this->generateComposeFile();
$this->executeNow([
"echo -n 'Generating nixpacks configuration... '",
]);
$this->executeNow([
$this->nixpacks_build_cmd(),
$this->execute_in_builder("cp {$this->workdir}/.nixpacks/Dockerfile {$this->workdir}/Dockerfile"),
$this->execute_in_builder("rm -f {$this->workdir}/.nixpacks/Dockerfile"),
], isDebuggable: true);
$this->executeNow([
"echo 'Done.'",
"echo -n 'Building image... '",
]);
if ($this->application->settings->is_static) {
$this->executeNow([
$this->execute_in_builder("docker build -f {$this->workdir}/Dockerfile --build-arg SOURCE_COMMIT={$this->git_commit} --progress plain -t {$this->application->uuid}:{$this->git_commit}-build {$this->workdir}"),
], isDebuggable: true);
$dockerfile = "FROM {$this->application->static_image}
WORKDIR /usr/share/nginx/html/
LABEL coolify.deploymentId={$this->deployment_uuid}
COPY --from={$this->application->uuid}:{$this->git_commit}-build /app/{$this->application->publish_directory} .";
$docker_file = base64_encode($dockerfile);
$this->executeNow([
$this->execute_in_builder("echo '{$docker_file}' | base64 -d > {$this->workdir}/Dockerfile-prod"),
$this->execute_in_builder("docker build -f {$this->workdir}/Dockerfile-prod --build-arg SOURCE_COMMIT={$this->git_commit} --progress plain -t {$this->application->uuid}:{$this->git_commit} {$this->workdir}"),
], hideFromOutput: true);
} else {
$this->executeNow([
$this->execute_in_builder("docker build -f {$this->workdir}/Dockerfile --build-arg SOURCE_COMMIT={$this->git_commit} --progress plain -t {$this->application->uuid}:{$this->git_commit} {$this->workdir}"),
], isDebuggable: true);
}
$this->executeNow([
"echo 'Done.'",
]);
// Stop running container
$this->stopRunningContainer();
// Start application
$this->startByComposeFile();
// Saving docker-compose.yml
Storage::disk('deployments')->put(Str::kebab($this->application->name) . '/docker-compose.yml', $this->docker_compose);
} catch (\Exception $e) {
$this->executeNow([
"echo 'Oops something is not okay, are you okay? 😢'",
"echo '\n\n{$e->getMessage()}'",
]);
throw new \Exception('Deployment finished');
} finally {
$this->executeNow(["docker rm -f {$this->deployment_uuid} >/dev/null 2>&1"], hideFromOutput: true);
dispatch(new ContainerStatusJob($this->application_uuid));
}
}
private function execute_in_builder(string $command)
{
return "docker exec {$this->deployment_uuid} bash -c '{$command}'";
}
private function generate_docker_compose()
{
$persistentStorages = $this->generate_local_persistent_volumes();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$ports = $this->application->settings->is_static ? [80] : $this->application->ports_exposes_array;
$docker_compose = [
'version' => '3.8',
'services' => [
$this->application->uuid => [
'image' => "{$this->application->uuid}:$this->git_commit",
'container_name' => $this->application->uuid,
'restart' => 'always',
'environment' => [
'PORT' => $ports[0]
],
'labels' => $this->set_labels_for_applications(),
'expose' => $ports,
'networks' => [
$this->destination->network,
],
'healthcheck' => [
'test' => [
'CMD-SHELL',
$this->generate_healthcheck_commands()
],
'interval' => $this->application->health_check_interval . 's',
'timeout' => $this->application->health_check_timeout . 's',
'retries' => $this->application->health_check_retries,
'start_period' => $this->application->health_check_start_period . 's'
],
]
],
'networks' => [
$this->destination->network => [
'external' => false,
'name' => $this->destination->network,
'attachable' => true,
]
]
];
if (count($this->application->ports_mappings_array) > 0) {
$docker_compose['services'][$this->application->uuid]['ports'] = $this->application->ports_mappings_array;
}
if (count($persistentStorages) > 0) {
$docker_compose['services'][$this->application->uuid]['volumes'] = $persistentStorages;
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
return Yaml::dump($docker_compose, 10);
}
private function generate_local_persistent_volumes()
{
foreach ($this->application->persistentStorages as $persistentStorage) {
$volume_name = $persistentStorage->host_path ?? $persistentStorage->name;
$local_persistent_volumes[] = $volume_name . ':' . $persistentStorage->mount_path;
}
return $local_persistent_volumes ?? [];
}
private function generate_local_persistent_volumes_only_volume_names()
{
foreach ($this->application->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$local_persistent_volumes_names[$persistentStorage->name] = [
'name' => $persistentStorage->name,
'external' => false,
];
}
return $local_persistent_volumes_names ?? [];
}
private function generate_healthcheck_commands()
{
if (!$this->application->health_check_port) {
$this->application->health_check_port = $this->application->ports_exposes_array[0];
}
if ($this->application->health_check_path) {
$generated_healthchecks_commands = [
"curl -s -X {$this->application->health_check_method} -f {$this->application->health_check_scheme}://{$this->application->health_check_host}:{$this->application->health_check_port}{$this->application->health_check_path} > /dev/null"
];
} else {
$generated_healthchecks_commands = [
"curl -s -X {$this->application->health_check_method} -f {$this->application->health_check_scheme}://{$this->application->health_check_host}:{$this->application->health_check_port}/"
];
}
return implode(' ', $generated_healthchecks_commands);
}
private function generate_jwt_token_for_github()
{
$signingKey = InMemory::plainText($this->source->privateKey->private_key);
$algorithm = new Sha256();
$tokenBuilder = (new Builder(new JoseEncoder(), ChainedFormatter::default()));
$now = new DateTimeImmutable();
$now = $now->setTime($now->format('H'), $now->format('i'));
$issuedToken = $tokenBuilder
->issuedBy($this->source->app_id)
->issuedAt($now)
->expiresAt($now->modify('+10 minutes'))
->getToken($algorithm, $signingKey)
->toString();
$token = Http::withHeaders([
'Authorization' => "Bearer $issuedToken",
'Accept' => 'application/vnd.github.machine-man-preview+json'
])->post("{$this->source->api_url}/app/installations/{$this->source->installation_id}/access_tokens");
if ($token->failed()) {
throw new \Exception("Failed to get access token for $this->application->name from " . $this->source->name . " with error: " . $token->json()['message']);
}
return $token->json()['token'];
}
private function set_labels_for_applications()
{
$labels = [];
$labels[] = 'coolify.managed=true';
$labels[] = 'coolify.version=' . config('coolify.version');
$labels[] = 'coolify.applicationId=' . $this->application->id;
$labels[] = 'coolify.type=application';
$labels[] = 'coolify.name=' . $this->application->name;
if ($this->application->fqdn) {
$labels[] = "traefik.http.routers.container.rule=Host(`{$this->application->fqdn}`)";
}
return $labels;
}
private function executeNow(
array|Collection $command,
string $propertyName = null,
bool $isFinished = false,
bool $hideFromOutput = false,
bool $isDebuggable = false,
bool $ignoreErrors = false
) {
static::$batch_counter++;
if ($command instanceof Collection) {
$commandText = $command->implode("\n");
} else {
$commandText = collect($command)->implode("\n");
}
$this->activity->properties = $this->activity->properties->merge([
'command' => $commandText,
]);
$this->activity->save();
if ($isDebuggable && !$this->application->settings->is_debug) {
$hideFromOutput = true;
}
$remoteProcess = resolve(RunRemoteProcess::class, [
'activity' => $this->activity,
'hideFromOutput' => $hideFromOutput,
'isFinished' => $isFinished,
'ignoreErrors' => $ignoreErrors,
]);
$result = $remoteProcess();
if ($propertyName) {
$this->activity->properties = $this->activity->properties->merge([
$propertyName => trim($result->output()),
]);
$this->activity->save();
}
if ($result->exitCode() != 0 && $result->errorOutput() && !$ignoreErrors) {
throw new \RuntimeException($result->errorOutput());
}
}
private function setGitImportSettings($git_clone_command)
{
if ($this->application->git_commit_sha) {
$git_clone_command = "{$git_clone_command} && cd {$this->workdir} && git checkout {$this->application->git_commit_sha}";
}
if ($this->application->settings->is_git_submodules_allowed) {
$git_clone_command = "{$git_clone_command} && cd {$this->workdir} && git submodule update --init --recursive";
}
if ($this->application->settings->is_git_lfs_allowed) {
$git_clone_command = "{$git_clone_command} && cd {$this->workdir} && git lfs pull";
}
return $git_clone_command;
}
private function gitImport()
{
$source_html_url = data_get($this->application, 'source.html_url');
$url = parse_url(filter_var($source_html_url, FILTER_SANITIZE_URL));
$source_html_url_host = $url['host'];
$source_html_url_scheme = $url['scheme'];
$git_clone_command = "git clone -q -b {$this->application->git_branch}";
if ($this->application->source->getMorphClass() == 'App\Models\GithubApp') {
if ($this->source->is_public) {
$git_clone_command = "{$git_clone_command} {$this->source->html_url}/{$this->application->git_repository} {$this->workdir}";
$git_clone_command = $this->setGitImportSettings($git_clone_command);
return [
$this->execute_in_builder($git_clone_command)
];
} else {
if (!$this->application->source->app_id) {
$private_key = base64_encode($this->application->source->privateKey->private_key);
$git_clone_command = "GIT_SSH_COMMAND=\"ssh -o LogLevel=ERROR -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -i /root/.ssh/id_rsa\" {$git_clone_command} git@$source_html_url_host:{$this->application->git_repository}.git {$this->workdir}";
$git_clone_command = $this->setGitImportSettings($git_clone_command);
return [
$this->execute_in_builder("mkdir -p /root/.ssh"),
$this->execute_in_builder("echo '{$private_key}' | base64 -d > /root/.ssh/id_rsa"),
$this->execute_in_builder("chmod 600 /root/.ssh/id_rsa"),
$this->execute_in_builder($git_clone_command)
];
} else {
$github_access_token = $this->generate_jwt_token_for_github();
return [
$this->execute_in_builder("git clone -q -b {$this->application->git_branch} $source_html_url_scheme://x-access-token:$github_access_token@$source_html_url_host/{$this->application->git_repository}.git {$this->workdir}")
];
}
}
}
}
private function nixpacks_build_cmd()
{
$nixpacks_command = "nixpacks build -o {$this->workdir} --no-error-without-start";
if ($this->application->install_command) {
$nixpacks_command .= " --install-cmd '{$this->application->install_command}'";
}
if ($this->application->build_command) {
$nixpacks_command .= " --build-cmd '{$this->application->build_command}'";
}
if ($this->application->start_command) {
$nixpacks_command .= " --start-cmd '{$this->application->start_command}'";
}
$nixpacks_command .= " {$this->workdir}";
return $this->execute_in_builder($nixpacks_command);
}
}

View File

@ -0,0 +1,83 @@
<?php
namespace App\Jobs;
use App\Models\InstanceSettings;
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Log;
class InstanceAutoUpdateJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $tries = 1;
public $timeout = 120;
public Server $server;
public string $latest_version;
public string $current_version;
public function __construct(private bool $force = false)
{
}
private function update()
{
if (config('app.env') === 'local') {
ray('Running update on local docker container');
instant_remote_process([
"sleep 10"
], $this->server);
ray('Update done');
return;
} else {
ray('Running update on production server');
instant_remote_process([
"curl -fsSL https://cdn.coollabs.io/coolify/upgrade.sh -o /data/coolify/source/upgrade.sh",
"bash /data/coolify/source/upgrade.sh $this->latest_version"
], $this->server);
return;
}
}
public function handle(): void
{
try {
ray('Running InstanceAutoUpdateJob');
$localhost_name = 'localhost';
if (config('app.env') === 'local') {
$localhost_name = 'testing-local-docker-container';
}
$this->server = Server::where('name', $localhost_name)->firstOrFail();
$this->latest_version = get_latest_version_of_coolify();
$this->current_version = config('version');
ray('latest version:' . $this->latest_version . " current version: " . $this->current_version . ' force: ' . $this->force);
if ($this->force) {
$this->update();
} else {
$instance_settings = InstanceSettings::get();
ray($instance_settings);
if (!$instance_settings->is_auto_update_enabled) {
throw new \Exception('Auto update is disabled');
}
if ($this->latest_version === $this->current_version) {
throw new \Exception('Already on latest version');
}
if (version_compare($this->latest_version, $this->current_version, '<')) {
throw new \Exception('Latest version is lower than current version?!');
}
$this->update();
}
return;
} catch (\Exception $e) {
ray('InstanceAutoUpdateJob failed');
ray($e->getMessage());
$this->fail($e->getMessage());
return;
}
}
}

View File

@ -4,17 +4,16 @@
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class DockerCleanupDanglingImagesJob implements ShouldQueue
class InstanceDockerCleanupJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 500;
/**
* Create a new job instance.
*/
@ -31,7 +30,7 @@ public function handle(): void
try {
$servers = Server::all();
foreach ($servers as $server) {
runRemoteCommandSync($server, ['docker image prune -f']);
instant_remote_process(['docker image prune -f'], $server);
}
} catch (\Exception $e) {
Log::error($e->getMessage());

View File

@ -0,0 +1,46 @@
<?php
namespace App\Jobs;
use App\Actions\Proxy\InstallProxy;
use App\Enums\ProxyTypes;
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class InstanceProxyCheckJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* Create a new job instance.
*/
public function __construct()
{
}
/**
* Execute the job.
*/
public function handle()
{
try {
$container_name = 'coolify-proxy';
$configuration_path = config('coolify.proxy_config_path');
$servers = Server::whereRelation('settings', 'is_validated', true)->where('extra_attributes->proxy_type', ProxyTypes::TRAEFIK_V2)->get();
foreach ($servers as $server) {
$status = get_container_status(server: $server, container_id: $container_name);
if ($status === 'running') {
continue;
}
resolve(InstallProxy::class)($server);
}
} catch (\Throwable $th) {
//throw $th;
}
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Jobs;
use App\Enums\ProxyTypes;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Models\Server;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Str;
use Illuminate\Queue\Middleware\WithoutOverlapping;
class ProxyContainerStatusJob implements ShouldQueue, ShouldBeUnique
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public Server $server;
public $tries = 1;
public $timeout = 120;
public function middleware(): array
{
return [new WithoutOverlapping($this->server->id)];
}
public function __construct(Server $server)
{
$this->server = $server;
}
public function uniqueId(): int
{
return $this->server->id;
}
public function handle(): void
{
try {
$container = get_container_status(server: $this->server, all_data: true, container_id: 'coolify-proxy', throwError: true);
$status = $container['State']['Status'];
if ($this->server->extra_attributes->proxy_status !== $status) {
$this->server->extra_attributes->proxy_status = $status;
if ($this->server->extra_attributes->proxy_status === 'running') {
$traefik = $container['Config']['Labels']['org.opencontainers.image.title'];
$version = $container['Config']['Labels']['org.opencontainers.image.version'];
if (isset($version) && isset($traefik) && $traefik === 'Traefik' && Str::of($version)->startsWith('v2')) {
$this->server->extra_attributes->proxy_type = ProxyTypes::TRAEFIK_V2->value;
}
}
$this->server->save();
}
} catch (\Exception $e) {
ray($e->getMessage());
}
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Http;
class SendMessageToDiscordJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/**
* The number of times the job may be attempted.
*
* @var int
*/
public $tries = 5;
/**
* The maximum number of unhandled exceptions to allow before failing.
*/
public int $maxExceptions = 3;
public function __construct(
public string $text,
public string $webhookUrl
) {}
/**
* Execute the job.
*/
public function handle(): void
{
$payload = [
'content' => $this->text,
];
Http::post($this->webhookUrl, $payload);
}
}

View File

@ -2,8 +2,11 @@
namespace App\Models;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Spatie\Activitylog\Models\Activity;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Spatie\SchemalessAttributes\Casts\SchemalessAttributes;
class Application extends BaseModel
{
@ -19,12 +22,13 @@ protected static function booted()
$application->persistentStorages()->delete();
});
}
protected $fillable = [
'name',
'project_id',
'description',
'git_repository',
'git_branch',
'git_full_url',
'build_pack',
'environment_id',
'destination_id',
@ -34,6 +38,7 @@ protected static function booted()
'ports_mappings',
'ports_exposes',
'publish_directory',
'private_key_id'
];
public function publishDirectory(): Attribute
@ -42,6 +47,27 @@ public function publishDirectory(): Attribute
set: fn ($value) => $value ? '/' . ltrim($value, '/') : null,
);
}
public function gitBranchLocation(): Attribute
{
return Attribute::make(
get: function () {
if (!is_null($this->source?->html_url) && !is_null($this->git_repository) && !is_null($this->git_branch)) {
return "{$this->source->html_url}/{$this->git_repository}/tree/{$this->git_branch}";
}
}
);
}
public function gitCommits(): Attribute
{
return Attribute::make(
get: function () {
if (!is_null($this->source?->html_url) && !is_null($this->git_repository) && !is_null($this->git_branch)) {
return "{$this->source->html_url}/{$this->git_repository}/commits/{$this->git_branch}";
}
}
);
}
public function baseDirectory(): Attribute
{
return Attribute::make(
@ -73,10 +99,52 @@ public function portsExposesArray(): Attribute
: explode(',', $this->ports_exposes)
);
}
// Normal Deployments
public function environment_variables(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', false);
}
public function runtime_environment_variables(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', false)->where('key', 'not like', 'NIXPACKS_%');
}
public function build_environment_variables(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', false)->where('is_build_time', true)->where('key', 'not like', 'NIXPACKS_%');
}
public function nixpacks_environment_variables(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', false)->where('key', 'like', 'NIXPACKS_%');
}
// Preview Deployments
public function environment_variables_preview(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', true);
}
public function runtime_environment_variables_preview(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', true)->where('key', 'not like', 'NIXPACKS_%');
}
public function build_environment_variables_preview(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', true)->where('is_build_time', true)->where('key', 'not like', 'NIXPACKS_%');
}
public function nixpacks_environment_variables_preview(): HasMany
{
return $this->hasMany(EnvironmentVariable::class)->where('is_preview', true)->where('key', 'like', 'NIXPACKS_%');
}
public function private_key()
{
return $this->belongsTo(PrivateKey::class);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function previews()
{
return $this->hasMany(ApplicationPreview::class);
}
public function settings()
{
return $this->hasOne(ApplicationSetting::class);
@ -94,13 +162,42 @@ public function persistentStorages()
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function deployments()
public function deployments(int $skip = 0, int $take = 10)
{
return Activity::where('subject_id', $this->id)->where('properties->deployment_uuid', '!=', null)->orderBy('created_at', 'desc')->get();
$deployments = ApplicationDeploymentQueue::where('application_id', $this->id)->orderBy('created_at', 'desc');
$count = $deployments->count();
$deployments = $deployments->skip($skip)->take($take)->get();
return [
'count' => $count,
'deployments' => $deployments
];
}
public function get_deployment(string $deployment_uuid)
{
return Activity::where('subject_id', $this->id)->where('properties->deployment_uuid', '=', $deployment_uuid)->first();
return Activity::where('subject_id', $this->id)->where('properties->type_uuid', '=', $deployment_uuid)->first();
}
public function isDeployable(): bool
{
if ($this->settings->is_auto_deploy_enabled) {
return true;
}
return false;
}
public function isPRDeployable(): bool
{
if ($this->settings->is_preview_deployments_enabled) {
return true;
}
return false;
}
public function deploymentType()
{
if (data_get($this, 'source')) {
return 'source';
}
if (data_get($this, 'private_key_id')) {
return 'deploy_key';
}
throw new \Exception('No deployment type found');
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Models;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Spatie\SchemalessAttributes\Casts\SchemalessAttributes;
class ApplicationDeploymentQueue extends Model
{
protected $fillable = [
'application_id',
'deployment_uuid',
'pull_request_id',
'force_rebuild',
'commit',
'status',
'is_webhook',
];
}

View File

@ -0,0 +1,23 @@
<?php
namespace App\Models;
class ApplicationPreview extends BaseModel
{
protected $fillable = [
'uuid',
'pull_request_id',
'pull_request_html_url',
'fqdn',
'status',
'application_id',
];
public function application()
{
return $this->belongsTo(Application::class);
}
static function findPreviewByApplicationAndPullId(int $application_id, int $pull_request_id)
{
return self::where('application_id', $application_id)->where('pull_request_id', $pull_request_id)->firstOrFail();
}
}

View File

@ -7,21 +7,37 @@
class ApplicationSetting extends Model
{
protected $cast = [
'is_static' => 'boolean',
'is_auto_deploy_enabled' => 'boolean',
'is_force_https_enabled' => 'boolean',
'is_debug_enabled' => 'boolean',
'is_preview_deployments_enabled' => 'boolean',
'is_git_submodules_enabled' => 'boolean',
'is_git_lfs_enabled' => 'boolean',
];
protected $fillable = [
'application_id',
'is_git_submodules_allowed',
'is_git_lfs_allowed',
'is_static',
'is_auto_deploy_enabled',
'is_force_https_enabled',
'is_debug_enabled',
'is_preview_deployments_enabled',
'is_git_submodules_enabled',
'is_git_lfs_enabled',
];
public function isStatic(): Attribute
{
return Attribute::make(
set: function ($value) {
if ($value) {
$this->application->ports_exposes = '80';
} else {
$this->application->ports_exposes = '3000';
if (is_null($this->application->ports_exposes)) {
if ($value) {
$this->application->ports_exposes = '80';
} else {
$this->application->ports_exposes = '3000';
}
$this->application->save();
}
$this->application->save();
return $value;
}
);

View File

@ -12,7 +12,10 @@ protected static function boot()
parent::boot();
static::creating(function (Model $model) {
$model->uuid = (string) new Cuid2(7);
// Generate a UUID if one isn't set
if (!$model->uuid) {
$model->uuid = (string) new Cuid2(7);
}
});
}
}

View File

@ -12,8 +12,4 @@ public function destination()
{
return $this->morphTo();
}
public function deployments()
{
return $this->morphMany(Deployment::class, 'type');
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Models;
use App\Models\EnvironmentVariable as ModelsEnvironmentVariable;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class EnvironmentVariable extends Model
{
protected static function booted()
{
static::created(function ($environment_variable) {
if (!$environment_variable->is_preview) {
ModelsEnvironmentVariable::create([
'key' => $environment_variable->key,
'value' => $environment_variable->value,
'is_build_time' => $environment_variable->is_build_time,
'application_id' => $environment_variable->application_id,
'is_preview' => true,
]);
}
});
}
protected $fillable = ['key', 'value', 'is_build_time', 'application_id', 'is_preview'];
protected $casts = [
"key" => 'string',
'value' => 'encrypted',
'is_build_time' => 'boolean',
];
private function get_environment_variables(string $environment_variable): string|null
{
// $team_id = session('currentTeam')->id;
if (str_contains(trim($environment_variable), '{{') && str_contains(trim($environment_variable), '}}')) {
$environment_variable = preg_replace('/\s+/', '', $environment_variable);
$environment_variable = str_replace('{{', '', $environment_variable);
$environment_variable = str_replace('}}', '', $environment_variable);
if (str_starts_with($environment_variable, 'global.')) {
$environment_variable = str_replace('global.', '', $environment_variable);
// $environment_variable = GlobalEnvironmentVariable::where('name', $environment_variable)->where('team_id', $team_id)->first()?->value;
return $environment_variable;
}
}
return decrypt($environment_variable);
}
private function set_environment_variables(string $environment_variable): string|null
{
$environment_variable = trim($environment_variable);
if (!str_contains(trim($environment_variable), '{{') && !str_contains(trim($environment_variable), '}}')) {
return encrypt($environment_variable);
}
return $environment_variable;
}
protected function value(): Attribute
{
return Attribute::make(
get: fn (string $value) => $this->get_environment_variables($value),
set: fn (string $value) => $this->set_environment_variables($value),
);
}
protected function key(): Attribute
{
return Attribute::make(
set: fn (string $value) => Str::of($value)->trim(),
);
}
}

View File

@ -2,11 +2,25 @@
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
class GithubApp extends BaseModel
{
protected $fillable = ['name', 'uuid', 'organization', 'api_url', 'html_url', 'custom_user', 'custom_port', 'team_id'];
protected $appends = ['type'];
protected $casts = [
'is_public' => 'boolean',
'type' => 'string'
];
protected static function booted(): void
{
static::deleting(function (GithubApp $github_app) {
$applications_count = Application::where('source_id', $github_app->id)->count();
if ($applications_count > 0) {
throw new \Exception('You cannot delete this GitHub App because it is in use by ' . $applications_count . ' application(s). Delete them first.');
}
});
}
public function applications()
{
return $this->morphMany(Application::class, 'source');
@ -15,4 +29,22 @@ public function privateKey()
{
return $this->belongsTo(PrivateKey::class);
}
public function type(): Attribute
{
return Attribute::make(
get: function () {
if ($this->getMorphClass() === 'App\Models\GithubApp') {
return 'github';
}
},
);
}
static public function public()
{
return GithubApp::where('team_id', session('currentTeam')->id)->where('is_public', true)->get();
}
static public function private()
{
return GithubApp::where('team_id', session('currentTeam')->id)->where('is_public', false)->get();
}
}

Some files were not shown because too many files have changed in this diff Show More