lasthourcloud/bootstrap/helpers/shared.php

2589 lines
112 KiB
PHP
Raw Normal View History

2023-05-24 12:26:50 +00:00
<?php
use App\Enums\ApplicationDeploymentStatus;
2024-03-13 17:26:30 +00:00
use App\Jobs\ServerFilesFromServerJob;
2023-10-20 12:51:01 +00:00
use App\Models\Application;
2024-06-12 09:31:14 +00:00
use App\Models\ApplicationDeploymentQueue;
use App\Models\ApplicationPreview;
2023-11-24 14:48:23 +00:00
use App\Models\EnvironmentVariable;
2023-06-12 10:00:01 +00:00
use App\Models\InstanceSettings;
2023-11-24 14:48:23 +00:00
use App\Models\LocalFileVolume;
use App\Models\LocalPersistentVolume;
2023-09-28 08:53:00 +00:00
use App\Models\Server;
2023-10-20 12:51:01 +00:00
use App\Models\Service;
2023-11-24 14:48:23 +00:00
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
2024-04-10 13:00:46 +00:00
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
2023-10-20 12:51:01 +00:00
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
2023-10-20 12:51:01 +00:00
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\Team;
2023-09-14 16:22:08 +00:00
use App\Models\User;
2023-09-06 12:31:38 +00:00
use App\Notifications\Channels\DiscordChannel;
use App\Notifications\Channels\EmailChannel;
use App\Notifications\Channels\TelegramChannel;
use App\Notifications\Internal\GeneralNotification;
use DanHarrin\LivewireRateLimiting\Exceptions\TooManyRequestsException;
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Mail\Message;
use Illuminate\Notifications\Messages\MailMessage;
2024-04-25 11:52:52 +00:00
use Illuminate\Process\Pool;
2024-04-16 18:57:54 +00:00
use Illuminate\Support\Collection;
2023-09-15 09:19:36 +00:00
use Illuminate\Support\Facades\Cache;
2023-10-04 12:40:26 +00:00
use Illuminate\Support\Facades\File;
2023-05-24 12:26:50 +00:00
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
2024-04-25 11:52:52 +00:00
use Illuminate\Support\Facades\Process;
2023-12-11 19:01:54 +00:00
use Illuminate\Support\Facades\Request;
2023-05-24 12:26:50 +00:00
use Illuminate\Support\Facades\Route;
2024-06-26 11:32:36 +00:00
use Illuminate\Support\Facades\Validator;
2023-05-24 12:26:50 +00:00
use Illuminate\Support\Str;
2023-09-27 10:45:53 +00:00
use Illuminate\Support\Stringable;
use Lcobucci\JWT\Encoding\ChainedFormatter;
use Lcobucci\JWT\Encoding\JoseEncoder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
2024-06-10 20:43:34 +00:00
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Token\Builder;
2024-04-03 11:45:49 +00:00
use phpseclib3\Crypt\EC;
2023-08-22 15:44:49 +00:00
use phpseclib3\Crypt\RSA;
2024-06-10 20:43:34 +00:00
use Poliander\Cron\CronExpression;
use PurplePixie\PhpDns\DNSQuery;
use Spatie\Url\Url;
2023-11-24 14:48:23 +00:00
use Symfony\Component\Yaml\Yaml;
2024-06-10 20:43:34 +00:00
use Visus\Cuid2\Cuid2;
2023-05-24 12:26:50 +00:00
2023-09-21 15:48:31 +00:00
function base_configuration_dir(): string
{
return '/data/coolify';
}
function application_configuration_dir(): string
{
2024-06-10 20:43:34 +00:00
return base_configuration_dir().'/applications';
2023-09-21 15:48:31 +00:00
}
function service_configuration_dir(): string
{
2024-06-10 20:43:34 +00:00
return base_configuration_dir().'/services';
}
function database_configuration_dir(): string
{
2024-06-10 20:43:34 +00:00
return base_configuration_dir().'/databases';
}
2023-09-07 11:23:34 +00:00
function database_proxy_dir($uuid): string
{
2024-06-10 20:43:34 +00:00
return base_configuration_dir()."/databases/$uuid/proxy";
2023-09-07 11:23:34 +00:00
}
function backup_dir(): string
{
2024-06-10 20:43:34 +00:00
return base_configuration_dir().'/backups';
}
2024-06-20 08:44:31 +00:00
function metrics_dir(): string
{
return base_configuration_dir().'/metrics';
}
function generate_readme_file(string $name, string $updated_at): string
{
return "Resource name: $name\nLatest Deployment Date: $updated_at";
}
2023-08-22 15:44:49 +00:00
function isInstanceAdmin()
2023-08-14 14:56:13 +00:00
{
2023-08-22 15:44:49 +00:00
return auth()?->user()?->isInstanceAdmin() ?? false;
2023-08-14 14:56:13 +00:00
}
2023-08-22 15:44:49 +00:00
function currentTeam()
{
return auth()?->user()?->currentTeam() ?? null;
}
function showBoarding(): bool
{
2024-05-21 12:29:06 +00:00
if (auth()->user()?->isMember()) {
return false;
}
2024-06-10 20:43:34 +00:00
2023-08-27 13:44:36 +00:00
return currentTeam()->show_boarding ?? false;
2023-08-22 15:44:49 +00:00
}
2023-09-08 16:33:26 +00:00
function refreshSession(?Team $team = null): void
2023-08-22 15:44:49 +00:00
{
2024-06-10 20:43:34 +00:00
if (! $team) {
2023-09-15 15:30:26 +00:00
if (auth()->user()?->currentTeam()) {
2023-09-15 09:28:44 +00:00
$team = Team::find(auth()->user()->currentTeam()->id);
} else {
$team = User::find(auth()->user()->id)->teams->first();
}
2023-09-08 16:33:26 +00:00
}
2024-06-10 20:43:34 +00:00
Cache::forget('team:'.auth()->user()->id);
Cache::remember('team:'.auth()->user()->id, 3600, function () use ($team) {
2023-09-08 16:33:26 +00:00
return $team;
});
2023-08-30 14:01:38 +00:00
session(['currentTeam' => $team]);
2023-08-22 15:44:49 +00:00
}
function handleError(?Throwable $error = null, ?Livewire\Component $livewire = null, ?string $customErrorMessage = null)
{
2023-12-28 16:53:47 +00:00
ray($error);
2023-11-20 09:32:06 +00:00
if ($error instanceof TooManyRequestsException) {
if (isset($livewire)) {
2024-03-27 10:35:57 +00:00
return $livewire->dispatch('error', "Too many requests. Please try again in {$error->secondsUntilAvailable} seconds.");
2023-11-20 09:32:06 +00:00
}
2024-06-10 20:43:34 +00:00
2023-11-20 09:32:06 +00:00
return "Too many requests. Please try again in {$error->secondsUntilAvailable} seconds.";
}
if ($error instanceof UniqueConstraintViolationException) {
if (isset($livewire)) {
return $livewire->dispatch('error', 'Duplicate entry found. Please use a different name.');
}
2024-06-10 20:43:34 +00:00
return 'Duplicate entry found. Please use a different name.';
}
2023-11-20 09:32:06 +00:00
if ($error instanceof Throwable) {
$message = $error->getMessage();
} else {
$message = null;
}
if ($customErrorMessage) {
2024-06-10 20:43:34 +00:00
$message = $customErrorMessage.' '.$message;
}
2023-11-20 09:32:06 +00:00
if (isset($livewire)) {
2023-12-07 18:06:32 +00:00
return $livewire->dispatch('error', $message);
}
2023-11-21 11:07:06 +00:00
throw new Exception($message);
2023-05-24 12:26:50 +00:00
}
function get_route_parameters(): array
2023-05-24 12:26:50 +00:00
{
return Route::current()->parameters();
}
function get_latest_sentinel_version(): string
{
try {
2024-06-20 08:44:31 +00:00
$response = Http::get('https://cdn.coollabs.io/sentinel/versions.json');
$versions = $response->json();
2024-06-18 14:43:18 +00:00
return data_get($versions, 'sentinel.version');
} catch (\Throwable $e) {
//throw $e;
ray($e->getMessage());
2024-06-10 20:43:34 +00:00
return '0.0.0';
}
}
function get_latest_version_of_coolify(): string
2023-05-24 12:26:50 +00:00
{
2023-06-19 13:43:53 +00:00
try {
$versions = File::get(base_path('versions.json'));
$versions = json_decode($versions, true);
2024-06-10 20:43:34 +00:00
2023-06-19 13:43:53 +00:00
return data_get($versions, 'coolify.v4.version');
// $response = Http::get('https://cdn.coollabs.io/coolify/versions.json');
// $versions = $response->json();
// return data_get($versions, 'coolify.v4.version');
} catch (\Throwable $e) {
2023-09-11 15:36:30 +00:00
//throw $e;
ray($e->getMessage());
2024-06-10 20:43:34 +00:00
2023-06-19 13:43:53 +00:00
return '0.0.0';
}
2023-05-24 12:26:50 +00:00
}
2023-09-19 13:51:13 +00:00
function generate_random_name(?string $cuid = null): string
2023-05-24 12:26:50 +00:00
{
$generator = new \Nubs\RandomNameGenerator\All(
[
2024-07-24 12:27:21 +00:00
new \Nubs\RandomNameGenerator\Alliteration,
]
);
2023-09-19 13:51:13 +00:00
if (is_null($cuid)) {
$cuid = new Cuid2(7);
}
2024-06-10 20:43:34 +00:00
return Str::kebab("{$generator->getName()}-$cuid");
2023-05-24 12:26:50 +00:00
}
2024-04-03 11:45:49 +00:00
function generateSSHKey(string $type = 'rsa')
{
if ($type === 'rsa') {
$key = RSA::createKey();
2024-06-10 20:43:34 +00:00
2024-04-03 11:45:49 +00:00
return [
'private' => $key->toString('PKCS1'),
2024-06-10 20:43:34 +00:00
'public' => $key->getPublicKey()->toString('OpenSSH', ['comment' => 'coolify-generated-ssh-key']),
2024-04-03 11:45:49 +00:00
];
2024-06-10 20:43:34 +00:00
} elseif ($type === 'ed25519') {
2024-04-03 11:45:49 +00:00
$key = EC::createKey('Ed25519');
2024-06-10 20:43:34 +00:00
2024-04-03 11:45:49 +00:00
return [
'private' => $key->toString('OpenSSH'),
2024-06-10 20:43:34 +00:00
'public' => $key->getPublicKey()->toString('OpenSSH', ['comment' => 'coolify-generated-ssh-key']),
2024-04-03 11:45:49 +00:00
];
}
throw new Exception('Invalid key type');
2023-08-22 15:44:49 +00:00
}
2023-08-31 13:00:59 +00:00
function formatPrivateKey(string $privateKey)
{
2023-08-22 15:44:49 +00:00
$privateKey = trim($privateKey);
2024-06-10 20:43:34 +00:00
if (! str_ends_with($privateKey, "\n")) {
2023-08-22 15:44:49 +00:00
$privateKey .= "\n";
}
2024-06-10 20:43:34 +00:00
2023-08-22 15:44:49 +00:00
return $privateKey;
}
2023-09-19 13:51:13 +00:00
function generate_application_name(string $git_repository, string $git_branch, ?string $cuid = null): string
2023-05-24 13:47:04 +00:00
{
2023-09-19 13:51:13 +00:00
if (is_null($cuid)) {
$cuid = new Cuid2(7);
}
2024-06-10 20:43:34 +00:00
return Str::kebab("$git_repository:$git_branch-$cuid");
2023-05-24 13:47:04 +00:00
}
2023-06-12 10:00:01 +00:00
function is_transactional_emails_active(): bool
2023-06-12 10:00:01 +00:00
{
2024-07-12 13:45:36 +00:00
return isEmailEnabled(\App\Models\InstanceSettings::get());
2023-06-12 10:00:01 +00:00
}
2023-06-12 14:39:48 +00:00
2024-06-10 20:43:34 +00:00
function set_transanctional_email_settings(?InstanceSettings $settings = null): ?string
2023-06-12 14:39:48 +00:00
{
2024-06-10 20:43:34 +00:00
if (! $settings) {
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
2023-08-15 12:11:38 +00:00
}
2023-09-02 11:39:44 +00:00
config()->set('mail.from.address', data_get($settings, 'smtp_from_address'));
config()->set('mail.from.name', data_get($settings, 'smtp_from_name'));
2023-08-31 13:00:59 +00:00
if (data_get($settings, 'resend_enabled')) {
config()->set('mail.default', 'resend');
config()->set('resend.api_key', data_get($settings, 'resend_api_key'));
2024-06-10 20:43:34 +00:00
2023-08-31 13:00:59 +00:00
return 'resend';
}
2023-08-31 13:00:59 +00:00
if (data_get($settings, 'smtp_enabled')) {
config()->set('mail.default', 'smtp');
config()->set('mail.mailers.smtp', [
2024-06-10 20:43:34 +00:00
'transport' => 'smtp',
'host' => data_get($settings, 'smtp_host'),
'port' => data_get($settings, 'smtp_port'),
'encryption' => data_get($settings, 'smtp_encryption'),
'username' => data_get($settings, 'smtp_username'),
'password' => data_get($settings, 'smtp_password'),
'timeout' => data_get($settings, 'smtp_timeout'),
'local_domain' => null,
2023-08-31 13:00:59 +00:00
]);
2024-06-10 20:43:34 +00:00
2023-08-31 13:00:59 +00:00
return 'smtp';
}
2024-06-10 20:43:34 +00:00
2023-08-31 13:00:59 +00:00
return null;
2023-06-12 14:39:48 +00:00
}
function base_ip(): string
2023-06-16 11:37:02 +00:00
{
if (isDev()) {
2024-06-10 20:43:34 +00:00
return 'localhost';
2023-07-28 11:40:47 +00:00
}
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
if ($settings->public_ipv4) {
return "$settings->public_ipv4";
}
if ($settings->public_ipv6) {
return "$settings->public_ipv6";
}
2024-06-10 20:43:34 +00:00
return 'localhost';
2023-06-16 11:35:35 +00:00
}
2024-06-10 20:43:34 +00:00
function getFqdnWithoutPort(string $fqdn)
2023-09-24 10:10:36 +00:00
{
2023-12-28 16:53:47 +00:00
try {
$url = Url::fromString($fqdn);
$host = $url->getHost();
$scheme = $url->getScheme();
$path = $url->getPath();
2024-06-10 20:43:34 +00:00
2023-12-28 16:53:47 +00:00
return "$scheme://$host$path";
} catch (\Throwable $e) {
return $fqdn;
}
}
/**
* If fqdn is set, return it, otherwise return public ip.
*/
function base_url(bool $withPort = true): string
2023-06-13 13:01:11 +00:00
{
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
2023-06-13 13:01:11 +00:00
if ($settings->fqdn) {
return $settings->fqdn;
}
2023-06-14 07:05:13 +00:00
$port = config('app.port');
if ($settings->public_ipv4) {
2023-06-16 09:01:27 +00:00
if ($withPort) {
if (isDev()) {
return "http://localhost:$port";
2023-06-16 09:01:27 +00:00
}
2024-06-10 20:43:34 +00:00
return "http://$settings->public_ipv4:$port";
2023-06-16 09:01:27 +00:00
}
if (isDev()) {
2024-06-10 20:43:34 +00:00
return 'http://localhost';
2023-06-16 09:01:27 +00:00
}
2024-06-10 20:43:34 +00:00
return "http://$settings->public_ipv4";
2023-06-14 07:05:13 +00:00
}
if ($settings->public_ipv6) {
2023-06-16 09:01:27 +00:00
if ($withPort) {
return "http://$settings->public_ipv6:$port";
2023-06-16 09:01:27 +00:00
}
2024-06-10 20:43:34 +00:00
return "http://$settings->public_ipv6";
2023-06-14 07:05:13 +00:00
}
2024-06-10 20:43:34 +00:00
2023-06-14 07:05:13 +00:00
return url('/');
2023-06-13 13:01:11 +00:00
}
2023-06-16 09:01:27 +00:00
2024-03-21 13:30:35 +00:00
function isSubscribed()
{
2024-03-29 23:23:48 +00:00
return isSubscriptionActive() || auth()->user()->isInstanceAdmin();
2024-03-21 13:30:35 +00:00
}
function isDev(): bool
2023-06-16 09:01:27 +00:00
{
return config('app.env') === 'local';
}
2023-08-31 07:56:37 +00:00
function isCloud(): bool
2023-07-13 13:07:42 +00:00
{
2024-06-10 20:43:34 +00:00
return ! config('coolify.self_hosted');
}
function validate_cron_expression($expression_to_validate): bool
{
$isValid = false;
$expression = new CronExpression($expression_to_validate);
$isValid = $expression->isValid();
if (isset(VALID_CRON_STRINGS[$expression_to_validate])) {
$isValid = true;
}
2024-06-10 20:43:34 +00:00
return $isValid;
}
function send_internal_notification(string $message): void
{
try {
$team = Team::find(0);
2024-02-06 10:11:26 +00:00
$team?->notify(new GeneralNotification($message));
2023-09-11 15:36:30 +00:00
} catch (\Throwable $e) {
ray($e->getMessage());
}
}
2023-09-12 12:51:35 +00:00
function send_user_an_email(MailMessage $mail, string $email, ?string $cc = null): void
{
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
2023-08-31 13:00:59 +00:00
$type = set_transanctional_email_settings($settings);
2024-06-10 20:43:34 +00:00
if (! $type) {
2023-08-31 13:00:59 +00:00
throw new Exception('No email settings found.');
}
2023-09-12 12:51:35 +00:00
if ($cc) {
Mail::send(
[],
[],
fn (Message $message) => $message
->to($email)
2023-09-14 16:41:21 +00:00
->replyTo($email)
2023-09-12 12:51:35 +00:00
->cc($cc)
->subject($mail->subject)
->html((string) $mail->render())
);
} else {
Mail::send(
[],
[],
fn (Message $message) => $message
->to($email)
->subject($mail->subject)
->html((string) $mail->render())
);
}
2023-08-31 13:00:59 +00:00
}
function isTestEmailEnabled($notifiable)
{
2023-10-06 08:47:48 +00:00
if (data_get($notifiable, 'use_instance_email_settings') && isInstanceAdmin()) {
return true;
2024-06-10 20:43:34 +00:00
} elseif (data_get($notifiable, 'smtp_enabled') || data_get($notifiable, 'resend_enabled') && auth()->user()->isAdminFromSession()) {
2023-10-06 08:47:48 +00:00
return true;
}
2024-06-10 20:43:34 +00:00
2023-10-06 08:47:48 +00:00
return false;
}
2023-08-31 13:00:59 +00:00
function isEmailEnabled($notifiable)
{
return data_get($notifiable, 'smtp_enabled') || data_get($notifiable, 'resend_enabled') || data_get($notifiable, 'use_instance_email_settings');
}
2023-09-06 12:31:38 +00:00
function setNotificationChannels($notifiable, $event)
{
$channels = [];
$isEmailEnabled = isEmailEnabled($notifiable);
$isDiscordEnabled = data_get($notifiable, 'discord_enabled');
$isTelegramEnabled = data_get($notifiable, 'telegram_enabled');
$isSubscribedToEmailEvent = data_get($notifiable, "smtp_notifications_$event");
2023-09-06 12:31:38 +00:00
$isSubscribedToDiscordEvent = data_get($notifiable, "discord_notifications_$event");
$isSubscribedToTelegramEvent = data_get($notifiable, "telegram_notifications_$event");
if ($isDiscordEnabled && $isSubscribedToDiscordEvent) {
$channels[] = DiscordChannel::class;
}
if ($isEmailEnabled && $isSubscribedToEmailEvent) {
2023-09-06 12:31:38 +00:00
$channels[] = EmailChannel::class;
}
if ($isTelegramEnabled && $isSubscribedToTelegramEvent) {
$channels[] = TelegramChannel::class;
}
2024-06-10 20:43:34 +00:00
2023-09-06 12:31:38 +00:00
return $channels;
}
function parseEnvFormatToArray($env_file_contents)
{
2024-06-10 20:43:34 +00:00
$env_array = [];
2023-09-08 14:16:59 +00:00
$lines = explode("\n", $env_file_contents);
foreach ($lines as $line) {
if ($line === '' || substr($line, 0, 1) === '#') {
continue;
}
$equals_pos = strpos($line, '=');
if ($equals_pos !== false) {
$key = substr($line, 0, $equals_pos);
$value = substr($line, $equals_pos + 1);
if (substr($value, 0, 1) === '"' && substr($value, -1) === '"') {
$value = substr($value, 1, -1);
} elseif (substr($value, 0, 1) === "'" && substr($value, -1) === "'") {
2023-09-08 14:16:59 +00:00
$value = substr($value, 1, -1);
}
$env_array[$key] = $value;
}
}
2024-06-10 20:43:34 +00:00
2023-09-08 14:16:59 +00:00
return $env_array;
}
2023-09-27 10:45:53 +00:00
function data_get_str($data, $key, $default = null): Stringable
{
$str = data_get($data, $key, $default) ?? $default;
2024-06-10 20:43:34 +00:00
return str($str);
2023-09-27 10:45:53 +00:00
}
2023-09-28 08:53:00 +00:00
2023-09-30 13:39:40 +00:00
function generateFqdn(Server $server, string $random)
{
$wildcard = data_get($server, 'settings.wildcard_domain');
if (is_null($wildcard) || $wildcard === '') {
$wildcard = sslip($server);
}
$url = Url::fromString($wildcard);
$host = $url->getHost();
$path = $url->getPath() === '/' ? '' : $url->getPath();
$scheme = $url->getScheme();
$finalFqdn = "$scheme://{$random}.$host$path";
2024-06-10 20:43:34 +00:00
2023-09-30 13:39:40 +00:00
return $finalFqdn;
}
2023-09-28 08:53:00 +00:00
function sslip(Server $server)
{
if (isDev() && $server->id === 0) {
2024-06-10 20:43:34 +00:00
return 'http://127.0.0.1.sslip.io';
2023-09-28 08:53:00 +00:00
}
if ($server->ip === 'host.docker.internal') {
$baseIp = base_ip();
2024-06-10 20:43:34 +00:00
2023-09-30 13:39:40 +00:00
return "http://$baseIp.sslip.io";
2023-09-28 08:53:00 +00:00
}
2024-06-10 20:43:34 +00:00
2023-09-30 13:39:40 +00:00
return "http://{$server->ip}.sslip.io";
2023-09-28 08:53:00 +00:00
}
2023-09-28 20:20:49 +00:00
function get_service_templates(bool $force = false): Collection
{
if ($force) {
try {
$response = Http::retry(3, 50)->get(config('constants.services.official'));
if ($response->failed()) {
return collect([]);
}
$services = $response->json();
2024-06-10 20:43:34 +00:00
return collect($services);
} catch (\Throwable $e) {
$services = File::get(base_path('templates/service-templates.json'));
2024-06-10 20:43:34 +00:00
return collect(json_decode($services))->sortKeys();
}
} else {
$services = File::get(base_path('templates/service-templates.json'));
2024-06-10 20:43:34 +00:00
return collect(json_decode($services))->sortKeys();
}
2023-09-28 20:20:49 +00:00
}
2023-10-20 12:51:01 +00:00
function getResourceByUuid(string $uuid, ?int $teamId = null)
{
2024-04-10 13:00:46 +00:00
if (is_null($teamId)) {
2023-10-20 12:51:01 +00:00
return null;
2024-04-10 13:00:46 +00:00
}
$resource = queryResourcesByUuid($uuid);
2024-06-10 20:43:34 +00:00
if (! is_null($resource) && $resource->environment->project->team_id === $teamId) {
2023-10-20 12:51:01 +00:00
return $resource;
}
2024-06-10 20:43:34 +00:00
2024-04-10 13:00:46 +00:00
return null;
2023-10-20 12:51:01 +00:00
}
2024-07-01 14:26:50 +00:00
function queryDatabaseByUuidWithinTeam(string $uuid, string $teamId)
{
$postgresql = StandalonePostgresql::whereUuid($uuid)->first();
if ($postgresql && $postgresql->team()->id == $teamId) {
return $postgresql->unsetRelation('environment')->unsetRelation('destination');
}
$redis = StandaloneRedis::whereUuid($uuid)->first();
if ($redis && $redis->team()->id == $teamId) {
return $redis->unsetRelation('environment');
}
$mongodb = StandaloneMongodb::whereUuid($uuid)->first();
if ($mongodb && $mongodb->team()->id == $teamId) {
return $mongodb->unsetRelation('environment');
}
$mysql = StandaloneMysql::whereUuid($uuid)->first();
if ($mysql && $mysql->team()->id == $teamId) {
return $mysql->unsetRelation('environment');
}
$mariadb = StandaloneMariadb::whereUuid($uuid)->first();
if ($mariadb && $mariadb->team()->id == $teamId) {
return $mariadb->unsetRelation('environment');
}
$keydb = StandaloneKeydb::whereUuid($uuid)->first();
if ($keydb && $keydb->team()->id == $teamId) {
return $keydb->unsetRelation('environment');
}
$dragonfly = StandaloneDragonfly::whereUuid($uuid)->first();
if ($dragonfly && $dragonfly->team()->id == $teamId) {
return $dragonfly->unsetRelation('environment');
}
$clickhouse = StandaloneClickhouse::whereUuid($uuid)->first();
if ($clickhouse && $clickhouse->team()->id == $teamId) {
return $clickhouse->unsetRelation('environment');
}
return null;
}
2023-10-20 12:51:01 +00:00
function queryResourcesByUuid(string $uuid)
{
$resource = null;
$application = Application::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($application) {
return $application;
}
2023-10-20 12:51:01 +00:00
$service = Service::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($service) {
return $service;
}
2023-10-20 12:51:01 +00:00
$postgresql = StandalonePostgresql::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($postgresql) {
return $postgresql;
}
2023-10-20 12:51:01 +00:00
$redis = StandaloneRedis::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($redis) {
return $redis;
}
2023-10-20 12:51:01 +00:00
$mongodb = StandaloneMongodb::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($mongodb) {
return $mongodb;
}
$mysql = StandaloneMysql::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($mysql) {
return $mysql;
}
$mariadb = StandaloneMariadb::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($mariadb) {
return $mariadb;
}
2024-04-10 13:00:46 +00:00
$keydb = StandaloneKeydb::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($keydb) {
return $keydb;
}
2024-04-10 13:00:46 +00:00
$dragonfly = StandaloneDragonfly::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($dragonfly) {
return $dragonfly;
}
2024-04-10 13:00:46 +00:00
$clickhouse = StandaloneClickhouse::whereUuid($uuid)->first();
2024-06-10 20:43:34 +00:00
if ($clickhouse) {
return $clickhouse;
}
2023-10-20 12:51:01 +00:00
return $resource;
}
2024-02-01 14:38:12 +00:00
function generatTagDeployWebhook($tag_name)
{
$baseUrl = base_url();
2024-06-10 20:43:34 +00:00
$api = Url::fromString($baseUrl).'/api/v1';
2024-02-02 10:50:28 +00:00
$endpoint = "/deploy?tag=$tag_name";
2024-06-10 20:43:34 +00:00
$url = $api.$endpoint;
2024-02-01 14:38:12 +00:00
return $url;
}
function generateDeployWebhook($resource)
{
$baseUrl = base_url();
2024-06-10 20:43:34 +00:00
$api = Url::fromString($baseUrl).'/api/v1';
$endpoint = '/deploy';
$uuid = data_get($resource, 'uuid');
2024-06-10 20:43:34 +00:00
$url = $api.$endpoint."?uuid=$uuid&force=false";
return $url;
}
2023-11-24 14:48:23 +00:00
function generateGitManualWebhook($resource, $type)
{
2024-06-10 20:43:34 +00:00
if ($resource->source_id !== 0 && ! is_null($resource->source_id)) {
2023-11-14 13:14:21 +00:00
return null;
}
if ($resource->getMorphClass() === 'App\Models\Application') {
$baseUrl = base_url();
2024-06-10 20:43:34 +00:00
$api = Url::fromString($baseUrl)."/webhooks/source/$type/events/manual";
return $api;
}
2024-06-10 20:43:34 +00:00
return null;
}
function removeAnsiColors($text)
{
return preg_replace('/\e[[][A-Za-z0-9];?[0-9]*m?/', '', $text);
}
2023-11-24 14:48:23 +00:00
function getTopLevelNetworks(Service|Application $resource)
{
if ($resource->getMorphClass() === 'App\Models\Service') {
if ($resource->docker_compose_raw) {
try {
$yaml = Yaml::parse($resource->docker_compose_raw);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
$services = data_get($yaml, 'services');
$topLevelNetworks = collect(data_get($yaml, 'networks', []));
$definedNetwork = collect([$resource->uuid]);
$services = collect($services)->map(function ($service, $_) use ($topLevelNetworks, $definedNetwork) {
$serviceNetworks = collect(data_get($service, 'networks', []));
$hasHostNetworkMode = data_get($service, 'network_mode') === 'host' ? true : false;
// Only add 'networks' key if 'network_mode' is not 'host'
2024-06-10 20:43:34 +00:00
if (! $hasHostNetworkMode) {
// Collect/create/update networks
if ($serviceNetworks->count() > 0) {
foreach ($serviceNetworks as $networkName => $networkDetails) {
2024-05-31 08:21:38 +00:00
if ($networkName === 'default') {
continue;
}
// ignore alias
if ($networkDetails['aliases'] ?? false) {
continue;
}
$networkExists = $topLevelNetworks->contains(function ($value, $key) use ($networkName) {
return $value == $networkName || $key == $networkName;
});
2024-06-10 20:43:34 +00:00
if (! $networkExists) {
$topLevelNetworks->put($networkDetails, null);
}
}
}
$definedNetworkExists = $topLevelNetworks->contains(function ($value, $_) use ($definedNetwork) {
return $value == $definedNetwork;
});
2024-06-10 20:43:34 +00:00
if (! $definedNetworkExists) {
foreach ($definedNetwork as $network) {
2024-06-10 20:43:34 +00:00
$topLevelNetworks->put($network, [
'name' => $network,
2024-06-10 20:43:34 +00:00
'external' => true,
]);
}
}
}
return $service;
});
2024-06-10 20:43:34 +00:00
return $topLevelNetworks->keys();
}
2024-06-10 20:43:34 +00:00
} elseif ($resource->getMorphClass() === 'App\Models\Application') {
try {
$yaml = Yaml::parse($resource->docker_compose_raw);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
$server = $resource->destination->server;
$topLevelNetworks = collect(data_get($yaml, 'networks', []));
$services = data_get($yaml, 'services');
$definedNetwork = collect([$resource->uuid]);
$services = collect($services)->map(function ($service, $_) use ($topLevelNetworks, $definedNetwork) {
$serviceNetworks = collect(data_get($service, 'networks', []));
// Collect/create/update networks
if ($serviceNetworks->count() > 0) {
foreach ($serviceNetworks as $networkName => $networkDetails) {
2024-05-31 08:21:38 +00:00
if ($networkName === 'default') {
continue;
}
// ignore alias
if ($networkDetails['aliases'] ?? false) {
continue;
}
$networkExists = $topLevelNetworks->contains(function ($value, $key) use ($networkName) {
return $value == $networkName || $key == $networkName;
});
2024-06-10 20:43:34 +00:00
if (! $networkExists) {
$topLevelNetworks->put($networkDetails, null);
}
}
}
$definedNetworkExists = $topLevelNetworks->contains(function ($value, $_) use ($definedNetwork) {
return $value == $definedNetwork;
});
2024-06-10 20:43:34 +00:00
if (! $definedNetworkExists) {
foreach ($definedNetwork as $network) {
2024-06-10 20:43:34 +00:00
$topLevelNetworks->put($network, [
'name' => $network,
2024-06-10 20:43:34 +00:00
'external' => true,
]);
}
}
2024-06-10 20:43:34 +00:00
return $service;
});
2024-06-10 20:43:34 +00:00
return $topLevelNetworks->keys();
}
}
2024-05-31 08:21:38 +00:00
function parseDockerComposeFile(Service|Application $resource, bool $isNew = false, int $pull_request_id = 0, ?int $preview_id = null)
2023-11-24 14:48:23 +00:00
{
if ($resource->getMorphClass() === 'App\Models\Service') {
if ($resource->docker_compose_raw) {
try {
$yaml = Yaml::parse($resource->docker_compose_raw);
} catch (\Exception $e) {
throw new \Exception($e->getMessage());
}
$allServices = get_service_templates();
2023-11-24 14:48:23 +00:00
$topLevelVolumes = collect(data_get($yaml, 'volumes', []));
$topLevelNetworks = collect(data_get($yaml, 'networks', []));
$topLevelConfigs = collect(data_get($yaml, 'configs', []));
$topLevelSecrets = collect(data_get($yaml, 'secrets', []));
2023-11-24 14:48:23 +00:00
$services = data_get($yaml, 'services');
$generatedServiceFQDNS = collect([]);
if (is_null($resource->destination)) {
$destination = $resource->server->destinations()->first();
if ($destination) {
$resource->destination()->associate($destination);
$resource->save();
}
}
$definedNetwork = collect([$resource->uuid]);
2024-05-31 08:21:38 +00:00
if ($topLevelVolumes->count() > 0) {
$tempTopLevelVolumes = collect([]);
foreach ($topLevelVolumes as $volumeName => $volume) {
if (is_null($volume)) {
continue;
}
$tempTopLevelVolumes->put($volumeName, $volume);
}
$topLevelVolumes = collect($tempTopLevelVolumes);
2024-05-31 08:21:38 +00:00
}
$services = collect($services)->map(function ($service, $serviceName) use ($topLevelVolumes, $topLevelNetworks, $definedNetwork, $isNew, $generatedServiceFQDNS, $resource, $allServices) {
// Workarounds for beta users.
if ($serviceName === 'registry') {
2024-06-10 20:43:34 +00:00
$tempServiceName = 'docker-registry';
} else {
$tempServiceName = $serviceName;
}
2024-03-12 18:09:08 +00:00
if (str(data_get($service, 'image'))->contains('glitchtip')) {
$tempServiceName = 'glitchtip';
}
if ($serviceName === 'supabase-kong') {
$tempServiceName = 'supabase';
}
$serviceDefinition = data_get($allServices, $tempServiceName);
$predefinedPort = data_get($serviceDefinition, 'port');
if ($serviceName === 'plausible') {
$predefinedPort = '8000';
}
// End of workarounds for beta users.
2023-11-24 14:48:23 +00:00
$serviceVolumes = collect(data_get($service, 'volumes', []));
$servicePorts = collect(data_get($service, 'ports', []));
$serviceNetworks = collect(data_get($service, 'networks', []));
$serviceVariables = collect(data_get($service, 'environment', []));
$serviceLabels = collect(data_get($service, 'labels', []));
$hasHostNetworkMode = data_get($service, 'network_mode') === 'host' ? true : false;
2023-11-24 14:48:23 +00:00
if ($serviceLabels->count() > 0) {
$removedLabels = collect([]);
$serviceLabels = $serviceLabels->filter(function ($serviceLabel, $serviceLabelName) use ($removedLabels) {
2024-06-10 20:43:34 +00:00
if (! str($serviceLabel)->contains('=')) {
2023-11-24 14:48:23 +00:00
$removedLabels->put($serviceLabelName, $serviceLabel);
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
return false;
}
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
return $serviceLabel;
});
foreach ($removedLabels as $removedLabelName => $removedLabel) {
$serviceLabels->push("$removedLabelName=$removedLabel");
}
}
$containerName = "$serviceName-{$resource->uuid}";
// Decide if the service is a database
$isDatabase = isDatabaseImage(data_get_str($service, 'image'));
2023-11-24 14:48:23 +00:00
$image = data_get_str($service, 'image');
data_set($service, 'is_database', $isDatabase);
// Create new serviceApplication or serviceDatabase
if ($isDatabase) {
if ($isNew) {
$savedService = ServiceDatabase::create([
'name' => $serviceName,
'image' => $image,
2024-06-10 20:43:34 +00:00
'service_id' => $resource->id,
2023-11-24 14:48:23 +00:00
]);
} else {
$savedService = ServiceDatabase::where([
'name' => $serviceName,
2024-06-10 20:43:34 +00:00
'service_id' => $resource->id,
2023-11-24 14:48:23 +00:00
])->first();
}
} else {
if ($isNew) {
$savedService = ServiceApplication::create([
'name' => $serviceName,
'image' => $image,
2024-06-10 20:43:34 +00:00
'service_id' => $resource->id,
2023-11-24 14:48:23 +00:00
]);
} else {
$savedService = ServiceApplication::where([
'name' => $serviceName,
2024-06-10 20:43:34 +00:00
'service_id' => $resource->id,
2023-11-24 14:48:23 +00:00
])->first();
}
}
if (is_null($savedService)) {
if ($isDatabase) {
$savedService = ServiceDatabase::create([
'name' => $serviceName,
'image' => $image,
2024-06-10 20:43:34 +00:00
'service_id' => $resource->id,
2023-11-24 14:48:23 +00:00
]);
} else {
$savedService = ServiceApplication::create([
'name' => $serviceName,
'image' => $image,
2024-06-10 20:43:34 +00:00
'service_id' => $resource->id,
2023-11-24 14:48:23 +00:00
]);
}
}
// Check if image changed
if ($savedService->image !== $image) {
$savedService->image = $image;
$savedService->save();
}
// Collect/create/update networks
if ($serviceNetworks->count() > 0) {
foreach ($serviceNetworks as $networkName => $networkDetails) {
2024-05-31 08:21:38 +00:00
if ($networkName === 'default') {
continue;
}
// ignore alias
if ($networkDetails['aliases'] ?? false) {
continue;
}
2023-11-24 14:48:23 +00:00
$networkExists = $topLevelNetworks->contains(function ($value, $key) use ($networkName) {
return $value == $networkName || $key == $networkName;
});
2024-06-10 20:43:34 +00:00
if (! $networkExists) {
2023-11-24 14:48:23 +00:00
$topLevelNetworks->put($networkDetails, null);
}
}
}
// Collect/create/update ports
$collectedPorts = collect([]);
if ($servicePorts->count() > 0) {
foreach ($servicePorts as $sport) {
if (is_string($sport) || is_numeric($sport)) {
$collectedPorts->push($sport);
}
if (is_array($sport)) {
$target = data_get($sport, 'target');
$published = data_get($sport, 'published');
$protocol = data_get($sport, 'protocol');
$collectedPorts->push("$target:$published/$protocol");
}
}
}
$savedService->ports = $collectedPorts->implode(',');
$savedService->save();
2024-06-10 20:43:34 +00:00
if (! $hasHostNetworkMode) {
// Add Coolify specific networks
$definedNetworkExists = $topLevelNetworks->contains(function ($value, $_) use ($definedNetwork) {
return $value == $definedNetwork;
});
2024-06-10 20:43:34 +00:00
if (! $definedNetworkExists) {
foreach ($definedNetwork as $network) {
2024-06-10 20:43:34 +00:00
$topLevelNetworks->put($network, [
'name' => $network,
2024-06-10 20:43:34 +00:00
'external' => true,
]);
}
2023-11-24 14:48:23 +00:00
}
$networks = collect();
foreach ($serviceNetworks as $key => $serviceNetwork) {
if (gettype($serviceNetwork) === 'string') {
// networks:
// - appwrite
$networks->put($serviceNetwork, null);
2024-06-10 20:43:34 +00:00
} elseif (gettype($serviceNetwork) === 'array') {
// networks:
// default:
// ipv4_address: 192.168.203.254
// $networks->put($serviceNetwork, null);
$networks->put($key, $serviceNetwork);
}
2023-11-24 14:48:23 +00:00
}
foreach ($definedNetwork as $key => $network) {
$networks->put($network, null);
}
data_set($service, 'networks', $networks->toArray());
2023-11-24 14:48:23 +00:00
}
// Collect/create/update volumes
if ($serviceVolumes->count() > 0) {
$serviceVolumes = $serviceVolumes->map(function ($volume) use ($savedService, $topLevelVolumes) {
$type = null;
$source = null;
$target = null;
$content = null;
$isDirectory = false;
if (is_string($volume)) {
$source = str($volume)->before(':');
$target = str($volume)->after(':')->beforeLast(':');
2023-11-24 14:48:23 +00:00
if ($source->startsWith('./') || $source->startsWith('/') || $source->startsWith('~')) {
$type = str('bind');
2023-11-24 14:48:23 +00:00
} else {
$type = str('volume');
2023-11-24 14:48:23 +00:00
}
2024-06-10 20:43:34 +00:00
} elseif (is_array($volume)) {
2023-11-24 14:48:23 +00:00
$type = data_get_str($volume, 'type');
$source = data_get_str($volume, 'source');
$target = data_get_str($volume, 'target');
$content = data_get($volume, 'content');
$isDirectory = (bool) data_get($volume, 'isDirectory', false) || (bool) data_get($volume, 'is_directory', false);
2023-11-24 14:48:23 +00:00
$foundConfig = $savedService->fileStorages()->whereMountPath($target)->first();
if ($foundConfig) {
$contentNotNull = data_get($foundConfig, 'content');
if ($contentNotNull) {
$content = $contentNotNull;
}
$isDirectory = (bool) data_get($volume, 'isDirectory', false) || (bool) data_get($volume, 'is_directory', false);
2023-11-24 14:48:23 +00:00
}
}
2024-03-18 11:40:58 +00:00
if ($type?->value() === 'bind') {
2024-06-10 20:43:34 +00:00
if ($source->value() === '/var/run/docker.sock') {
2023-11-24 14:48:23 +00:00
return $volume;
}
if ($source->value() === '/tmp' || $source->value() === '/tmp/') {
return $volume;
}
LocalFileVolume::updateOrCreate(
[
'mount_path' => $target,
'resource_id' => $savedService->id,
2024-06-10 20:43:34 +00:00
'resource_type' => get_class($savedService),
2023-11-24 14:48:23 +00:00
],
[
'fs_path' => $source,
'mount_path' => $target,
'content' => $content,
'is_directory' => $isDirectory,
'resource_id' => $savedService->id,
2024-06-10 20:43:34 +00:00
'resource_type' => get_class($savedService),
2023-11-24 14:48:23 +00:00
]
);
2024-06-10 20:43:34 +00:00
} elseif ($type->value() === 'volume') {
2024-05-31 08:21:38 +00:00
if ($topLevelVolumes->has($source->value())) {
$v = $topLevelVolumes->get($source->value());
if (data_get($v, 'driver_opts.type') === 'cifs') {
return $volume;
}
2024-05-31 08:21:38 +00:00
}
2023-11-24 14:48:23 +00:00
$slugWithoutUuid = Str::slug($source, '-');
$name = "{$savedService->service->uuid}_{$slugWithoutUuid}";
if (is_string($volume)) {
$source = str($volume)->before(':');
$target = str($volume)->after(':')->beforeLast(':');
2023-11-24 14:48:23 +00:00
$source = $name;
$volume = "$source:$target";
2024-06-10 20:43:34 +00:00
} elseif (is_array($volume)) {
2023-11-24 14:48:23 +00:00
data_set($volume, 'source', $name);
}
$topLevelVolumes->put($name, [
'name' => $name,
]);
LocalPersistentVolume::updateOrCreate(
[
'mount_path' => $target,
'resource_id' => $savedService->id,
2024-06-10 20:43:34 +00:00
'resource_type' => get_class($savedService),
2023-11-24 14:48:23 +00:00
],
[
'name' => $name,
'mount_path' => $target,
'resource_id' => $savedService->id,
2024-06-10 20:43:34 +00:00
'resource_type' => get_class($savedService),
2023-11-24 14:48:23 +00:00
]
);
}
2024-03-13 17:26:30 +00:00
dispatch(new ServerFilesFromServerJob($savedService));
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
return $volume;
});
data_set($service, 'volumes', $serviceVolumes->toArray());
}
// Add env_file with at least .env to the service
// $envFile = collect(data_get($service, 'env_file', []));
// if ($envFile->count() > 0) {
// if (!$envFile->contains('.env')) {
// $envFile->push('.env');
// }
// } else {
// $envFile = collect(['.env']);
// }
// data_set($service, 'env_file', $envFile->toArray());
// Get variables from the service
foreach ($serviceVariables as $variableName => $variable) {
if (is_numeric($variableName)) {
$variable = str($variable);
2023-11-24 14:48:23 +00:00
if ($variable->contains('=')) {
// - SESSION_SECRET=123
// - SESSION_SECRET=
$key = $variable->before('=');
$value = $variable->after('=');
} else {
// - SESSION_SECRET
$key = $variable;
$value = null;
}
} else {
// SESSION_SECRET: 123
// SESSION_SECRET:
$key = str($variableName);
$value = str($variable);
2023-11-24 14:48:23 +00:00
}
if ($key->startsWith('SERVICE_FQDN')) {
if ($isNew || $savedService->fqdn === null) {
$name = $key->after('SERVICE_FQDN_')->beforeLast('_')->lower();
$fqdn = generateFqdn($resource->server, "{$name->value()}-{$resource->uuid}");
if (substr_count($key->value(), '_') === 3) {
// SERVICE_FQDN_UMAMI_1000
$port = $key->afterLast('_');
} else {
$last = $key->afterLast('_');
if (is_numeric($last->value())) {
// SERVICE_FQDN_3001
$port = $last;
} else {
// SERVICE_FQDN_UMAMI
$port = null;
}
2023-11-24 14:48:23 +00:00
}
if ($port) {
$fqdn = "$fqdn:$port";
}
if (substr_count($key->value(), '_') >= 2) {
if ($value) {
$path = $value->value();
} else {
$path = null;
2023-11-24 14:48:23 +00:00
}
if ($generatedServiceFQDNS->count() > 0) {
$alreadyGenerated = $generatedServiceFQDNS->has($key->value());
if ($alreadyGenerated) {
$fqdn = $generatedServiceFQDNS->get($key->value());
} else {
$generatedServiceFQDNS->put($key->value(), $fqdn);
}
} else {
$generatedServiceFQDNS->put($key->value(), $fqdn);
}
$fqdn = "$fqdn$path";
}
2024-06-10 20:43:34 +00:00
if (! $isDatabase) {
2023-11-24 14:48:23 +00:00
if ($savedService->fqdn) {
2024-06-10 20:43:34 +00:00
data_set($savedService, 'fqdn', $savedService->fqdn.','.$fqdn);
2023-11-24 14:48:23 +00:00
} else {
data_set($savedService, 'fqdn', $fqdn);
2023-11-24 14:48:23 +00:00
}
$savedService->save();
}
EnvironmentVariable::create([
'key' => $key,
'value' => $fqdn,
'is_build_time' => false,
'service_id' => $resource->id,
'is_preview' => false,
]);
2023-11-24 14:48:23 +00:00
}
// Caddy needs exact port in some cases.
2024-06-10 20:43:34 +00:00
if ($predefinedPort && ! $key->endsWith("_{$predefinedPort}")) {
$fqdns_exploded = str($savedService->fqdn)->explode(',');
if ($fqdns_exploded->count() > 1) {
continue;
}
2024-05-03 09:26:00 +00:00
$env = EnvironmentVariable::where([
'key' => $key,
'service_id' => $resource->id,
])->first();
if ($env) {
$env_url = Url::fromString($savedService->fqdn);
$env_port = $env_url->getPort();
if ($env_port !== $predefinedPort) {
$env_url = $env_url->withPort($predefinedPort);
$savedService->fqdn = $env_url->__toString();
$savedService->save();
}
}
}
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
// data_forget($service, "environment.$variableName");
// $yaml = data_forget($yaml, "services.$serviceName.environment.$variableName");
// if (count(data_get($yaml, 'services.' . $serviceName . '.environment')) === 0) {
// $yaml = data_forget($yaml, "services.$serviceName.environment");
// }
continue;
}
if ($value?->startsWith('$')) {
$foundEnv = EnvironmentVariable::where([
'key' => $key,
'service_id' => $resource->id,
])->first();
$value = str(replaceVariables($value));
$key = $value;
2023-11-24 14:48:23 +00:00
if ($value->startsWith('SERVICE_')) {
$foundEnv = EnvironmentVariable::where([
'key' => $key,
'service_id' => $resource->id,
])->first();
2023-11-28 11:05:04 +00:00
['command' => $command, 'forService' => $forService, 'generatedValue' => $generatedValue, 'port' => $port] = parseEnvVariable($value);
2024-06-10 20:43:34 +00:00
if (! is_null($command)) {
if ($command?->value() === 'FQDN' || $command?->value() === 'URL') {
if (Str::lower($forService) === $serviceName) {
$fqdn = generateFqdn($resource->server, $containerName);
} else {
2024-06-10 20:43:34 +00:00
$fqdn = generateFqdn($resource->server, Str::lower($forService).'-'.$resource->uuid);
2023-11-24 14:48:23 +00:00
}
if ($port) {
$fqdn = "$fqdn:$port";
2024-02-21 11:22:32 +00:00
}
if ($foundEnv) {
$fqdn = data_get($foundEnv, 'value');
2024-05-22 13:45:30 +00:00
// if ($savedService->fqdn) {
// $savedServiceFqdn = Url::fromString($savedService->fqdn);
// $parsedFqdn = Url::fromString($fqdn);
// $savedServicePath = $savedServiceFqdn->getPath();
// $parsedFqdnPath = $parsedFqdn->getPath();
// if ($savedServicePath != $parsedFqdnPath) {
// $fqdn = $parsedFqdn->withPath($savedServicePath)->__toString();
// $foundEnv->value = $fqdn;
// $foundEnv->save();
// }
// }
} else {
if ($command->value() === 'URL') {
$fqdn = str($fqdn)->after('://')->value();
}
EnvironmentVariable::create([
2024-03-12 18:09:08 +00:00
'key' => $key,
'value' => $fqdn,
'is_build_time' => false,
2024-03-12 18:09:08 +00:00
'service_id' => $resource->id,
'is_preview' => false,
]);
}
2024-06-10 20:43:34 +00:00
if (! $isDatabase) {
if ($command->value() === 'FQDN' && is_null($savedService->fqdn) && ! $foundEnv) {
$savedService->fqdn = $fqdn;
$savedService->save();
}
// Caddy needs exact port in some cases.
2024-06-10 20:43:34 +00:00
if ($predefinedPort && ! $key->endsWith("_{$predefinedPort}") && $command?->value() === 'FQDN' && $resource->server->proxyType() === 'CADDY') {
$fqdns_exploded = str($savedService->fqdn)->explode(',');
if ($fqdns_exploded->count() > 1) {
continue;
}
$env = EnvironmentVariable::where([
'key' => $key,
'service_id' => $resource->id,
])->first();
if ($env) {
$env_url = Url::fromString($env->value);
$env_port = $env_url->getPort();
if ($env_port !== $predefinedPort) {
$env_url = $env_url->withPort($predefinedPort);
$savedService->fqdn = $env_url->__toString();
$savedService->save();
}
}
}
}
} else {
$generatedValue = generateEnvValue($command, $resource);
2024-06-10 20:43:34 +00:00
if (! $foundEnv) {
EnvironmentVariable::create([
'key' => $key,
'value' => $generatedValue,
'is_build_time' => false,
'service_id' => $resource->id,
'is_preview' => false,
]);
}
2023-11-24 14:48:23 +00:00
}
}
} else {
if ($value->contains(':-')) {
$key = $value->before(':');
$defaultValue = $value->after(':-');
2024-06-10 20:43:34 +00:00
} elseif ($value->contains('-')) {
2023-11-24 14:48:23 +00:00
$key = $value->before('-');
$defaultValue = $value->after('-');
2024-06-10 20:43:34 +00:00
} elseif ($value->contains(':?')) {
2023-11-24 14:48:23 +00:00
$key = $value->before(':');
$defaultValue = $value->after(':?');
2024-06-10 20:43:34 +00:00
} elseif ($value->contains('?')) {
2023-11-24 14:48:23 +00:00
$key = $value->before('?');
$defaultValue = $value->after('?');
} else {
$key = $value;
$defaultValue = null;
}
$foundEnv = EnvironmentVariable::where([
'key' => $key,
'service_id' => $resource->id,
])->first();
2023-11-24 14:48:23 +00:00
if ($foundEnv) {
$defaultValue = data_get($foundEnv, 'value');
}
EnvironmentVariable::updateOrCreate([
'key' => $key,
'service_id' => $resource->id,
], [
'value' => $defaultValue,
'is_build_time' => false,
'service_id' => $resource->id,
'is_preview' => false,
]);
}
}
}
// Add labels to the service
if ($savedService->serviceType()) {
$fqdns = generateServiceSpecificFqdns($savedService);
2023-11-24 14:48:23 +00:00
} else {
$fqdns = collect(data_get($savedService, 'fqdns'))->filter();
2023-11-24 14:48:23 +00:00
}
$defaultLabels = defaultLabels($resource->id, $containerName, type: 'service', subType: $isDatabase ? 'database' : 'application', subId: $savedService->id);
$serviceLabels = $serviceLabels->merge($defaultLabels);
2024-06-10 20:43:34 +00:00
if (! $isDatabase && $fqdns->count() > 0) {
2023-11-24 14:48:23 +00:00
if ($fqdns) {
$serviceLabels = $serviceLabels->merge(fqdnLabelsForTraefik(
uuid: $resource->uuid,
domains: $fqdns,
is_force_https_enabled: true,
serviceLabels: $serviceLabels,
is_gzip_enabled: $savedService->isGzipEnabled(),
is_stripprefix_enabled: $savedService->isStripprefixEnabled(),
2024-05-22 19:10:37 +00:00
service_name: $serviceName,
image: data_get($service, 'image')
2024-03-04 11:50:56 +00:00
));
2024-03-11 14:08:05 +00:00
$serviceLabels = $serviceLabels->merge(fqdnLabelsForCaddy(
network: $resource->destination->network,
uuid: $resource->uuid,
domains: $fqdns,
is_force_https_enabled: true,
serviceLabels: $serviceLabels,
is_gzip_enabled: $savedService->isGzipEnabled(),
is_stripprefix_enabled: $savedService->isStripprefixEnabled(),
2024-05-22 19:10:37 +00:00
service_name: $serviceName,
image: data_get($service, 'image')
2024-03-11 14:08:05 +00:00
));
2023-11-24 14:48:23 +00:00
}
}
if ($resource->server->isLogDrainEnabled() && $savedService->isLogDrainEnabled()) {
2023-11-24 14:48:23 +00:00
data_set($service, 'logging', [
'driver' => 'fluentd',
'options' => [
2024-06-10 20:43:34 +00:00
'fluentd-address' => 'tcp://127.0.0.1:24224',
'fluentd-async' => 'true',
'fluentd-sub-second-precision' => 'true',
],
2023-11-24 14:48:23 +00:00
]);
}
2024-05-15 15:52:14 +00:00
if ($serviceLabels->count() > 0) {
if ($resource->is_container_label_escape_enabled) {
$serviceLabels = $serviceLabels->map(function ($value, $key) {
return escapeDollarSign($value);
});
}
}
2023-11-24 14:48:23 +00:00
data_set($service, 'labels', $serviceLabels->toArray());
data_forget($service, 'is_database');
2024-06-10 20:43:34 +00:00
if (! data_get($service, 'restart')) {
data_set($service, 'restart', RESTART_MODE);
}
2024-05-23 09:12:53 +00:00
if (data_get($service, 'restart') === 'no' || data_get($service, 'exclude_from_hc')) {
$savedService->update(['exclude_from_status' => true]);
}
2023-11-24 14:48:23 +00:00
data_set($service, 'container_name', $containerName);
data_forget($service, 'volumes.*.content');
data_forget($service, 'volumes.*.isDirectory');
data_forget($service, 'volumes.*.is_directory');
2024-05-23 09:12:53 +00:00
data_forget($service, 'exclude_from_hc');
data_set($service, 'environment', $serviceVariables->toArray());
updateCompose($savedService);
2024-06-10 20:43:34 +00:00
return $service;
});
$envs_from_coolify = $resource->environment_variables()->get();
$services = collect($services)->map(function ($service, $serviceName) use ($resource, $envs_from_coolify) {
$serviceVariables = collect(data_get($service, 'environment', []));
$parsedServiceVariables = collect([]);
foreach ($serviceVariables as $key => $value) {
if (is_numeric($key)) {
$value = str($value);
if ($value->contains('=')) {
$key = $value->before('=')->value();
$value = $value->after('=')->value();
} else {
$key = $value->value();
$value = null;
}
$parsedServiceVariables->put($key, $value);
} else {
$parsedServiceVariables->put($key, $value);
}
}
$parsedServiceVariables->put('COOLIFY_CONTAINER_NAME', "$serviceName-{$resource->uuid}");
$parsedServiceVariables = $parsedServiceVariables->map(function ($value, $key) use ($envs_from_coolify) {
if (! str($value)->startsWith('$')) {
$found_env = $envs_from_coolify->where('key', $key)->first();
if ($found_env) {
return $found_env->value;
}
}
return $value;
});
data_set($service, 'environment', $parsedServiceVariables->toArray());
2023-11-24 14:48:23 +00:00
return $service;
});
$finalServices = [
'services' => $services->toArray(),
'volumes' => $topLevelVolumes->toArray(),
'networks' => $topLevelNetworks->toArray(),
'configs' => $topLevelConfigs->toArray(),
'secrets' => $topLevelSecrets->toArray(),
2023-11-24 14:48:23 +00:00
];
$yaml = data_forget($yaml, 'services.*.volumes.*.content');
2023-11-24 14:48:23 +00:00
$resource->docker_compose_raw = Yaml::dump($yaml, 10, 2);
$resource->docker_compose = Yaml::dump($finalServices, 10, 2);
$resource->save();
$resource->saveComposeConfigs();
2024-06-10 20:43:34 +00:00
return collect($finalServices);
2023-11-24 14:48:23 +00:00
} else {
return collect([]);
}
2024-06-10 20:43:34 +00:00
} elseif ($resource->getMorphClass() === 'App\Models\Application') {
$isSameDockerComposeFile = false;
if ($resource->dockerComposePrLocation() === $resource->dockerComposeLocation()) {
$isSameDockerComposeFile = true;
}
try {
$yaml = Yaml::parse($resource->docker_compose_raw);
} catch (\Exception $e) {
return;
2023-11-24 14:48:23 +00:00
}
$server = $resource->destination->server;
$topLevelVolumes = collect(data_get($yaml, 'volumes', []));
if ($pull_request_id !== 0) {
$topLevelVolumes = collect([]);
}
2024-05-31 08:21:38 +00:00
if ($topLevelVolumes->count() > 0) {
$tempTopLevelVolumes = collect([]);
foreach ($topLevelVolumes as $volumeName => $volume) {
if (is_null($volume)) {
continue;
}
$tempTopLevelVolumes->put($volumeName, $volume);
}
$topLevelVolumes = collect($tempTopLevelVolumes);
2024-05-31 08:21:38 +00:00
}
2023-11-24 14:48:23 +00:00
$topLevelNetworks = collect(data_get($yaml, 'networks', []));
$topLevelConfigs = collect(data_get($yaml, 'configs', []));
$topLevelSecrets = collect(data_get($yaml, 'secrets', []));
2023-11-24 14:48:23 +00:00
$services = data_get($yaml, 'services');
$generatedServiceFQDNS = collect([]);
if (is_null($resource->destination)) {
$destination = $server->destinations()->first();
if ($destination) {
$resource->destination()->associate($destination);
$resource->save();
}
}
$definedNetwork = collect([$resource->uuid]);
if ($pull_request_id !== 0) {
$definedNetwork = collect(["{$resource->uuid}-$pull_request_id"]);
}
$services = collect($services)->map(function ($service, $serviceName) use ($topLevelVolumes, $topLevelNetworks, $definedNetwork, $isNew, $generatedServiceFQDNS, $resource, $server, $pull_request_id, $preview_id) {
2023-11-24 14:48:23 +00:00
$serviceVolumes = collect(data_get($service, 'volumes', []));
$servicePorts = collect(data_get($service, 'ports', []));
$serviceNetworks = collect(data_get($service, 'networks', []));
$serviceVariables = collect(data_get($service, 'environment', []));
2024-05-14 11:33:29 +00:00
$serviceDependencies = collect(data_get($service, 'depends_on', []));
2023-11-24 14:48:23 +00:00
$serviceLabels = collect(data_get($service, 'labels', []));
$serviceBuildVariables = collect(data_get($service, 'build.args', []));
$serviceVariables = $serviceVariables->merge($serviceBuildVariables);
2023-11-24 14:48:23 +00:00
if ($serviceLabels->count() > 0) {
$removedLabels = collect([]);
$serviceLabels = $serviceLabels->filter(function ($serviceLabel, $serviceLabelName) use ($removedLabels) {
2024-06-10 20:43:34 +00:00
if (! str($serviceLabel)->contains('=')) {
2023-11-24 14:48:23 +00:00
$removedLabels->put($serviceLabelName, $serviceLabel);
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
return false;
}
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
return $serviceLabel;
});
foreach ($removedLabels as $removedLabelName => $removedLabel) {
$serviceLabels->push("$removedLabelName=$removedLabel");
}
}
2024-05-15 15:52:14 +00:00
$baseName = generateApplicationContainerName($resource, $pull_request_id);
$containerName = "$serviceName-$baseName";
2024-07-11 08:55:15 +00:00
if ($resource->compose_parsing_version === '1') {
if (count($serviceVolumes) > 0) {
$serviceVolumes = $serviceVolumes->map(function ($volume) use ($resource, $topLevelVolumes, $pull_request_id) {
if (is_string($volume)) {
$volume = str($volume);
if ($volume->contains(':') && ! $volume->startsWith('/')) {
$name = $volume->before(':');
$mount = $volume->after(':');
if ($name->startsWith('.') || $name->startsWith('~')) {
$dir = base_configuration_dir().'/applications/'.$resource->uuid;
if ($name->startsWith('.')) {
$name = $name->replaceFirst('.', $dir);
}
if ($name->startsWith('~')) {
$name = $name->replaceFirst('~', $dir);
}
if ($pull_request_id !== 0) {
$name = $name."-pr-$pull_request_id";
}
$volume = str("$name:$mount");
2024-07-11 08:55:15 +00:00
} else {
if ($pull_request_id !== 0) {
$name = $name."-pr-$pull_request_id";
$volume = str("$name:$mount");
if ($topLevelVolumes->has($name)) {
$v = $topLevelVolumes->get($name);
if (data_get($v, 'driver_opts.type') === 'cifs') {
// Do nothing
} else {
if (is_null(data_get($v, 'name'))) {
data_set($v, 'name', $name);
data_set($topLevelVolumes, $name, $v);
}
}
} else {
2024-07-11 08:55:15 +00:00
$topLevelVolumes->put($name, [
'name' => $name,
]);
}
} else {
if ($topLevelVolumes->has($name->value())) {
$v = $topLevelVolumes->get($name->value());
if (data_get($v, 'driver_opts.type') === 'cifs') {
// Do nothing
} else {
if (is_null(data_get($v, 'name'))) {
data_set($topLevelVolumes, $name->value(), $v);
}
}
2024-07-11 08:55:15 +00:00
} else {
$topLevelVolumes->put($name->value(), [
'name' => $name->value(),
]);
}
2024-07-11 08:55:15 +00:00
}
}
} else {
if ($volume->startsWith('/')) {
$name = $volume->before(':');
$mount = $volume->after(':');
if ($pull_request_id !== 0) {
$name = $name."-pr-$pull_request_id";
}
$volume = str("$name:$mount");
}
}
} elseif (is_array($volume)) {
$source = data_get($volume, 'source');
$target = data_get($volume, 'target');
$read_only = data_get($volume, 'read_only');
if ($source && $target) {
if ((str($source)->startsWith('.') || str($source)->startsWith('~'))) {
$dir = base_configuration_dir().'/applications/'.$resource->uuid;
if (str($source, '.')) {
$source = str($source)->replaceFirst('.', $dir);
}
if (str($source, '~')) {
$source = str($source)->replaceFirst('~', $dir);
}
if ($pull_request_id !== 0) {
$source = $source."-pr-$pull_request_id";
}
if ($read_only) {
data_set($volume, 'source', $source.':'.$target.':ro');
} else {
2024-07-11 08:55:15 +00:00
data_set($volume, 'source', $source.':'.$target);
}
} else {
2024-07-11 08:55:15 +00:00
if ($pull_request_id !== 0) {
$source = $source."-pr-$pull_request_id";
}
if ($read_only) {
data_set($volume, 'source', $source.':'.$target.':ro');
} else {
data_set($volume, 'source', $source.':'.$target);
}
if (! str($source)->startsWith('/')) {
if ($topLevelVolumes->has($source)) {
$v = $topLevelVolumes->get($source);
if (data_get($v, 'driver_opts.type') === 'cifs') {
// Do nothing
} else {
if (is_null(data_get($v, 'name'))) {
data_set($v, 'name', $source);
data_set($topLevelVolumes, $source, $v);
}
}
2024-07-11 08:55:15 +00:00
} else {
$topLevelVolumes->put($source, [
'name' => $source,
]);
}
}
}
}
2024-07-11 08:55:15 +00:00
}
if (is_array($volume)) {
return data_get($volume, 'source');
}
return $volume->value();
});
data_set($service, 'volumes', $serviceVolumes->toArray());
}
} elseif ($resource->compose_parsing_version === '2') {
if (count($serviceVolumes) > 0) {
$serviceVolumes = $serviceVolumes->map(function ($volume) use ($resource, $topLevelVolumes, $pull_request_id) {
if (is_string($volume)) {
$volume = str($volume);
if ($volume->contains(':') && ! $volume->startsWith('/')) {
2024-03-19 10:48:25 +00:00
$name = $volume->before(':');
$mount = $volume->after(':');
2024-07-11 08:55:15 +00:00
if ($name->startsWith('.') || $name->startsWith('~')) {
$dir = base_configuration_dir().'/applications/'.$resource->uuid;
if ($name->startsWith('.')) {
$name = $name->replaceFirst('.', $dir);
}
if ($name->startsWith('~')) {
$name = $name->replaceFirst('~', $dir);
}
if ($pull_request_id !== 0) {
$name = $name."-pr-$pull_request_id";
}
$volume = str("$name:$mount");
2024-03-19 10:48:25 +00:00
} else {
2024-07-11 08:55:15 +00:00
if ($pull_request_id !== 0) {
$uuid = $resource->uuid;
$name = $uuid."-$name-pr-$pull_request_id";
$volume = str("$name:$mount");
if ($topLevelVolumes->has($name)) {
$v = $topLevelVolumes->get($name);
if (data_get($v, 'driver_opts.type') === 'cifs') {
// Do nothing
} else {
if (is_null(data_get($v, 'name'))) {
data_set($v, 'name', $name);
data_set($topLevelVolumes, $name, $v);
}
}
} else {
$topLevelVolumes->put($name, [
'name' => $name,
]);
}
} else {
$uuid = $resource->uuid;
$name = str($uuid."-$name");
$volume = str("$name:$mount");
if ($topLevelVolumes->has($name->value())) {
$v = $topLevelVolumes->get($name->value());
if (data_get($v, 'driver_opts.type') === 'cifs') {
// Do nothing
} else {
if (is_null(data_get($v, 'name'))) {
data_set($topLevelVolumes, $name->value(), $v);
}
}
} else {
$topLevelVolumes->put($name->value(), [
'name' => $name->value(),
]);
}
}
2024-03-19 10:48:25 +00:00
}
} else {
2024-07-11 08:55:15 +00:00
if ($volume->startsWith('/')) {
$name = $volume->before(':');
$mount = $volume->after(':');
if ($pull_request_id !== 0) {
$name = $name."-pr-$pull_request_id";
}
$volume = str("$name:$mount");
2024-03-19 10:48:25 +00:00
}
2024-07-11 08:55:15 +00:00
}
} elseif (is_array($volume)) {
$source = data_get($volume, 'source');
$target = data_get($volume, 'target');
$read_only = data_get($volume, 'read_only');
if ($source && $target) {
$uuid = $resource->uuid;
2024-07-17 06:09:33 +00:00
if ((str($source)->startsWith('.') || str($source)->startsWith('~') || str($source)->startsWith('/'))) {
2024-07-11 08:55:15 +00:00
$dir = base_configuration_dir().'/applications/'.$resource->uuid;
if (str($source, '.')) {
$source = str($source)->replaceFirst('.', $dir);
}
if (str($source, '~')) {
$source = str($source)->replaceFirst('~', $dir);
}
if ($read_only) {
data_set($volume, 'source', $source.':'.$target.':ro');
} else {
data_set($volume, 'source', $source.':'.$target);
}
} else {
2024-07-11 08:55:15 +00:00
if ($pull_request_id === 0) {
$source = $uuid."-$source";
} else {
$source = $uuid."-$source-pr-$pull_request_id";
}
if ($read_only) {
data_set($volume, 'source', $source.':'.$target.':ro');
} else {
data_set($volume, 'source', $source.':'.$target);
}
if (! str($source)->startsWith('/')) {
if ($topLevelVolumes->has($source)) {
$v = $topLevelVolumes->get($source);
if (data_get($v, 'driver_opts.type') === 'cifs') {
// Do nothing
} else {
if (is_null(data_get($v, 'name'))) {
data_set($v, 'name', $source);
data_set($topLevelVolumes, $source, $v);
}
}
2024-07-11 08:55:15 +00:00
} else {
$topLevelVolumes->put($source, [
'name' => $source,
]);
}
}
}
}
}
2024-07-11 08:55:15 +00:00
if (is_array($volume)) {
return data_get($volume, 'source');
}
dispatch(new ServerFilesFromServerJob($resource));
2024-06-10 20:43:34 +00:00
2024-07-11 08:55:15 +00:00
return $volume->value();
});
data_set($service, 'volumes', $serviceVolumes->toArray());
}
}
2024-03-19 10:48:25 +00:00
2024-05-14 11:33:29 +00:00
if ($pull_request_id !== 0 && count($serviceDependencies) > 0) {
$serviceDependencies = $serviceDependencies->map(function ($dependency) use ($pull_request_id) {
2024-06-10 20:43:34 +00:00
return $dependency."-pr-$pull_request_id";
2024-05-14 11:33:29 +00:00
});
data_set($service, 'depends_on', $serviceDependencies->toArray());
}
2023-11-24 14:48:23 +00:00
// Decide if the service is a database
$isDatabase = isDatabaseImage(data_get_str($service, 'image'));
2023-11-24 14:48:23 +00:00
data_set($service, 'is_database', $isDatabase);
// Collect/create/update networks
if ($serviceNetworks->count() > 0) {
foreach ($serviceNetworks as $networkName => $networkDetails) {
2024-05-31 08:21:38 +00:00
if ($networkName === 'default') {
continue;
}
// ignore alias
if ($networkDetails['aliases'] ?? false) {
continue;
}
2023-11-24 14:48:23 +00:00
$networkExists = $topLevelNetworks->contains(function ($value, $key) use ($networkName) {
return $value == $networkName || $key == $networkName;
});
2024-06-10 20:43:34 +00:00
if (! $networkExists) {
2023-11-24 14:48:23 +00:00
$topLevelNetworks->put($networkDetails, null);
}
}
}
// Collect/create/update ports
$collectedPorts = collect([]);
if ($servicePorts->count() > 0) {
foreach ($servicePorts as $sport) {
if (is_string($sport) || is_numeric($sport)) {
$collectedPorts->push($sport);
}
if (is_array($sport)) {
$target = data_get($sport, 'target');
$published = data_get($sport, 'published');
$protocol = data_get($sport, 'protocol');
$collectedPorts->push("$target:$published/$protocol");
}
}
}
if ($collectedPorts->count() > 0) {
// ray($collectedPorts->implode(','));
}
$definedNetworkExists = $topLevelNetworks->contains(function ($value, $_) use ($definedNetwork) {
return $value == $definedNetwork;
});
2024-06-10 20:43:34 +00:00
if (! $definedNetworkExists) {
2023-11-24 14:48:23 +00:00
foreach ($definedNetwork as $network) {
if ($pull_request_id !== 0) {
2024-06-10 20:43:34 +00:00
$topLevelNetworks->put($network, [
'name' => $network,
2024-06-10 20:43:34 +00:00
'external' => true,
]);
} else {
2024-06-10 20:43:34 +00:00
$topLevelNetworks->put($network, [
'name' => $network,
2024-06-10 20:43:34 +00:00
'external' => true,
]);
}
2023-11-24 14:48:23 +00:00
}
}
$networks = collect();
foreach ($serviceNetworks as $key => $serviceNetwork) {
if (gettype($serviceNetwork) === 'string') {
// networks:
// - appwrite
$networks->put($serviceNetwork, null);
2024-06-10 20:43:34 +00:00
} elseif (gettype($serviceNetwork) === 'array') {
2023-11-24 14:48:23 +00:00
// networks:
// default:
// ipv4_address: 192.168.203.254
// $networks->put($serviceNetwork, null);
$networks->put($key, $serviceNetwork);
}
}
foreach ($definedNetwork as $key => $network) {
$networks->put($network, null);
}
if (data_get($resource, 'settings.connect_to_docker_network')) {
$network = $resource->destination->network;
$networks->put($network, null);
2024-06-10 20:43:34 +00:00
$topLevelNetworks->put($network, [
'name' => $network,
2024-06-10 20:43:34 +00:00
'external' => true,
]);
}
2023-11-24 14:48:23 +00:00
data_set($service, 'networks', $networks->toArray());
// Get variables from the service
foreach ($serviceVariables as $variableName => $variable) {
if (is_numeric($variableName)) {
$variable = str($variable);
2023-11-24 14:48:23 +00:00
if ($variable->contains('=')) {
// - SESSION_SECRET=123
// - SESSION_SECRET=
$key = $variable->before('=');
$value = $variable->after('=');
} else {
// - SESSION_SECRET
$key = $variable;
$value = null;
}
} else {
// SESSION_SECRET: 123
// SESSION_SECRET:
$key = str($variableName);
$value = str($variable);
2023-11-24 14:48:23 +00:00
}
if ($key->startsWith('SERVICE_FQDN')) {
if ($isNew) {
$name = $key->after('SERVICE_FQDN_')->beforeLast('_')->lower();
$fqdn = generateFqdn($server, "{$name->value()}-{$resource->uuid}");
if (substr_count($key->value(), '_') === 3) {
// SERVICE_FQDN_UMAMI_1000
$port = $key->afterLast('_');
} else {
// SERVICE_FQDN_UMAMI
$port = null;
}
if ($port) {
$fqdn = "$fqdn:$port";
}
if (substr_count($key->value(), '_') >= 2) {
if ($value) {
$path = $value->value();
} else {
$path = null;
2023-11-24 14:48:23 +00:00
}
if ($generatedServiceFQDNS->count() > 0) {
$alreadyGenerated = $generatedServiceFQDNS->has($key->value());
if ($alreadyGenerated) {
$fqdn = $generatedServiceFQDNS->get($key->value());
} else {
$generatedServiceFQDNS->put($key->value(), $fqdn);
}
} else {
$generatedServiceFQDNS->put($key->value(), $fqdn);
}
$fqdn = "$fqdn$path";
}
}
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
continue;
}
if ($value?->startsWith('$')) {
$foundEnv = EnvironmentVariable::where([
'key' => $key,
2023-12-20 15:15:13 +00:00
'application_id' => $resource->id,
'is_preview' => false,
2023-11-24 14:48:23 +00:00
])->first();
$value = str(replaceVariables($value));
$key = $value;
2023-11-24 14:48:23 +00:00
if ($value->startsWith('SERVICE_')) {
$foundEnv = EnvironmentVariable::where([
'key' => $key,
'application_id' => $resource->id,
])->first();
2023-11-28 11:05:04 +00:00
['command' => $command, 'forService' => $forService, 'generatedValue' => $generatedValue, 'port' => $port] = parseEnvVariable($value);
2024-06-10 20:43:34 +00:00
if (! is_null($command)) {
if ($command?->value() === 'FQDN' || $command?->value() === 'URL') {
if (Str::lower($forService) === $serviceName) {
$fqdn = generateFqdn($server, $containerName);
} else {
2024-06-10 20:43:34 +00:00
$fqdn = generateFqdn($server, Str::lower($forService).'-'.$resource->uuid);
}
if ($port) {
$fqdn = "$fqdn:$port";
}
if ($foundEnv) {
$fqdn = data_get($foundEnv, 'value');
} else {
if ($command?->value() === 'URL') {
$fqdn = str($fqdn)->after('://')->value();
}
EnvironmentVariable::create([
'key' => $key,
'value' => $fqdn,
'is_build_time' => false,
'application_id' => $resource->id,
'is_preview' => false,
]);
}
2023-11-24 14:48:23 +00:00
} else {
$generatedValue = generateEnvValue($command);
2024-06-10 20:43:34 +00:00
if (! $foundEnv) {
EnvironmentVariable::create([
'key' => $key,
'value' => $generatedValue,
'is_build_time' => false,
'application_id' => $resource->id,
'is_preview' => false,
]);
2023-11-24 14:48:23 +00:00
}
}
}
} else {
if ($value->contains(':-')) {
$key = $value->before(':');
$defaultValue = $value->after(':-');
2024-06-10 20:43:34 +00:00
} elseif ($value->contains('-')) {
2023-11-24 14:48:23 +00:00
$key = $value->before('-');
$defaultValue = $value->after('-');
2024-06-10 20:43:34 +00:00
} elseif ($value->contains(':?')) {
2023-11-24 14:48:23 +00:00
$key = $value->before(':');
$defaultValue = $value->after(':?');
2024-06-10 20:43:34 +00:00
} elseif ($value->contains('?')) {
2023-11-24 14:48:23 +00:00
$key = $value->before('?');
$defaultValue = $value->after('?');
} else {
$key = $value;
$defaultValue = null;
}
2024-01-02 10:46:02 +00:00
$foundEnv = EnvironmentVariable::where([
'key' => $key,
'application_id' => $resource->id,
'is_preview' => false,
])->first();
2023-11-24 14:48:23 +00:00
if ($foundEnv) {
$defaultValue = data_get($foundEnv, 'value');
}
$isBuildTime = data_get($foundEnv, 'is_build_time', false);
2023-12-20 15:15:13 +00:00
if ($foundEnv) {
$foundEnv->update([
'key' => $key,
'application_id' => $resource->id,
'is_build_time' => $isBuildTime,
'value' => $defaultValue,
]);
} else {
EnvironmentVariable::create([
'key' => $key,
'value' => $defaultValue,
'is_build_time' => $isBuildTime,
'application_id' => $resource->id,
'is_preview' => false,
]);
}
2023-11-24 14:48:23 +00:00
}
}
}
// Add labels to the service
if ($resource->serviceType()) {
$fqdns = generateServiceSpecificFqdns($resource);
2023-11-24 14:48:23 +00:00
} else {
$domains = collect(json_decode($resource->docker_compose_domains)) ?? [];
if ($domains) {
$fqdns = data_get($domains, "$serviceName.domain");
if ($fqdns) {
$fqdns = str($fqdns)->explode(',');
if ($pull_request_id !== 0) {
$preview = $resource->previews()->find($preview_id);
$docker_compose_domains = collect(json_decode(data_get($preview, 'docker_compose_domains')));
if ($docker_compose_domains->count() > 0) {
$found_fqdn = data_get($docker_compose_domains, "$serviceName.domain");
if ($found_fqdn) {
$fqdns = collect($found_fqdn);
} else {
$fqdns = collect([]);
}
} else {
$fqdns = $fqdns->map(function ($fqdn) use ($pull_request_id, $resource) {
$preview = ApplicationPreview::findPreviewByApplicationAndPullId($resource->id, $pull_request_id);
$url = Url::fromString($fqdn);
$template = $resource->preview_url_template;
$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}}', $pull_request_id, $preview_fqdn);
$preview_fqdn = "$schema://$preview_fqdn";
$preview->fqdn = $preview_fqdn;
$preview->save();
2024-06-10 20:43:34 +00:00
return $preview_fqdn;
});
}
}
2024-03-11 14:08:05 +00:00
$serviceLabels = $serviceLabels->merge(fqdnLabelsForTraefik(
uuid: $resource->uuid,
2024-03-11 14:08:05 +00:00
domains: $fqdns,
serviceLabels: $serviceLabels,
2024-05-22 19:10:37 +00:00
generate_unique_uuid: $resource->build_pack === 'dockercompose',
image: data_get($service, 'image'),
is_force_https_enabled: $resource->isForceHttpsEnabled(),
is_gzip_enabled: $resource->isGzipEnabled(),
is_stripprefix_enabled: $resource->isStripprefixEnabled(),
2024-03-11 14:08:05 +00:00
));
$serviceLabels = $serviceLabels->merge(fqdnLabelsForCaddy(
network: $resource->destination->network,
uuid: $resource->uuid,
2024-03-11 14:08:05 +00:00
domains: $fqdns,
2024-05-22 19:10:37 +00:00
serviceLabels: $serviceLabels,
image: data_get($service, 'image'),
is_force_https_enabled: $resource->isForceHttpsEnabled(),
is_gzip_enabled: $resource->isGzipEnabled(),
is_stripprefix_enabled: $resource->isStripprefixEnabled(),
2024-03-11 14:08:05 +00:00
));
2023-11-24 14:48:23 +00:00
}
}
}
$defaultLabels = defaultLabels($resource->id, $containerName, $pull_request_id, type: 'application');
2023-11-24 14:48:23 +00:00
$serviceLabels = $serviceLabels->merge($defaultLabels);
if ($server->isLogDrainEnabled() && $resource->isLogDrainEnabled()) {
2023-11-24 14:48:23 +00:00
data_set($service, 'logging', [
'driver' => 'fluentd',
'options' => [
2024-06-10 20:43:34 +00:00
'fluentd-address' => 'tcp://127.0.0.1:24224',
'fluentd-async' => 'true',
'fluentd-sub-second-precision' => 'true',
],
2023-11-24 14:48:23 +00:00
]);
}
2024-05-15 15:52:14 +00:00
if ($serviceLabels->count() > 0) {
if ($resource->settings->is_container_label_escape_enabled) {
$serviceLabels = $serviceLabels->map(function ($value, $key) {
return escapeDollarSign($value);
});
}
}
2023-11-24 14:48:23 +00:00
data_set($service, 'labels', $serviceLabels->toArray());
data_forget($service, 'is_database');
2024-06-10 20:43:34 +00:00
if (! data_get($service, 'restart')) {
data_set($service, 'restart', RESTART_MODE);
}
2023-11-24 14:48:23 +00:00
data_set($service, 'container_name', $containerName);
data_forget($service, 'volumes.*.content');
data_forget($service, 'volumes.*.isDirectory');
2023-11-24 14:48:23 +00:00
return $service;
});
2024-03-19 10:48:25 +00:00
if ($pull_request_id !== 0) {
$services->each(function ($service, $serviceName) use ($pull_request_id, $services) {
2024-06-10 20:43:34 +00:00
$services[$serviceName."-pr-$pull_request_id"] = $service;
2024-03-19 10:48:25 +00:00
data_forget($services, $serviceName);
});
}
2023-11-24 14:48:23 +00:00
$finalServices = [
'services' => $services->toArray(),
'volumes' => $topLevelVolumes->toArray(),
'networks' => $topLevelNetworks->toArray(),
'configs' => $topLevelConfigs->toArray(),
'secrets' => $topLevelSecrets->toArray(),
2023-11-24 14:48:23 +00:00
];
if ($isSameDockerComposeFile) {
$resource->docker_compose_raw = Yaml::dump($yaml, 10, 2);
$resource->docker_compose = Yaml::dump($finalServices, 10, 2);
} else {
$resource->docker_compose_raw = Yaml::dump($yaml, 10, 2);
$resource->docker_compose = Yaml::dump($finalServices, 10, 2);
}
2023-11-24 14:48:23 +00:00
$resource->save();
2024-06-10 20:43:34 +00:00
2023-11-24 14:48:23 +00:00
return collect($finalServices);
}
}
2023-11-28 11:05:04 +00:00
function parseEnvVariable(Str|string $value)
{
$value = str($value);
$count = substr_count($value->value(), '_');
$command = null;
$forService = null;
$generatedValue = null;
$port = null;
if ($value->startsWith('SERVICE')) {
if ($count === 2) {
if ($value->startsWith('SERVICE_FQDN') || $value->startsWith('SERVICE_URL')) {
// SERVICE_FQDN_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
$forService = $value->afterLast('_');
} else {
// SERVICE_BASE64_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
}
2023-11-28 11:05:04 +00:00
}
if ($count === 3) {
if ($value->startsWith('SERVICE_FQDN') || $value->startsWith('SERVICE_URL')) {
// SERVICE_FQDN_UMAMI_1000
$command = $value->after('SERVICE_')->before('_');
$forService = $value->after('SERVICE_')->after('_')->before('_');
$port = $value->afterLast('_');
if (filter_var($port, FILTER_VALIDATE_INT) === false) {
$port = null;
}
} else {
// SERVICE_BASE64_64_UMAMI
$command = $value->after('SERVICE_')->beforeLast('_');
2023-12-28 16:53:47 +00:00
}
2023-11-28 11:05:04 +00:00
}
}
2024-06-10 20:43:34 +00:00
2023-11-28 11:05:04 +00:00
return [
'command' => $command,
'forService' => $forService,
'generatedValue' => $generatedValue,
'port' => $port,
];
}
2024-03-04 07:49:53 +00:00
function generateEnvValue(string $command, ?Service $service = null)
2023-11-28 11:05:04 +00:00
{
switch ($command) {
case 'PASSWORD':
$generatedValue = Str::password(symbols: false);
break;
case 'PASSWORD_64':
$generatedValue = Str::password(length: 64, symbols: false);
break;
2024-03-04 11:50:56 +00:00
// This is not base64, it's just a random string
2023-11-28 11:05:04 +00:00
case 'BASE64_64':
2024-03-04 11:50:56 +00:00
$generatedValue = Str::random(64);
2023-11-28 11:05:04 +00:00
break;
case 'BASE64_128':
2024-03-04 11:50:56 +00:00
$generatedValue = Str::random(128);
2023-11-28 11:05:04 +00:00
break;
case 'BASE64':
case 'BASE64_32':
2024-03-04 11:50:56 +00:00
$generatedValue = Str::random(32);
break;
// This is base64,
case 'REALBASE64_64':
$generatedValue = base64_encode(Str::random(64));
break;
case 'REALBASE64_128':
$generatedValue = base64_encode(Str::random(128));
break;
case 'REALBASE64':
case 'REALBASE64_32':
$generatedValue = base64_encode(Str::random(32));
2023-11-28 11:05:04 +00:00
break;
case 'USER':
$generatedValue = Str::random(16);
break;
case 'SUPABASEANON':
$signingKey = $service->environment_variables()->where('key', 'SERVICE_PASSWORD_JWT')->first();
if (is_null($signingKey)) {
return;
} else {
$signingKey = $signingKey->value;
}
$key = InMemory::plainText($signingKey);
2024-07-24 12:27:21 +00:00
$algorithm = new Sha256;
$tokenBuilder = (new Builder(new JoseEncoder, ChainedFormatter::default()));
$now = new DateTimeImmutable;
$now = $now->setTime($now->format('H'), $now->format('i'));
$token = $tokenBuilder
->issuedBy('supabase')
->issuedAt($now)
->expiresAt($now->modify('+100 year'))
->withClaim('role', 'anon')
->getToken($algorithm, $key);
$generatedValue = $token->toString();
break;
case 'SUPABASESERVICE':
$signingKey = $service->environment_variables()->where('key', 'SERVICE_PASSWORD_JWT')->first();
if (is_null($signingKey)) {
return;
} else {
$signingKey = $signingKey->value;
}
$key = InMemory::plainText($signingKey);
2024-07-24 12:27:21 +00:00
$algorithm = new Sha256;
$tokenBuilder = (new Builder(new JoseEncoder, ChainedFormatter::default()));
$now = new DateTimeImmutable;
$now = $now->setTime($now->format('H'), $now->format('i'));
$token = $tokenBuilder
->issuedBy('supabase')
->issuedAt($now)
->expiresAt($now->modify('+100 year'))
->withClaim('role', 'service_role')
->getToken($algorithm, $key);
$generatedValue = $token->toString();
break;
default:
$generatedValue = Str::random(16);
break;
2023-11-28 11:05:04 +00:00
}
2024-06-10 20:43:34 +00:00
2023-11-28 11:05:04 +00:00
return $generatedValue;
}
2023-12-11 19:01:54 +00:00
2023-12-11 19:13:41 +00:00
function getRealtime()
{
2023-12-11 19:01:54 +00:00
$envDefined = env('PUSHER_PORT');
2023-12-11 19:22:31 +00:00
if (empty($envDefined)) {
2023-12-11 19:13:41 +00:00
$url = Url::fromString(Request::getSchemeAndHttpHost());
$port = $url->getPort();
if ($port) {
return '6001';
} else {
return null;
}
2023-12-11 19:01:54 +00:00
} else {
2023-12-11 19:13:41 +00:00
return $envDefined;
2023-12-11 19:01:54 +00:00
}
}
function validate_dns_entry(string $fqdn, Server $server)
{
2024-06-10 20:43:34 +00:00
// https://www.cloudflare.com/ips-v4/#
$cloudflare_ips = collect(['173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18', '190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13', '172.64.0.0/13', '131.0.72.0/22']);
$url = Url::fromString($fqdn);
$host = $url->getHost();
if (str($host)->contains('sslip.io')) {
return true;
}
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
$is_dns_validation_enabled = data_get($settings, 'is_dns_validation_enabled');
2024-06-10 20:43:34 +00:00
if (! $is_dns_validation_enabled) {
return true;
}
$dns_servers = data_get($settings, 'custom_dns_servers');
$dns_servers = str($dns_servers)->explode(',');
if ($server->id === 0) {
$ip = data_get($settings, 'public_ipv4', data_get($settings, 'public_ipv6', $server->ip));
} else {
$ip = $server->ip;
}
$found_matching_ip = false;
$type = \PurplePixie\PhpDns\DNSTypes::NAME_A;
foreach ($dns_servers as $dns_server) {
try {
ray("Checking $host on $dns_server");
$query = new DNSQuery($dns_server);
$results = $query->query($host, $type);
if ($results === false || $query->hasError()) {
2024-06-10 20:43:34 +00:00
ray('Error: '.$query->getLasterror());
} else {
foreach ($results as $result) {
if ($result->getType() == $type) {
if (ip_match($result->getData(), $cloudflare_ips->toArray(), $match)) {
ray("Found match in Cloudflare IPs: $match");
$found_matching_ip = true;
break;
}
if ($result->getData() === $ip) {
2024-06-10 20:43:34 +00:00
ray($host.' has IP address '.$result->getData());
ray($result->getString());
$found_matching_ip = true;
break;
}
}
}
}
} catch (\Exception $e) {
}
}
ray("Found match: $found_matching_ip");
2024-06-10 20:43:34 +00:00
return $found_matching_ip;
}
function ip_match($ip, $cidrs, &$match = null)
{
foreach ((array) $cidrs as $cidr) {
2024-06-10 20:43:34 +00:00
[$subnet, $mask] = explode('/', $cidr);
if (((ip2long($ip) & ($mask = ~((1 << (32 - $mask)) - 1))) == (ip2long($subnet) & $mask))) {
$match = $cidr;
2024-06-10 20:43:34 +00:00
return true;
}
}
2024-06-10 20:43:34 +00:00
return false;
}
function checkIfDomainIsAlreadyUsed(Collection|array $domains, ?string $teamId = null, ?string $uuid = null)
2024-07-01 09:39:10 +00:00
{
if (is_null($teamId)) {
return response()->json(['error' => 'Team ID is required.'], 400);
}
if (is_array($domains)) {
$domains = collect($domains);
}
$domains = $domains->map(function ($domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
return str($domain);
});
$applications = Application::ownedByCurrentTeamAPI($teamId)->get(['fqdn', 'uuid']);
$serviceApplications = ServiceApplication::ownedByCurrentTeamAPI($teamId)->get(['fqdn', 'uuid']);
if ($uuid) {
$applications = $applications->filter(fn ($app) => $app->uuid !== $uuid);
$serviceApplications = $serviceApplications->filter(fn ($app) => $app->uuid !== $uuid);
}
2024-07-01 09:39:10 +00:00
$domainFound = false;
foreach ($applications as $app) {
if (is_null($app->fqdn)) {
continue;
}
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
$domainFound = true;
break;
}
}
}
if ($domainFound) {
return true;
}
foreach ($serviceApplications as $app) {
if (str($app->fqdn)->isEmpty()) {
2024-07-01 09:39:10 +00:00
continue;
}
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
$domainFound = true;
break;
}
}
}
if ($domainFound) {
return true;
}
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
2024-07-01 09:39:10 +00:00
if (data_get($settings, 'fqdn')) {
$domain = data_get($settings, 'fqdn');
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
return true;
}
}
}
function check_domain_usage(ServiceApplication|Application|null $resource = null, ?string $domain = null)
2024-01-30 08:22:34 +00:00
{
if ($resource) {
if ($resource->getMorphClass() === 'App\Models\Application' && $resource->build_pack === 'dockercompose') {
2024-06-10 20:43:34 +00:00
$domains = data_get(json_decode($resource->docker_compose_domains, true), '*.domain');
$domains = collect($domains);
} else {
$domains = collect($resource->fqdns);
}
2024-06-10 20:43:34 +00:00
} elseif ($domain) {
$domains = collect($domain);
} else {
2024-06-10 20:43:34 +00:00
throw new \RuntimeException('No resource or FQDN provided.');
}
$domains = $domains->map(function ($domain) {
2024-02-01 09:53:05 +00:00
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
2024-06-10 20:43:34 +00:00
return str($domain);
2024-01-30 08:22:34 +00:00
});
$apps = Application::all();
foreach ($apps as $app) {
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
2024-02-01 09:53:05 +00:00
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
2024-01-30 08:22:34 +00:00
if ($domains->contains($naked_domain)) {
if (data_get($resource, 'uuid')) {
if ($resource->uuid !== $app->uuid) {
throw new \RuntimeException("Domain $naked_domain is already in use by another resource called: <br><br>{$app->name}.");
}
2024-06-10 20:43:34 +00:00
} elseif ($domain) {
throw new \RuntimeException("Domain $naked_domain is already in use by another resource called: <br><br>{$app->name}.");
2024-01-30 08:22:34 +00:00
}
}
}
}
$apps = ServiceApplication::all();
foreach ($apps as $app) {
$list_of_domains = collect(explode(',', $app->fqdn))->filter(fn ($fqdn) => $fqdn !== '');
foreach ($list_of_domains as $domain) {
2024-02-01 09:53:05 +00:00
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
2024-01-30 08:22:34 +00:00
if ($domains->contains($naked_domain)) {
if (data_get($resource, 'uuid')) {
if ($resource->uuid !== $app->uuid) {
throw new \RuntimeException("Domain $naked_domain is already in use by another resource called: <br><br>{$app->name}.");
}
2024-06-10 20:43:34 +00:00
} elseif ($domain) {
throw new \RuntimeException("Domain $naked_domain is already in use by another resource called: <br><br>{$app->name}.");
2024-01-30 08:22:34 +00:00
}
}
}
}
if ($resource) {
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
if (data_get($settings, 'fqdn')) {
$domain = data_get($settings, 'fqdn');
if (str($domain)->endsWith('/')) {
$domain = str($domain)->beforeLast('/');
}
$naked_domain = str($domain)->value();
if ($domains->contains($naked_domain)) {
throw new \RuntimeException("Domain $naked_domain is already in use by this Coolify instance.");
}
}
}
2024-01-30 08:22:34 +00:00
}
2024-04-16 18:57:54 +00:00
function parseCommandsByLineForSudo(Collection $commands, Server $server): array
{
2024-04-16 18:57:54 +00:00
$commands = $commands->map(function ($line) {
2024-06-10 20:43:34 +00:00
if (! str($line)->startsWith('cd') && ! str($line)->startsWith('command') && ! str($line)->startsWith('echo') && ! str($line)->startsWith('true')) {
2024-04-16 18:57:54 +00:00
return "sudo $line";
}
2024-06-10 20:43:34 +00:00
2024-04-16 18:57:54 +00:00
return $line;
});
$commands = $commands->map(function ($line) use ($server) {
if (Str::startsWith($line, 'sudo mkdir -p')) {
2024-06-10 20:43:34 +00:00
return "$line && sudo chown -R $server->user:$server->user ".Str::after($line, 'sudo mkdir -p').' && sudo chmod -R o-rwx '.Str::after($line, 'sudo mkdir -p');
2024-04-16 18:57:54 +00:00
}
2024-06-10 20:43:34 +00:00
2024-04-16 18:57:54 +00:00
return $line;
});
$commands = $commands->map(function ($line) {
$line = str($line);
if (str($line)->contains('$(')) {
$line = $line->replace('$(', '$(sudo ');
2024-04-16 18:57:54 +00:00
}
if (str($line)->contains('||')) {
$line = $line->replace('||', '|| sudo');
2024-04-16 18:57:54 +00:00
}
if (str($line)->contains('&&')) {
$line = $line->replace('&&', '&& sudo');
2024-04-16 18:57:54 +00:00
}
if (str($line)->contains(' | ')) {
$line = $line->replace(' | ', ' | sudo ');
}
2024-06-10 20:43:34 +00:00
return $line->value();
2024-04-16 18:57:54 +00:00
});
return $commands->toArray();
}
function parseLineForSudo(string $command, Server $server): string
{
2024-06-10 20:43:34 +00:00
if (! str($command)->startSwith('cd') && ! str($command)->startSwith('command')) {
$command = "sudo $command";
}
if (Str::startsWith($command, 'sudo mkdir -p')) {
2024-06-10 20:43:34 +00:00
$command = "$command && sudo chown -R $server->user:$server->user ".Str::after($command, 'sudo mkdir -p').' && sudo chmod -R o-rwx '.Str::after($command, 'sudo mkdir -p');
}
if (str($command)->contains('$(') || str($command)->contains('`')) {
$command = str($command)->replace('$(', '$(sudo ')->replace('`', '`sudo ')->value();
}
if (str($command)->contains('||')) {
$command = str($command)->replace('||', '|| sudo ')->value();
}
if (str($command)->contains('&&')) {
$command = str($command)->replace('&&', '&& sudo ')->value();
}
return $command;
}
2024-04-25 11:52:52 +00:00
function get_public_ips()
{
try {
echo "Refreshing public ips!\n";
2024-07-12 13:45:36 +00:00
$settings = \App\Models\InstanceSettings::get();
2024-04-25 11:52:52 +00:00
[$first, $second] = Process::concurrently(function (Pool $pool) {
$pool->path(__DIR__)->command('curl -4s https://ifconfig.io');
$pool->path(__DIR__)->command('curl -6s https://ifconfig.io');
});
$ipv4 = $first->output();
if ($ipv4) {
$ipv4 = trim($ipv4);
$validate_ipv4 = filter_var($ipv4, FILTER_VALIDATE_IP);
if ($validate_ipv4 == false) {
echo "Invalid ipv4: $ipv4\n";
2024-06-10 20:43:34 +00:00
2024-04-25 11:52:52 +00:00
return;
}
$settings->update(['public_ipv4' => $ipv4]);
}
$ipv6 = $second->output();
if ($ipv6) {
$ipv6 = trim($ipv6);
$validate_ipv6 = filter_var($ipv6, FILTER_VALIDATE_IP);
if ($validate_ipv6 == false) {
echo "Invalid ipv6: $ipv6\n";
2024-06-10 20:43:34 +00:00
2024-04-25 11:52:52 +00:00
return;
}
$settings->update(['public_ipv6' => $ipv6]);
}
} catch (\Throwable $e) {
echo "Error: {$e->getMessage()}\n";
}
}
2024-06-11 10:38:24 +00:00
function isAnyDeploymentInprogress()
{
// Only use it in the deployment script
$count = ApplicationDeploymentQueue::whereIn('status', [ApplicationDeploymentStatus::IN_PROGRESS, ApplicationDeploymentStatus::QUEUED])->count();
if ($count > 0) {
echo "There are $count deployments in progress. Exiting...\n";
exit(1);
}
echo "No deployments in progress.\n";
exit(0);
}
2024-06-18 14:42:42 +00:00
2024-06-18 14:43:18 +00:00
function generateSentinelToken()
{
2024-06-18 14:42:42 +00:00
$token = Str::random(64);
2024-06-18 14:43:18 +00:00
2024-06-18 14:42:42 +00:00
return $token;
}
2024-06-25 19:22:23 +00:00
function isBase64Encoded($strValue)
{
return base64_encode(base64_decode($strValue, true)) === $strValue;
}
2024-06-26 11:32:36 +00:00
function customApiValidator(Collection|array $item, array $rules)
{
if (is_array($item)) {
$item = collect($item);
}
return Validator::make($item->toArray(), $rules, [
'required' => 'This field is required.',
]);
}