Merge branch 'v4-next' into notifications

This commit is contained in:
Andras Bacsai 2023-06-01 08:22:07 +02:00
commit 2d9db6d9cb
204 changed files with 5744 additions and 2545 deletions

View File

@ -8,6 +8,7 @@ GROUPID=
PROJECT_PATH_ON_HOST=/Users/your-username-here/code/coollabsio/coolify
SERVEO_URL=<for receiving webhooks locally https://serveo.net/>
MUX_ENABLED=false
RAY_HOST=ray@host.docker.internal
############################################################################################################
APP_NAME=Coolify

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
@ -18,3 +24,5 @@ DB_PASSWORD=
QUEUE_CONNECTION=redis
REDIS_HOST=coolify-redis
REDIS_PASSWORD=
CACHE_DRIVER=redis

4
.gitignore vendored
View File

@ -25,3 +25,7 @@ _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://coolify-cdn.b-cdn.net/files/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

@ -4,12 +4,15 @@
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;
@ -52,7 +55,7 @@ public function __invoke(): ProcessResult
$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;
@ -97,7 +100,7 @@ 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)
@ -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(),
];

View File

@ -11,7 +11,7 @@ class CheckProxySettingsInSync
public function __invoke(Server $server, bool $reset = false)
{
$proxy_path = config('coolify.proxy_config_path');
$output = instantRemoteProcess([
$output = instant_remote_process([
"cat $proxy_path/docker-compose.yml",
], $server, false);
if (is_null($output) || $reset) {
@ -23,7 +23,7 @@ public function __invoke(Server $server, bool $reset = false)
$server->extra_attributes->last_saved_proxy_settings = Str::of($docker_compose_yml_base64)->pipe('md5')->value;
$server->save();
if (is_null($output) || $reset) {
instantRemoteProcess([
instant_remote_process([
"mkdir -p $proxy_path",
"echo '$docker_compose_yml_base64' | base64 -d > $proxy_path/docker-compose.yml",
], $server);

View File

@ -2,16 +2,12 @@
namespace App\Actions\Proxy;
use App\Enums\ActivityTypes;
use App\Models\InstanceSettings;
use App\Models\Server;
use Spatie\Activitylog\Models\Activity;
use Illuminate\Support\Str;
use Spatie\Url\Url;
class InstallProxy
{
public function __invoke(Server $server): Activity
{
$proxy_path = config('coolify.proxy_config_path');
@ -26,7 +22,7 @@ public function __invoke(Server $server): Activity
return "docker network ls --format '{{.Name}}' | grep '^$network$' >/dev/null 2>&1 || docker network create --attachable $network > /dev/null 2>&1";
});
$configuration = instantRemoteProcess([
$configuration = instant_remote_process([
"cat $proxy_path/docker-compose.yml",
], $server, false);
if (is_null($configuration)) {
@ -38,16 +34,16 @@ public function __invoke(Server $server): Activity
$server->extra_attributes->last_applied_proxy_settings = Str::of($docker_compose_yml_base64)->pipe('md5')->value;
$server->save();
$env_file_base64 = base64_encode(
$this->getEnvContents()
);
$activity = remoteProcess([
// $env_file_base64 = base64_encode(
// $this->getEnvContents()
// );
$activity = remote_process([
...$create_networks_command,
"echo 'Docker networks created...'",
"mkdir -p $proxy_path",
"cd $proxy_path",
"echo '$docker_compose_yml_base64' | base64 -d > $proxy_path/docker-compose.yml",
"echo '$env_file_base64' | base64 -d > $proxy_path/.env",
// "echo '$env_file_base64' | base64 -d > $proxy_path/.env",
"echo 'Docker compose file created...'",
"echo 'Pulling docker image...'",
'docker compose pull -q',
@ -56,23 +52,20 @@ public function __invoke(Server $server): Activity
"echo 'Starting proxy...'",
'docker compose up -d --remove-orphans',
"echo 'Proxy installed successfully...'"
], $server, ActivityTypes::INLINE->value);
], $server);
return $activity;
}
protected function getEnvContents()
{
$instance_fqdn = InstanceSettings::get()->fqdn ?? config('app.url');
$url = Url::fromString($instance_fqdn);
$data = [
'TRAEFIK_DASHBOARD_HOST' => $url->getHost(),
'LETS_ENCRYPT_EMAIL' => '',
];
// protected function getEnvContents()
// {
// $data = [
// 'LETS_ENCRYPT_EMAIL' => '',
// ];
return collect($data)
->map(fn ($v, $k) => "{$k}={$v}")
->push(PHP_EOL)
->implode(PHP_EOL);
}
// return collect($data)
// ->map(fn ($v, $k) => "{$k}={$v}")
// ->push(PHP_EOL)
// ->implode(PHP_EOL);
// }
}

View File

@ -10,14 +10,14 @@ class InstallDocker
public function __invoke(Server $server)
{
$config = base64_encode('{ "live-restore": true }');
$activity = remoteProcess([
$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, ActivityTypes::INLINE->value);
], $server);
return $activity;
}

View File

@ -60,7 +60,7 @@ public function handle()
];
return PendingRequest::withHeaders($headers)->post('https://api.bunny.net/purge', [
"urls" => [$url],
]);
])->throw();
});
try {
Http::pool(fn (Pool $pool) => [
@ -72,18 +72,14 @@ public function handle()
$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/$versions"),
]);
Http::pool(fn (Pool $pool) => [
$pool->purge(url: "$bunny_cdn/$bunny_cdn_path/$compose_file"),
$pool->purge(url: "$bunny_cdn/$bunny_cdn_path/$compose_file_prod"),
$pool->purge(url: "$bunny_cdn/$bunny_cdn_path/$production_env"),
$pool->purge(url: "$bunny_cdn/$bunny_cdn_path/$upgrade_script"),
$pool->purge(url: "$bunny_cdn/$bunny_cdn_path/$install_script"),
$pool->purge(url: "$bunny_cdn/$bunny_cdn_path/$docker_install_script"),
$pool->purge(url: "$bunny_cdn/$versions"),
]);
Http::withHeaders([
'AccessKey' => env('BUNNY_API_KEY'),
'Accept' => 'application/json',
])->get('https://api.bunny.net/purge', [
"url" => "$bunny_cdn/$bunny_cdn_path/*",
"async" => false
])->throw();
echo "All files uploaded & purged...\n";
return;
throw new \Exception("Something went wrong.");
} catch (\Exception $e) {
echo $e->getMessage();
}

View File

@ -2,9 +2,9 @@
namespace App\Console;
use App\Jobs\ContainerStatusJob;
use App\Jobs\DockerCleanupDanglingImagesJob;
use App\Jobs\ProxyCheckJob;
use App\Jobs\InstanceAutoUpdateJob;
use App\Jobs\InstanceProxyCheckJob;
use App\Jobs\InstanceDockerCleanupJob;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
@ -15,9 +15,11 @@ class Kernel extends ConsoleKernel
*/
protected function schedule(Schedule $schedule): void
{
$schedule->job(new ContainerStatusJob)->everyMinute();
$schedule->job(new DockerCleanupDanglingImagesJob)->everyMinute();
// $schedule->job(new ProxyCheckJob)->everyMinute();
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->job(new InstanceDockerCleanupJob)->everyFiveMinutes();
$schedule->job(new InstanceAutoUpdateJob)->everyFifteenMinutes();
// $schedule->job(new InstanceProxyCheckJob)->everyMinute();
}
/**

View File

@ -1,15 +0,0 @@
<?php
namespace App\Data;
use Spatie\LaravelData\Data;
class ApplicationPreview extends Data
{
public function __construct(
public int $pullRequestId,
public string $branch,
public ?string $commit,
) {
}
}

View File

@ -8,4 +8,5 @@ enum ProcessStatus: string
case IN_PROGRESS = 'in_progress';
case FINISHED = 'finished';
case ERROR = 'error';
case CANCELLED = 'cancelled';
}

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,6 +2,7 @@
namespace App\Http\Controllers;
use App\Models\ApplicationDeploymentQueue;
use Illuminate\Http\Request;
use Spatie\Activitylog\Models\Activity;
@ -21,7 +22,7 @@ public function configuration()
if (!$application) {
return redirect()->route('dashboard');
}
return view('project.application.configuration', ['application' => $application,]);
return view('project.application.configuration', ['application' => $application]);
}
public function deployments()
{
@ -37,7 +38,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()
@ -64,9 +65,18 @@ public function deployment()
'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,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,7 +27,7 @@ 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 new()

View File

@ -13,7 +13,7 @@ class CheckUpdate extends Component
public function checkUpdate()
{
$this->latestVersion = getLatestVersionOfCoolify();
$this->latestVersion = get_latest_version_of_coolify();
$this->currentVersion = config('version');
if ($this->latestVersion === 'latest') {
$this->updateAvailable = true;

View File

@ -25,13 +25,13 @@ public function delete()
if ($this->destination->attachedTo()) {
return $this->emit('error', 'You must delete all resources before deleting this destination.');
}
instantRemoteProcess(["docker network disconnect {$this->destination->network} coolify-proxy"], $this->destination->server, throwError: false);
instantRemoteProcess(['docker network rm -f ' . $this->destination->network], $this->destination->server);
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 generalErrorHandler($e);
return general_error_handler($e);
}
}
}

View File

@ -33,7 +33,7 @@ public function mount()
}
}
$this->network = new Cuid2(7);
$this->name = generateRandomName();
$this->name = generate_random_name();
}
public function submit()
@ -45,8 +45,8 @@ public function submit()
return;
}
$server = Server::find($this->server_id);
instantRemoteProcess(['docker network create --attachable ' . $this->network], $server, throwError: false);
instantRemoteProcess(["docker network connect $this->network coolify-proxy"], $server, throwError: false);
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,

View File

@ -2,51 +2,19 @@
namespace App\Http\Livewire;
use App\Enums\ActivityTypes;
use App\Models\Server;
use App\Jobs\InstanceAutoUpdateJob;
use Livewire\Component;
class ForceUpgrade extends Component
{
public bool $visible = false;
public function upgrade()
{
if (config('app.env') === 'local') {
$server = Server::where('ip', 'coolify-testing-host')->first();
if (!$server) {
return;
}
instantRemoteProcess([
"sleep 2"
], $server);
remoteProcess([
"sleep 10"
], $server, ActivityTypes::INLINE->value);
$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;
}
instantRemoteProcess([
"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",
], $server);
instantRemoteProcess([
"docker compose -f /data/coolify/source/docker-compose.yml -f /data/coolify/source/docker-compose.prod.yml pull",
], $server);
remoteProcess([
"bash /data/coolify/source/upgrade.sh $latestVersion"
], $server, ActivityTypes::INLINE->value);
$this->emit('updateInitiated');
try {
$this->visible = true;
dispatch(new InstanceAutoUpdateJob(force: true));
} catch (\Exception $e) {
return general_error_handler($e, $this);
}
}
}

View File

@ -35,7 +35,7 @@ public function changePrivateKey()
$this->private_key->save();
session('currentTeam')->privateKeys = PrivateKey::where('team_id', session('currentTeam')->id)->get();
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
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

@ -2,8 +2,27 @@
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,47 @@ class Deploy extends Component
protected array $command = [];
protected $source;
protected $listeners = [
'applicationStatusChanged' => 'applicationStatusChanged',
];
public function mount()
{
$this->parameters = getParameters();
$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)
{
return redirect()->route('project.application.deployment', $this->parameters);
}
public function start()
{
$this->setDeploymentUuid();
$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()
{
instantRemoteProcess(["docker rm -f {$this->application->uuid}"], $this->destination->server);
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();
}
}

View File

@ -3,18 +3,21 @@
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->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)
@ -23,7 +26,7 @@ public function polling()
$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,41 @@
<?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 = true;
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 && count($this->deployments) < $take) {
$this->show_next = false;
return;
}
}
}

View File

@ -23,7 +23,7 @@ class Add extends Component
];
public function mount()
{
$this->parameters = getParameters();
$this->parameters = get_parameters();
}
public function submit()
{

View File

@ -26,7 +26,7 @@ public function submit($data)
$this->application->refresh();
$this->emit('clearAddEnv');
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
}

View File

@ -17,7 +17,7 @@ class Show extends Component
];
public function mount()
{
$this->parameters = getParameters();
$this->parameters = get_parameters();
}
public function submit()
{

View File

@ -3,8 +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
{
@ -17,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',
@ -48,41 +51,68 @@ public function instantSave()
{
// @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->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()
{
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 generalErrorHandler($e, $this);
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->type_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

@ -2,10 +2,84 @@
namespace App\Http\Livewire\Project\Application;
use App\Jobs\ContainerStatusJob;
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 ContainerStatusJob(
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()
{
['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();
}
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

@ -13,7 +13,6 @@ class ResourceLimits extends Component
'application.limits_memory_swap' => 'required|string',
'application.limits_memory_swappiness' => 'required|integer|min:0|max:100',
'application.limits_memory_reservation' => 'required|string',
'application.limits_memory_oom_kill' => 'boolean',
'application.limits_cpus' => 'nullable',
'application.limits_cpuset' => 'nullable',
'application.limits_cpu_shares' => 'nullable',
@ -45,7 +44,7 @@ public function submit()
$this->validate();
$this->application->save();
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
}

View File

@ -5,27 +5,48 @@
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 function revertImage($tag)
public array $parameters;
public function mount()
{
dd("Reverting to {$this->application->uuid}:{$tag}");
$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 = instantRemoteProcess([
$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 = instantRemoteProcess([
$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) {
@ -33,7 +54,7 @@ public function loadImages()
})->map(function ($item) {
$item = Str::of($item)->explode('#');
if ($item[1] === $this->current) {
$is_current = true;
// $is_current = true;
}
return [
'tag' => $item[1],
@ -42,7 +63,7 @@ public function loadImages()
];
})->toArray();
} catch (\Throwable $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
}

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->emit('applicationStatusChanged');
$this->application->refresh();
}
}

View File

@ -23,7 +23,7 @@ class Add extends Component
];
public function mount()
{
$this->parameters = getParameters();
$this->parameters = get_parameters();
}
public function submit()
{

View File

@ -27,7 +27,7 @@ public function submit($data)
$this->application->refresh();
$this->emit('clearAddStorage');
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
}

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

@ -5,11 +5,16 @@
use App\Models\Project;
use Livewire\Component;
class Delete extends 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([
@ -17,9 +22,9 @@ public function delete()
]);
$project = Project::findOrFail($this->project_id);
if ($project->applications->count() > 0) {
return $this->emit('error', 'Project has applications, please delete them first.');
return $this->emit('error', 'Project has resources defined, please delete them first.');
}
$project->delete();
return redirect()->route('dashboard');
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

@ -110,7 +110,7 @@ public function submit()
$environment = $project->load(['environments'])->environments->where('name', $this->parameters['environment_name'])->first();
$application = Application::create([
'name' => generateRandomName(),
'name' => generate_random_name(),
'repository_project_id' => $this->selected_repository_id,
'git_repository' => "{$this->selected_repository_owner}/{$this->selected_repository_repo}",
'git_branch' => $this->selected_branch_name,
@ -129,12 +129,12 @@ public function submit()
'environment_name' => $environment->name
]);
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
public function mount()
{
$this->parameters = getParameters();
$this->parameters = get_parameters();
$this->query = request()->query();
$this->repositories = $this->branches = collect();
$this->github_apps = GithubApp::private();

View File

@ -34,7 +34,7 @@ public function mount()
if (config('app.env') === 'local') {
$this->repository_url = 'https://github.com/coollabsio/coolify-examples/tree/nodejs-fastify';
}
$this->parameters = getParameters();
$this->parameters = get_parameters();
$this->query = request()->query();
$this->private_keys = PrivateKey::where('team_id', session('currentTeam')->id)->get();
}
@ -74,7 +74,7 @@ public function submit()
$project = Project::where('uuid', $this->parameters['project_uuid'])->first();
$environment = $project->load(['environments'])->environments->where('name', $this->parameters['environment_name'])->first();
$application_init = [
'name' => generateRandomName(),
'name' => generate_random_name(),
'git_repository' => $git_repository,
'git_branch' => $git_branch,
'git_full_url' => "git@$git_host:$git_repository.git",
@ -96,7 +96,7 @@ public function submit()
'application_uuid' => $application->uuid,
]);
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
}

View File

@ -37,7 +37,7 @@ public function mount()
$this->repository_url = 'https://github.com/coollabsio/coolify-examples/tree/nodejs-fastify';
$this->port = 3000;
}
$this->parameters = getParameters();
$this->parameters = get_parameters();
$this->query = request()->query();
}
@ -78,7 +78,7 @@ public function submit()
$application_init = [
'name' => generateRandomName(),
'name' => generate_application_name($git_repository, $git_branch),
'git_repository' => $git_repository,
'git_branch' => $git_branch,
'build_pack' => 'nixpacks',
@ -106,7 +106,7 @@ public function submit()
'application_uuid' => $application->uuid,
]);
} catch (\Exception $e) {
return generalErrorHandler($e);
return general_error_handler($e);
}
}
}

View File

@ -26,10 +26,10 @@ public function runCommand()
{
try {
$this->validate();
$activity = remoteProcess([$this->command], Server::where('uuid', $this->server)->first(), ActivityTypes::INLINE->value);
$activity = remote_process([$this->command], Server::where('uuid', $this->server)->first());
$this->emit('newMonitorActivity', $activity->id);
} catch (\Exception $e) {
return generalErrorHandler($e);
return general_error_handler($e);
}
}
}

View File

@ -36,7 +36,7 @@ public function installDocker()
public function validateServer()
{
try {
$this->uptime = instantRemoteProcess(['uptime'], $this->server, false);
$this->uptime = instant_remote_process(['uptime'], $this->server, false);
if (!$this->uptime) {
$this->uptime = 'Server not reachable.';
throw new \Exception('Server not reachable.');
@ -47,16 +47,16 @@ public function validateServer()
$this->emit('serverValidated');
}
}
$this->dockerVersion = instantRemoteProcess(['docker version|head -2|grep -i version'], $this->server, false);
$this->dockerVersion = instant_remote_process(['docker version|head -2|grep -i version'], $this->server, false);
if (!$this->dockerVersion) {
$this->dockerVersion = 'Not installed.';
}
$this->dockerComposeVersion = instantRemoteProcess(['docker compose version|head -2|grep -i version'], $this->server, false);
$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 generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
public function delete()

View File

@ -30,7 +30,7 @@ class ByIp extends Component
];
public function mount()
{
$this->name = generateRandomName();
$this->name = generate_random_name();
$this->private_key_id = $this->private_keys->first()->id;
}
public function setPrivateKey(string $private_key_id)
@ -61,7 +61,7 @@ public function submit()
$server->settings->save();
return redirect()->route('server.show', $server->uuid);
} catch (\Exception $e) {
return generalErrorHandler($e);
return general_error_handler($e);
}
}
}

View File

@ -4,7 +4,6 @@
use App\Models\PrivateKey as ModelsPrivateKey;
use App\Models\Server;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Livewire\Component;
@ -19,13 +18,12 @@ public function setPrivateKey($private_key_id)
'private_key_id' => $private_key_id
]);
// Delete the old ssh mux file to force a new one to be created
Storage::disk('local')->delete(".ssh/ssh_mux_{$server->first()->ip}_{$server->first()->port}_{$server->first()->user}");
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 = getParameters();
$this->parameters = get_parameters();
$this->private_keys = ModelsPrivateKey::where('team_id', session('currentTeam')->id)->get();
}
}

View File

@ -39,7 +39,7 @@ public function installProxy()
public function proxyStatus()
{
$this->server->extra_attributes->proxy_status = checkContainerStatus(server: $this->server, container_id: 'coolify-proxy');
$this->server->extra_attributes->proxy_status = get_container_status(server: $this->server, container_id: 'coolify-proxy');
$this->server->save();
$this->server->refresh();
}
@ -51,7 +51,7 @@ public function setProxy()
}
public function stopProxy()
{
instantRemoteProcess([
instant_remote_process([
"docker rm -f coolify-proxy",
], $this->server);
$this->server->extra_attributes->proxy_status = 'exited';
@ -65,11 +65,11 @@ public function saveConfiguration()
$docker_compose_yml_base64 = base64_encode($this->proxy_settings);
$this->server->extra_attributes->last_saved_proxy_settings = Str::of($docker_compose_yml_base64)->pipe('md5')->value;
$this->server->save();
instantRemoteProcess([
instant_remote_process([
"echo '$docker_compose_yml_base64' | base64 -d > $proxy_path/docker-compose.yml",
], $this->server);
} catch (\Exception $e) {
return generalErrorHandler($e);
return general_error_handler($e);
}
}
public function resetProxy()
@ -77,7 +77,7 @@ public function resetProxy()
try {
$this->proxy_settings = resolve(CheckProxySettingsInSync::class)($this->server, true);
} catch (\Exception $e) {
return generalErrorHandler($e);
return general_error_handler($e);
}
}
public function checkProxySettingsInSync()
@ -85,7 +85,7 @@ public function checkProxySettingsInSync()
try {
$this->proxy_settings = resolve(CheckProxySettingsInSync::class)($this->server);
} catch (\Exception $e) {
return generalErrorHandler($e);
return general_error_handler($e);
}
}
}

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,30 +14,174 @@ 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()
{
$this->resetErrorBag();
@ -44,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

@ -35,7 +35,7 @@ public function submit()
$this->validate();
$this->github_app->save();
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
public function instantSave()
@ -45,7 +45,7 @@ public function instantSave()
$this->github_app->save();
$this->emit('saved', 'GitHub settings updated!');
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
public function mount()
@ -54,7 +54,7 @@ public function mount()
if ($settings->fqdn) {
$this->host = $settings->fqdn;
}
$this->parameters = getParameters();
$this->parameters = get_parameters();
$this->is_system_wide = $this->github_app->is_system_wide;
}
public function delete()
@ -63,7 +63,7 @@ public function delete()
$this->github_app->delete();
redirect()->route('dashboard');
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
}

View File

@ -1,6 +1,6 @@
<?php
namespace App\Http\Livewire\Source;
namespace App\Http\Livewire\Source\Github;
use App\Models\GithubApp;
use Livewire\Component;
@ -17,7 +17,7 @@ class Create extends Component
public function mount()
{
$this->name = generateRandomName();
$this->name = generate_random_name();
}
public function createGitHubApp()
{
@ -43,7 +43,7 @@ public function createGitHubApp()
]);
redirect()->route('source.github.show', ['github_app_uuid' => $github_app->uuid]);
} catch (\Exception $e) {
return generalErrorHandler($e, $this);
return general_error_handler($e, $this);
}
}
}

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,658 @@
<?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) {
$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) {
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) {
$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 ContainerStatusJob(
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();
foreach ($this->application->runtime_environment_variables 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([]);
foreach ($this->application->nixpacks_environment_variables 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}"]);
foreach ($this->application->build_environment_variables 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;
if ($this->pull_request_id) {
$persistent_storages = [];
$volume_names = [];
$environment_variables = [];
} else {
$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) {
$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()
{
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 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) {
$labels[] = 'coolify.pullRequestId=' . $this->pull_request_id;
}
if ($this->application->fqdn) {
if ($this->pull_request_id) {
$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) {
$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) {
$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) {
$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

@ -3,72 +3,86 @@
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 ContainerStatusJob implements ShouldQueue
class ContainerStatusJob implements ShouldQueue, ShouldBeUnique
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function __construct(
public string|null $container_id = null,
) {
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 {
if ($this->container_id) {
$this->checkContainerStatus();
$status = get_container_status(server: $this->application->destination->server, container_id: $this->container_name, throwError: false);
ray('Container ' . $this->container_name . ' statuus is ' . $status);
if ($this->pull_request_id) {
$preview = ApplicationPreview::findPreviewByApplicationAndPullId($this->application->id, $this->pull_request_id);
$preview->status = $status;
$preview->save();
} else {
$this->checkAllServers();
$this->application->status = $status;
$this->application->save();
}
} catch (\Exception $e) {
Log::error($e->getMessage());
}
}
protected function checkAllServers()
protected function check_container_status()
{
$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 = instantRemoteProcess(['docker ps -a -q --format \'{{json .}}\''], $server);
$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) {
$application->status = checkContainerStatus(server: $application->destination->server, container_id: $this->container_id);
$application->save();
if ($this->application->destination->server) {
$this->application->status = get_container_status(server: $this->application->destination->server, container_id: $this->application->uuid);
$this->application->save();
}
}
// protected function check_all_servers()
// {
// $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 = instant_remote_process(['docker ps -a -q --format \'{{json .}}\''], $server);
// $containers = $containers->concat(format_docker_command_output_to_json($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);
// }
// }
}

View File

@ -19,18 +19,19 @@ class CoolifyTask implements ShouldQueue
*/
public function __construct(
public Activity $activity,
){}
) {
}
/**
* Execute the job.
*/
public function handle(): void
{
$remoteProcess = resolve(RunRemoteProcess::class, [
$remote_process = resolve(RunRemoteProcess::class, [
'activity' => $this->activity,
]);
$remoteProcess();
$remote_process();
// @TODO: Remove file at $this->activity->getExtraProperty('private_key_location') after process is finished
}
}

View File

@ -1,518 +0,0 @@
<?php
namespace App\Jobs;
use App\Actions\CoolifyTask\RunRemoteProcess;
use App\Data\CoolifyTaskArgs;
use App\Enums\ActivityTypes;
use App\Models\Application;
use App\Models\InstanceSettings;
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\Log;
use Illuminate\Support\Facades\Storage;
use Spatie\Activitylog\Models\Activity;
use Symfony\Component\Yaml\Yaml;
use Illuminate\Support\Str;
use Spatie\Url\Url;
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;
protected $build_args;
protected $env_args;
public static int $batch_counter = 0;
public $timeout = 3600;
/**
* 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 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("[]");
}
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::get();
if ($this->application->deploymentType() === 'source') {
$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)... '",
]);
$this->executeNow([
"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);
// Import git repository
$this->executeNow([
"echo 'Done.'",
"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);
$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);
// Generate docker-compose.yml
$this->generateComposeFile();
$this->executeNow([
"echo 'Done.'",
"echo -n 'Building image... '",
]);
$this->generate_build_env_variables();
$this->add_build_env_variables_to_dockerfile();
if ($this->application->settings->is_static) {
$this->executeNow([
$this->execute_in_builder("docker build -f {$this->workdir}/Dockerfile {$this->build_args} --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 {$this->build_args} --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 {$this->build_args} --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();
} catch (\Exception $e) {
$this->executeNow([
"echo '\nOops something is not okay, are you okay? 😢'",
"echo '\n\n{$e->getMessage()}'",
]);
$this->fail($e->getMessage());
} finally {
// Saving docker-compose.yml
if (isset($this->docker_compose)) {
Storage::disk('deployments')->put(Str::kebab($this->application->name) . '/docker-compose.yml', $this->docker_compose);
}
$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_environment_variables($ports)
{
$environment_variables = collect();
foreach ($this->application->runtime_environment_variables 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([]);
foreach ($this->application->nixpacks_environment_variables 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}"]);
foreach ($this->application->build_environment_variables 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->executeNow([
$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->executeNow([
$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;
$persistentStorages = $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->application->uuid => [
'image' => "{$this->application->uuid}:$this->git_commit",
'container_name' => $this->application->uuid,
'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,
'oom_kill_disable' => $this->application->limits_memory_oom_kill,
'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) {
$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 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->application->fqdn) {
$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();
$slug = Str::slug($url);
$label_id = "{$this->application->uuid}-{$slug}";
if ($path === '/') {
$labels[] = "traefik.http.routers.{$label_id}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)";
} else {
$labels[] = "traefik.http.routers.{$label_id}.rule=Host(`{$host}`) && PathPrefix(`{$path}`)";
$labels[] = "traefik.http.routers.{$label_id}.middlewares={$label_id}-stripprefix";
$labels[] = "traefik.http.middlewares.{$label_id}-stripprefix.stripprefix.prefixes={$path}";
}
}
}
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 !== '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_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()
{
$git_clone_command = "git clone -q -b {$this->application->git_branch}";
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->setGitImportSettings($git_clone_command);
return [
$this->execute_in_builder($git_clone_command)
];
} else {
$github_access_token = generate_github_installation_token($this->source);
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}")
];
}
}
}
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->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)
];
}
}
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);
}
}

View File

@ -0,0 +1,73 @@
<?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, ShouldBeUnique
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $tries = 1;
public $timeout = 120;
public function uniqueId(): int
{
return 1;
}
public function __construct(private bool $force = false)
{
}
public function handle(): void
{
try {
$localhost_name = 'localhost';
if (config('app.env') === 'local') {
$localhost_name = 'testing-local-docker-container';
}
$server = Server::where('name', $localhost_name)->firstOrFail();
$latest_version = get_latest_version_of_coolify();
$current_version = config('version');
if (config('app.env') === 'local') {
instant_remote_process([
"sleep 10"
], $server);
return;
} else {
if (!$this->force) {
$instance_settings = InstanceSettings::get();
if (!$instance_settings->is_auto_update_enabled) {
$this->fail('Auto update is disabled');
return;
}
if ($latest_version === $current_version) {
$this->fail("Already on latest version");
return;
}
if (version_compare($latest_version, $current_version, '<')) {
$this->fail("Latest version is lower than current version?!");
return;
}
}
instant_remote_process([
"curl -fsSL https://coolify-cdn.b-cdn.net/files/upgrade.sh -o /data/coolify/source/upgrade.sh",
"bash /data/coolify/source/upgrade.sh $latest_version"
], $server);
return;
}
} catch (\Exception $e) {
Log::error($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) {
instantRemoteProcess(['docker image prune -f'], $server);
instant_remote_process(['docker image prune -f'], $server);
}
} catch (\Exception $e) {
Log::error($e->getMessage());

View File

@ -3,6 +3,7 @@
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;
@ -10,7 +11,7 @@
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ProxyCheckJob implements ShouldQueue
class InstanceProxyCheckJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
@ -29,10 +30,10 @@ public function handle()
try {
$container_name = 'coolify-proxy';
$configuration_path = config('coolify.proxy_config_path');
$servers = Server::whereRelation('settings', 'is_validated', true)->get();
$servers = Server::whereRelation('settings', 'is_validated', true)->where('extra_attributes->proxy_type', ProxyTypes::TRAEFIK_V2)->get();
foreach ($servers as $server) {
$status = checkContainerStatus(server: $server, container_id: $container_name);
$status = get_container_status(server: $server, container_id: $container_name);
if ($status === 'running') {
continue;
}

View File

@ -41,14 +41,6 @@ protected static function booted()
'private_key_id'
];
public $casts = [
'previews' => SchemalessAttributes::class,
'limits_memory_oom_kill' => 'boolean',
];
public function scopeWithExtraAttributes(): Builder
{
return $this->previews->modelScope();
}
public function publishDirectory(): Attribute
{
return Attribute::make(
@ -131,6 +123,10 @@ public function environment()
{
return $this->belongsTo(Environment::class);
}
public function previews()
{
return $this->hasMany(ApplicationPreview::class);
}
public function settings()
{
return $this->hasOne(ApplicationSetting::class);
@ -148,9 +144,15 @@ 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->type', '=', 'deployment')->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)
{
@ -158,7 +160,14 @@ public function get_deployment(string $deployment_uuid)
}
public function isDeployable(): bool
{
if ($this->settings->is_auto_deploy) {
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;

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

View File

@ -28,6 +28,11 @@ protected static function booted()
'extra_attributes' => SchemalessAttributes::class,
];
public function scopeWithExtraAttributes(): Builder
{
return $this->extra_attributes->modelScope();
}
public function standaloneDockers()
{
return $this->hasMany(StandaloneDocker::class);
@ -38,10 +43,7 @@ public function swarmDockers()
return $this->hasMany(SwarmDocker::class);
}
public function scopeWithExtraAttributes(): Builder
{
return $this->extra_attributes->modelScope();
}
public function privateKey()
{

View File

@ -12,38 +12,19 @@
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'id',
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
@ -52,9 +33,15 @@ protected static function boot()
$model->uuid = (string) new Cuid2(7);
});
}
public function isRoot()
public function isPartOfRootTeam()
{
return $this->id == 0;
$found_root_team = auth()->user()->teams->filter(function ($team) {
if ($team->id == 0) {
return true;
}
return false;
});
return $found_root_team->count() > 0;
}
public function teams()
{
@ -68,15 +55,14 @@ public function currentTeam()
public function otherTeams()
{
$team_id = data_get(session('currentTeam'), 'id');
$team_id = session('currentTeam')->id;
return auth()->user()->teams->filter(function ($team) use ($team_id) {
return $team->id != $team_id;
});
}
public function resources()
{
$team_id = data_get(session('currentTeam'), 'id');
$team_id = session('currentTeam')->id;
$data = Application::where('team_id', $team_id)->get();
return $data;
}

View File

@ -2,12 +2,8 @@
namespace App\Providers;
use App\Jobs\CoolifyTask;
use Illuminate\Queue\Events\JobProcessed;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;
class AppServiceProvider extends ServiceProvider
{
@ -16,9 +12,6 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
// if (config('app.env') === 'production' && Str::contains(config('version'), ['nightly'])) {
// Process::run('php artisan migrate:fresh --force --seed --seeder=ProductionSeeder');
// }
}
/**
@ -26,10 +19,10 @@ public function register(): void
*/
public function boot(): void
{
Queue::after(function (JobProcessed $event) {
// @TODO: Remove `coolify-builder` container after the remoteProcess job is finishged and remoteProcess->type == `deployment`.
if ($event->job->resolveName() === CoolifyTask::class) {
}
Http::macro('github', function (string $api_url) {
return Http::withHeaders([
'Accept' => 'application/vnd.github.v3+json'
])->baseUrl($api_url);
});
}
}

View File

@ -55,6 +55,9 @@ public function boot(): void
return $user;
}
});
Fortify::requestPasswordResetLinkView(function () {
return view('auth.forgot-password');
});
Fortify::createUsersUsing(CreateNewUser::class);
Fortify::updateUserProfileInformationUsing(UpdateUserProfileInformation::class);
Fortify::updateUserPasswordsUsing(UpdateUserPassword::class);

View File

@ -1,318 +0,0 @@
<?php
use App\Actions\CoolifyTask\PrepareCoolifyTask;
use App\Data\CoolifyTaskArgs;
use App\Models\GithubApp;
use App\Models\Server;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\QueryException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Spatie\Activitylog\Contracts\Activity;
use Illuminate\Support\Str;
use Visus\Cuid2\Cuid2;
if (!function_exists('generalErrorHandler')) {
function generalErrorHandler(\Throwable $e, $that = null, $isJson = false)
{
try {
if ($e instanceof QueryException) {
if ($e->errorInfo[0] === '23505') {
throw new \Exception('Duplicate entry found.', '23505');
} else if (count($e->errorInfo) === 4) {
throw new \Exception($e->errorInfo[3]);
} else {
throw new \Exception($e->errorInfo[2]);
}
} else {
throw new \Exception($e->getMessage());
}
} catch (\Throwable $error) {
if ($that) {
return $that->emit('error', $error->getMessage());
} elseif ($isJson) {
return response()->json([
'code' => $error->getCode(),
'error' => $error->getMessage(),
]);
} else {
// dump($error);
}
}
}
}
if (!function_exists('remoteProcess')) {
/**
* Run a Remote Process, which SSH's asynchronously into a machine to run the command(s).
* @TODO Change 'root' to 'coolify' when it's able to run Docker commands without sudo
*
*/
function remoteProcess(
array $command,
Server $server,
string $type,
?string $type_uuid = null,
?Model $model = null,
): Activity {
$command_string = implode("\n", $command);
// @TODO: Check if the user has access to this server
// checkTeam($server->team_id);
$private_key_location = savePrivateKeyForServer($server);
return resolve(PrepareCoolifyTask::class, [
'remoteProcessArgs' => new CoolifyTaskArgs(
server_ip: $server->ip,
private_key_location: $private_key_location,
command: <<<EOT
{$command_string}
EOT,
port: $server->port,
user: $server->user,
type: $type,
type_uuid: $type_uuid,
model: $model,
),
])();
}
}
// function checkTeam(string $team_id)
// {
// $found_team = auth()->user()->teams->pluck('id')->contains($team_id);
// if (!$found_team) {
// throw new \RuntimeException('You do not have access to this server.');
// }
// }
if (!function_exists('savePrivateKeyForServer')) {
function savePrivateKeyForServer(Server $server)
{
$temp_file = "id.root@{$server->ip}";
Storage::disk('ssh-keys')->put($temp_file, $server->privateKey->private_key);
return '/var/www/html/storage/app/ssh-keys/' . $temp_file;
}
}
if (!function_exists('generateSshCommand')) {
function generateSshCommand(string $private_key_location, string $server_ip, string $user, string $port, string $command, bool $isMux = true)
{
Storage::disk('local')->makeDirectory('.ssh');
$delimiter = 'EOF-COOLIFY-SSH';
$ssh_command = "ssh ";
if ($isMux && config('coolify.mux_enabled')) {
$ssh_command .= '-o ControlMaster=auto -o ControlPersist=1m -o ControlPath=/var/www/html/storage/app/.ssh/ssh_mux_%h_%p_%r ';
}
$ssh_command .= "-i {$private_key_location} "
. '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '
. '-o PasswordAuthentication=no '
. '-o ConnectTimeout=3600 '
. '-o ServerAliveInterval=60 '
. '-o RequestTTY=no '
. '-o LogLevel=ERROR '
. "-p {$port} "
. "{$user}@{$server_ip} "
. " 'bash -se' << \\$delimiter" . PHP_EOL
. $command . PHP_EOL
. $delimiter;
return $ssh_command;
}
}
if (!function_exists('formatDockerCmdOutputToJson')) {
function formatDockerCmdOutputToJson($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
->reject(fn ($line) => empty($line))
->map(fn ($outputLine) => json_decode($outputLine, true, flags: JSON_THROW_ON_ERROR));
}
}
if (!function_exists('formatDockerLabelsToJson')) {
function formatDockerLabelsToJson($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
->reject(fn ($line) => empty($line))
->map(function ($outputLine) {
$outputArray = explode(',', $outputLine);
return collect($outputArray)
->map(function ($outputLine) {
return explode('=', $outputLine);
})
->mapWithKeys(function ($outputLine) {
return [$outputLine[0] => $outputLine[1]];
});
})[0];
}
}
if (!function_exists('instantRemoteProcess')) {
function instantRemoteProcess(array $command, Server $server, $throwError = true)
{
$command_string = implode("\n", $command);
$private_key_location = savePrivateKeyForServer($server);
$ssh_command = generateSshCommand($private_key_location, $server->ip, $server->user, $server->port, $command_string);
$process = Process::run($ssh_command);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
if (!$throwError) {
return null;
}
throw new \RuntimeException($process->errorOutput());
}
return $output;
}
}
if (!function_exists('getLatestVersionOfCoolify')) {
function getLatestVersionOfCoolify()
{
$response = Http::get('https://coolify-cdn.b-cdn.net/versions.json');
$versions = $response->json();
return data_get($versions, 'coolify.v4.version');
}
}
if (!function_exists('generateRandomName')) {
function generateRandomName()
{
$generator = \Nubs\RandomNameGenerator\All::create();
$cuid = new Cuid2(7);
return Str::kebab("{$generator->getName()}-{$cuid}");
}
}
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 Symfony\Component\Yaml\Yaml;
if (!function_exists('generate_github_installation_token')) {
function generate_github_installation_token(GithubApp $source)
{
$signingKey = InMemory::plainText($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($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("{$source->api_url}/app/installations/{$source->installation_id}/access_tokens");
if ($token->failed()) {
throw new \Exception("Failed to get access token for " . $source->name . " with error: " . $token->json()['message']);
}
return $token->json()['token'];
}
}
if (!function_exists('generate_github_jwt_token')) {
function generate_github_jwt_token(GithubApp $source)
{
$signingKey = InMemory::plainText($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($source->app_id)
->issuedAt($now->modify('-1 minute'))
->expiresAt($now->modify('+10 minutes'))
->getToken($algorithm, $signingKey)
->toString();
return $issuedToken;
}
}
if (!function_exists('getParameters')) {
function getParameters()
{
return Route::current()->parameters();
}
}
if (!function_exists('checkContainerStatus')) {
function checkContainerStatus(Server $server, string $container_id, bool $throwError = false)
{
$container = instantRemoteProcess(["docker inspect --format '{{json .State}}' {$container_id}"], $server, $throwError);
if (!$container) {
return 'exited';
}
$container = formatDockerCmdOutputToJson($container);
return $container[0]['Status'];
}
}
if (!function_exists('getProxyConfiguration')) {
function getProxyConfiguration(Server $server)
{
$proxy_config_path = config('coolify.proxy_config_path');
$networks = collect($server->standaloneDockers)->map(function ($docker) {
return $docker['network'];
})->unique();
if ($networks->count() === 0) {
$networks = collect(['coolify']);
}
$array_of_networks = collect([]);
$networks->map(function ($network) use ($array_of_networks) {
$array_of_networks[$network] = [
"external" => true,
];
});
return Yaml::dump([
"version" => "3.8",
"networks" => $array_of_networks->toArray(),
"services" => [
"traefik" => [
"container_name" => "coolify-proxy", # Do not modify this! You will break everything!
"image" => "traefik:v2.10",
"restart" => "always",
"extra_hosts" => [
"host.docker.internal:host-gateway",
],
"networks" => $networks->toArray(), # Do not modify this! You will break everything!
"ports" => [
"80:80",
"443:443",
"8080:8080",
],
"volumes" => [
"/var/run/docker.sock:/var/run/docker.sock:ro",
"{$proxy_config_path}/letsencrypt:/letsencrypt", # Do not modify this! You will break everything!
"{$proxy_config_path}/traefik.auth:/auth/traefik.auth", # Do not modify this! You will break everything!
],
"command" => [
"--api.dashboard=true",
"--api.insecure=true",
"--entrypoints.http.address=:80",
"--entrypoints.https.address=:443",
"--providers.docker=true",
"--providers.docker.exposedbydefault=false",
],
"labels" => [
"traefik.enable=true", # Do not modify this! You will break everything!
"traefik.http.routers.traefik.entrypoints=http",
'traefik.http.routers.traefik.rule=Host(`${TRAEFIK_DASHBOARD_HOST}`)',
"traefik.http.routers.traefik.service=api@internal",
"traefik.http.services.traefik.loadbalancer.server.port=8080",
"traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https",
],
],
],
], 4, 2);
}
}

View File

@ -0,0 +1,51 @@
<?php
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
function queue_application_deployment(int $application_id, string $deployment_uuid, int|null $pull_request_id = 0, string $commit = 'HEAD', bool $force_rebuild = false, bool $is_webhook = false)
{
$deployment = ApplicationDeploymentQueue::create([
'application_id' => $application_id,
'deployment_uuid' => $deployment_uuid,
'pull_request_id' => $pull_request_id,
'force_rebuild' => $force_rebuild,
'is_webhook' => $is_webhook,
'commit' => $commit,
]);
$queued_deployments = ApplicationDeploymentQueue::where('application_id', $application_id)->where('status', 'queued')->get()->sortByDesc('created_at');
$running_deployments = ApplicationDeploymentQueue::where('application_id', $application_id)->where('status', 'in_progress')->get()->sortByDesc('created_at');
ray('Q:' . $queued_deployments->count() . 'R:' . $running_deployments->count() . '| Queuing deployment: ' . $deployment_uuid . ' of applicationID: ' . $application_id . ' pull request: ' . $pull_request_id . ' with commit: ' . $commit . ' and is it forced: ' . $force_rebuild);
if ($queued_deployments->count() > 1) {
$queued_deployments = $queued_deployments->skip(1);
$queued_deployments->each(function ($queued_deployment, $key) {
$queued_deployment->status = 'cancelled by system';
$queued_deployment->save();
});
}
if ($running_deployments->count() > 0) {
return;
}
dispatch(new ApplicationDeploymentJob(
application_deployment_queue_id: $deployment->id,
application_id: $application_id,
deployment_uuid: $deployment_uuid,
force_rebuild: $force_rebuild,
rollback_commit: $commit,
pull_request_id: $pull_request_id,
));
}
function queue_next_deployment(Application $application)
{
$next_found = ApplicationDeploymentQueue::where('application_id', $application->id)->where('status', 'queued')->first();
if ($next_found) {
dispatch(new ApplicationDeploymentJob(
application_deployment_queue_id: $next_found->id,
application_id: $next_found->application_id,
deployment_uuid: $next_found->deployment_uuid,
force_rebuild: $next_found->force_rebuild,
));
}
}

View File

@ -0,0 +1,49 @@
<?php
use App\Models\Server;
use Illuminate\Support\Collection;
function format_docker_command_output_to_json($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
->reject(fn ($line) => empty($line))
->map(fn ($outputLine) => json_decode($outputLine, true, flags: JSON_THROW_ON_ERROR));
}
function format_docker_labels_to_json($rawOutput): Collection
{
$outputLines = explode(PHP_EOL, $rawOutput);
return collect($outputLines)
->reject(fn ($line) => empty($line))
->map(function ($outputLine) {
$outputArray = explode(',', $outputLine);
return collect($outputArray)
->map(function ($outputLine) {
return explode('=', $outputLine);
})
->mapWithKeys(function ($outputLine) {
return [$outputLine[0] => $outputLine[1]];
});
})[0];
}
function get_container_status(Server $server, string $container_id, bool $throwError = false)
{
$container = instant_remote_process(["docker inspect --format '{{json .State}}' {$container_id}"], $server, $throwError);
if (!$container) {
return 'exited';
}
$container = format_docker_command_output_to_json($container);
return $container[0]['Status'];
}
function generate_container_name(string $uuid, int|null $pull_request_id = null)
{
if ($pull_request_id) {
return $uuid . '-pr-' . $pull_request_id;
} else {
return $uuid;
}
}

View File

@ -0,0 +1,65 @@
<?php
use App\Models\GithubApp;
use App\Models\GitlabApp;
use Illuminate\Support\Facades\Http;
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;
function generate_github_installation_token(GithubApp $source)
{
$signingKey = InMemory::plainText($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($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("{$source->api_url}/app/installations/{$source->installation_id}/access_tokens");
if ($token->failed()) {
throw new \Exception("Failed to get access token for " . $source->name . " with error: " . $token->json()['message']);
}
return $token->json()['token'];
}
function generate_github_jwt_token(GithubApp $source)
{
$signingKey = InMemory::plainText($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($source->app_id)
->issuedAt($now->modify('-1 minute'))
->expiresAt($now->modify('+10 minutes'))
->getToken($algorithm, $signingKey)
->toString();
return $issuedToken;
}
function get_from_git_api(GithubApp|GitlabApp $source, $endpoint)
{
if ($source->getMorphClass() == 'App\Models\GithubApp') {
if ($source->is_public) {
$response = Http::github($source->api_url)->get($endpoint);
}
}
$json = $response->json();
if ($response->status() !== 200) {
throw new \Exception("Failed to get data from {$source->name} with error: " . $json['message']);
}
return [
'rate_limit_remaining' => $response->header('X-RateLimit-Remaining'),
'data' => collect($json)
];
}

View File

@ -0,0 +1,77 @@
<?php
use App\Models\Server;
use Symfony\Component\Yaml\Yaml;
if (!function_exists('getProxyConfiguration')) {
function getProxyConfiguration(Server $server)
{
$proxy_path = config('coolify.proxy_config_path');
if (config('app.env') === 'local') {
$proxy_path = $proxy_path . '/testing-host-1/';
}
$networks = collect($server->standaloneDockers)->map(function ($docker) {
return $docker['network'];
})->unique();
if ($networks->count() === 0) {
$networks = collect(['coolify']);
}
$array_of_networks = collect([]);
$networks->map(function ($network) use ($array_of_networks) {
$array_of_networks[$network] = [
"external" => true,
];
});
$config = [
"version" => "3.8",
"networks" => $array_of_networks->toArray(),
"services" => [
"traefik" => [
"container_name" => "coolify-proxy",
"image" => "traefik:v2.10",
"restart" => "always",
"extra_hosts" => [
"host.docker.internal:host-gateway",
],
"networks" => $networks->toArray(),
"ports" => [
"80:80",
"443:443",
"8080:8080",
],
"volumes" => [
"/var/run/docker.sock:/var/run/docker.sock:ro",
"{$proxy_path}:/traefik",
],
"command" => [
"--api.dashboard=true",
"--api.insecure=true",
"--entrypoints.http.address=:80",
"--entrypoints.https.address=:443",
"--providers.docker=true",
"--providers.docker.exposedbydefault=false",
"--providers.file.directory=/traefik/dynamic/",
"--providers.file.watch=true",
"--certificatesresolvers.letsencrypt.acme.httpchallenge=true",
"--certificatesresolvers.letsencrypt.acme.storage=/traefik/acme.json",
"--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=http",
],
"labels" => [
"traefik.enable=true",
"traefik.http.routers.traefik.entrypoints=http",
"traefik.http.routers.traefik.middlewares=traefik-basic-auth@file",
"traefik.http.routers.traefik.service=api@internal",
"traefik.http.services.traefik.loadbalancer.server.port=8080",
// Global Middlewares
"traefik.http.middlewares.redirect-to-https.redirectscheme.scheme=https",
"traefik.http.middlewares.gzip.compress=true",
],
],
],
];
if (config('app.env') === 'local') {
$config['services']['traefik']['command'][] = "--log.level=debug";
}
return Yaml::dump($config, 4, 2);
}
}

View File

@ -0,0 +1,101 @@
<?php
use App\Actions\CoolifyTask\PrepareCoolifyTask;
use App\Data\CoolifyTaskArgs;
use App\Enums\ActivityTypes;
use App\Models\Server;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Sleep;
use Spatie\Activitylog\Models\Activity;
/**
* Run a Remote Process, which SSH's asynchronously into a machine to run the command(s).
* @TODO Change 'root' to 'coolify' when it's able to run Docker commands without sudo
*
*/
function remote_process(
array $command,
Server $server,
string $type = ActivityTypes::INLINE->value,
?string $type_uuid = null,
?Model $model = null,
): Activity {
$command_string = implode("\n", $command);
// @TODO: Check if the user has access to this server
// checkTeam($server->team_id);
$private_key_location = save_private_key_for_server($server);
return resolve(PrepareCoolifyTask::class, [
'remoteProcessArgs' => new CoolifyTaskArgs(
server_ip: $server->ip,
private_key_location: $private_key_location,
command: <<<EOT
{$command_string}
EOT,
port: $server->port,
user: $server->user,
type: $type,
type_uuid: $type_uuid,
model: $model,
),
])();
}
function save_private_key_for_server(Server $server)
{
$temp_file = "id.root@{$server->ip}";
Storage::disk('ssh-keys')->put($temp_file, $server->privateKey->private_key);
Storage::disk('ssh-mux')->makeDirectory('.');
return '/var/www/html/storage/app/ssh/keys/' . $temp_file;
}
function generate_ssh_command(string $private_key_location, string $server_ip, string $user, string $port, string $command, bool $isMux = true)
{
$delimiter = 'EOF-COOLIFY-SSH';
$ssh_command = "ssh ";
if ($isMux && config('coolify.mux_enabled')) {
$ssh_command .= '-o ControlMaster=auto -o ControlPersist=1m -o ControlPath=/var/www/html/storage/app/ssh/mux/%h_%p_%r ';
}
$ssh_command .= "-i {$private_key_location} "
. '-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '
. '-o PasswordAuthentication=no '
. '-o ConnectTimeout=3600 '
. '-o ServerAliveInterval=20 '
. '-o RequestTTY=no '
. '-o LogLevel=ERROR '
. "-p {$port} "
. "{$user}@{$server_ip} "
. " 'bash -se' << \\$delimiter" . PHP_EOL
. $command . PHP_EOL
. $delimiter;
return $ssh_command;
}
function instant_remote_process(array $command, Server $server, $throwError = true, $repeat = 1)
{
$command_string = implode("\n", $command);
$private_key_location = save_private_key_for_server($server);
$ssh_command = generate_ssh_command($private_key_location, $server->ip, $server->user, $server->port, $command_string);
$process = Process::run($ssh_command);
$output = trim($process->output());
$exitCode = $process->exitCode();
if ($exitCode !== 0) {
if ($repeat > 1) {
Sleep::for(200)->milliseconds();
ray('executing again');
return instant_remote_process($command, $server, $throwError, $repeat - 1);
}
ray($process->errorOutput());
if (!$throwError) {
return null;
}
throw new \RuntimeException($process->errorOutput());
}
return $output;
}

View File

@ -0,0 +1,60 @@
<?php
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;
use Visus\Cuid2\Cuid2;
use Illuminate\Support\Str;
function general_error_handler(\Throwable $e, $that = null, $isJson = false)
{
try {
ray('ERROR OCCURED: ' . $e->getMessage());
if ($e instanceof QueryException) {
if ($e->errorInfo[0] === '23505') {
throw new \Exception('Duplicate entry found.', '23505');
} else if (count($e->errorInfo) === 4) {
throw new \Exception($e->errorInfo[3]);
} else {
throw new \Exception($e->errorInfo[2]);
}
} else {
throw new \Exception($e->getMessage());
}
} catch (\Throwable $error) {
if ($that) {
return $that->emit('error', $error->getMessage());
} elseif ($isJson) {
return response()->json([
'code' => $error->getCode(),
'error' => $error->getMessage(),
]);
} else {
ray($error);
}
}
}
function get_parameters()
{
return Route::current()->parameters();
}
function get_latest_version_of_coolify()
{
$response = Http::get('https://coolify-cdn.b-cdn.net/versions.json');
$versions = $response->json();
return data_get($versions, 'coolify.v4.version');
}
function generate_random_name()
{
$generator = \Nubs\RandomNameGenerator\All::create();
$cuid = new Cuid2(7);
return Str::kebab("{$generator->getName()}-{$cuid}");
}
function generate_application_name(string $git_repository, string $git_branch)
{
$cuid = new Cuid2(7);
return Str::kebab("{$git_repository}:{$git_branch}-{$cuid}");
}

View File

@ -0,0 +1,5 @@
<?php
$files = glob(__DIR__ . '/helpers/*.php');
foreach ($files as $file) {
require($file);
}

View File

@ -2,7 +2,10 @@
"name": "laravel/laravel",
"type": "project",
"description": "The Laravel Framework.",
"keywords": ["framework", "laravel"],
"keywords": [
"framework",
"laravel"
],
"license": "MIT",
"require": {
"php": "^8.2",
@ -17,6 +20,7 @@
"lcobucci/jwt": "^5.0.0",
"livewire/livewire": "^v2.12.3",
"nubs/random-name-generator": "^2.2",
"sentry/sentry-laravel": "^3.4",
"spatie/laravel-activitylog": "^4.7.3",
"spatie/laravel-data": "^3.4.3",
"spatie/laravel-ray": "^1.32.4",
@ -26,6 +30,8 @@
"visus/cuid2": "^2.0.0"
},
"require-dev": {
"serversideup/spin": "^v1.1.0",
"barryvdh/laravel-ide-helper": "^2.13",
"fakerphp/faker": "^v1.21.0",
"laravel/dusk": "^v7.7.0",
"laravel/pint": "^v1.8.0",
@ -33,14 +39,13 @@
"nunomaduro/collision": "^v7.4.0",
"pestphp/pest": "^v2.4.0",
"phpunit/phpunit": "^10.0.19",
"serversideup/spin": "^v1.1.0",
"spatie/laravel-ignition": "^2.1.0",
"symfony/http-client": "^6.2",
"toshy/bunnynet-php": "^3.0"
},
"autoload": {
"files": [
"bootstrap/helpers.php"
"bootstrap/includeHelpers.php"
],
"psr-4": {
"App\\": "app/",
@ -59,7 +64,16 @@
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
"@php artisan vendor:publish --tag=laravel-assets --ansi --force",
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"@php artisan ide-helper:generate",
"@php artisan ide-helper:meta",
"@php artisan ide-helper:models --nowrite"
],
"post-install-cmd": [
"@php artisan ide-helper:generate",
"@php artisan ide-helper:meta",
"@php artisan ide-helper:models --nowrite"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""

2020
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -29,7 +29,6 @@
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
@ -39,14 +38,20 @@
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'url' => env('APP_URL') . '/storage',
'visibility' => 'public',
'throw' => false,
],
'ssh-mux' => [
'driver' => 'local',
'root' => storage_path('app/ssh/mux'),
'visibility' => 'private',
'throw' => false,
],
'ssh-keys' => [
'driver' => 'local',
'root' => storage_path('app/ssh-keys'),
'root' => storage_path('app/ssh/keys'),
'visibility' => 'private',
'throw' => false,
],

View File

@ -180,7 +180,7 @@
*/
'defaults' => [
'supervisor-1' => [
's6' => [
'connection' => 'redis',
'queue' => ['default'],
'balance' => 'auto',
@ -190,25 +190,27 @@
'maxJobs' => 0,
'memory' => 128,
'tries' => 1,
'timeout' => 600,
'timeout' => 3600,
'nice' => 0,
],
],
'environments' => [
'production' => [
'supervisor-1' => [
's6' => [
'autoScalingStrategy' => 'size',
'maxProcesses' => env('HORIZON_MAX_PROCESSES', 10),
'balanceMaxShift' => env('HORIZON_BALANCE_MAX_SHIFT', 1),
'balanceCooldown' => env('HORIZON_BALANCE_COOLDOWN', 3),
'balanceCooldown' => env('HORIZON_BALANCE_COOLDOWN', 1),
],
],
'local' => [
'supervisor-1' => [
's6' => [
'autoScalingStrategy' => 'size',
'maxProcesses' => env('HORIZON_MAX_PROCESSES', 10),
'balanceMaxShift' => env('HORIZON_BALANCE_MAX_SHIFT', 1),
'balanceCooldown' => env('HORIZON_BALANCE_COOLDOWN', 3),
'balanceCooldown' => env('HORIZON_BALANCE_COOLDOWN', 1),
],
],
],

84
config/sentry.php Normal file
View File

@ -0,0 +1,84 @@
<?php
return [
// @see https://docs.sentry.io/product/sentry-basics/dsn-explainer/
'dsn' => env('SENTRY_LARAVEL_DSN', env('SENTRY_DSN')),
// The release version of your application
// Example with dynamic git hash: trim(exec('git --git-dir ' . base_path('.git') . ' log --pretty="%h" -n1 HEAD'))
'release' => env('SENTRY_RELEASE'),
// When left empty or `null` the Laravel environment will be used
'environment' => env('SENTRY_ENVIRONMENT'),
'breadcrumbs' => [
// Capture Laravel logs in breadcrumbs
'logs' => true,
// Capture Laravel cache events in breadcrumbs
'cache' => true,
// Capture Livewire components in breadcrumbs
'livewire' => true,
// Capture SQL queries in breadcrumbs
'sql_queries' => true,
// Capture bindings on SQL queries logged in breadcrumbs
'sql_bindings' => true,
// Capture queue job information in breadcrumbs
'queue_info' => true,
// Capture command information in breadcrumbs
'command_info' => true,
// Capture HTTP client requests information in breadcrumbs
'http_client_requests' => true,
],
'tracing' => [
// Trace queue jobs as their own transactions
'queue_job_transactions' => env('SENTRY_TRACE_QUEUE_ENABLED', false),
// Capture queue jobs as spans when executed on the sync driver
'queue_jobs' => true,
// Capture SQL queries as spans
'sql_queries' => true,
// Try to find out where the SQL query originated from and add it to the query spans
'sql_origin' => true,
// Capture views as spans
'views' => true,
// Capture Livewire components as spans
'livewire' => true,
// Capture HTTP client requests as spans
'http_client_requests' => true,
// Capture Redis operations as spans (this enables Redis events in Laravel)
'redis_commands' => env('SENTRY_TRACE_REDIS_COMMANDS', false),
// Try to find out where the Redis command originated from and add it to the command spans
'redis_origin' => true,
// Indicates if the tracing integrations supplied by Sentry should be loaded
'default_integrations' => true,
// Indicates that requests without a matching route should be traced
'missing_routes' => false,
],
// @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#send-default-pii
'send_default_pii' => env('SENTRY_SEND_DEFAULT_PII', false),
// @see: https://docs.sentry.io/platforms/php/guides/laravel/configuration/options/#traces-sample-rate
'traces_sample_rate' => env('SENTRY_TRACES_SAMPLE_RATE') === null ? null : (float)env('SENTRY_TRACES_SAMPLE_RATE'),
'profiles_sample_rate' => env('SENTRY_PROFILES_SAMPLE_RATE') === null ? null : (float)env('SENTRY_PROFILES_SAMPLE_RATE'),
];

View File

@ -18,7 +18,6 @@ class UserFactory extends Factory
public function definition(): array
{
return [
'name' => fake()->name(),
'uuid' => Str::uuid(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),

View File

@ -15,7 +15,7 @@ public function up(): void
$table->id();
$table->string('uuid')->unique();
$table->boolean('is_root_user')->default(false);
$table->string('name');
$table->string('name')->default('Your Name Here');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');

View File

@ -9,7 +9,7 @@ class CreateActivityLogTable extends Migration
public function up()
{
Schema::connection(config('activitylog.database_connection'))->create(config('activitylog.table_name'), function (Blueprint $table) {
$table->bigIncrements('id');
$table->id();
$table->string('log_name')->nullable();
$table->text('description');
$table->nullableMorphs('subject', 'subject');

View File

@ -15,16 +15,15 @@ public function up(): void
$table->id();
$table->string('fqdn')->nullable();
$table->string('wildcard_domain')->nullable();
$table->string('redirect_url')->nullable();
// $table->string('preview_domain_separator')->default('.');
$table->string('default_redirect_404')->nullable();
$table->integer('public_port_min')->default(9000);
$table->integer('public_port_max')->default(9100);
// $table->string('custom_dns_servers')->default('1.1.1.1,8.8.8.8');
$table->boolean('do_not_track')->default(false);
$table->boolean('is_auto_update_enabled')->default(true);
// $table->boolean('is_dns_check_enabled')->default(true);
$table->boolean('is_registration_enabled')->default(true);
$table->boolean('is_https_forced')->default(true);
// $table->string('custom_dns_servers')->default('1.1.1.1,8.8.8.8');
// $table->string('preview_domain_separator')->default('.');
// $table->boolean('is_dns_check_enabled')->default(true);
$table->timestamps();
});
}

View File

@ -41,8 +41,6 @@ public function up(): void
$table->string('base_directory')->default('/');
$table->string('publish_directory')->nullable();
$table->schemalessAttributes('previews');
$table->string('health_check_path')->default('/');
$table->string('health_check_port')->nullable();
$table->string('health_check_host')->default('localhost');
@ -59,13 +57,13 @@ public function up(): void
$table->string('limits_memory_swap')->default("0");
$table->integer('limits_memory_swappiness')->default(60);
$table->string('limits_memory_reservation')->default("0");
$table->boolean('limits_memory_oom_kill')->default(false);
$table->string('limits_cpus')->default("0");
$table->string('limits_cpuset')->nullable()->default("0");
$table->integer('limits_cpu_shares')->default(1024);
$table->string('status')->default('exited');
$table->string('preview_url_template')->default('{{pr_id}}.{{domain}}');
$table->nullableMorphs('destination');
$table->nullableMorphs('source');

View File

@ -14,14 +14,15 @@ public function up(): void
Schema::create('application_settings', function (Blueprint $table) {
$table->id();
$table->boolean('is_static')->default(false);
$table->boolean('is_git_submodules_allowed')->default(true);
$table->boolean('is_git_lfs_allowed')->default(true);
$table->boolean('is_auto_deploy')->default(true);
$table->boolean('is_dual_cert')->default(false);
$table->boolean('is_debug')->default(false);
$table->boolean('is_previews')->default(false);
$table->boolean('is_custom_ssl')->default(false);
$table->boolean('is_http2')->default(false);
$table->boolean('is_git_submodules_enabled')->default(true);
$table->boolean('is_git_lfs_enabled')->default(true);
$table->boolean('is_auto_deploy_enabled')->default(true);
$table->boolean('is_force_https_enabled')->default(true);
$table->boolean('is_debug_enabled')->default(false);
$table->boolean('is_preview_deployments_enabled')->default(false);
// $table->boolean('is_dual_cert')->default(false);
// $table->boolean('is_custom_ssl')->default(false);
// $table->boolean('is_http2')->default(false);
$table->foreignId('application_id');
$table->timestamps();
});

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('application_previews', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->integer('pull_request_id');
$table->string('pull_request_html_url');
$table->string('fqdn')->unique()->nullable();
$table->string('status')->default('exited');
$table->foreignId('application_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('application_previews');
}
};

View File

@ -0,0 +1,34 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('application_deployment_queues', function (Blueprint $table) {
$table->id();
$table->string('application_id');
$table->string('deployment_uuid')->unique();
$table->integer('pull_request_id')->default(0);
$table->boolean('force_rebuild')->default(false);
$table->string('commit')->default('HEAD');
$table->string('status')->default('queued');
$table->boolean('is_webhook')->default(false);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('application_deployment_queues');
}
};

View File

@ -0,0 +1,25 @@
<?php
namespace Database\Seeders;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Models\Environment;
use App\Models\GithubApp;
use App\Models\StandaloneDocker;
use Illuminate\Database\Seeder;
class ApplicationPreviewSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
// $application_1 = Application::find(1);
// ApplicationPreview::create([
// 'application_id' => $application_1->id,
// 'pull_request_id' => 1
// ]);
}
}

View File

@ -26,6 +26,7 @@ public function run(): void
Application::create([
'name' => 'coollabsio/coolify-examples:nodejs-fastify',
'fqdn' => 'http://foo.com',
'repository_project_id' => 603035348,
'git_repository' => 'coollabsio/coolify-examples',
'git_branch' => 'nodejs-fastify',
@ -36,17 +37,7 @@ public function run(): void
'destination_id' => $standalone_docker_1->id,
'destination_type' => StandaloneDocker::class,
'source_id' => $github_public_source->id,
'source_type' => GithubApp::class,
'previews' => [
ApplicationPreview::from([
'pullRequestId' => 1,
'branch' => 'nodejs-fastify'
]),
ApplicationPreview::from([
'pullRequestId' => 2,
'branch' => 'nodejs-fastify'
])
]
'source_type' => GithubApp::class
]);
}
}

View File

@ -18,7 +18,7 @@ class ApplicationSettingsSeeder extends Seeder
public function run(): void
{
$application_1 = Application::find(1)->load(['settings']);
$application_1->settings->is_debug = false;
$application_1->settings->is_debug_enabled = false;
$application_1->settings->save();
}
}

View File

@ -26,6 +26,7 @@ public function run(): void
GitlabAppSeeder::class,
ApplicationSeeder::class,
ApplicationSettingsSeeder::class,
ApplicationPreviewSeeder::class,
DBSeeder::class,
ServiceSeeder::class,
EnvironmentVariableSeeder::class,

View File

@ -14,7 +14,6 @@ public function run(): void
{
InstanceSettings::create([
'id' => 0,
'is_https_forced' => false,
'is_registration_enabled' => true,
]);
}

View File

@ -2,12 +2,15 @@
namespace Database\Seeders;
use App\Data\ServerMetadata;
use App\Enums\ProxyStatus;
use App\Enums\ProxyTypes;
use App\Models\GithubApp;
use App\Models\GitlabApp;
use App\Models\InstanceSettings;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\Server;
use App\Models\StandaloneDocker;
use App\Models\Team;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Storage;
@ -53,7 +56,7 @@ public function run(): void
// Save SSH Keys for the Coolify Host
$coolify_key_name = "id.root@host.docker.internal";
$coolify_key = Storage::disk('local')->get("ssh-keys/{$coolify_key_name}");
$coolify_key = Storage::disk('ssh-keys')->get("{$coolify_key_name}");
if ($coolify_key) {
$private_key = PrivateKey::find(0);
@ -72,23 +75,37 @@ public function run(): void
} else {
// TODO: Add a command to generate a new SSH key for the Coolify host machine (localhost).
echo "No SSH key found for the Coolify host machine (localhost).\n";
echo "Please generate one and save it in storage/app/ssh-keys/{$coolify_key_name}\n";
exit(1);
echo "Please generate one and save it in storage/app/ssh/keys/{$coolify_key_name}\n";
}
// Add Coolify host (localhost) as Server if it doesn't exist
if (Server::find(0) == null) {
$server = Server::create([
$server_details = [
'id' => 0,
'name' => "localhost",
'description' => "This is the local machine",
'description' => "This is the server where Coolify is running on. Don't delete this!",
'user' => 'root',
'ip' => "host.docker.internal",
'team_id' => 0,
'private_key_id' => 0,
]);
'private_key_id' => 0
];
if (env('COOLIFY_DEFAULT_PROXY') == 'traefik') {
$server_details['extra_attributes'] = ServerMetadata::from([
'proxy_type' => ProxyTypes::TRAEFIK_V2->value,
'proxy_status' => ProxyStatus::EXITED->value
]);
}
$server = Server::create($server_details);
$server->settings->is_validated = true;
$server->settings->save();
}
if (StandaloneDocker::find(0) == null) {
StandaloneDocker::create([
'id' => 0,
'name' => 'localhost-coolify',
'network' => 'coolify',
'server_id' => 0,
]);
}
}
}

View File

@ -11,12 +11,10 @@ public function run(): void
{
User::factory()->create([
"id" => 0,
'name' => 'Root User',
'email' => 'test@example.com',
'is_root_user' => true,
]);
User::factory()->create([
'name' => 'Normal User',
'email' => 'test2@example.com',
]);
}

View File

@ -67,5 +67,10 @@ services:
ports:
- '${FORWARD_MAILPIT_PORT:-1025}:1025'
- '${FORWARD_MAILPIT_DASHBOARD_PORT:-8025}:8025'
buggregator:
image: ghcr.io/buggregator/server:latest
container_name: coolify-debug
ports:
- 23517:8000
networks:
- coolify

View File

@ -1,15 +1,14 @@
version: '3.8'
services:
coolify:
image: "ghcr.io/coollabsio/coolify:${APP_TAG:-4.0.0-nightly.0}"
image: "ghcr.io/coollabsio/coolify:${LATEST_IMAGE:-4.0.0-nightly.0}"
volumes:
- type: bind
source: /data/coolify/source/.env
target: /var/www/html/.env
read_only: true
- /data/coolify/ssh:/var/www/html/storage/app/ssh
- /data/coolify/deployments:/var/www/html/storage/app/deployments
- /data/coolify/ssh-keys:/var/www/html/storage/app/ssh-keys
- /data/coolify/proxy:/var/www/html/storage/app/proxy
environment:
- APP_ENV=production
- APP_DEBUG

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