repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/CustomEmailNotification.php | app/Notifications/CustomEmailNotification.php | <?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
class CustomEmailNotification extends Notification implements ShouldQueue
{
use Queueable;
public $backoff = [10, 20, 30, 40, 50];
public $tries = 5;
public $maxExceptions = 5;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Test.php | app/Notifications/Test.php | <?php
namespace App\Notifications;
use App\Notifications\Channels\DiscordChannel;
use App\Notifications\Channels\EmailChannel;
use App\Notifications\Channels\PushoverChannel;
use App\Notifications\Channels\SlackChannel;
use App\Notifications\Channels\TelegramChannel;
use App\Notifications\Channels\WebhookChannel;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Queue\Middleware\RateLimited;
class Test extends Notification implements ShouldQueue
{
use Queueable;
public $tries = 5;
public bool $isTestNotification = true;
public function __construct(public ?string $emails = null, public ?string $channel = null, public ?bool $ping = false)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
if ($this->channel) {
$channels = match ($this->channel) {
'email' => [EmailChannel::class],
'discord' => [DiscordChannel::class],
'telegram' => [TelegramChannel::class],
'slack' => [SlackChannel::class],
'pushover' => [PushoverChannel::class],
'webhook' => [WebhookChannel::class],
default => [],
};
} else {
$channels = $notifiable->getEnabledChannels('test');
}
return $channels;
}
public function middleware(object $notifiable, string $channel)
{
return match ($channel) {
EmailChannel::class => [new RateLimited('email')],
default => [],
};
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject('Coolify: Test Email');
$mail->view('emails.test');
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':white_check_mark: Test Success',
description: 'This is a test Discord notification from Coolify. :cross_mark: :warning: :information_source:',
color: DiscordMessage::successColor(),
isCritical: $this->ping,
);
$message->addField(name: 'Dashboard', value: '[Link]('.base_url().')', inline: true);
return $message;
}
public function toTelegram(): array
{
return [
'message' => 'Coolify: This is a test Telegram notification from Coolify.',
'buttons' => [
[
'text' => 'Go to your dashboard',
'url' => isDev() ? 'https://staging-but-dev.coolify.io' : base_url(),
],
],
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Test Pushover Notification',
message: 'This is a test Pushover notification from Coolify.',
buttons: [
[
'text' => 'Go to your dashboard',
'url' => base_url(),
],
],
);
}
public function toSlack(): SlackMessage
{
return new SlackMessage(
title: 'Test Slack Notification',
description: 'This is a test Slack notification from Coolify.'
);
}
public function toWebhook(): array
{
return [
'success' => true,
'message' => 'This is a test webhook notification from Coolify.',
'event' => 'test',
'url' => base_url(),
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Notification.php | app/Notifications/Notification.php | <?php
namespace Illuminate\Notifications;
use App\Notifications\Channels\SendsEmail;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
interface Notification
{
public function toMail(SendsEmail $notifiable): MailMessage;
public function toPushover(): PushoverMessage;
public function toDiscord(): DiscordMessage;
public function toSlack(): SlackMessage;
public function toTelegram();
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/SslExpirationNotification.php | app/Notifications/SslExpirationNotification.php | <?php
namespace App\Notifications;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Collection;
use Spatie\Url\Url;
class SslExpirationNotification extends CustomEmailNotification
{
protected Collection $resources;
protected array $urls = [];
public function __construct(array|Collection $resources)
{
$this->onQueue('high');
$this->resources = collect($resources);
// Collect URLs for each resource
$this->resources->each(function ($resource) {
if (data_get($resource, 'environment.project.uuid')) {
$routeName = match ($resource->type()) {
'application' => 'project.application.configuration',
'database' => 'project.database.configuration',
'service' => 'project.service.configuration',
default => null
};
if ($routeName) {
$route = route($routeName, [
'project_uuid' => data_get($resource, 'environment.project.uuid'),
'environment_uuid' => data_get($resource, 'environment.uuid'),
$resource->type().'_uuid' => data_get($resource, 'uuid'),
]);
$settings = instanceSettings();
if (data_get($settings, 'fqdn')) {
$url = Url::fromString($route);
$url = $url->withPort(null);
$fqdn = data_get($settings, 'fqdn');
$fqdn = str_replace(['http://', 'https://'], '', $fqdn);
$url = $url->withHost($fqdn);
$this->urls[$resource->name] = $url->__toString();
} else {
$this->urls[$resource->name] = $route;
}
}
}
});
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('ssl_certificate_renewal');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject('Coolify: [Action Required] SSL Certificates Renewed - Manual Redeployment Needed');
$mail->view('emails.ssl-certificate-renewed', [
'resources' => $this->resources,
'urls' => $this->urls,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$resourceNames = $this->resources->pluck('name')->join(', ');
$message = new DiscordMessage(
title: '🔒 SSL Certificates Renewed',
description: "SSL certificates have been renewed for: {$resourceNames}.\n\n**Action Required:** These resources need to be redeployed manually.",
color: DiscordMessage::warningColor(),
);
foreach ($this->urls as $name => $url) {
$message->addField($name, "[View Resource]({$url})");
}
return $message;
}
public function toTelegram(): array
{
$resourceNames = $this->resources->pluck('name')->join(', ');
$message = "Coolify: SSL certificates have been renewed for: {$resourceNames}.\n\nAction Required: These resources need to be redeployed manually for the new SSL certificates to take effect.";
$buttons = [];
foreach ($this->urls as $name => $url) {
$buttons[] = [
'text' => "View {$name}",
'url' => $url,
];
}
return [
'message' => $message,
'buttons' => $buttons,
];
}
public function toPushover(): PushoverMessage
{
$resourceNames = $this->resources->pluck('name')->join(', ');
$message = "SSL certificates have been renewed for: {$resourceNames}<br/><br/>";
$message .= '<b>Action Required:</b> These resources need to be redeployed manually for the new SSL certificates to take effect.';
$buttons = [];
foreach ($this->urls as $name => $url) {
$buttons[] = [
'text' => "View {$name}",
'url' => $url,
];
}
return new PushoverMessage(
title: 'SSL Certificates Renewed',
level: 'warning',
message: $message,
buttons: $buttons,
);
}
public function toSlack(): SlackMessage
{
$resourceNames = $this->resources->pluck('name')->join(', ');
$description = "SSL certificates have been renewed for: {$resourceNames}\n\n";
$description .= '**Action Required:** These resources need to be redeployed manually for the new SSL certificates to take effect.';
if (! empty($this->urls)) {
$description .= "\n\n**Resource URLs:**\n";
foreach ($this->urls as $name => $url) {
$description .= "• {$name}: {$url}\n";
}
}
return new SlackMessage(
title: '🔒 SSL Certificates Renewed',
description: $description,
color: SlackMessage::warningColor()
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Application/StatusChanged.php | app/Notifications/Application/StatusChanged.php | <?php
namespace App\Notifications\Application;
use App\Models\Application;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class StatusChanged extends CustomEmailNotification
{
public string $resource_name;
public string $project_uuid;
public string $environment_uuid;
public string $environment_name;
public ?string $resource_url = null;
public ?string $fqdn;
public function __construct(public Application $resource)
{
$this->onQueue('high');
$this->resource_name = data_get($resource, 'name');
$this->project_uuid = data_get($resource, 'environment.project.uuid');
$this->environment_uuid = data_get($resource, 'environment.uuid');
$this->environment_name = data_get($resource, 'environment.name');
$this->fqdn = data_get($resource, 'fqdn', null);
if (str($this->fqdn)->explode(',')->count() > 1) {
$this->fqdn = str($this->fqdn)->explode(',')->first();
}
$this->resource_url = base_url()."/project/{$this->project_uuid}/environment/{$this->environment_uuid}/application/{$this->resource->uuid}";
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('status_change');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$fqdn = $this->fqdn;
$mail->subject("Coolify: {$this->resource_name} has been stopped");
$mail->view('emails.application-status-changes', [
'name' => $this->resource_name,
'fqdn' => $fqdn,
'resource_url' => $this->resource_url,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
return new DiscordMessage(
title: ':cross_mark: Application stopped',
description: '[Open Application in Coolify]('.$this->resource_url.')',
color: DiscordMessage::errorColor(),
isCritical: true,
);
}
public function toTelegram(): array
{
$message = 'Coolify: '.$this->resource_name.' has been stopped.';
return [
'message' => $message,
'buttons' => [
[
'text' => 'Open Application in Coolify',
'url' => $this->resource_url,
],
],
];
}
public function toPushover(): PushoverMessage
{
$message = $this->resource_name.' has been stopped.';
return new PushoverMessage(
title: 'Application stopped',
level: 'error',
message: $message,
buttons: [
[
'text' => 'Open Application in Coolify',
'url' => $this->resource_url,
],
],
);
}
public function toSlack(): SlackMessage
{
$title = 'Application stopped';
$description = "{$this->resource_name} has been stopped";
$description .= "\n\n*Project:* ".data_get($this->resource, 'environment.project.name');
$description .= "\n*Environment:* {$this->environment_name}";
$description .= "\n*Application URL:* {$this->resource_url}";
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
return [
'success' => false,
'message' => 'Application stopped',
'event' => 'status_changed',
'application_name' => $this->resource_name,
'application_uuid' => $this->resource->uuid,
'url' => $this->resource_url,
'project' => data_get($this->resource, 'environment.project.name'),
'environment' => $this->environment_name,
'fqdn' => $this->fqdn,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Application/DeploymentSuccess.php | app/Notifications/Application/DeploymentSuccess.php | <?php
namespace App\Notifications\Application;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class DeploymentSuccess extends CustomEmailNotification
{
public Application $application;
public ?ApplicationPreview $preview = null;
public string $deployment_uuid;
public string $application_name;
public string $project_uuid;
public string $environment_uuid;
public string $environment_name;
public ?string $deployment_url = null;
public ?string $fqdn;
public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $preview = null)
{
$this->onQueue('high');
$this->application = $application;
$this->deployment_uuid = $deployment_uuid;
$this->preview = $preview;
$this->application_name = data_get($application, 'name');
$this->project_uuid = data_get($application, 'environment.project.uuid');
$this->environment_uuid = data_get($application, 'environment.uuid');
$this->environment_name = data_get($application, 'environment.name');
$this->fqdn = data_get($application, 'fqdn');
if (str($this->fqdn)->explode(',')->count() > 1) {
$this->fqdn = str($this->fqdn)->explode(',')->first();
}
$this->deployment_url = base_url()."/project/{$this->project_uuid}/environment/{$this->environment_uuid}/application/{$this->application->uuid}/deployment/{$this->deployment_uuid}";
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('deployment_success');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$pull_request_id = data_get($this->preview, 'pull_request_id', 0);
$fqdn = $this->fqdn;
if ($pull_request_id === 0) {
$mail->subject("Coolify: New version is deployed of {$this->application_name}");
} else {
$fqdn = $this->preview->fqdn;
$mail->subject("Coolify: Pull request #{$pull_request_id} of {$this->application_name} deployed successfully");
}
$mail->view('emails.application-deployment-success', [
'name' => $this->application_name,
'fqdn' => $fqdn,
'deployment_url' => $this->deployment_url,
'pull_request_id' => $pull_request_id,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
if ($this->preview) {
$message = new DiscordMessage(
title: ':white_check_mark: Preview deployment successful',
description: 'Pull request: '.$this->preview->pull_request_id,
color: DiscordMessage::successColor(),
);
if ($this->preview->fqdn) {
$message->addField('Application', '[Link]('.$this->preview->fqdn.')');
}
$message->addField('Project', data_get($this->application, 'environment.project.name'), true);
$message->addField('Environment', $this->environment_name, true);
$message->addField('Name', $this->application_name, true);
$message->addField('Deployment logs', '[Link]('.$this->deployment_url.')');
} else {
if ($this->fqdn) {
$description = '[Open application]('.$this->fqdn.')';
} else {
$description = '';
}
$message = new DiscordMessage(
title: ':white_check_mark: New version successfully deployed',
description: $description,
color: DiscordMessage::successColor(),
);
$message->addField('Project', data_get($this->application, 'environment.project.name'), true);
$message->addField('Environment', $this->environment_name, true);
$message->addField('Name', $this->application_name, true);
$message->addField('Deployment logs', '[Link]('.$this->deployment_url.')');
}
return $message;
}
public function toTelegram(): array
{
if ($this->preview) {
$message = 'Coolify: New PR'.$this->preview->pull_request_id.' version successfully deployed of '.$this->application_name.'';
if ($this->preview->fqdn) {
$buttons[] = [
'text' => 'Open Application',
'url' => $this->preview->fqdn,
];
}
} else {
$message = '✅ New version successfully deployed of '.$this->application_name.'';
if ($this->fqdn) {
$buttons[] = [
'text' => 'Open Application',
'url' => $this->fqdn,
];
}
}
$buttons[] = [
'text' => 'Deployment logs',
'url' => $this->deployment_url,
];
return [
'message' => $message,
'buttons' => [
...$buttons,
],
];
}
public function toPushover(): PushoverMessage
{
if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} successfully deployed";
$message = 'New PR'.$this->preview->pull_request_id.' version successfully deployed of '.$this->application_name.'';
if ($this->preview->fqdn) {
$buttons[] = [
'text' => 'Open Application',
'url' => $this->preview->fqdn,
];
}
} else {
$title = 'New version successfully deployed';
$message = 'New version successfully deployed of '.$this->application_name.'';
if ($this->fqdn) {
$buttons[] = [
'text' => 'Open Application',
'url' => $this->fqdn,
];
}
}
$buttons[] = [
'text' => 'Deployment logs',
'url' => $this->deployment_url,
];
return new PushoverMessage(
title: $title,
level: 'success',
message: $message,
buttons: [
...$buttons,
],
);
}
public function toSlack(): SlackMessage
{
if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} successfully deployed";
$description = "New version successfully deployed for {$this->application_name}";
if ($this->preview->fqdn) {
$description .= "\nPreview URL: {$this->preview->fqdn}";
}
} else {
$title = 'New version successfully deployed';
$description = "New version successfully deployed for {$this->application_name}";
if ($this->fqdn) {
$description .= "\nApplication URL: {$this->fqdn}";
}
}
$description .= "\n\n*Project:* ".data_get($this->application, 'environment.project.name');
$description .= "\n*Environment:* {$this->environment_name}";
$description .= "\n*<{$this->deployment_url}|Deployment Logs>*";
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::successColor()
);
}
public function toWebhook(): array
{
$data = [
'success' => true,
'message' => 'New version successfully deployed',
'event' => 'deployment_success',
'application_name' => $this->application_name,
'application_uuid' => $this->application->uuid,
'deployment_uuid' => $this->deployment_uuid,
'deployment_url' => $this->deployment_url,
'project' => data_get($this->application, 'environment.project.name'),
'environment' => $this->environment_name,
];
if ($this->preview) {
$data['pull_request_id'] = $this->preview->pull_request_id;
$data['preview_fqdn'] = $this->preview->fqdn;
}
if ($this->fqdn) {
$data['fqdn'] = $this->fqdn;
}
return $data;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Application/DeploymentFailed.php | app/Notifications/Application/DeploymentFailed.php | <?php
namespace App\Notifications\Application;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class DeploymentFailed extends CustomEmailNotification
{
public Application $application;
public ?ApplicationPreview $preview = null;
public string $deployment_uuid;
public string $application_name;
public string $project_uuid;
public string $environment_uuid;
public string $environment_name;
public ?string $deployment_url = null;
public ?string $fqdn = null;
public function __construct(Application $application, string $deployment_uuid, ?ApplicationPreview $preview = null)
{
$this->onQueue('high');
$this->application = $application;
$this->deployment_uuid = $deployment_uuid;
$this->preview = $preview;
$this->application_name = data_get($application, 'name');
$this->project_uuid = data_get($application, 'environment.project.uuid');
$this->environment_uuid = data_get($application, 'environment.uuid');
$this->environment_name = data_get($application, 'environment.name');
$this->fqdn = data_get($application, 'fqdn');
if (str($this->fqdn)->explode(',')->count() > 1) {
$this->fqdn = str($this->fqdn)->explode(',')->first();
}
$this->deployment_url = base_url()."/project/{$this->project_uuid}/environment/{$this->environment_uuid}/application/{$this->application->uuid}/deployment/{$this->deployment_uuid}";
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('deployment_failure');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$pull_request_id = data_get($this->preview, 'pull_request_id', 0);
$fqdn = $this->fqdn;
if ($pull_request_id === 0) {
$mail->subject('Coolify: Deployment failed of '.$this->application_name.'.');
} else {
$fqdn = $this->preview->fqdn;
$mail->subject('Coolify: Deployment failed of pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.'.');
}
$mail->view('emails.application-deployment-failed', [
'name' => $this->application_name,
'fqdn' => $fqdn,
'deployment_url' => $this->deployment_url,
'pull_request_id' => data_get($this->preview, 'pull_request_id', 0),
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
if ($this->preview) {
$message = new DiscordMessage(
title: ':cross_mark: Deployment failed',
description: 'Pull request: '.$this->preview->pull_request_id,
color: DiscordMessage::errorColor(),
isCritical: true,
);
$message->addField('Project', data_get($this->application, 'environment.project.name'), true);
$message->addField('Environment', $this->environment_name, true);
$message->addField('Name', $this->application_name, true);
$message->addField('Deployment Logs', '[Link]('.$this->deployment_url.')');
if ($this->fqdn) {
$message->addField('Domain', $this->fqdn, true);
}
} else {
if ($this->fqdn) {
$description = '[Open application]('.$this->fqdn.')';
} else {
$description = '';
}
$message = new DiscordMessage(
title: ':cross_mark: Deployment failed',
description: $description,
color: DiscordMessage::errorColor(),
isCritical: true,
);
$message->addField('Project', data_get($this->application, 'environment.project.name'), true);
$message->addField('Environment', $this->environment_name, true);
$message->addField('Name', $this->application_name, true);
$message->addField('Deployment Logs', '[Link]('.$this->deployment_url.')');
}
return $message;
}
public function toTelegram(): array
{
if ($this->preview) {
$message = 'Coolify: Pull request #'.$this->preview->pull_request_id.' of '.$this->application_name.' ('.$this->preview->fqdn.') deployment failed: ';
} else {
$message = 'Coolify: Deployment failed of '.$this->application_name.' ('.$this->fqdn.'): ';
}
$buttons[] = [
'text' => 'Deployment logs',
'url' => $this->deployment_url,
];
return [
'message' => $message,
'buttons' => [
...$buttons,
],
];
}
public function toPushover(): PushoverMessage
{
if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} deployment failed";
$message = "Pull request deployment failed for {$this->application_name}";
} else {
$title = 'Deployment failed';
$message = "Deployment failed for {$this->application_name}";
}
$buttons[] = [
'text' => 'Deployment logs',
'url' => $this->deployment_url,
];
return new PushoverMessage(
title: $title,
level: 'error',
message: $message,
buttons: [
...$buttons,
],
);
}
public function toSlack(): SlackMessage
{
if ($this->preview) {
$title = "Pull request #{$this->preview->pull_request_id} deployment failed";
$description = "Pull request deployment failed for {$this->application_name}";
if ($this->preview->fqdn) {
$description .= "\nPreview URL: {$this->preview->fqdn}";
}
} else {
$title = 'Deployment failed';
$description = "Deployment failed for {$this->application_name}";
if ($this->fqdn) {
$description .= "\nApplication URL: {$this->fqdn}";
}
}
$description .= "\n\n*Project:* ".data_get($this->application, 'environment.project.name');
$description .= "\n*Environment:* {$this->environment_name}";
$description .= "\n*<{$this->deployment_url}|Deployment Logs>*";
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
$data = [
'success' => false,
'message' => 'Deployment failed',
'event' => 'deployment_failed',
'application_name' => $this->application_name,
'application_uuid' => $this->application->uuid,
'deployment_uuid' => $this->deployment_uuid,
'deployment_url' => $this->deployment_url,
'project' => data_get($this->application, 'environment.project.name'),
'environment' => $this->environment_name,
];
if ($this->preview) {
$data['pull_request_id'] = $this->preview->pull_request_id;
$data['preview_fqdn'] = $this->preview->fqdn;
}
if ($this->fqdn) {
$data['fqdn'] = $this->fqdn;
}
return $data;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/ScheduledTask/TaskSuccess.php | app/Notifications/ScheduledTask/TaskSuccess.php | <?php
namespace App\Notifications\ScheduledTask;
use App\Models\ScheduledTask;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class TaskSuccess extends CustomEmailNotification
{
public ?string $url = null;
public function __construct(public ScheduledTask $task, public string $output)
{
$this->onQueue('high');
if ($task->application) {
$this->url = $task->application->taskLink($task->uuid);
} elseif ($task->service) {
$this->url = $task->service->taskLink($task->uuid);
}
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('scheduled_task_success');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Scheduled task ({$this->task->name}) succeeded.");
$mail->view('emails.scheduled-task-success', [
'task' => $this->task,
'url' => $this->url,
'output' => $this->output,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':white_check_mark: Scheduled task succeeded',
description: "Scheduled task ({$this->task->name}) succeeded.",
color: DiscordMessage::successColor(),
);
if ($this->url) {
$message->addField('Scheduled task', '[Link]('.$this->url.')');
}
return $message;
}
public function toTelegram(): array
{
$message = "Coolify: Scheduled task ({$this->task->name}) succeeded.";
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
'url' => (string) $this->url,
];
}
return [
'message' => $message,
];
}
public function toPushover(): PushoverMessage
{
$message = "Coolify: Scheduled task ({$this->task->name}) succeeded.";
$buttons = [];
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
'url' => (string) $this->url,
];
}
return new PushoverMessage(
title: 'Scheduled task succeeded',
level: 'success',
message: $message,
buttons: $buttons,
);
}
public function toSlack(): SlackMessage
{
$title = 'Scheduled task succeeded';
$description = "Scheduled task ({$this->task->name}) succeeded.";
if ($this->url) {
$description .= "\n\n*Task URL:* {$this->url}";
}
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::successColor()
);
}
public function toWebhook(): array
{
$data = [
'success' => true,
'message' => 'Scheduled task succeeded',
'event' => 'task_success',
'task_name' => $this->task->name,
'task_uuid' => $this->task->uuid,
'output' => $this->output,
];
if ($this->task->application) {
$data['application_uuid'] = $this->task->application->uuid;
} elseif ($this->task->service) {
$data['service_uuid'] = $this->task->service->uuid;
}
if ($this->url) {
$data['url'] = $this->url;
}
return $data;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/ScheduledTask/TaskFailed.php | app/Notifications/ScheduledTask/TaskFailed.php | <?php
namespace App\Notifications\ScheduledTask;
use App\Models\ScheduledTask;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class TaskFailed extends CustomEmailNotification
{
public ?string $url = null;
public function __construct(public ScheduledTask $task, public string $output)
{
$this->onQueue('high');
if ($task->application) {
$this->url = $task->application->taskLink($task->uuid);
} elseif ($task->service) {
$this->url = $task->service->taskLink($task->uuid);
}
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('scheduled_task_failure');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: [ACTION REQUIRED] Scheduled task ({$this->task->name}) failed.");
$mail->view('emails.scheduled-task-failed', [
'task' => $this->task,
'url' => $this->url,
'output' => $this->output,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':cross_mark: Scheduled task failed',
description: "Scheduled task ({$this->task->name}) failed.",
color: DiscordMessage::errorColor(),
);
if ($this->url) {
$message->addField('Scheduled task', '[Link]('.$this->url.')');
}
return $message;
}
public function toTelegram(): array
{
$message = "Coolify: Scheduled task ({$this->task->name}) failed with output: {$this->output}";
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
'url' => (string) $this->url,
];
}
return [
'message' => $message,
];
}
public function toPushover(): PushoverMessage
{
$message = "Scheduled task ({$this->task->name}) failed<br/>";
if ($this->output) {
$message .= "<br/><b>Error Output:</b>{$this->output}";
}
$buttons = [];
if ($this->url) {
$buttons[] = [
'text' => 'Open task in Coolify',
'url' => (string) $this->url,
];
}
return new PushoverMessage(
title: 'Scheduled task failed',
level: 'error',
message: $message,
buttons: $buttons,
);
}
public function toSlack(): SlackMessage
{
$title = 'Scheduled task failed';
$description = "Scheduled task ({$this->task->name}) failed.";
if ($this->output) {
$description .= "\n\n*Error Output:* {$this->output}";
}
if ($this->url) {
$description .= "\n\n*Task URL:* {$this->url}";
}
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
$data = [
'success' => false,
'message' => 'Scheduled task failed',
'event' => 'task_failed',
'task_name' => $this->task->name,
'task_uuid' => $this->task->uuid,
'output' => $this->output,
];
if ($this->task->application) {
$data['application_uuid'] = $this->task->application->uuid;
} elseif ($this->task->service) {
$data['service_uuid'] = $this->task->service->uuid;
}
if ($this->url) {
$data['url'] = $this->url;
}
return $data;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Container/ContainerStopped.php | app/Notifications/Container/ContainerStopped.php | <?php
namespace App\Notifications\Container;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class ContainerStopped extends CustomEmailNotification
{
public function __construct(public string $name, public Server $server, public ?string $url = null)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('status_change');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: A resource has been stopped unexpectedly on {$this->server->name}");
$mail->view('emails.container-stopped', [
'containerName' => $this->name,
'serverName' => $this->server->name,
'url' => $this->url,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':cross_mark: Resource stopped',
description: "{$this->name} has been stopped unexpectedly on {$this->server->name}.",
color: DiscordMessage::errorColor(),
);
if ($this->url) {
$message->addField('Resource', '[Link]('.$this->url.')');
}
return $message;
}
public function toTelegram(): array
{
$message = "Coolify: A resource ($this->name) has been stopped unexpectedly on {$this->server->name}";
$payload = [
'message' => $message,
];
if ($this->url) {
$payload['buttons'] = [
[
[
'text' => 'Open Application in Coolify',
'url' => $this->url,
],
],
];
}
return $payload;
}
public function toPushover(): PushoverMessage
{
$buttons = [];
if ($this->url) {
$buttons[] = [
'text' => 'Open Application in Coolify',
'url' => $this->url,
];
}
return new PushoverMessage(
title: 'Resource stopped',
level: 'error',
message: "A resource ({$this->name}) has been stopped unexpectedly on {$this->server->name}",
buttons: $buttons,
);
}
public function toSlack(): SlackMessage
{
$title = 'Resource stopped';
$description = "A resource ({$this->name}) has been stopped unexpectedly on {$this->server->name}";
if ($this->url) {
$description .= "\n*Resource URL:* {$this->url}";
}
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
$data = [
'success' => false,
'message' => 'Resource stopped unexpectedly',
'event' => 'container_stopped',
'container_name' => $this->name,
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
];
if ($this->url) {
$data['url'] = $this->url;
}
return $data;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Container/ContainerRestarted.php | app/Notifications/Container/ContainerRestarted.php | <?php
namespace App\Notifications\Container;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class ContainerRestarted extends CustomEmailNotification
{
public function __construct(public string $name, public Server $server, public ?string $url = null)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('status_change');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: A resource ({$this->name}) has been restarted automatically on {$this->server->name}");
$mail->view('emails.container-restarted', [
'containerName' => $this->name,
'serverName' => $this->server->name,
'url' => $this->url,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':warning: Resource restarted',
description: "{$this->name} has been restarted automatically on {$this->server->name}.",
color: DiscordMessage::infoColor(),
);
if ($this->url) {
$message->addField('Resource', '[Link]('.$this->url.')');
}
return $message;
}
public function toTelegram(): array
{
$message = "Coolify: A resource ({$this->name}) has been restarted automatically on {$this->server->name}";
$payload = [
'message' => $message,
];
if ($this->url) {
$payload['buttons'] = [
[
[
'text' => 'Check Proxy in Coolify',
'url' => $this->url,
],
],
];
}
return $payload;
}
public function toPushover(): PushoverMessage
{
$buttons = [];
if ($this->url) {
$buttons[] = [
'text' => 'Check Proxy in Coolify',
'url' => $this->url,
];
}
return new PushoverMessage(
title: 'Resource restarted',
level: 'warning',
message: "A resource ({$this->name}) has been restarted automatically on {$this->server->name}",
buttons: $buttons,
);
}
public function toSlack(): SlackMessage
{
$title = 'Resource restarted';
$description = "A resource ({$this->name}) has been restarted automatically on {$this->server->name}";
if ($this->url) {
$description .= "\n*Resource URL:* {$this->url}";
}
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::warningColor()
);
}
public function toWebhook(): array
{
$data = [
'success' => true,
'message' => 'Resource restarted automatically',
'event' => 'container_restarted',
'container_name' => $this->name,
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
];
if ($this->url) {
$data['url'] = $this->url;
}
return $data;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/TelegramChannel.php | app/Notifications/Channels/TelegramChannel.php | <?php
namespace App\Notifications\Channels;
use App\Jobs\SendMessageToTelegramJob;
class TelegramChannel
{
public function send($notifiable, $notification): void
{
$data = $notification->toTelegram($notifiable);
$settings = $notifiable->telegramNotificationSettings;
$message = data_get($data, 'message');
$buttons = data_get($data, 'buttons', []);
$telegramToken = $settings->telegram_token;
$chatId = $settings->telegram_chat_id;
$threadId = match (get_class($notification)) {
\App\Notifications\Application\DeploymentSuccess::class => $settings->telegram_notifications_deployment_success_thread_id,
\App\Notifications\Application\DeploymentFailed::class => $settings->telegram_notifications_deployment_failure_thread_id,
\App\Notifications\Application\StatusChanged::class,
\App\Notifications\Container\ContainerRestarted::class,
\App\Notifications\Container\ContainerStopped::class => $settings->telegram_notifications_status_change_thread_id,
\App\Notifications\Database\BackupSuccess::class => $settings->telegram_notifications_backup_success_thread_id,
\App\Notifications\Database\BackupFailed::class => $settings->telegram_notifications_backup_failure_thread_id,
\App\Notifications\ScheduledTask\TaskSuccess::class => $settings->telegram_notifications_scheduled_task_success_thread_id,
\App\Notifications\ScheduledTask\TaskFailed::class => $settings->telegram_notifications_scheduled_task_failure_thread_id,
\App\Notifications\Server\DockerCleanupSuccess::class => $settings->telegram_notifications_docker_cleanup_success_thread_id,
\App\Notifications\Server\DockerCleanupFailed::class => $settings->telegram_notifications_docker_cleanup_failure_thread_id,
\App\Notifications\Server\HighDiskUsage::class => $settings->telegram_notifications_server_disk_usage_thread_id,
\App\Notifications\Server\Unreachable::class => $settings->telegram_notifications_server_unreachable_thread_id,
\App\Notifications\Server\Reachable::class => $settings->telegram_notifications_server_reachable_thread_id,
\App\Notifications\Server\ServerPatchCheck::class => $settings->telegram_notifications_server_patch_thread_id,
default => null,
};
if (! $telegramToken || ! $chatId || ! $message) {
return;
}
SendMessageToTelegramJob::dispatch($message, $buttons, $telegramToken, $chatId, $threadId);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/WebhookChannel.php | app/Notifications/Channels/WebhookChannel.php | <?php
namespace App\Notifications\Channels;
use App\Jobs\SendWebhookJob;
use Illuminate\Notifications\Notification;
class WebhookChannel
{
/**
* Send the given notification.
*/
public function send($notifiable, Notification $notification): void
{
$webhookSettings = $notifiable->webhookNotificationSettings;
if (! $webhookSettings || ! $webhookSettings->isEnabled() || ! $webhookSettings->webhook_url) {
if (isDev()) {
ray('Webhook notification skipped - not enabled or no URL configured');
}
return;
}
$payload = $notification->toWebhook();
if (isDev()) {
ray('Dispatching webhook notification', [
'notification' => get_class($notification),
'url' => $webhookSettings->webhook_url,
'payload' => $payload,
]);
}
SendWebhookJob::dispatch($payload, $webhookSettings->webhook_url);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/SendsPushover.php | app/Notifications/Channels/SendsPushover.php | <?php
namespace App\Notifications\Channels;
interface SendsPushover
{
public function routeNotificationForPushover();
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/SendsEmail.php | app/Notifications/Channels/SendsEmail.php | <?php
namespace App\Notifications\Channels;
interface SendsEmail
{
public function getRecipients(): array;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/TransactionalEmailChannel.php | app/Notifications/Channels/TransactionalEmailChannel.php | <?php
namespace App\Notifications\Channels;
use App\Models\User;
use Exception;
use Illuminate\Mail\Message;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Facades\Mail;
class TransactionalEmailChannel
{
public function send(User $notifiable, Notification $notification): void
{
$settings = instanceSettings();
if (! data_get($settings, 'smtp_enabled') && ! data_get($settings, 'resend_enabled')) {
return;
}
// Check if notification has a custom recipient (for email changes)
$email = property_exists($notification, 'newEmail') && $notification->newEmail
? $notification->newEmail
: $notifiable->email;
if (! $email) {
return;
}
$this->bootConfigs();
$mailMessage = $notification->toMail($notifiable);
Mail::send(
[],
[],
fn (Message $message) => $message
->to($email)
->subject($mailMessage->subject)
->html((string) $mailMessage->render())
);
}
private function bootConfigs(): void
{
$type = set_transanctional_email_settings();
if (blank($type)) {
throw new Exception('No email settings found.');
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/SendsDiscord.php | app/Notifications/Channels/SendsDiscord.php | <?php
namespace App\Notifications\Channels;
interface SendsDiscord
{
public function routeNotificationForDiscord();
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/PushoverChannel.php | app/Notifications/Channels/PushoverChannel.php | <?php
namespace App\Notifications\Channels;
use App\Jobs\SendMessageToPushoverJob;
use Illuminate\Notifications\Notification;
class PushoverChannel
{
public function send(SendsPushover $notifiable, Notification $notification): void
{
$message = $notification->toPushover();
$pushoverSettings = $notifiable->pushoverNotificationSettings;
if (! $pushoverSettings || ! $pushoverSettings->isEnabled() || ! $pushoverSettings->pushover_user_key || ! $pushoverSettings->pushover_api_token) {
return;
}
SendMessageToPushoverJob::dispatch($message, $pushoverSettings->pushover_api_token, $pushoverSettings->pushover_user_key);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/EmailChannel.php | app/Notifications/Channels/EmailChannel.php | <?php
namespace App\Notifications\Channels;
use App\Exceptions\NonReportableException;
use App\Models\Team;
use Exception;
use Illuminate\Notifications\Notification;
use Resend;
class EmailChannel
{
public function __construct() {}
public function send(SendsEmail $notifiable, Notification $notification): void
{
try {
// Get team and validate membership before proceeding
$team = data_get($notifiable, 'id');
$members = Team::find($team)->members;
$useInstanceEmailSettings = $notifiable->emailNotificationSettings->use_instance_email_settings;
$isTransactionalEmail = data_get($notification, 'isTransactionalEmail', false);
$customEmails = data_get($notification, 'emails', null);
if ($useInstanceEmailSettings || $isTransactionalEmail) {
$settings = instanceSettings();
} else {
$settings = $notifiable->emailNotificationSettings;
}
$isResendEnabled = $settings->resend_enabled;
$isSmtpEnabled = $settings->smtp_enabled;
if ($customEmails) {
$recipients = [$customEmails];
} else {
$recipients = $notifiable->getRecipients();
}
// Validate team membership for all recipients
if (count($recipients) === 0) {
throw new Exception('No email recipients found');
}
// Skip team membership validation for test notifications
$isTestNotification = data_get($notification, 'isTestNotification', false);
if (! $isTestNotification) {
foreach ($recipients as $recipient) {
// Check if the recipient is part of the team
if (! $members->contains('email', $recipient)) {
$emailSettings = $notifiable->emailNotificationSettings;
data_set($emailSettings, 'smtp_password', '********');
data_set($emailSettings, 'resend_api_key', '********');
send_internal_notification(sprintf(
"Recipient is not part of the team: %s\nTeam: %s\nNotification: %s\nNotifiable: %s\nEmail Settings:\n%s",
$recipient,
$team,
get_class($notification),
get_class($notifiable),
json_encode($emailSettings, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
));
throw new Exception('Recipient is not part of the team');
}
}
}
$mailMessage = $notification->toMail($notifiable);
if ($isResendEnabled) {
$resend = Resend::client($settings->resend_api_key);
$from = "{$settings->smtp_from_name} <{$settings->smtp_from_address}>";
$resend->emails->send([
'from' => $from,
'to' => $recipients,
'subject' => $mailMessage->subject,
'html' => (string) $mailMessage->render(),
]);
} elseif ($isSmtpEnabled) {
$encryption = match (strtolower($settings->smtp_encryption)) {
'starttls' => null,
'tls' => 'tls',
'none' => null,
default => null,
};
$transport = new \Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport(
$settings->smtp_host,
$settings->smtp_port,
$encryption
);
$transport->setUsername($settings->smtp_username ?? '');
$transport->setPassword($settings->smtp_password ?? '');
$mailer = new \Symfony\Component\Mailer\Mailer($transport);
$fromEmail = $settings->smtp_from_address ?? 'noreply@localhost';
$fromName = $settings->smtp_from_name ?? 'System';
$from = new \Symfony\Component\Mime\Address($fromEmail, $fromName);
$email = (new \Symfony\Component\Mime\Email)
->from($from)
->to(...$recipients)
->subject($mailMessage->subject)
->html((string) $mailMessage->render());
$mailer->send($email);
}
} catch (\Resend\Exceptions\ErrorException $e) {
// Map HTTP status codes to user-friendly messages
$userMessage = match ($e->getErrorCode()) {
403 => 'Invalid Resend API key. Please verify your API key in the Resend dashboard and update it in settings.',
401 => 'Your Resend API key has restricted permissions. Please use an API key with Full Access permissions.',
429 => 'Resend rate limit exceeded. Please try again in a few minutes.',
400 => 'Email validation failed: '.$e->getErrorMessage(),
default => 'Failed to send email via Resend: '.$e->getErrorMessage(),
};
// Log detailed error for admin debugging (redact sensitive data)
$emailSettings = $notifiable->emailNotificationSettings ?? instanceSettings();
data_set($emailSettings, 'smtp_password', '********');
data_set($emailSettings, 'resend_api_key', '********');
send_internal_notification(sprintf(
"Resend Error\nStatus Code: %s\nMessage: %s\nNotification: %s\nEmail Settings:\n%s",
$e->getErrorCode(),
$e->getErrorMessage(),
get_class($notification),
json_encode($emailSettings, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)
));
// Don't report expected errors (invalid keys, validation) to Sentry
if (in_array($e->getErrorCode(), [403, 401, 400])) {
throw NonReportableException::fromException(new \Exception($userMessage, $e->getCode(), $e));
}
throw new \Exception($userMessage, $e->getCode(), $e);
} catch (\Resend\Exceptions\TransporterException $e) {
send_internal_notification("Resend Transport Error: {$e->getMessage()}");
throw new \Exception('Unable to connect to Resend API. Please check your internet connection and try again.');
} catch (\Throwable $e) {
// Check if this is a Resend domain verification error on cloud instances
if (isCloud() && str_contains($e->getMessage(), 'domain is not verified')) {
// Throw as NonReportableException so it won't go to Sentry
throw NonReportableException::fromException($e);
}
throw $e;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/SendsSlack.php | app/Notifications/Channels/SendsSlack.php | <?php
namespace App\Notifications\Channels;
interface SendsSlack
{
public function routeNotificationForSlack();
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/DiscordChannel.php | app/Notifications/Channels/DiscordChannel.php | <?php
namespace App\Notifications\Channels;
use App\Jobs\SendMessageToDiscordJob;
use Illuminate\Notifications\Notification;
class DiscordChannel
{
/**
* Send the given notification.
*/
public function send(SendsDiscord $notifiable, Notification $notification): void
{
$message = $notification->toDiscord();
$discordSettings = $notifiable->discordNotificationSettings;
if (! $discordSettings || ! $discordSettings->isEnabled() || ! $discordSettings->discord_webhook_url) {
return;
}
if (! $discordSettings->discord_ping_enabled) {
$message->isCritical = false;
}
SendMessageToDiscordJob::dispatch($message, $discordSettings->discord_webhook_url);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/SlackChannel.php | app/Notifications/Channels/SlackChannel.php | <?php
namespace App\Notifications\Channels;
use App\Jobs\SendMessageToSlackJob;
use Illuminate\Notifications\Notification;
class SlackChannel
{
/**
* Send the given notification.
*/
public function send(SendsSlack $notifiable, Notification $notification): void
{
$message = $notification->toSlack();
$slackSettings = $notifiable->slackNotificationSettings;
if (! $slackSettings || ! $slackSettings->isEnabled() || ! $slackSettings->slack_webhook_url) {
return;
}
SendMessageToSlackJob::dispatch($message, $slackSettings->slack_webhook_url);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Channels/SendsTelegram.php | app/Notifications/Channels/SendsTelegram.php | <?php
namespace App\Notifications\Channels;
interface SendsTelegram
{
public function routeNotificationForTelegram();
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Dto/SlackMessage.php | app/Notifications/Dto/SlackMessage.php | <?php
namespace App\Notifications\Dto;
class SlackMessage
{
public function __construct(
public string $title,
public string $description,
public string $color = '#0099ff'
) {}
public static function infoColor(): string
{
return '#0099ff';
}
public static function errorColor(): string
{
return '#ff0000';
}
public static function successColor(): string
{
return '#00ff00';
}
public static function warningColor(): string
{
return '#ffa500';
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Dto/PushoverMessage.php | app/Notifications/Dto/PushoverMessage.php | <?php
namespace App\Notifications\Dto;
use Illuminate\Support\Facades\Log;
class PushoverMessage
{
public function __construct(
public string $title,
public string $message,
public array $buttons = [],
public string $level = 'info',
) {}
public function getLevelIcon(): string
{
return match ($this->level) {
'info' => 'ℹ️',
'error' => '❌',
'success' => '✅ ',
'warning' => '⚠️',
};
}
public function toPayload(string $token, string $user): array
{
$levelIcon = $this->getLevelIcon();
$payload = [
'token' => $token,
'user' => $user,
'title' => "{$levelIcon} {$this->title}",
'message' => $this->message,
'html' => 1,
];
foreach ($this->buttons as $button) {
$buttonUrl = data_get($button, 'url');
$text = data_get($button, 'text', 'Click here');
if ($buttonUrl && str_contains($buttonUrl, 'http://localhost')) {
$buttonUrl = str_replace('http://localhost', config('app.url'), $buttonUrl);
}
$payload['message'] .= " <a href='".$buttonUrl."'>".$text.'</a>';
}
Log::info('Pushover message', $payload);
return $payload;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Dto/DiscordMessage.php | app/Notifications/Dto/DiscordMessage.php | <?php
namespace App\Notifications\Dto;
class DiscordMessage
{
private array $fields = [];
public function __construct(
public string $title,
public string $description,
public int $color,
public bool $isCritical = false,
) {}
public static function successColor(): int
{
return hexdec('a1ffa5');
}
public static function warningColor(): int
{
return hexdec('ffa743');
}
public static function errorColor(): int
{
return hexdec('ff705f');
}
public static function infoColor(): int
{
return hexdec('4f545c');
}
public function addField(string $name, string $value, bool $inline = false): self
{
$this->fields[] = [
'name' => $name,
'value' => $value,
'inline' => $inline,
];
return $this;
}
public function toPayload(): array
{
$footerText = 'Coolify v'.config('constants.coolify.version');
if (isCloud()) {
$footerText = 'Coolify Cloud';
}
$payload = [
'embeds' => [
[
'title' => $this->title,
'description' => $this->description,
'color' => $this->color,
'fields' => $this->addTimestampToFields($this->fields),
'footer' => [
'text' => $footerText,
],
],
],
];
if ($this->isCritical) {
$payload['content'] = '@here';
}
return $payload;
}
private function addTimestampToFields(array $fields): array
{
$fields[] = [
'name' => 'Time',
'value' => '<t:'.now()->timestamp.':R>',
'inline' => true,
];
return $fields;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Database/BackupFailed.php | app/Notifications/Database/BackupFailed.php | <?php
namespace App\Notifications\Database;
use App\Models\ScheduledDatabaseBackup;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class BackupFailed extends CustomEmailNotification
{
public string $name;
public string $frequency;
public function __construct(ScheduledDatabaseBackup $backup, public $database, public $output, public $database_name)
{
$this->onQueue('high');
$this->name = $database->name;
$this->frequency = $backup->frequency;
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('backup_failure');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: [ACTION REQUIRED] Database Backup FAILED for {$this->database->name}");
$mail->view('emails.backup-failed', [
'name' => $this->name,
'database_name' => $this->database_name,
'frequency' => $this->frequency,
'output' => $this->output,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':cross_mark: Database backup failed',
description: "Database backup for {$this->name} (db:{$this->database_name}) has FAILED.",
color: DiscordMessage::errorColor(),
isCritical: true,
);
$message->addField('Frequency', $this->frequency, true);
$message->addField('Output', $this->output);
return $message;
}
public function toTelegram(): array
{
$message = "Coolify: Database backup for {$this->name} (db:{$this->database_name}) with frequency of {$this->frequency} was FAILED.\n\nReason:\n{$this->output}";
return [
'message' => $message,
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Database backup failed',
level: 'error',
message: "Database backup for {$this->name} (db:{$this->database_name}) was FAILED<br/><br/><b>Frequency:</b> {$this->frequency} .<br/><b>Reason:</b> {$this->output}",
);
}
public function toSlack(): SlackMessage
{
$title = 'Database backup failed';
$description = "Database backup for {$this->name} (db:{$this->database_name}) has FAILED.";
$description .= "\n\n*Frequency:* {$this->frequency}";
$description .= "\n\n*Error Output:* {$this->output}";
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
$url = base_url().'/project/'.data_get($this->database, 'environment.project.uuid').'/environment/'.data_get($this->database, 'environment.uuid').'/database/'.$this->database->uuid;
return [
'success' => false,
'message' => 'Database backup failed',
'event' => 'backup_failed',
'database_name' => $this->name,
'database_uuid' => $this->database->uuid,
'database_type' => $this->database_name,
'frequency' => $this->frequency,
'error_output' => $this->output,
'url' => $url,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Database/BackupSuccess.php | app/Notifications/Database/BackupSuccess.php | <?php
namespace App\Notifications\Database;
use App\Models\ScheduledDatabaseBackup;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class BackupSuccess extends CustomEmailNotification
{
public string $name;
public string $frequency;
public function __construct(ScheduledDatabaseBackup $backup, public $database, public $database_name)
{
$this->onQueue('high');
$this->name = $database->name;
$this->frequency = $backup->frequency;
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('backup_success');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Backup successfully done for {$this->database->name}");
$mail->view('emails.backup-success', [
'name' => $this->name,
'database_name' => $this->database_name,
'frequency' => $this->frequency,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':white_check_mark: Database backup successful',
description: "Database backup for {$this->name} (db:{$this->database_name}) was successful.",
color: DiscordMessage::successColor(),
);
$message->addField('Frequency', $this->frequency, true);
return $message;
}
public function toTelegram(): array
{
$message = "Coolify: Database backup for {$this->name} (db:{$this->database_name}) with frequency of {$this->frequency} was successful.";
return [
'message' => $message,
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Database backup successful',
level: 'success',
message: "Database backup for {$this->name} (db:{$this->database_name}) was successful.<br/><br/><b>Frequency:</b> {$this->frequency}.",
);
}
public function toSlack(): SlackMessage
{
$title = 'Database backup successful';
$description = "Database backup for {$this->name} (db:{$this->database_name}) was successful.";
$description .= "\n\n*Frequency:* {$this->frequency}";
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::successColor()
);
}
public function toWebhook(): array
{
$url = base_url().'/project/'.data_get($this->database, 'environment.project.uuid').'/environment/'.data_get($this->database, 'environment.uuid').'/database/'.$this->database->uuid;
return [
'success' => true,
'message' => 'Database backup successful',
'event' => 'backup_success',
'database_name' => $this->name,
'database_uuid' => $this->database->uuid,
'database_type' => $this->database_name,
'frequency' => $this->frequency,
'url' => $url,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Database/BackupSuccessWithS3Warning.php | app/Notifications/Database/BackupSuccessWithS3Warning.php | <?php
namespace App\Notifications\Database;
use App\Models\ScheduledDatabaseBackup;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class BackupSuccessWithS3Warning extends CustomEmailNotification
{
public string $name;
public string $frequency;
public ?string $s3_storage_url = null;
public function __construct(ScheduledDatabaseBackup $backup, public $database, public $database_name, public $s3_error)
{
$this->onQueue('high');
$this->name = $database->name;
$this->frequency = $backup->frequency;
if ($backup->s3) {
$this->s3_storage_url = base_url().'/storages/'.$backup->s3->uuid;
}
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('backup_failure');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Backup succeeded locally but S3 upload failed for {$this->database->name}");
$mail->view('emails.backup-success-with-s3-warning', [
'name' => $this->name,
'database_name' => $this->database_name,
'frequency' => $this->frequency,
's3_error' => $this->s3_error,
's3_storage_url' => $this->s3_storage_url,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':warning: Database backup succeeded locally, S3 upload failed',
description: "Database backup for {$this->name} (db:{$this->database_name}) was created successfully on local storage, but failed to upload to S3.",
color: DiscordMessage::warningColor(),
);
$message->addField('Frequency', $this->frequency, true);
$message->addField('S3 Error', $this->s3_error);
if ($this->s3_storage_url) {
$message->addField('S3 Storage', '[Check Configuration]('.$this->s3_storage_url.')');
}
return $message;
}
public function toTelegram(): array
{
$message = "Coolify: Database backup for {$this->name} (db:{$this->database_name}) with frequency of {$this->frequency} succeeded locally but failed to upload to S3.\n\nS3 Error:\n{$this->s3_error}";
if ($this->s3_storage_url) {
$message .= "\n\nCheck S3 Configuration: {$this->s3_storage_url}";
}
return [
'message' => $message,
];
}
public function toPushover(): PushoverMessage
{
$message = "Database backup for {$this->name} (db:{$this->database_name}) was created successfully on local storage, but failed to upload to S3.<br/><br/><b>Frequency:</b> {$this->frequency}.<br/><b>S3 Error:</b> {$this->s3_error}";
if ($this->s3_storage_url) {
$message .= "<br/><br/><a href=\"{$this->s3_storage_url}\">Check S3 Configuration</a>";
}
return new PushoverMessage(
title: 'Database backup succeeded locally, S3 upload failed',
level: 'warning',
message: $message,
);
}
public function toSlack(): SlackMessage
{
$title = 'Database backup succeeded locally, S3 upload failed';
$description = "Database backup for {$this->name} (db:{$this->database_name}) was created successfully on local storage, but failed to upload to S3.";
$description .= "\n\n*Frequency:* {$this->frequency}";
$description .= "\n\n*S3 Error:* {$this->s3_error}";
if ($this->s3_storage_url) {
$description .= "\n\n*S3 Storage:* <{$this->s3_storage_url}|Check Configuration>";
}
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::warningColor()
);
}
public function toWebhook(): array
{
$url = base_url().'/project/'.data_get($this->database, 'environment.project.uuid').'/environment/'.data_get($this->database, 'environment.uuid').'/database/'.$this->database->uuid;
$data = [
'success' => true,
'message' => 'Database backup succeeded locally, S3 upload failed',
'event' => 'backup_success_with_s3_warning',
'database_name' => $this->name,
'database_uuid' => $this->database->uuid,
'database_type' => $this->database_name,
'frequency' => $this->frequency,
's3_error' => $this->s3_error,
'url' => $url,
];
if ($this->s3_storage_url) {
$data['s3_storage_url'] = $this->s3_storage_url;
}
return $data;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/DockerCleanupSuccess.php | app/Notifications/Server/DockerCleanupSuccess.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class DockerCleanupSuccess extends CustomEmailNotification
{
public function __construct(public Server $server, public string $message)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('docker_cleanup_success');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Docker cleanup job succeeded on {$this->server->name}");
$mail->view('emails.docker-cleanup-success', [
'name' => $this->server->name,
'text' => $this->message,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
return new DiscordMessage(
title: ':white_check_mark: Coolify: Docker cleanup job succeeded on '.$this->server->name,
description: $this->message,
color: DiscordMessage::successColor(),
);
}
public function toTelegram(): array
{
return [
'message' => "Coolify: Docker cleanup job succeeded on {$this->server->name}!\n\n{$this->message}",
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Docker cleanup job succeeded',
level: 'success',
message: "Docker cleanup job succeeded on {$this->server->name}!\n\n{$this->message}",
);
}
public function toSlack(): SlackMessage
{
return new SlackMessage(
title: 'Coolify: Docker cleanup job succeeded',
description: "Docker cleanup job succeeded on '{$this->server->name}'!\n\n{$this->message}",
color: SlackMessage::successColor()
);
}
public function toWebhook(): array
{
$url = base_url().'/server/'.$this->server->uuid;
return [
'success' => true,
'message' => 'Docker cleanup job succeeded',
'event' => 'docker_cleanup_success',
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
'cleanup_message' => $this->message,
'url' => $url,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/TraefikVersionOutdated.php | app/Notifications/Server/TraefikVersionOutdated.php | <?php
namespace App\Notifications\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Collection;
class TraefikVersionOutdated extends CustomEmailNotification
{
public function __construct(public Collection $servers)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('traefik_outdated');
}
private function formatVersion(string $version): string
{
// Add 'v' prefix if not present for consistent display
return str_starts_with($version, 'v') ? $version : "v{$version}";
}
private function getUpgradeTarget(array $info): string
{
// For minor upgrades, use the upgrade_target field (e.g., "v3.6")
if (($info['type'] ?? 'patch_update') === 'minor_upgrade' && isset($info['upgrade_target'])) {
return $this->formatVersion($info['upgrade_target']);
}
// For patch updates, show the full version
return $this->formatVersion($info['latest'] ?? 'unknown');
}
public function toMail($notifiable = null): MailMessage
{
$mail = new MailMessage;
$count = $this->servers->count();
// Transform servers to include URLs
$serversWithUrls = $this->servers->map(function ($server) {
return [
'name' => $server->name,
'uuid' => $server->uuid,
'url' => base_url().'/server/'.$server->uuid.'/proxy',
'outdatedInfo' => $server->outdatedInfo ?? [],
];
});
$mail->subject("Coolify: Traefik proxy outdated on {$count} server(s)");
$mail->view('emails.traefik-version-outdated', [
'servers' => $serversWithUrls,
'count' => $count,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$count = $this->servers->count();
$hasUpgrades = $this->servers->contains(fn ($s) => ($s->outdatedInfo['type'] ?? 'patch_update') === 'minor_upgrade' ||
isset($s->outdatedInfo['newer_branch_target'])
);
$description = "**{$count} server(s)** running outdated Traefik proxy. Update recommended for security and features.\n\n";
$description .= "**Affected servers:**\n";
foreach ($this->servers as $server) {
$info = $server->outdatedInfo ?? [];
$current = $this->formatVersion($info['current'] ?? 'unknown');
$latest = $this->formatVersion($info['latest'] ?? 'unknown');
$upgradeTarget = $this->getUpgradeTarget($info);
$isPatch = ($info['type'] ?? 'patch_update') === 'patch_update';
$hasNewerBranch = isset($info['newer_branch_target']);
if ($isPatch && $hasNewerBranch) {
$newerBranchTarget = $info['newer_branch_target'];
$newerBranchLatest = $this->formatVersion($info['newer_branch_latest']);
$description .= "• {$server->name}: {$current} → {$upgradeTarget} (patch update available)\n";
$description .= " ↳ Also available: {$newerBranchTarget} (latest patch: {$newerBranchLatest}) - new minor version\n";
} elseif ($isPatch) {
$description .= "• {$server->name}: {$current} → {$upgradeTarget} (patch update available)\n";
} else {
$description .= "• {$server->name}: {$current} (latest patch: {$latest}) → {$upgradeTarget} (new minor version available)\n";
}
}
$description .= "\n⚠️ It is recommended to test before switching the production version.";
if ($hasUpgrades) {
$description .= "\n\n📖 **For minor version upgrades**: Read the Traefik changelog before upgrading to understand breaking changes and new features.";
}
return new DiscordMessage(
title: ':warning: Coolify: Traefik proxy outdated',
description: $description,
color: DiscordMessage::warningColor(),
);
}
public function toTelegram(): array
{
$count = $this->servers->count();
$hasUpgrades = $this->servers->contains(fn ($s) => ($s->outdatedInfo['type'] ?? 'patch_update') === 'minor_upgrade' ||
isset($s->outdatedInfo['newer_branch_target'])
);
$message = "⚠️ Coolify: Traefik proxy outdated on {$count} server(s)!\n\n";
$message .= "Update recommended for security and features.\n";
$message .= "📊 Affected servers:\n";
foreach ($this->servers as $server) {
$info = $server->outdatedInfo ?? [];
$current = $this->formatVersion($info['current'] ?? 'unknown');
$latest = $this->formatVersion($info['latest'] ?? 'unknown');
$upgradeTarget = $this->getUpgradeTarget($info);
$isPatch = ($info['type'] ?? 'patch_update') === 'patch_update';
$hasNewerBranch = isset($info['newer_branch_target']);
if ($isPatch && $hasNewerBranch) {
$newerBranchTarget = $info['newer_branch_target'];
$newerBranchLatest = $this->formatVersion($info['newer_branch_latest']);
$message .= "• {$server->name}: {$current} → {$upgradeTarget} (patch update available)\n";
$message .= " ↳ Also available: {$newerBranchTarget} (latest patch: {$newerBranchLatest}) - new minor version\n";
} elseif ($isPatch) {
$message .= "• {$server->name}: {$current} → {$upgradeTarget} (patch update available)\n";
} else {
$message .= "• {$server->name}: {$current} (latest patch: {$latest}) → {$upgradeTarget} (new minor version available)\n";
}
}
$message .= "\n⚠️ It is recommended to test before switching the production version.";
if ($hasUpgrades) {
$message .= "\n\n📖 For minor version upgrades: Read the Traefik changelog before upgrading to understand breaking changes and new features.";
}
return [
'message' => $message,
'buttons' => [],
];
}
public function toPushover(): PushoverMessage
{
$count = $this->servers->count();
$hasUpgrades = $this->servers->contains(fn ($s) => ($s->outdatedInfo['type'] ?? 'patch_update') === 'minor_upgrade' ||
isset($s->outdatedInfo['newer_branch_target'])
);
$message = "Traefik proxy outdated on {$count} server(s)!\n";
$message .= "Affected servers:\n";
foreach ($this->servers as $server) {
$info = $server->outdatedInfo ?? [];
$current = $this->formatVersion($info['current'] ?? 'unknown');
$latest = $this->formatVersion($info['latest'] ?? 'unknown');
$upgradeTarget = $this->getUpgradeTarget($info);
$isPatch = ($info['type'] ?? 'patch_update') === 'patch_update';
$hasNewerBranch = isset($info['newer_branch_target']);
if ($isPatch && $hasNewerBranch) {
$newerBranchTarget = $info['newer_branch_target'];
$newerBranchLatest = $this->formatVersion($info['newer_branch_latest']);
$message .= "• {$server->name}: {$current} → {$upgradeTarget} (patch update available)\n";
$message .= " Also: {$newerBranchTarget} (latest: {$newerBranchLatest}) - new minor version\n";
} elseif ($isPatch) {
$message .= "• {$server->name}: {$current} → {$upgradeTarget} (patch update available)\n";
} else {
$message .= "• {$server->name}: {$current} (latest patch: {$latest}) → {$upgradeTarget} (new minor version available)\n";
}
}
$message .= "\nIt is recommended to test before switching the production version.";
if ($hasUpgrades) {
$message .= "\n\nFor minor version upgrades: Read the Traefik changelog before upgrading.";
}
return new PushoverMessage(
title: 'Traefik proxy outdated',
level: 'warning',
message: $message,
);
}
public function toSlack(): SlackMessage
{
$count = $this->servers->count();
$hasUpgrades = $this->servers->contains(fn ($s) => ($s->outdatedInfo['type'] ?? 'patch_update') === 'minor_upgrade' ||
isset($s->outdatedInfo['newer_branch_target'])
);
$description = "Traefik proxy outdated on {$count} server(s)!\n";
$description .= "*Affected servers:*\n";
foreach ($this->servers as $server) {
$info = $server->outdatedInfo ?? [];
$current = $this->formatVersion($info['current'] ?? 'unknown');
$latest = $this->formatVersion($info['latest'] ?? 'unknown');
$upgradeTarget = $this->getUpgradeTarget($info);
$isPatch = ($info['type'] ?? 'patch_update') === 'patch_update';
$hasNewerBranch = isset($info['newer_branch_target']);
if ($isPatch && $hasNewerBranch) {
$newerBranchTarget = $info['newer_branch_target'];
$newerBranchLatest = $this->formatVersion($info['newer_branch_latest']);
$description .= "• `{$server->name}`: {$current} → {$upgradeTarget} (patch update available)\n";
$description .= " ↳ Also available: {$newerBranchTarget} (latest patch: {$newerBranchLatest}) - new minor version\n";
} elseif ($isPatch) {
$description .= "• `{$server->name}`: {$current} → {$upgradeTarget} (patch update available)\n";
} else {
$description .= "• `{$server->name}`: {$current} (latest patch: {$latest}) → {$upgradeTarget} (new minor version available)\n";
}
}
$description .= "\n:warning: It is recommended to test before switching the production version.";
if ($hasUpgrades) {
$description .= "\n\n:book: For minor version upgrades: Read the Traefik changelog before upgrading to understand breaking changes and new features.";
}
return new SlackMessage(
title: 'Coolify: Traefik proxy outdated',
description: $description,
color: SlackMessage::warningColor()
);
}
public function toWebhook(): array
{
$servers = $this->servers->map(function ($server) {
$info = $server->outdatedInfo ?? [];
$webhookData = [
'name' => $server->name,
'uuid' => $server->uuid,
'current_version' => $info['current'] ?? 'unknown',
'latest_version' => $info['latest'] ?? 'unknown',
'update_type' => $info['type'] ?? 'patch_update',
];
// For minor upgrades, include the upgrade target (e.g., "v3.6")
if (($info['type'] ?? 'patch_update') === 'minor_upgrade' && isset($info['upgrade_target'])) {
$webhookData['upgrade_target'] = $info['upgrade_target'];
}
// Include newer branch info if available
if (isset($info['newer_branch_target'])) {
$webhookData['newer_branch_target'] = $info['newer_branch_target'];
$webhookData['newer_branch_latest'] = $info['newer_branch_latest'];
}
return $webhookData;
})->toArray();
return [
'success' => false,
'message' => 'Traefik proxy outdated',
'event' => 'traefik_version_outdated',
'affected_servers_count' => $this->servers->count(),
'servers' => $servers,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/ForceEnabled.php | app/Notifications/Server/ForceEnabled.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class ForceEnabled extends CustomEmailNotification
{
public function __construct(public Server $server)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('server_force_enabled');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Server ({$this->server->name}) enabled again!");
$mail->view('emails.server-force-enabled', [
'name' => $this->server->name,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
return new DiscordMessage(
title: ':white_check_mark: Server enabled',
description: "Server '{$this->server->name}' enabled again!",
color: DiscordMessage::successColor(),
);
}
public function toTelegram(): array
{
return [
'message' => "Coolify: Server ({$this->server->name}) enabled again!",
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Server enabled',
level: 'success',
message: "Server ({$this->server->name}) enabled again!",
);
}
public function toSlack(): SlackMessage
{
return new SlackMessage(
title: 'Server enabled',
description: "Server '{$this->server->name}' enabled again!",
color: SlackMessage::successColor()
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/HetznerDeletionFailed.php | app/Notifications/Server/HetznerDeletionFailed.php | <?php
namespace App\Notifications\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class HetznerDeletionFailed extends CustomEmailNotification
{
public function __construct(public int $hetznerServerId, public int $teamId, public string $errorMessage)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
ray('hello');
ray($notifiable);
return $notifiable->getEnabledChannels('hetzner_deletion_failed');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: [ACTION REQUIRED] Failed to delete Hetzner server #{$this->hetznerServerId}");
$mail->view('emails.hetzner-deletion-failed', [
'hetznerServerId' => $this->hetznerServerId,
'errorMessage' => $this->errorMessage,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
return new DiscordMessage(
title: ':cross_mark: Coolify: [ACTION REQUIRED] Failed to delete Hetzner server',
description: "Failed to delete Hetzner server #{$this->hetznerServerId} from Hetzner Cloud.\n\n**Error:** {$this->errorMessage}\n\nThe server has been removed from Coolify, but may still exist in your Hetzner Cloud account. Please check your Hetzner Cloud console and manually delete the server if needed.",
color: DiscordMessage::errorColor(),
);
}
public function toTelegram(): array
{
return [
'message' => "Coolify: [ACTION REQUIRED] Failed to delete Hetzner server #{$this->hetznerServerId} from Hetzner Cloud.\n\nError: {$this->errorMessage}\n\nThe server has been removed from Coolify, but may still exist in your Hetzner Cloud account. Please check your Hetzner Cloud console and manually delete the server if needed.",
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Hetzner Server Deletion Failed',
level: 'error',
message: "[ACTION REQUIRED] Failed to delete Hetzner server #{$this->hetznerServerId}.\n\nError: {$this->errorMessage}\n\nThe server has been removed from Coolify, but may still exist in your Hetzner Cloud account. Please check and manually delete if needed.",
);
}
public function toSlack(): SlackMessage
{
return new SlackMessage(
title: 'Coolify: [ACTION REQUIRED] Hetzner Server Deletion Failed',
description: "Failed to delete Hetzner server #{$this->hetznerServerId} from Hetzner Cloud.\n\nError: {$this->errorMessage}\n\nThe server has been removed from Coolify, but may still exist in your Hetzner Cloud account. Please check your Hetzner Cloud console and manually delete the server if needed.",
color: SlackMessage::errorColor()
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/DockerCleanupFailed.php | app/Notifications/Server/DockerCleanupFailed.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class DockerCleanupFailed extends CustomEmailNotification
{
public function __construct(public Server $server, public string $message)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('docker_cleanup_failure');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: [ACTION REQUIRED] Docker cleanup job failed on {$this->server->name}");
$mail->view('emails.docker-cleanup-failed', [
'name' => $this->server->name,
'text' => $this->message,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
return new DiscordMessage(
title: ':cross_mark: Coolify: [ACTION REQUIRED] Docker cleanup job failed on '.$this->server->name,
description: $this->message,
color: DiscordMessage::errorColor(),
);
}
public function toTelegram(): array
{
return [
'message' => "Coolify: [ACTION REQUIRED] Docker cleanup job failed on {$this->server->name}!\n\n{$this->message}",
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Docker cleanup job failed',
level: 'error',
message: "[ACTION REQUIRED] Docker cleanup job failed on {$this->server->name}!\n\n{$this->message}",
);
}
public function toSlack(): SlackMessage
{
return new SlackMessage(
title: 'Coolify: [ACTION REQUIRED] Docker cleanup job failed',
description: "Docker cleanup job failed on '{$this->server->name}'!\n\n{$this->message}",
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
$url = base_url().'/server/'.$this->server->uuid;
return [
'success' => false,
'message' => 'Docker cleanup job failed',
'event' => 'docker_cleanup_failed',
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
'error_message' => $this->message,
'url' => $url,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/Reachable.php | app/Notifications/Server/Reachable.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class Reachable extends CustomEmailNotification
{
protected bool $isRateLimited = false;
public function __construct(public Server $server)
{
$this->onQueue('high');
$this->isRateLimited = isEmailRateLimited(
limiterKey: 'server-reachable:'.$this->server->id,
);
}
public function via(object $notifiable): array
{
if ($this->isRateLimited) {
return [];
}
return $notifiable->getEnabledChannels('server_reachable');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Server ({$this->server->name}) revived.");
$mail->view('emails.server-revived', [
'name' => $this->server->name,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
return new DiscordMessage(
title: ":white_check_mark: Server '{$this->server->name}' revived",
description: 'All automations & integrations are turned on again!',
color: DiscordMessage::successColor(),
);
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Server revived',
message: "Server '{$this->server->name}' revived. All automations & integrations are turned on again!",
level: 'success',
);
}
public function toTelegram(): array
{
return [
'message' => "Coolify: Server '{$this->server->name}' revived. All automations & integrations are turned on again!",
];
}
public function toSlack(): SlackMessage
{
return new SlackMessage(
title: 'Server revived',
description: "Server '{$this->server->name}' revived.\nAll automations & integrations are turned on again!",
color: SlackMessage::successColor()
);
}
public function toWebhook(): array
{
$url = base_url().'/server/'.$this->server->uuid;
return [
'success' => true,
'message' => 'Server revived',
'event' => 'server_reachable',
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
'url' => $url,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/ServerPatchCheck.php | app/Notifications/Server/ServerPatchCheck.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class ServerPatchCheck extends CustomEmailNotification
{
public string $serverUrl;
public function __construct(public Server $server, public array $patchData)
{
$this->onQueue('high');
$this->serverUrl = base_url().'/server/'.$this->server->uuid.'/security/patches';
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('server_patch');
}
public function toMail($notifiable = null): MailMessage
{
$mail = new MailMessage;
// Handle error case
if (isset($this->patchData['error'])) {
$mail->subject("Coolify: [ERROR] Failed to check patches on {$this->server->name}");
$mail->view('emails.server-patches-error', [
'name' => $this->server->name,
'error' => $this->patchData['error'],
'osId' => $this->patchData['osId'] ?? 'unknown',
'package_manager' => $this->patchData['package_manager'] ?? 'unknown',
'server_url' => $this->serverUrl,
]);
return $mail;
}
$totalUpdates = $this->patchData['total_updates'] ?? 0;
$mail->subject("Coolify: [ACTION REQUIRED] {$totalUpdates} server patches available on {$this->server->name}");
$mail->view('emails.server-patches', [
'name' => $this->server->name,
'total_updates' => $totalUpdates,
'updates' => $this->patchData['updates'] ?? [],
'osId' => $this->patchData['osId'] ?? 'unknown',
'package_manager' => $this->patchData['package_manager'] ?? 'unknown',
'server_url' => $this->serverUrl,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
// Handle error case
if (isset($this->patchData['error'])) {
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$error = $this->patchData['error'];
$description = "**Failed to check for updates** on server {$this->server->name}\n\n";
$description .= "**Error Details:**\n";
$description .= '• OS: '.ucfirst($osId)."\n";
$description .= "• Package Manager: {$packageManager}\n";
$description .= "• Error: {$error}\n\n";
$description .= "[Manage Server]($this->serverUrl)";
return new DiscordMessage(
title: ':x: Coolify: [ERROR] Failed to check patches on '.$this->server->name,
description: $description,
color: DiscordMessage::errorColor(),
);
}
$totalUpdates = $this->patchData['total_updates'] ?? 0;
$updates = $this->patchData['updates'] ?? [];
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$description = "**{$totalUpdates} package updates** available for server {$this->server->name}\n\n";
$description .= "**Summary:**\n";
$description .= '• OS: '.ucfirst($osId)."\n";
$description .= "• Package Manager: {$packageManager}\n";
$description .= "• Total Updates: {$totalUpdates}\n\n";
// Show first few packages
if (count($updates) > 0) {
$description .= "**Sample Updates:**\n";
$sampleUpdates = array_slice($updates, 0, 5);
foreach ($sampleUpdates as $update) {
$description .= "• {$update['package']}: {$update['current_version']} → {$update['new_version']}\n";
}
if (count($updates) > 5) {
$description .= '• ... and '.(count($updates) - 5)." more packages\n";
}
// Check for critical packages
$criticalPackages = collect($updates)->filter(function ($update) {
return str_contains(strtolower($update['package']), 'docker') ||
str_contains(strtolower($update['package']), 'kernel') ||
str_contains(strtolower($update['package']), 'openssh') ||
str_contains(strtolower($update['package']), 'ssl');
});
if ($criticalPackages->count() > 0) {
$description .= "\n **Critical packages detected** ({$criticalPackages->count()} packages may require restarts)";
}
$description .= "\n [Manage Server Patches]($this->serverUrl)";
}
return new DiscordMessage(
title: ':warning: Coolify: [ACTION REQUIRED] Server patches available on '.$this->server->name,
description: $description,
color: DiscordMessage::errorColor(),
);
}
public function toTelegram(): array
{
// Handle error case
if (isset($this->patchData['error'])) {
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$error = $this->patchData['error'];
$message = "❌ Coolify: [ERROR] Failed to check patches on {$this->server->name}!\n\n";
$message .= "📊 Error Details:\n";
$message .= '• OS: '.ucfirst($osId)."\n";
$message .= "• Package Manager: {$packageManager}\n";
$message .= "• Error: {$error}\n\n";
return [
'message' => $message,
'buttons' => [
[
'text' => 'Manage Server',
'url' => $this->serverUrl,
],
],
];
}
$totalUpdates = $this->patchData['total_updates'] ?? 0;
$updates = $this->patchData['updates'] ?? [];
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$message = "🔧 Coolify: [ACTION REQUIRED] {$totalUpdates} server patches available on {$this->server->name}!\n\n";
$message .= "📊 Summary:\n";
$message .= '• OS: '.ucfirst($osId)."\n";
$message .= "• Package Manager: {$packageManager}\n";
$message .= "• Total Updates: {$totalUpdates}\n\n";
if (count($updates) > 0) {
$message .= "📦 Sample Updates:\n";
$sampleUpdates = array_slice($updates, 0, 5);
foreach ($sampleUpdates as $update) {
$message .= "• {$update['package']}: {$update['current_version']} → {$update['new_version']}\n";
}
if (count($updates) > 5) {
$message .= '• ... and '.(count($updates) - 5)." more packages\n";
}
// Check for critical packages
$criticalPackages = collect($updates)->filter(function ($update) {
return str_contains(strtolower($update['package']), 'docker') ||
str_contains(strtolower($update['package']), 'kernel') ||
str_contains(strtolower($update['package']), 'openssh') ||
str_contains(strtolower($update['package']), 'ssl');
});
if ($criticalPackages->count() > 0) {
$message .= "\n⚠️ Critical packages detected: {$criticalPackages->count()} packages may require restarts\n";
foreach ($criticalPackages->take(3) as $package) {
$message .= "• {$package['package']}: {$package['current_version']} → {$package['new_version']}\n";
}
if ($criticalPackages->count() > 3) {
$message .= '• ... and '.($criticalPackages->count() - 3)." more critical packages\n";
}
}
}
return [
'message' => $message,
'buttons' => [
[
'text' => 'Manage Server Patches',
'url' => $this->serverUrl,
],
],
];
}
public function toPushover(): PushoverMessage
{
// Handle error case
if (isset($this->patchData['error'])) {
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$error = $this->patchData['error'];
$message = "[ERROR] Failed to check patches on {$this->server->name}!\n\n";
$message .= "Error Details:\n";
$message .= '• OS: '.ucfirst($osId)."\n";
$message .= "• Package Manager: {$packageManager}\n";
$message .= "• Error: {$error}\n\n";
return new PushoverMessage(
title: 'Server patch check failed',
level: 'error',
message: $message,
buttons: [
[
'text' => 'Manage Server',
'url' => $this->serverUrl,
],
],
);
}
$totalUpdates = $this->patchData['total_updates'] ?? 0;
$updates = $this->patchData['updates'] ?? [];
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$message = "[ACTION REQUIRED] {$totalUpdates} server patches available on {$this->server->name}!\n\n";
$message .= "Summary:\n";
$message .= '• OS: '.ucfirst($osId)."\n";
$message .= "• Package Manager: {$packageManager}\n";
$message .= "• Total Updates: {$totalUpdates}\n\n";
if (count($updates) > 0) {
$message .= "Sample Updates:\n";
$sampleUpdates = array_slice($updates, 0, 3);
foreach ($sampleUpdates as $update) {
$message .= "• {$update['package']}: {$update['current_version']} → {$update['new_version']}\n";
}
if (count($updates) > 3) {
$message .= '• ... and '.(count($updates) - 3)." more packages\n";
}
// Check for critical packages
$criticalPackages = collect($updates)->filter(function ($update) {
return str_contains(strtolower($update['package']), 'docker') ||
str_contains(strtolower($update['package']), 'kernel') ||
str_contains(strtolower($update['package']), 'openssh') ||
str_contains(strtolower($update['package']), 'ssl');
});
if ($criticalPackages->count() > 0) {
$message .= "\nCritical packages detected: {$criticalPackages->count()} may require restarts";
}
}
return new PushoverMessage(
title: 'Server patches available',
level: 'error',
message: $message,
buttons: [
[
'text' => 'Manage Server Patches',
'url' => $this->serverUrl,
],
],
);
}
public function toSlack(): SlackMessage
{
// Handle error case
if (isset($this->patchData['error'])) {
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$error = $this->patchData['error'];
$description = "Failed to check patches on '{$this->server->name}'!\n\n";
$description .= "*Error Details:*\n";
$description .= '• OS: '.ucfirst($osId)."\n";
$description .= "• Package Manager: {$packageManager}\n";
$description .= "• Error: `{$error}`\n\n";
$description .= "\n:link: <{$this->serverUrl}|Manage Server>";
return new SlackMessage(
title: 'Coolify: [ERROR] Server patch check failed',
description: $description,
color: SlackMessage::errorColor()
);
}
$totalUpdates = $this->patchData['total_updates'] ?? 0;
$updates = $this->patchData['updates'] ?? [];
$osId = $this->patchData['osId'] ?? 'unknown';
$packageManager = $this->patchData['package_manager'] ?? 'unknown';
$description = "{$totalUpdates} server patches available on '{$this->server->name}'!\n\n";
$description .= "*Summary:*\n";
$description .= '• OS: '.ucfirst($osId)."\n";
$description .= "• Package Manager: {$packageManager}\n";
$description .= "• Total Updates: {$totalUpdates}\n\n";
if (count($updates) > 0) {
$description .= "*Sample Updates:*\n";
$sampleUpdates = array_slice($updates, 0, 5);
foreach ($sampleUpdates as $update) {
$description .= "• `{$update['package']}`: {$update['current_version']} → {$update['new_version']}\n";
}
if (count($updates) > 5) {
$description .= '• ... and '.(count($updates) - 5)." more packages\n";
}
// Check for critical packages
$criticalPackages = collect($updates)->filter(function ($update) {
return str_contains(strtolower($update['package']), 'docker') ||
str_contains(strtolower($update['package']), 'kernel') ||
str_contains(strtolower($update['package']), 'openssh') ||
str_contains(strtolower($update['package']), 'ssl');
});
if ($criticalPackages->count() > 0) {
$description .= "\n:warning: *Critical packages detected:* {$criticalPackages->count()} packages may require restarts\n";
foreach ($criticalPackages->take(3) as $package) {
$description .= "• `{$package['package']}`: {$package['current_version']} → {$package['new_version']}\n";
}
if ($criticalPackages->count() > 3) {
$description .= '• ... and '.($criticalPackages->count() - 3)." more critical packages\n";
}
}
}
$description .= "\n:link: <{$this->serverUrl}|Manage Server Patches>";
return new SlackMessage(
title: 'Coolify: [ACTION REQUIRED] Server patches available',
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
// Handle error case
if (isset($this->patchData['error'])) {
return [
'success' => false,
'message' => 'Failed to check patches',
'event' => 'server_patch_check_error',
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
'os_id' => $this->patchData['osId'] ?? 'unknown',
'package_manager' => $this->patchData['package_manager'] ?? 'unknown',
'error' => $this->patchData['error'],
'url' => $this->serverUrl,
];
}
$totalUpdates = $this->patchData['total_updates'] ?? 0;
$updates = $this->patchData['updates'] ?? [];
// Check for critical packages
$criticalPackages = collect($updates)->filter(function ($update) {
return str_contains(strtolower($update['package']), 'docker') ||
str_contains(strtolower($update['package']), 'kernel') ||
str_contains(strtolower($update['package']), 'openssh') ||
str_contains(strtolower($update['package']), 'ssl');
});
return [
'success' => false,
'message' => 'Server patches available',
'event' => 'server_patch_check',
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
'total_updates' => $totalUpdates,
'os_id' => $this->patchData['osId'] ?? 'unknown',
'package_manager' => $this->patchData['package_manager'] ?? 'unknown',
'updates' => $updates,
'critical_packages_count' => $criticalPackages->count(),
'url' => $this->serverUrl,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/ForceDisabled.php | app/Notifications/Server/ForceDisabled.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class ForceDisabled extends CustomEmailNotification
{
public function __construct(public Server $server)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('server_force_disabled');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Server ({$this->server->name}) disabled because it is not paid!");
$mail->view('emails.server-force-disabled', [
'name' => $this->server->name,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':cross_mark: Server disabled',
description: "Server ({$this->server->name}) disabled because it is not paid!",
color: DiscordMessage::errorColor(),
);
$message->addField('Please update your subscription to enable the server again!', '[Link](https://app.coolify.io/subscriptions)');
return $message;
}
public function toTelegram(): array
{
return [
'message' => "Coolify: Server ({$this->server->name}) disabled because it is not paid!\n All automations and integrations are stopped.\nPlease update your subscription to enable the server again [here](https://app.coolify.io/subscriptions).",
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Server disabled',
level: 'error',
message: "Server ({$this->server->name}) disabled because it is not paid!\n All automations and integrations are stopped.<br/>Please update your subscription to enable the server again [here](https://app.coolify.io/subscriptions).",
);
}
public function toSlack(): SlackMessage
{
$title = 'Server disabled';
$description = "Server ({$this->server->name}) disabled because it is not paid!\n";
$description .= "All automations and integrations are stopped.\n\n";
$description .= 'Please update your subscription to enable the server again: https://app.coolify.io/subscriptions';
return new SlackMessage(
title: $title,
description: $description,
color: SlackMessage::errorColor()
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/HighDiskUsage.php | app/Notifications/Server/HighDiskUsage.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class HighDiskUsage extends CustomEmailNotification
{
public function __construct(public Server $server, public int $disk_usage, public int $server_disk_usage_notification_threshold)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('server_disk_usage');
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Server ({$this->server->name}) high disk usage detected!");
$mail->view('emails.high-disk-usage', [
'name' => $this->server->name,
'disk_usage' => $this->disk_usage,
'threshold' => $this->server_disk_usage_notification_threshold,
]);
return $mail;
}
public function toDiscord(): DiscordMessage
{
$message = new DiscordMessage(
title: ':cross_mark: High disk usage detected',
description: "Server '{$this->server->name}' high disk usage detected!",
color: DiscordMessage::errorColor(),
isCritical: true,
);
$message->addField('Disk usage', "{$this->disk_usage}%", true);
$message->addField('Threshold', "{$this->server_disk_usage_notification_threshold}%", true);
$message->addField('What to do?', '[Link](https://coolify.io/docs/knowledge-base/server/automated-cleanup)', true);
$message->addField('Change Settings', '[Threshold]('.base_url().'/server/'.$this->server->uuid.'#advanced) | [Notification]('.base_url().'/notifications/discord)');
return $message;
}
public function toTelegram(): array
{
return [
'message' => "Coolify: Server '{$this->server->name}' high disk usage detected!\nDisk usage: {$this->disk_usage}%. Threshold: {$this->server_disk_usage_notification_threshold}%.\nPlease cleanup your disk to prevent data-loss.\nHere are some tips: https://coolify.io/docs/knowledge-base/server/automated-cleanup.",
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'High disk usage detected',
level: 'warning',
message: "Server '{$this->server->name}' high disk usage detected!<br/><br/><b>Disk usage:</b> {$this->disk_usage}%.<br/><b>Threshold:</b> {$this->server_disk_usage_notification_threshold}%.<br/>Please cleanup your disk to prevent data-loss.",
buttons: [
'Change settings' => base_url().'/server/'.$this->server->uuid.'#advanced',
'Tips for cleanup' => 'https://coolify.io/docs/knowledge-base/server/automated-cleanup',
],
);
}
public function toSlack(): SlackMessage
{
$description = "Server '{$this->server->name}' high disk usage detected!\n";
$description .= "Disk usage: {$this->disk_usage}%\n";
$description .= "Threshold: {$this->server_disk_usage_notification_threshold}%\n\n";
$description .= "Please cleanup your disk to prevent data-loss.\n";
$description .= "Tips for cleanup: https://coolify.io/docs/knowledge-base/server/automated-cleanup\n";
$description .= "Change settings:\n";
$description .= '- Threshold: '.base_url().'/server/'.$this->server->uuid."#advanced\n";
$description .= '- Notifications: '.base_url().'/notifications/slack';
return new SlackMessage(
title: 'High disk usage detected',
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
return [
'success' => false,
'message' => 'High disk usage detected',
'event' => 'high_disk_usage',
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
'disk_usage' => $this->disk_usage,
'threshold' => $this->server_disk_usage_notification_threshold,
'url' => base_url().'/server/'.$this->server->uuid,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Server/Unreachable.php | app/Notifications/Server/Unreachable.php | <?php
namespace App\Notifications\Server;
use App\Models\Server;
use App\Notifications\CustomEmailNotification;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Notifications\Messages\MailMessage;
class Unreachable extends CustomEmailNotification
{
protected bool $isRateLimited = false;
public function __construct(public Server $server)
{
$this->onQueue('high');
$this->isRateLimited = isEmailRateLimited(
limiterKey: 'server-unreachable:'.$this->server->id,
);
}
public function via(object $notifiable): array
{
if ($this->isRateLimited) {
return [];
}
return $notifiable->getEnabledChannels('server_unreachable');
}
public function toMail(): ?MailMessage
{
$mail = new MailMessage;
$mail->subject("Coolify: Your server ({$this->server->name}) is unreachable.");
$mail->view('emails.server-lost-connection', [
'name' => $this->server->name,
]);
return $mail;
}
public function toDiscord(): ?DiscordMessage
{
$message = new DiscordMessage(
title: ':cross_mark: Server unreachable',
description: "Your server '{$this->server->name}' is unreachable.",
color: DiscordMessage::errorColor(),
);
$message->addField('IMPORTANT', 'We automatically try to revive your server and turn on all automations & integrations.');
return $message;
}
public function toTelegram(): ?array
{
return [
'message' => "Coolify: Your server '{$this->server->name}' is unreachable. All automations & integrations are turned off! Please check your server! IMPORTANT: We automatically try to revive your server and turn on all automations & integrations.",
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'Server unreachable',
level: 'error',
message: "Your server '{$this->server->name}' is unreachable.<br/>All automations & integrations are turned off!<br/><br/><b>IMPORTANT:</b> We automatically try to revive your server and turn on all automations & integrations.",
);
}
public function toSlack(): SlackMessage
{
$description = "Your server '{$this->server->name}' is unreachable.\n";
$description .= "All automations & integrations are turned off!\n\n";
$description .= '*IMPORTANT:* We automatically try to revive your server and turn on all automations & integrations.';
return new SlackMessage(
title: 'Server unreachable',
description: $description,
color: SlackMessage::errorColor()
);
}
public function toWebhook(): array
{
$url = base_url().'/server/'.$this->server->uuid;
return [
'success' => false,
'message' => 'Server unreachable',
'event' => 'server_unreachable',
'server_name' => $this->server->name,
'server_uuid' => $this->server->uuid,
'url' => $url,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/Internal/GeneralNotification.php | app/Notifications/Internal/GeneralNotification.php | <?php
namespace App\Notifications\Internal;
use App\Notifications\Dto\DiscordMessage;
use App\Notifications\Dto\PushoverMessage;
use App\Notifications\Dto\SlackMessage;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
class GeneralNotification extends Notification implements ShouldQueue
{
use Queueable;
public $tries = 1;
public function __construct(public string $message)
{
$this->onQueue('high');
}
public function via(object $notifiable): array
{
return $notifiable->getEnabledChannels('general');
}
public function toDiscord(): DiscordMessage
{
return new DiscordMessage(
title: 'Coolify: General Notification',
description: $this->message,
color: DiscordMessage::infoColor(),
);
}
public function toTelegram(): array
{
return [
'message' => $this->message,
];
}
public function toPushover(): PushoverMessage
{
return new PushoverMessage(
title: 'General Notification',
level: 'info',
message: $this->message,
);
}
public function toSlack(): SlackMessage
{
return new SlackMessage(
title: 'Coolify: General Notification',
description: $this->message,
color: SlackMessage::infoColor(),
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/TransactionalEmails/EmailChangeVerification.php | app/Notifications/TransactionalEmails/EmailChangeVerification.php | <?php
namespace App\Notifications\TransactionalEmails;
use App\Models\User;
use App\Notifications\Channels\TransactionalEmailChannel;
use App\Notifications\CustomEmailNotification;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Carbon;
class EmailChangeVerification extends CustomEmailNotification
{
public function via(): array
{
return [TransactionalEmailChannel::class];
}
public function __construct(
public User $user,
public string $verificationCode,
public string $newEmail,
public Carbon $expiresAt,
public bool $isTransactionalEmail = true
) {
$this->onQueue('high');
}
public function toMail(): MailMessage
{
// Use the configured expiry minutes value
$expiryMinutes = config('constants.email_change.verification_code_expiry_minutes', 10);
$mail = new MailMessage;
$mail->subject('Coolify: Verify Your New Email Address');
$mail->view('emails.email-change-verification', [
'newEmail' => $this->newEmail,
'verificationCode' => $this->verificationCode,
'expiryMinutes' => $expiryMinutes,
]);
return $mail;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/TransactionalEmails/Test.php | app/Notifications/TransactionalEmails/Test.php | <?php
namespace App\Notifications\TransactionalEmails;
use App\Notifications\Channels\EmailChannel;
use App\Notifications\CustomEmailNotification;
use Illuminate\Notifications\Messages\MailMessage;
class Test extends CustomEmailNotification
{
public bool $isTestNotification = true;
public function __construct(public string $emails, public bool $isTransactionalEmail = true)
{
$this->onQueue('high');
}
public function via(): array
{
return [EmailChannel::class];
}
public function toMail(): MailMessage
{
$mail = new MailMessage;
$mail->subject('Coolify: Test Email');
$mail->view('emails.test');
return $mail;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/TransactionalEmails/ResetPassword.php | app/Notifications/TransactionalEmails/ResetPassword.php | <?php
namespace App\Notifications\TransactionalEmails;
use App\Models\InstanceSettings;
use Exception;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
class ResetPassword extends Notification
{
public static $createUrlCallback;
public static $toMailCallback;
public $token;
public InstanceSettings $settings;
public function __construct($token, public bool $isTransactionalEmail = true)
{
$this->settings = instanceSettings();
$this->token = $token;
}
public static function createUrlUsing($callback)
{
static::$createUrlCallback = $callback;
}
public static function toMailUsing($callback)
{
static::$toMailCallback = $callback;
}
public function via($notifiable)
{
$type = set_transanctional_email_settings();
if (blank($type)) {
throw new Exception('No email settings found.');
}
return ['mail'];
}
public function toMail($notifiable)
{
if (static::$toMailCallback) {
return call_user_func(static::$toMailCallback, $notifiable, $this->token);
}
return $this->buildMailMessage($this->resetUrl($notifiable));
}
protected function buildMailMessage($url)
{
$mail = new MailMessage;
$mail->subject('Coolify: Reset Password');
$mail->view('emails.reset-password', ['url' => $url, 'count' => config('auth.passwords.'.config('auth.defaults.passwords').'.expire')]);
return $mail;
}
protected function resetUrl($notifiable)
{
if (static::$createUrlCallback) {
return call_user_func(static::$createUrlCallback, $notifiable, $this->token);
}
return url(route('password.reset', [
'token' => $this->token,
'email' => $notifiable->getEmailForPasswordReset(),
], false));
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Notifications/TransactionalEmails/InvitationLink.php | app/Notifications/TransactionalEmails/InvitationLink.php | <?php
namespace App\Notifications\TransactionalEmails;
use App\Models\Team;
use App\Models\TeamInvitation;
use App\Models\User;
use App\Notifications\Channels\TransactionalEmailChannel;
use App\Notifications\CustomEmailNotification;
use Illuminate\Notifications\Messages\MailMessage;
class InvitationLink extends CustomEmailNotification
{
public function via(): array
{
return [TransactionalEmailChannel::class];
}
public function __construct(public User $user, public bool $isTransactionalEmail = true)
{
$this->onQueue('high');
}
public function toMail(): MailMessage
{
$invitation = TeamInvitation::whereEmail($this->user->email)->first();
$invitation_team = Team::find($invitation->team->id);
$mail = new MailMessage;
$mail->subject('Coolify: Invitation for '.$invitation_team->name);
$mail->view('emails.invitation-link', [
'team' => $invitation_team->name,
'email' => $this->user->email,
'invitation_link' => $invitation->link,
]);
return $mail;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Kernel.php | app/Console/Kernel.php | <?php
namespace App\Console;
use App\Jobs\CheckForUpdatesJob;
use App\Jobs\CheckHelperImageJob;
use App\Jobs\CheckTraefikVersionJob;
use App\Jobs\CleanupInstanceStuffsJob;
use App\Jobs\CleanupOrphanedPreviewContainersJob;
use App\Jobs\PullChangelog;
use App\Jobs\PullTemplatesFromCDN;
use App\Jobs\RegenerateSslCertJob;
use App\Jobs\ScheduledJobManager;
use App\Jobs\ServerManagerJob;
use App\Jobs\UpdateCoolifyJob;
use App\Models\InstanceSettings;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
private Schedule $scheduleInstance;
private InstanceSettings $settings;
private string $updateCheckFrequency;
private string $instanceTimezone;
protected function schedule(Schedule $schedule): void
{
$this->scheduleInstance = $schedule;
$this->settings = instanceSettings();
$this->updateCheckFrequency = $this->settings->update_check_frequency ?: '0 * * * *';
$this->instanceTimezone = $this->settings->instance_timezone ?: config('app.timezone');
if (validate_timezone($this->instanceTimezone) === false) {
$this->instanceTimezone = config('app.timezone');
}
// $this->scheduleInstance->job(new CleanupStaleMultiplexedConnections)->hourly();
$this->scheduleInstance->command('cleanup:redis')->weekly();
if (isDev()) {
// Instance Jobs
$this->scheduleInstance->command('horizon:snapshot')->everyMinute();
$this->scheduleInstance->job(new CleanupInstanceStuffsJob)->everyMinute()->onOneServer();
$this->scheduleInstance->job(new CheckHelperImageJob)->everyTenMinutes()->onOneServer();
// Server Jobs
$this->scheduleInstance->job(new ServerManagerJob)->everyMinute()->onOneServer();
// Scheduled Jobs (Backups & Tasks)
$this->scheduleInstance->job(new ScheduledJobManager)->everyMinute()->onOneServer();
$this->scheduleInstance->command('uploads:clear')->everyTwoMinutes();
} else {
// Instance Jobs
$this->scheduleInstance->command('horizon:snapshot')->everyFiveMinutes();
$this->scheduleInstance->command('cleanup:unreachable-servers')->daily()->onOneServer();
$this->scheduleInstance->job(new PullTemplatesFromCDN)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();
$this->scheduleInstance->job(new PullChangelog)->cron($this->updateCheckFrequency)->timezone($this->instanceTimezone)->onOneServer();
$this->scheduleInstance->job(new CleanupInstanceStuffsJob)->everyTwoMinutes()->onOneServer();
$this->scheduleUpdates();
// Server Jobs
$this->scheduleInstance->job(new ServerManagerJob)->everyMinute()->onOneServer();
$this->pullImages();
// Scheduled Jobs (Backups & Tasks)
$this->scheduleInstance->job(new ScheduledJobManager)->everyMinute()->onOneServer();
$this->scheduleInstance->job(new RegenerateSslCertJob)->twiceDaily();
$this->scheduleInstance->job(new CheckTraefikVersionJob)->weekly()->sundays()->at('00:00')->timezone($this->instanceTimezone)->onOneServer();
$this->scheduleInstance->command('cleanup:database --yes')->daily();
$this->scheduleInstance->command('uploads:clear')->everyTwoMinutes();
// Cleanup orphaned PR preview containers daily
$this->scheduleInstance->job(new CleanupOrphanedPreviewContainersJob)->daily()->onOneServer();
}
}
private function pullImages(): void
{
$this->scheduleInstance->job(new CheckHelperImageJob)
->cron($this->updateCheckFrequency)
->timezone($this->instanceTimezone)
->onOneServer();
}
private function scheduleUpdates(): void
{
$this->scheduleInstance->job(new CheckForUpdatesJob)
->cron($this->updateCheckFrequency)
->timezone($this->instanceTimezone)
->onOneServer();
if ($this->settings->is_auto_update_enabled) {
$autoUpdateFrequency = $this->settings->auto_update_frequency;
$this->scheduleInstance->job(new UpdateCoolifyJob)
->cron($autoUpdateFrequency)
->timezone($this->instanceTimezone)
->onOneServer();
}
}
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CleanupApplicationDeploymentQueue.php | app/Console/Commands/CleanupApplicationDeploymentQueue.php | <?php
namespace App\Console\Commands;
use App\Models\ApplicationDeploymentQueue;
use Illuminate\Console\Command;
class CleanupApplicationDeploymentQueue extends Command
{
protected $signature = 'cleanup:deployment-queue {--team-id=}';
protected $description = 'Cleanup application deployment queue.';
public function handle()
{
$team_id = $this->option('team-id');
$servers = \App\Models\Server::where('team_id', $team_id)->get();
foreach ($servers as $server) {
$deployments = ApplicationDeploymentQueue::whereIn('status', ['in_progress', 'queued'])->where('server_id', $server->id)->get();
foreach ($deployments as $deployment) {
$deployment->update(['status' => 'failed']);
instant_remote_process(['docker rm -f '.$deployment->deployment_uuid], $server, false);
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Init.php | app/Console/Commands/Init.php | <?php
namespace App\Console\Commands;
use App\Enums\ActivityTypes;
use App\Enums\ApplicationDeploymentStatus;
use App\Jobs\CheckHelperImageJob;
use App\Jobs\PullChangelog;
use App\Models\ApplicationDeploymentQueue;
use App\Models\Environment;
use App\Models\InstanceSettings;
use App\Models\ScheduledDatabaseBackup;
use App\Models\ScheduledDatabaseBackupExecution;
use App\Models\ScheduledTaskExecution;
use App\Models\Server;
use App\Models\StandalonePostgresql;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Http;
class Init extends Command
{
protected $signature = 'app:init';
protected $description = 'Cleanup instance related stuffs';
public $servers = null;
public InstanceSettings $settings;
public function handle()
{
Artisan::call('optimize:clear');
Artisan::call('optimize');
try {
$this->pullTemplatesFromCDN();
} catch (\Throwable $e) {
echo "Could not pull templates from CDN: {$e->getMessage()}\n";
}
try {
$this->pullChangelogFromGitHub();
} catch (\Throwable $e) {
echo "Could not changelogs from github: {$e->getMessage()}\n";
}
try {
$this->pullHelperImage();
} catch (\Throwable $e) {
echo "Error in pullHelperImage command: {$e->getMessage()}\n";
}
if (isCloud()) {
return;
}
$this->settings = instanceSettings();
$this->servers = Server::all();
$do_not_track = data_get($this->settings, 'do_not_track', true);
if ($do_not_track == false) {
$this->sendAliveSignal();
}
get_public_ips();
// Backward compatibility
$this->replaceSlashInEnvironmentName();
$this->restoreCoolifyDbBackup();
$this->updateUserEmails();
//
$this->updateTraefikLabels();
$this->cleanupUnusedNetworkFromCoolifyProxy();
try {
$this->call('cleanup:redis', ['--restart' => true, '--clear-locks' => true]);
} catch (\Throwable $e) {
echo "Error in cleanup:redis command: {$e->getMessage()}\n";
}
try {
$this->call('cleanup:names');
} catch (\Throwable $e) {
echo "Error in cleanup:names command: {$e->getMessage()}\n";
}
try {
$this->call('cleanup:stucked-resources');
} catch (\Throwable $e) {
echo "Error in cleanup:stucked-resources command: {$e->getMessage()}\n";
echo "Continuing with initialization - cleanup errors will not prevent Coolify from starting\n";
}
try {
$updatedCount = ApplicationDeploymentQueue::whereIn('status', [
ApplicationDeploymentStatus::IN_PROGRESS->value,
ApplicationDeploymentStatus::QUEUED->value,
])->update([
'status' => ApplicationDeploymentStatus::FAILED->value,
]);
if ($updatedCount > 0) {
echo "Marked {$updatedCount} stuck deployments as failed\n";
}
} catch (\Throwable $e) {
echo "Could not cleanup inprogress deployments: {$e->getMessage()}\n";
}
try {
$updatedTaskCount = ScheduledTaskExecution::where('status', 'running')->update([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
]);
if ($updatedTaskCount > 0) {
echo "Marked {$updatedTaskCount} stuck scheduled task executions as failed\n";
}
} catch (\Throwable $e) {
echo "Could not cleanup stuck scheduled task executions: {$e->getMessage()}\n";
}
try {
$updatedBackupCount = ScheduledDatabaseBackupExecution::where('status', 'running')->update([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
]);
if ($updatedBackupCount > 0) {
echo "Marked {$updatedBackupCount} stuck database backup executions as failed\n";
}
} catch (\Throwable $e) {
echo "Could not cleanup stuck database backup executions: {$e->getMessage()}\n";
}
try {
$localhost = $this->servers->where('id', 0)->first();
if ($localhost) {
$localhost->setupDynamicProxyConfiguration();
}
} catch (\Throwable $e) {
echo "Could not setup dynamic configuration: {$e->getMessage()}\n";
}
if (! is_null(config('constants.coolify.autoupdate', null))) {
if (config('constants.coolify.autoupdate') == true) {
echo "Enabling auto-update\n";
$this->settings->update(['is_auto_update_enabled' => true]);
} else {
echo "Disabling auto-update\n";
$this->settings->update(['is_auto_update_enabled' => false]);
}
}
}
private function pullHelperImage()
{
CheckHelperImageJob::dispatch();
}
private function pullTemplatesFromCDN()
{
$response = Http::retry(3, 1000)->get(config('constants.services.official'));
if ($response->successful()) {
$services = $response->json();
File::put(base_path('templates/'.config('constants.services.file_name')), json_encode($services));
}
}
private function pullChangelogFromGitHub()
{
try {
PullChangelog::dispatch();
echo "Changelog fetch initiated\n";
} catch (\Throwable $e) {
echo "Could not fetch changelog from GitHub: {$e->getMessage()}\n";
}
}
private function updateUserEmails()
{
try {
User::whereRaw('email ~ \'[A-Z]\'')->get()->each(function (User $user) {
$user->update(['email' => $user->email]);
});
} catch (\Throwable $e) {
echo "Error in updating user emails: {$e->getMessage()}\n";
}
}
private function updateTraefikLabels()
{
try {
Server::where('proxy->type', 'TRAEFIK_V2')->update(['proxy->type' => 'TRAEFIK']);
} catch (\Throwable $e) {
echo "Error in updating traefik labels: {$e->getMessage()}\n";
}
}
private function cleanupUnusedNetworkFromCoolifyProxy()
{
foreach ($this->servers as $server) {
if (! $server->isFunctional()) {
continue;
}
if (! $server->isProxyShouldRun()) {
continue;
}
try {
['networks' => $networks, 'allNetworks' => $allNetworks] = collectDockerNetworksByServer($server);
$removeNetworks = $allNetworks->diff($networks);
$commands = collect();
foreach ($removeNetworks as $network) {
$out = instant_remote_process(["docker network inspect -f json $network | jq '.[].Containers | if . == {} then null else . end'"], $server, false);
if (empty($out)) {
$commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");
$commands->push("docker network rm $network >/dev/null 2>&1 || true");
} else {
$data = collect(json_decode($out, true));
if ($data->count() === 1) {
// If only coolify-proxy itself is connected to that network (it should not be possible, but who knows)
$isCoolifyProxyItself = data_get($data->first(), 'Name') === 'coolify-proxy';
if ($isCoolifyProxyItself) {
$commands->push("docker network disconnect $network coolify-proxy >/dev/null 2>&1 || true");
$commands->push("docker network rm $network >/dev/null 2>&1 || true");
}
}
}
}
if ($commands->isNotEmpty()) {
remote_process(command: $commands, type: ActivityTypes::INLINE->value, server: $server, ignore_errors: false);
}
} catch (\Throwable $e) {
echo "Error in cleaning up unused networks from coolify proxy: {$e->getMessage()}\n";
}
}
}
private function restoreCoolifyDbBackup()
{
if (version_compare('4.0.0-beta.179', config('constants.coolify.version'), '<=')) {
try {
$database = StandalonePostgresql::withTrashed()->find(0);
if ($database && $database->trashed()) {
$database->restore();
$scheduledBackup = ScheduledDatabaseBackup::find(0);
if (! $scheduledBackup) {
ScheduledDatabaseBackup::create([
'id' => 0,
'enabled' => true,
'save_s3' => false,
'frequency' => '0 0 * * *',
'database_id' => $database->id,
'database_type' => \App\Models\StandalonePostgresql::class,
'team_id' => 0,
]);
}
}
} catch (\Throwable $e) {
echo "Error in restoring coolify db backup: {$e->getMessage()}\n";
}
}
}
private function sendAliveSignal()
{
$id = config('app.id');
$version = config('constants.coolify.version');
try {
Http::get("https://undead.coolify.io/v4/alive?appId=$id&version=$version");
} catch (\Throwable $e) {
echo "Error in sending live signal: {$e->getMessage()}\n";
}
}
private function replaceSlashInEnvironmentName()
{
if (version_compare('4.0.0-beta.298', config('constants.coolify.version'), '<=')) {
$environments = Environment::all();
foreach ($environments as $environment) {
if (str_contains($environment->name, '/')) {
$environment->name = str_replace('/', '-', $environment->name);
$environment->save();
}
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/ServicesDelete.php | app/Console/Commands/ServicesDelete.php | <?php
namespace App\Console\Commands;
use App\Jobs\DeleteResourceJob;
use App\Models\Application;
use App\Models\Server;
use App\Models\Service;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use Illuminate\Console\Command;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\multiselect;
use function Laravel\Prompts\select;
class ServicesDelete extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'services:delete';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Delete a service from the database';
/**
* Execute the console command.
*/
public function handle()
{
$resource = select(
'What service do you want to delete?',
['Application', 'Database', 'Service', 'Server'],
);
if ($resource === 'Application') {
$this->deleteApplication();
} elseif ($resource === 'Database') {
$this->deleteDatabase();
} elseif ($resource === 'Service') {
$this->deleteService();
} elseif ($resource === 'Server') {
$this->deleteServer();
}
}
private function deleteServer()
{
$servers = Server::all();
if ($servers->count() === 0) {
$this->error('There are no applications to delete.');
return;
}
$serversToDelete = multiselect(
label: 'What server do you want to delete?',
options: $servers->pluck('name', 'id')->sortKeys(),
);
foreach ($serversToDelete as $server) {
$toDelete = $servers->where('id', $server)->first();
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources?');
if (! $confirmed) {
break;
}
$toDelete->delete();
}
}
}
private function deleteApplication()
{
$applications = Application::all();
if ($applications->count() === 0) {
$this->error('There are no applications to delete.');
return;
}
$applicationsToDelete = multiselect(
'What application do you want to delete?',
$applications->pluck('name', 'id')->sortKeys(),
);
foreach ($applicationsToDelete as $application) {
$toDelete = $applications->where('id', $application)->first();
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources? ');
if (! $confirmed) {
break;
}
DeleteResourceJob::dispatch($toDelete);
}
}
}
private function deleteDatabase()
{
// Collect all databases from all types with unique identifiers
$allDatabases = collect();
$databaseOptions = collect();
// Add PostgreSQL databases
foreach (StandalonePostgresql::all() as $db) {
$key = "postgresql_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (PostgreSQL)");
}
// Add MySQL databases
foreach (StandaloneMysql::all() as $db) {
$key = "mysql_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (MySQL)");
}
// Add MariaDB databases
foreach (StandaloneMariadb::all() as $db) {
$key = "mariadb_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (MariaDB)");
}
// Add MongoDB databases
foreach (StandaloneMongodb::all() as $db) {
$key = "mongodb_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (MongoDB)");
}
// Add Redis databases
foreach (StandaloneRedis::all() as $db) {
$key = "redis_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (Redis)");
}
// Add KeyDB databases
foreach (StandaloneKeydb::all() as $db) {
$key = "keydb_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (KeyDB)");
}
// Add Dragonfly databases
foreach (StandaloneDragonfly::all() as $db) {
$key = "dragonfly_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (Dragonfly)");
}
// Add ClickHouse databases
foreach (StandaloneClickhouse::all() as $db) {
$key = "clickhouse_{$db->id}";
$allDatabases->put($key, $db);
$databaseOptions->put($key, "{$db->name} (ClickHouse)");
}
if ($allDatabases->count() === 0) {
$this->error('There are no databases to delete.');
return;
}
$databasesToDelete = multiselect(
'What database do you want to delete?',
$databaseOptions->sortKeys(),
);
foreach ($databasesToDelete as $databaseKey) {
$toDelete = $allDatabases->get($databaseKey);
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources?');
if (! $confirmed) {
return;
}
DeleteResourceJob::dispatch($toDelete);
}
}
}
private function deleteService()
{
$services = Service::all();
if ($services->count() === 0) {
$this->error('There are no services to delete.');
return;
}
$servicesToDelete = multiselect(
'What service do you want to delete?',
$services->pluck('name', 'id')->sortKeys(),
);
foreach ($servicesToDelete as $service) {
$toDelete = $services->where('id', $service)->first();
if ($toDelete) {
$this->info($toDelete);
$confirmed = confirm('Are you sure you want to delete all selected resources?');
if (! $confirmed) {
return;
}
DeleteResourceJob::dispatch($toDelete);
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Migration.php | app/Console/Commands/Migration.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Migration extends Command
{
protected $signature = 'start:migration';
protected $description = 'Start Migration';
public function handle()
{
if (config('constants.migration.is_migration_enabled')) {
$this->info('Migration is enabled on this server.');
$this->call('migrate', ['--force' => true, '--isolated' => true]);
exit(0);
} else {
$this->info('Migration is disabled on this server.');
exit(0);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/RootResetPassword.php | app/Console/Commands/RootResetPassword.php | <?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Hash;
use function Laravel\Prompts\password;
class RootResetPassword extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'root:reset-password';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Reset Root Password';
/**
* Execute the console command.
*/
public function handle()
{
$this->info('You are about to reset the root password.');
$password = password('Give me a new password for root user: ');
$passwordAgain = password('Again');
if ($password != $passwordAgain) {
$this->error('Passwords do not match.');
return;
}
$this->info('Updating root password...');
try {
$user = User::find(0);
if (! $user) {
$this->error('Root user not found.');
return;
}
$user->update(['password' => Hash::make($password)]);
$this->info('Root password updated successfully.');
} catch (\Exception $e) {
$this->error('Failed to update root password.');
return;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CleanupUnreachableServers.php | app/Console/Commands/CleanupUnreachableServers.php | <?php
namespace App\Console\Commands;
use App\Models\Server;
use Illuminate\Console\Command;
class CleanupUnreachableServers extends Command
{
protected $signature = 'cleanup:unreachable-servers';
protected $description = 'Cleanup Unreachable Servers (7 days)';
public function handle()
{
echo "Running unreachable server cleanup...\n";
$servers = Server::where('unreachable_count', 3)->where('unreachable_notification_sent', true)->where('updated_at', '<', now()->subDays(7))->get();
if ($servers->count() > 0) {
foreach ($servers as $server) {
echo "Cleanup unreachable server ($server->id) with name $server->name";
$server->update([
'ip' => '1.2.3.4',
]);
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Seeder.php | app/Console/Commands/Seeder.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Seeder extends Command
{
protected $signature = 'start:seeder';
protected $description = 'Start Seeder';
public function handle()
{
if (config('constants.seeder.is_seeder_enabled')) {
$this->info('Seeder is enabled on this server.');
$this->call('db:seed', ['--class' => 'ProductionSeeder', '--force' => true]);
exit(0);
} else {
$this->info('Seeder is disabled on this server.');
exit(0);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CleanupStuckedResources.php | app/Console/Commands/CleanupStuckedResources.php | <?php
namespace App\Console\Commands;
use App\Jobs\CleanupHelperContainersJob;
use App\Jobs\DeleteResourceJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\ApplicationPreview;
use App\Models\ScheduledDatabaseBackup;
use App\Models\ScheduledTask;
use App\Models\Server;
use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
use App\Models\SslCertificate;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\Team;
use Illuminate\Console\Command;
class CleanupStuckedResources extends Command
{
protected $signature = 'cleanup:stucked-resources';
protected $description = 'Cleanup Stucked Resources';
public function handle()
{
$this->cleanup_stucked_resources();
}
private function cleanup_stucked_resources()
{
try {
$teams = Team::all()->filter(function ($team) {
return $team->members()->count() === 0 && $team->servers()->count() === 0;
});
foreach ($teams as $team) {
$team->delete();
}
$servers = Server::all()->filter(function ($server) {
return $server->isFunctional();
});
if (isCloud()) {
$servers = $servers->filter(function ($server) {
return data_get($server->team->subscription, 'stripe_invoice_paid', false) === true;
});
}
foreach ($servers as $server) {
CleanupHelperContainersJob::dispatch($server);
}
} catch (\Throwable $e) {
echo "Error in cleaning stucked resources: {$e->getMessage()}\n";
}
try {
$servers = Server::onlyTrashed()->get();
foreach ($servers as $server) {
echo "Force deleting stuck server: {$server->name}\n";
$server->forceDelete();
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck servers: {$e->getMessage()}\n";
}
try {
$applicationsDeploymentQueue = ApplicationDeploymentQueue::get();
foreach ($applicationsDeploymentQueue as $applicationDeploymentQueue) {
if (is_null($applicationDeploymentQueue->application)) {
echo "Deleting stuck application deployment queue: {$applicationDeploymentQueue->id}\n";
$applicationDeploymentQueue->delete();
}
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck application deployment queue: {$e->getMessage()}\n";
}
try {
$applications = Application::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($applications as $application) {
echo "Deleting stuck application: {$application->name}\n";
DeleteResourceJob::dispatch($application);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck application: {$e->getMessage()}\n";
}
try {
$applicationsPreviews = ApplicationPreview::get();
foreach ($applicationsPreviews as $applicationPreview) {
if (! data_get($applicationPreview, 'application')) {
echo "Deleting stuck application preview: {$applicationPreview->uuid}\n";
DeleteResourceJob::dispatch($applicationPreview);
}
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck application: {$e->getMessage()}\n";
}
try {
$applicationsPreviews = ApplicationPreview::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($applicationsPreviews as $applicationPreview) {
echo "Deleting stuck application preview: {$applicationPreview->fqdn}\n";
DeleteResourceJob::dispatch($applicationPreview);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck application: {$e->getMessage()}\n";
}
try {
$postgresqls = StandalonePostgresql::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($postgresqls as $postgresql) {
echo "Deleting stuck postgresql: {$postgresql->name}\n";
DeleteResourceJob::dispatch($postgresql);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck postgresql: {$e->getMessage()}\n";
}
try {
$rediss = StandaloneRedis::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($rediss as $redis) {
echo "Deleting stuck redis: {$redis->name}\n";
DeleteResourceJob::dispatch($redis);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck redis: {$e->getMessage()}\n";
}
try {
$keydbs = StandaloneKeydb::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($keydbs as $keydb) {
echo "Deleting stuck keydb: {$keydb->name}\n";
DeleteResourceJob::dispatch($keydb);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck keydb: {$e->getMessage()}\n";
}
try {
$dragonflies = StandaloneDragonfly::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($dragonflies as $dragonfly) {
echo "Deleting stuck dragonfly: {$dragonfly->name}\n";
DeleteResourceJob::dispatch($dragonfly);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck dragonfly: {$e->getMessage()}\n";
}
try {
$clickhouses = StandaloneClickhouse::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($clickhouses as $clickhouse) {
echo "Deleting stuck clickhouse: {$clickhouse->name}\n";
DeleteResourceJob::dispatch($clickhouse);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck clickhouse: {$e->getMessage()}\n";
}
try {
$mongodbs = StandaloneMongodb::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($mongodbs as $mongodb) {
echo "Deleting stuck mongodb: {$mongodb->name}\n";
DeleteResourceJob::dispatch($mongodb);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck mongodb: {$e->getMessage()}\n";
}
try {
$mysqls = StandaloneMysql::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($mysqls as $mysql) {
echo "Deleting stuck mysql: {$mysql->name}\n";
DeleteResourceJob::dispatch($mysql);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck mysql: {$e->getMessage()}\n";
}
try {
$mariadbs = StandaloneMariadb::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($mariadbs as $mariadb) {
echo "Deleting stuck mariadb: {$mariadb->name}\n";
DeleteResourceJob::dispatch($mariadb);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck mariadb: {$e->getMessage()}\n";
}
try {
$services = Service::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($services as $service) {
echo "Deleting stuck service: {$service->name}\n";
DeleteResourceJob::dispatch($service);
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck service: {$e->getMessage()}\n";
}
try {
$serviceApps = ServiceApplication::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($serviceApps as $serviceApp) {
echo "Deleting stuck serviceapp: {$serviceApp->name}\n";
$serviceApp->forceDelete();
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck serviceapp: {$e->getMessage()}\n";
}
try {
$serviceDbs = ServiceDatabase::withTrashed()->whereNotNull('deleted_at')->get();
foreach ($serviceDbs as $serviceDb) {
echo "Deleting stuck serviceapp: {$serviceDb->name}\n";
$serviceDb->forceDelete();
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck serviceapp: {$e->getMessage()}\n";
}
try {
$scheduled_tasks = ScheduledTask::all();
foreach ($scheduled_tasks as $scheduled_task) {
if (! $scheduled_task->service && ! $scheduled_task->application) {
echo "Deleting stuck scheduledtask: {$scheduled_task->name}\n";
$scheduled_task->delete();
}
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck scheduledtasks: {$e->getMessage()}\n";
}
try {
$scheduled_backups = ScheduledDatabaseBackup::all();
foreach ($scheduled_backups as $scheduled_backup) {
try {
$server = $scheduled_backup->server();
if (! $server) {
echo "Deleting stuck scheduledbackup: {$scheduled_backup->name}\n";
$scheduled_backup->delete();
}
} catch (\Throwable $e) {
echo "Error checking server for scheduledbackup {$scheduled_backup->id}: {$e->getMessage()}\n";
}
}
} catch (\Throwable $e) {
echo "Error in cleaning stuck scheduledbackups: {$e->getMessage()}\n";
}
// Cleanup any resources that are not attached to any environment or destination or server
try {
$applications = Application::all();
foreach ($applications as $application) {
if (! data_get($application, 'environment')) {
echo 'Application without environment: '.$application->name.'\n';
DeleteResourceJob::dispatch($application);
continue;
}
if (! $application->destination()) {
echo 'Application without destination: '.$application->name.'\n';
DeleteResourceJob::dispatch($application);
continue;
}
if (! data_get($application, 'destination.server')) {
echo 'Application without server: '.$application->name.'\n';
DeleteResourceJob::dispatch($application);
continue;
}
}
} catch (\Throwable $e) {
echo "Error in application: {$e->getMessage()}\n";
}
try {
$postgresqls = StandalonePostgresql::all()->where('id', '!=', 0);
foreach ($postgresqls as $postgresql) {
if (! data_get($postgresql, 'environment')) {
echo 'Postgresql without environment: '.$postgresql->name.'\n';
DeleteResourceJob::dispatch($postgresql);
continue;
}
if (! $postgresql->destination()) {
echo 'Postgresql without destination: '.$postgresql->name.'\n';
DeleteResourceJob::dispatch($postgresql);
continue;
}
if (! data_get($postgresql, 'destination.server')) {
echo 'Postgresql without server: '.$postgresql->name.'\n';
DeleteResourceJob::dispatch($postgresql);
continue;
}
}
} catch (\Throwable $e) {
echo "Error in postgresql: {$e->getMessage()}\n";
}
try {
$redis = StandaloneRedis::all();
foreach ($redis as $redis) {
if (! data_get($redis, 'environment')) {
echo 'Redis without environment: '.$redis->name.'\n';
DeleteResourceJob::dispatch($redis);
continue;
}
if (! $redis->destination()) {
echo 'Redis without destination: '.$redis->name.'\n';
DeleteResourceJob::dispatch($redis);
continue;
}
if (! data_get($redis, 'destination.server')) {
echo 'Redis without server: '.$redis->name.'\n';
DeleteResourceJob::dispatch($redis);
continue;
}
}
} catch (\Throwable $e) {
echo "Error in redis: {$e->getMessage()}\n";
}
try {
$mongodbs = StandaloneMongodb::all();
foreach ($mongodbs as $mongodb) {
if (! data_get($mongodb, 'environment')) {
echo 'Mongodb without environment: '.$mongodb->name.'\n';
DeleteResourceJob::dispatch($mongodb);
continue;
}
if (! $mongodb->destination()) {
echo 'Mongodb without destination: '.$mongodb->name.'\n';
DeleteResourceJob::dispatch($mongodb);
continue;
}
if (! data_get($mongodb, 'destination.server')) {
echo 'Mongodb without server: '.$mongodb->name.'\n';
DeleteResourceJob::dispatch($mongodb);
continue;
}
}
} catch (\Throwable $e) {
echo "Error in mongodb: {$e->getMessage()}\n";
}
try {
$mysqls = StandaloneMysql::all();
foreach ($mysqls as $mysql) {
if (! data_get($mysql, 'environment')) {
echo 'Mysql without environment: '.$mysql->name.'\n';
DeleteResourceJob::dispatch($mysql);
continue;
}
if (! $mysql->destination()) {
echo 'Mysql without destination: '.$mysql->name.'\n';
DeleteResourceJob::dispatch($mysql);
continue;
}
if (! data_get($mysql, 'destination.server')) {
echo 'Mysql without server: '.$mysql->name.'\n';
DeleteResourceJob::dispatch($mysql);
continue;
}
}
} catch (\Throwable $e) {
echo "Error in mysql: {$e->getMessage()}\n";
}
try {
$mariadbs = StandaloneMariadb::all();
foreach ($mariadbs as $mariadb) {
if (! data_get($mariadb, 'environment')) {
echo 'Mariadb without environment: '.$mariadb->name.'\n';
DeleteResourceJob::dispatch($mariadb);
continue;
}
if (! $mariadb->destination()) {
echo 'Mariadb without destination: '.$mariadb->name.'\n';
DeleteResourceJob::dispatch($mariadb);
continue;
}
if (! data_get($mariadb, 'destination.server')) {
echo 'Mariadb without server: '.$mariadb->name.'\n';
DeleteResourceJob::dispatch($mariadb);
continue;
}
}
} catch (\Throwable $e) {
echo "Error in mariadb: {$e->getMessage()}\n";
}
try {
$services = Service::all();
foreach ($services as $service) {
if (! data_get($service, 'environment')) {
echo 'Service without environment: '.$service->name.'\n';
DeleteResourceJob::dispatch($service);
continue;
}
if (! $service->destination()) {
echo 'Service without destination: '.$service->name.'\n';
DeleteResourceJob::dispatch($service);
continue;
}
if (! data_get($service, 'server')) {
echo 'Service without server: '.$service->name.'\n';
DeleteResourceJob::dispatch($service);
continue;
}
}
} catch (\Throwable $e) {
echo "Error in service: {$e->getMessage()}\n";
}
try {
$serviceApplications = ServiceApplication::all();
foreach ($serviceApplications as $service) {
if (! data_get($service, 'service')) {
echo 'ServiceApplication without service: '.$service->name.'\n';
$service->forceDelete();
continue;
}
}
} catch (\Throwable $e) {
echo "Error in serviceApplications: {$e->getMessage()}\n";
}
try {
$serviceDatabases = ServiceDatabase::all();
foreach ($serviceDatabases as $service) {
if (! data_get($service, 'service')) {
echo 'ServiceDatabase without service: '.$service->name.'\n';
$service->forceDelete();
continue;
}
}
} catch (\Throwable $e) {
echo "Error in ServiceDatabases: {$e->getMessage()}\n";
}
try {
$orphanedCerts = SslCertificate::whereNotIn('server_id', function ($query) {
$query->select('id')->from('servers');
})->get();
foreach ($orphanedCerts as $cert) {
echo "Deleting orphaned SSL certificate: {$cert->id} (server_id: {$cert->server_id})\n";
$cert->delete();
}
} catch (\Throwable $e) {
echo "Error in cleaning orphaned SSL certificates: {$e->getMessage()}\n";
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/ViewScheduledLogs.php | app/Console/Commands/ViewScheduledLogs.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
class ViewScheduledLogs extends Command
{
protected $signature = 'logs:scheduled
{--lines=50 : Number of lines to display}
{--follow : Follow the log file (tail -f)}
{--date= : Specific date (Y-m-d format, defaults to today)}
{--task-name= : Filter by task name (partial match)}
{--task-id= : Filter by task ID}
{--backup-name= : Filter by backup name (partial match)}
{--backup-id= : Filter by backup ID}
{--errors : View error logs only}
{--all : View both normal and error logs}
{--hourly : Filter hourly jobs}
{--daily : Filter daily jobs}
{--weekly : Filter weekly jobs}
{--monthly : Filter monthly jobs}
{--frequency= : Filter by specific cron expression}';
protected $description = 'View scheduled backups and tasks logs with optional filtering';
public function handle()
{
$date = $this->option('date') ?: now()->format('Y-m-d');
$logPaths = $this->getLogPaths($date);
if (empty($logPaths)) {
$this->showAvailableLogFiles($date);
return;
}
$lines = $this->option('lines');
$follow = $this->option('follow');
// Build grep filters
$filters = $this->buildFilters();
$filterDescription = $this->getFilterDescription();
$logTypeDescription = $this->getLogTypeDescription();
if ($follow) {
$this->info("Following {$logTypeDescription} logs for {$date}{$filterDescription} (Press Ctrl+C to stop)...");
$this->line('');
if (count($logPaths) === 1) {
$logPath = $logPaths[0];
if ($filters) {
passthru("tail -f {$logPath} | grep -E '{$filters}'");
} else {
passthru("tail -f {$logPath}");
}
} else {
// Multiple files - use multitail or tail with process substitution
$logPathsStr = implode(' ', $logPaths);
if ($filters) {
passthru("tail -f {$logPathsStr} | grep -E '{$filters}'");
} else {
passthru("tail -f {$logPathsStr}");
}
}
} else {
$this->info("Showing last {$lines} lines of {$logTypeDescription} logs for {$date}{$filterDescription}:");
$this->line('');
if (count($logPaths) === 1) {
$logPath = $logPaths[0];
if ($filters) {
passthru("tail -n {$lines} {$logPath} | grep -E '{$filters}'");
} else {
passthru("tail -n {$lines} {$logPath}");
}
} else {
// Multiple files - concatenate and sort by timestamp
$logPathsStr = implode(' ', $logPaths);
if ($filters) {
passthru("tail -n {$lines} {$logPathsStr} | sort | grep -E '{$filters}'");
} else {
passthru("tail -n {$lines} {$logPathsStr} | sort");
}
}
}
}
private function getLogPaths(string $date): array
{
$paths = [];
if ($this->option('errors')) {
// Error logs only
$errorPath = storage_path("logs/scheduled-errors-{$date}.log");
if (File::exists($errorPath)) {
$paths[] = $errorPath;
}
} elseif ($this->option('all')) {
// Both normal and error logs
$normalPath = storage_path("logs/scheduled-{$date}.log");
$errorPath = storage_path("logs/scheduled-errors-{$date}.log");
if (File::exists($normalPath)) {
$paths[] = $normalPath;
}
if (File::exists($errorPath)) {
$paths[] = $errorPath;
}
} else {
// Normal logs only (default)
$normalPath = storage_path("logs/scheduled-{$date}.log");
if (File::exists($normalPath)) {
$paths[] = $normalPath;
}
}
return $paths;
}
private function showAvailableLogFiles(string $date): void
{
$logType = $this->getLogTypeDescription();
$this->warn("No {$logType} logs found for date {$date}");
// Show available log files
$normalFiles = File::glob(storage_path('logs/scheduled-*.log'));
$errorFiles = File::glob(storage_path('logs/scheduled-errors-*.log'));
if (! empty($normalFiles) || ! empty($errorFiles)) {
$this->info('Available scheduled log files:');
if (! empty($normalFiles)) {
$this->line(' Normal logs:');
foreach ($normalFiles as $file) {
$basename = basename($file);
$this->line(" - {$basename}");
}
}
if (! empty($errorFiles)) {
$this->line(' Error logs:');
foreach ($errorFiles as $file) {
$basename = basename($file);
$this->line(" - {$basename}");
}
}
}
}
private function getLogTypeDescription(): string
{
if ($this->option('errors')) {
return 'error';
} elseif ($this->option('all')) {
return 'all';
} else {
return 'normal';
}
}
private function buildFilters(): ?string
{
$filters = [];
if ($taskName = $this->option('task-name')) {
$filters[] = '"task_name":"[^"]*'.preg_quote($taskName, '/').'[^"]*"';
}
if ($taskId = $this->option('task-id')) {
$filters[] = '"task_id":'.preg_quote($taskId, '/');
}
if ($backupName = $this->option('backup-name')) {
$filters[] = '"backup_name":"[^"]*'.preg_quote($backupName, '/').'[^"]*"';
}
if ($backupId = $this->option('backup-id')) {
$filters[] = '"backup_id":'.preg_quote($backupId, '/');
}
// Frequency filters
if ($this->option('hourly')) {
$filters[] = $this->getFrequencyPattern('hourly');
}
if ($this->option('daily')) {
$filters[] = $this->getFrequencyPattern('daily');
}
if ($this->option('weekly')) {
$filters[] = $this->getFrequencyPattern('weekly');
}
if ($this->option('monthly')) {
$filters[] = $this->getFrequencyPattern('monthly');
}
if ($frequency = $this->option('frequency')) {
$filters[] = '"frequency":"'.preg_quote($frequency, '/').'"';
}
return empty($filters) ? null : implode('|', $filters);
}
private function getFrequencyPattern(string $type): string
{
$patterns = [
'hourly' => [
'0 \* \* \* \*', // 0 * * * *
'@hourly', // @hourly
],
'daily' => [
'0 0 \* \* \*', // 0 0 * * *
'@daily', // @daily
'@midnight', // @midnight
],
'weekly' => [
'0 0 \* \* [0-6]', // 0 0 * * 0-6 (any day of week)
'@weekly', // @weekly
],
'monthly' => [
'0 0 1 \* \*', // 0 0 1 * * (first of month)
'@monthly', // @monthly
],
];
$typePatterns = $patterns[$type] ?? [];
// For grep, we need to match the frequency field in JSON
return '"frequency":"('.implode('|', $typePatterns).')"';
}
private function getFilterDescription(): string
{
$descriptions = [];
if ($taskName = $this->option('task-name')) {
$descriptions[] = "task name: {$taskName}";
}
if ($taskId = $this->option('task-id')) {
$descriptions[] = "task ID: {$taskId}";
}
if ($backupName = $this->option('backup-name')) {
$descriptions[] = "backup name: {$backupName}";
}
if ($backupId = $this->option('backup-id')) {
$descriptions[] = "backup ID: {$backupId}";
}
// Frequency filters
if ($this->option('hourly')) {
$descriptions[] = 'hourly jobs';
}
if ($this->option('daily')) {
$descriptions[] = 'daily jobs';
}
if ($this->option('weekly')) {
$descriptions[] = 'weekly jobs';
}
if ($this->option('monthly')) {
$descriptions[] = 'monthly jobs';
}
if ($frequency = $this->option('frequency')) {
$descriptions[] = "frequency: {$frequency}";
}
return empty($descriptions) ? '' : ' (filtered by '.implode(', ', $descriptions).')';
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/HorizonManage.php | app/Console/Commands/HorizonManage.php | <?php
namespace App\Console\Commands;
use App\Enums\ApplicationDeploymentStatus;
use App\Models\ApplicationDeploymentQueue;
use App\Repositories\CustomJobRepository;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Laravel\Horizon\Contracts\JobRepository;
use Laravel\Horizon\Contracts\MetricsRepository;
use Laravel\Horizon\Repositories\RedisJobRepository;
use function Laravel\Prompts\multiselect;
use function Laravel\Prompts\select;
use function Laravel\Prompts\table;
use function Laravel\Prompts\text;
class HorizonManage extends Command
{
protected $signature = 'horizon:manage {--can-i-restart-this-worker} {--job-status=}';
protected $description = 'Manage horizon';
public function handle()
{
if ($this->option('can-i-restart-this-worker')) {
return $this->isThereAJobInProgress();
}
if ($this->option('job-status')) {
return $this->getJobStatus($this->option('job-status'));
}
$action = select(
label: 'What to do?',
options: [
'pending' => 'Pending Jobs',
'running' => 'Running Jobs',
'can-i-restart-this-worker' => 'Can I restart this worker?',
'job-status' => 'Job Status',
'workers' => 'Workers',
'failed' => 'Failed Jobs',
'failed-delete' => 'Failed Jobs - Delete',
'purge-queues' => 'Purge Queues',
]
);
if ($action === 'can-i-restart-this-worker') {
$this->isThereAJobInProgress();
}
if ($action === 'job-status') {
$jobId = text('Which job to check?');
$jobStatus = $this->getJobStatus($jobId);
$this->info('Job Status: '.$jobStatus);
}
if ($action === 'pending') {
$pendingJobs = app(JobRepository::class)->getPending();
$pendingJobsTable = [];
if (count($pendingJobs) === 0) {
$this->info('No pending jobs found.');
return;
}
foreach ($pendingJobs as $pendingJob) {
$pendingJobsTable[] = [
'id' => $pendingJob->id,
'name' => $pendingJob->name,
'status' => $pendingJob->status,
'reserved_at' => $pendingJob->reserved_at ? now()->parse($pendingJob->reserved_at)->format('Y-m-d H:i:s') : null,
];
}
table($pendingJobsTable);
}
if ($action === 'failed') {
$failedJobs = app(JobRepository::class)->getFailed();
$failedJobsTable = [];
if (count($failedJobs) === 0) {
$this->info('No failed jobs found.');
return;
}
foreach ($failedJobs as $failedJob) {
$failedJobsTable[] = [
'id' => $failedJob->id,
'name' => $failedJob->name,
'failed_at' => $failedJob->failed_at ? now()->parse($failedJob->failed_at)->format('Y-m-d H:i:s') : null,
];
}
table($failedJobsTable);
}
if ($action === 'failed-delete') {
$failedJobs = app(JobRepository::class)->getFailed();
$failedJobsTable = [];
foreach ($failedJobs as $failedJob) {
$failedJobsTable[] = [
'id' => $failedJob->id,
'name' => $failedJob->name,
'failed_at' => $failedJob->failed_at ? now()->parse($failedJob->failed_at)->format('Y-m-d H:i:s') : null,
];
}
app(MetricsRepository::class)->clear();
if (count($failedJobsTable) === 0) {
$this->info('No failed jobs found.');
return;
}
$jobIds = multiselect(
label: 'Which job to delete?',
options: collect($failedJobsTable)->mapWithKeys(fn ($job) => [$job['id'] => $job['id'].' - '.$job['name']])->toArray(),
);
foreach ($jobIds as $jobId) {
Artisan::queue('horizon:forget', ['id' => $jobId]);
}
}
if ($action === 'running') {
$redisJobRepository = app(CustomJobRepository::class);
$runningJobs = $redisJobRepository->getReservedJobs();
$runningJobsTable = [];
if (count($runningJobs) === 0) {
$this->info('No running jobs found.');
return;
}
foreach ($runningJobs as $runningJob) {
$runningJobsTable[] = [
'id' => $runningJob->id,
'name' => $runningJob->name,
'reserved_at' => $runningJob->reserved_at ? now()->parse($runningJob->reserved_at)->format('Y-m-d H:i:s') : null,
];
}
table($runningJobsTable);
}
if ($action === 'workers') {
$redisJobRepository = app(CustomJobRepository::class);
$workers = $redisJobRepository->getHorizonWorkers();
$workersTable = [];
foreach ($workers as $worker) {
$workersTable[] = [
'name' => $worker->name,
];
}
table($workersTable);
}
if ($action === 'purge-queues') {
$getQueues = app(CustomJobRepository::class)->getQueues();
$queueName = select(
label: 'Which queue to purge?',
options: $getQueues,
);
$redisJobRepository = app(RedisJobRepository::class);
$redisJobRepository->purge($queueName);
}
}
public function isThereAJobInProgress()
{
$runningJobs = ApplicationDeploymentQueue::where('horizon_job_worker', gethostname())->where('status', ApplicationDeploymentStatus::IN_PROGRESS->value)->get();
$count = $runningJobs->count();
if ($count === 0) {
return false;
}
return true;
}
public function getJobStatus(string $jobId)
{
return getJobStatus($jobId);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/RootChangeEmail.php | app/Console/Commands/RootChangeEmail.php | <?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Command;
class RootChangeEmail extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'root:change-email';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Change Root Email';
/**
* Execute the console command.
*/
public function handle()
{
//
$this->info('You are about to change the root user\'s email.');
$email = $this->ask('Give me a new email for root user');
$this->info('Updating root email...');
try {
User::find(0)->update(['email' => $email]);
$this->info('Root user\'s email updated successfully.');
} catch (\Exception $e) {
$this->error('Failed to update root user\'s email.');
return;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CleanupRedis.php | app/Console/Commands/CleanupRedis.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;
class CleanupRedis extends Command
{
protected $signature = 'cleanup:redis {--dry-run : Show what would be deleted without actually deleting} {--skip-overlapping : Skip overlapping queue cleanup} {--clear-locks : Clear stale WithoutOverlapping locks} {--restart : Aggressive cleanup mode for system restart (marks all processing jobs as failed)}';
protected $description = 'Cleanup Redis (Horizon jobs, metrics, overlapping queues, cache locks, and related data)';
public function handle()
{
$redis = Redis::connection('horizon');
$prefix = config('horizon.prefix');
$dryRun = $this->option('dry-run');
$skipOverlapping = $this->option('skip-overlapping');
$deletedCount = 0;
$totalKeys = 0;
// Get all keys with the horizon prefix
$keys = $redis->keys('*');
$totalKeys = count($keys);
foreach ($keys as $key) {
$keyWithoutPrefix = str_replace($prefix, '', $key);
$type = $redis->command('type', [$keyWithoutPrefix]);
// Handle hash-type keys (individual jobs)
if ($type === 5) {
if ($this->shouldDeleteHashKey($redis, $keyWithoutPrefix, $dryRun)) {
$deletedCount++;
}
}
// Handle other key types (metrics, lists, etc.)
else {
if ($this->shouldDeleteOtherKey($redis, $keyWithoutPrefix, $key, $dryRun)) {
$deletedCount++;
}
}
}
// Clean up overlapping queues if not skipped
if (! $skipOverlapping) {
$overlappingCleaned = $this->cleanupOverlappingQueues($redis, $prefix, $dryRun);
$deletedCount += $overlappingCleaned;
}
// Clean up stale cache locks (WithoutOverlapping middleware)
if ($this->option('clear-locks')) {
$locksCleaned = $this->cleanupCacheLocks($dryRun);
$deletedCount += $locksCleaned;
}
// Clean up stuck jobs (restart mode = aggressive, runtime mode = conservative)
$isRestart = $this->option('restart');
if ($isRestart || $this->option('clear-locks')) {
$jobsCleaned = $this->cleanupStuckJobs($redis, $prefix, $dryRun, $isRestart);
$deletedCount += $jobsCleaned;
}
if ($dryRun) {
$this->info("Redis cleanup: would delete {$deletedCount} items");
} else {
$this->info("Redis cleanup: deleted {$deletedCount} items");
}
}
private function shouldDeleteHashKey($redis, $keyWithoutPrefix, $dryRun)
{
$data = $redis->command('hgetall', [$keyWithoutPrefix]);
$status = data_get($data, 'status');
// Delete completed and failed jobs
if (in_array($status, ['completed', 'failed'])) {
if (! $dryRun) {
$redis->command('del', [$keyWithoutPrefix]);
}
return true;
}
return false;
}
private function shouldDeleteOtherKey($redis, $keyWithoutPrefix, $fullKey, $dryRun)
{
// Clean up various Horizon data structures
$patterns = [
'recent_jobs' => 'Recent jobs list',
'failed_jobs' => 'Failed jobs list',
'completed_jobs' => 'Completed jobs list',
'job_classes' => 'Job classes metrics',
'queues' => 'Queue metrics',
'processes' => 'Process metrics',
'supervisors' => 'Supervisor data',
'metrics' => 'General metrics',
'workload' => 'Workload data',
];
foreach ($patterns as $pattern => $description) {
if (str_contains($keyWithoutPrefix, $pattern)) {
if (! $dryRun) {
$redis->command('del', [$keyWithoutPrefix]);
}
return true;
}
}
// Clean up old timestamped data (older than 7 days)
if (preg_match('/(\d{10})/', $keyWithoutPrefix, $matches)) {
$timestamp = (int) $matches[1];
$weekAgo = now()->subDays(7)->timestamp;
if ($timestamp < $weekAgo) {
if (! $dryRun) {
$redis->command('del', [$keyWithoutPrefix]);
}
return true;
}
}
return false;
}
private function cleanupOverlappingQueues($redis, $prefix, $dryRun)
{
$cleanedCount = 0;
$queueKeys = [];
// Find all queue-related keys
$allKeys = $redis->keys('*');
foreach ($allKeys as $key) {
$keyWithoutPrefix = str_replace($prefix, '', $key);
if (str_contains($keyWithoutPrefix, 'queue:') || preg_match('/queues?[:\-]/', $keyWithoutPrefix)) {
$queueKeys[] = $keyWithoutPrefix;
}
}
// Group queues by name pattern to find duplicates
$queueGroups = [];
foreach ($queueKeys as $queueKey) {
// Extract queue name (remove timestamps, suffixes)
$baseName = preg_replace('/[:\-]\d+$/', '', $queueKey);
$baseName = preg_replace('/[:\-](pending|reserved|delayed|processing)$/', '', $baseName);
if (! isset($queueGroups[$baseName])) {
$queueGroups[$baseName] = [];
}
$queueGroups[$baseName][] = $queueKey;
}
// Process each group for overlaps
foreach ($queueGroups as $baseName => $keys) {
if (count($keys) > 1) {
$cleanedCount += $this->deduplicateQueueGroup($redis, $baseName, $keys, $dryRun);
}
// Also check for duplicate jobs within individual queues
foreach ($keys as $queueKey) {
$cleanedCount += $this->deduplicateQueueContents($redis, $queueKey, $dryRun);
}
}
return $cleanedCount;
}
private function deduplicateQueueGroup($redis, $baseName, $keys, $dryRun)
{
$cleanedCount = 0;
// Sort keys to keep the most recent one
usort($keys, function ($a, $b) {
// Prefer keys without timestamps (they're usually the main queue)
$aHasTimestamp = preg_match('/\d{10}/', $a);
$bHasTimestamp = preg_match('/\d{10}/', $b);
if ($aHasTimestamp && ! $bHasTimestamp) {
return 1;
}
if (! $aHasTimestamp && $bHasTimestamp) {
return -1;
}
// If both have timestamps, prefer the newer one
if ($aHasTimestamp && $bHasTimestamp) {
preg_match('/(\d{10})/', $a, $aMatches);
preg_match('/(\d{10})/', $b, $bMatches);
return ($bMatches[1] ?? 0) <=> ($aMatches[1] ?? 0);
}
return strcmp($a, $b);
});
// Keep the first (preferred) key, remove others that are empty or redundant
$keepKey = array_shift($keys);
foreach ($keys as $redundantKey) {
$type = $redis->command('type', [$redundantKey]);
$shouldDelete = false;
if ($type === 1) { // LIST type
$length = $redis->command('llen', [$redundantKey]);
if ($length == 0) {
$shouldDelete = true;
}
} elseif ($type === 3) { // SET type
$count = $redis->command('scard', [$redundantKey]);
if ($count == 0) {
$shouldDelete = true;
}
} elseif ($type === 4) { // ZSET type
$count = $redis->command('zcard', [$redundantKey]);
if ($count == 0) {
$shouldDelete = true;
}
}
if ($shouldDelete) {
if (! $dryRun) {
$redis->command('del', [$redundantKey]);
}
$cleanedCount++;
}
}
return $cleanedCount;
}
private function deduplicateQueueContents($redis, $queueKey, $dryRun)
{
$cleanedCount = 0;
$type = $redis->command('type', [$queueKey]);
if ($type === 1) { // LIST type - common for job queues
$length = $redis->command('llen', [$queueKey]);
if ($length > 1) {
$items = $redis->command('lrange', [$queueKey, 0, -1]);
$uniqueItems = array_unique($items);
if (count($uniqueItems) < count($items)) {
$duplicates = count($items) - count($uniqueItems);
if (! $dryRun) {
// Rebuild the list with unique items
$redis->command('del', [$queueKey]);
foreach (array_reverse($uniqueItems) as $item) {
$redis->command('lpush', [$queueKey, $item]);
}
}
$cleanedCount += $duplicates;
}
}
}
return $cleanedCount;
}
private function cleanupCacheLocks(bool $dryRun): int
{
$cleanedCount = 0;
// Use the default Redis connection (database 0) where cache locks are stored
$redis = Redis::connection('default');
// Get all keys matching WithoutOverlapping lock pattern
$allKeys = $redis->keys('*');
$lockKeys = [];
foreach ($allKeys as $key) {
// Match cache lock keys: they contain 'laravel-queue-overlap'
if (preg_match('/overlap/i', $key)) {
$lockKeys[] = $key;
}
}
if (empty($lockKeys)) {
return 0;
}
foreach ($lockKeys as $lockKey) {
// Check TTL to identify stale locks
$ttl = $redis->ttl($lockKey);
// TTL = -1 means no expiration (stale lock!)
// TTL = -2 means key doesn't exist
// TTL > 0 means lock is valid and will expire
if ($ttl === -1) {
if ($dryRun) {
$this->warn(" Would delete STALE lock (no expiration): {$lockKey}");
} else {
$redis->del($lockKey);
}
$cleanedCount++;
}
}
return $cleanedCount;
}
/**
* Clean up stuck jobs based on mode (restart vs runtime).
*
* @param mixed $redis Redis connection
* @param string $prefix Horizon prefix
* @param bool $dryRun Dry run mode
* @param bool $isRestart Restart mode (aggressive) vs runtime mode (conservative)
* @return int Number of jobs cleaned
*/
private function cleanupStuckJobs($redis, string $prefix, bool $dryRun, bool $isRestart): int
{
$cleanedCount = 0;
$now = time();
// Get all keys with the horizon prefix
$cursor = 0;
$keys = [];
do {
$result = $redis->scan($cursor, ['match' => '*', 'count' => 100]);
// Guard against scan() returning false
if ($result === false) {
$this->error('Redis scan failed, stopping key retrieval');
break;
}
$cursor = $result[0];
$keys = array_merge($keys, $result[1]);
} while ($cursor !== 0);
foreach ($keys as $key) {
$keyWithoutPrefix = str_replace($prefix, '', $key);
$type = $redis->command('type', [$keyWithoutPrefix]);
// Only process hash-type keys (individual jobs)
if ($type !== 5) {
continue;
}
$data = $redis->command('hgetall', [$keyWithoutPrefix]);
$status = data_get($data, 'status');
$payload = data_get($data, 'payload');
// Only process jobs in "processing" or "reserved" state
if (! in_array($status, ['processing', 'reserved'])) {
continue;
}
// Parse job payload to get job class and started time
$payloadData = json_decode($payload, true);
// Check for JSON decode errors
if ($payloadData === null || json_last_error() !== JSON_ERROR_NONE) {
$errorMsg = json_last_error_msg();
$truncatedPayload = is_string($payload) ? substr($payload, 0, 200) : 'non-string payload';
$this->error("Failed to decode job payload for {$keyWithoutPrefix}: {$errorMsg}. Payload: {$truncatedPayload}");
continue;
}
$jobClass = data_get($payloadData, 'displayName', 'Unknown');
// Prefer reserved_at (when job started processing), fallback to created_at
$reservedAt = (int) data_get($data, 'reserved_at', 0);
$createdAt = (int) data_get($data, 'created_at', 0);
$startTime = $reservedAt ?: $createdAt;
// If we can't determine when the job started, skip it
if (! $startTime) {
continue;
}
// Calculate how long the job has been processing
$processingTime = $now - $startTime;
$shouldFail = false;
$reason = '';
if ($isRestart) {
// RESTART MODE: Mark ALL processing/reserved jobs as failed
// Safe because all workers are dead on restart
$shouldFail = true;
$reason = 'System restart - all workers terminated';
} else {
// RUNTIME MODE: Only mark truly stuck jobs as failed
// Be conservative to avoid killing legitimate long-running jobs
// Skip ApplicationDeploymentJob entirely (has dynamic_timeout, can run 2+ hours)
if (str_contains($jobClass, 'ApplicationDeploymentJob')) {
continue;
}
// Skip DatabaseBackupJob (large backups can take hours)
if (str_contains($jobClass, 'DatabaseBackupJob')) {
continue;
}
// For other jobs, only fail if processing > 12 hours
if ($processingTime > 43200) { // 12 hours
$shouldFail = true;
$reason = 'Processing for more than 12 hours';
}
}
if ($shouldFail) {
if ($dryRun) {
$this->warn(" Would mark as FAILED: {$jobClass} (processing for ".round($processingTime / 60, 1)." min) - {$reason}");
} else {
// Mark job as failed
$redis->command('hset', [$keyWithoutPrefix, 'status', 'failed']);
$redis->command('hset', [$keyWithoutPrefix, 'failed_at', $now]);
$redis->command('hset', [$keyWithoutPrefix, 'exception', "Job cleaned up by cleanup:redis - {$reason}"]);
}
$cleanedCount++;
}
}
return $cleanedCount;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Horizon.php | app/Console/Commands/Horizon.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Horizon extends Command
{
protected $signature = 'start:horizon';
protected $description = 'Start Horizon';
public function handle()
{
if (config('constants.horizon.is_horizon_enabled')) {
$this->info('Horizon is enabled on this server.');
$this->call('horizon');
exit(0);
} else {
exit(0);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/UpdateServiceVersions.php | app/Console/Commands/UpdateServiceVersions.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use Symfony\Component\Yaml\Yaml;
class UpdateServiceVersions extends Command
{
protected $signature = 'services:update-versions
{--service= : Update specific service template}
{--dry-run : Show what would be updated without making changes}
{--registry= : Filter by registry (dockerhub, ghcr, quay, codeberg)}';
protected $description = 'Update service template files with latest Docker image versions from registries';
protected array $stats = [
'total' => 0,
'updated' => 0,
'failed' => 0,
'skipped' => 0,
];
protected array $registryCache = [];
protected array $majorVersionUpdates = [];
public function handle(): int
{
$this->info('Starting service version update...');
$templateFiles = $this->getTemplateFiles();
$this->stats['total'] = count($templateFiles);
foreach ($templateFiles as $file) {
$this->processTemplate($file);
}
$this->newLine();
$this->displayStats();
return self::SUCCESS;
}
protected function getTemplateFiles(): array
{
$pattern = base_path('templates/compose/*.yaml');
$files = glob($pattern);
if ($service = $this->option('service')) {
$files = array_filter($files, fn ($file) => basename($file) === "$service.yaml");
}
return $files;
}
protected function processTemplate(string $filePath): void
{
$filename = basename($filePath);
$this->info("Processing: {$filename}");
try {
$content = file_get_contents($filePath);
$yaml = Yaml::parse($content);
if (! isset($yaml['services'])) {
$this->warn(" No services found in {$filename}");
$this->stats['skipped']++;
return;
}
$updated = false;
$updatedYaml = $yaml;
foreach ($yaml['services'] as $serviceName => $serviceConfig) {
if (! isset($serviceConfig['image'])) {
continue;
}
$currentImage = $serviceConfig['image'];
// Check if using 'latest' tag and log for manual review
if (str_contains($currentImage, ':latest')) {
$registryUrl = $this->getRegistryUrl($currentImage);
$this->warn(" {$serviceName}: {$currentImage} (using 'latest' tag)");
if ($registryUrl) {
$this->line(" → Manual review: {$registryUrl}");
}
}
$latestVersion = $this->getLatestVersion($currentImage);
if ($latestVersion && $latestVersion !== $currentImage) {
$this->line(" {$serviceName}: {$currentImage} → {$latestVersion}");
$updatedYaml['services'][$serviceName]['image'] = $latestVersion;
$updated = true;
} else {
$this->line(" {$serviceName}: {$currentImage} (up to date)");
}
}
if ($updated) {
if (! $this->option('dry-run')) {
$this->updateYamlFile($filePath, $content, $updatedYaml);
$this->stats['updated']++;
} else {
$this->warn(' [DRY RUN] Would update this file');
$this->stats['updated']++;
}
} else {
$this->stats['skipped']++;
}
} catch (\Throwable $e) {
$this->error(" Failed: {$e->getMessage()}");
$this->stats['failed']++;
}
$this->newLine();
}
protected function getLatestVersion(string $image): ?string
{
// Parse the image string
[$repository, $currentTag] = $this->parseImage($image);
// Determine registry and fetch latest version
$result = null;
if (str_starts_with($repository, 'ghcr.io/')) {
$result = $this->getGhcrLatestVersion($repository, $currentTag);
} elseif (str_starts_with($repository, 'quay.io/')) {
$result = $this->getQuayLatestVersion($repository, $currentTag);
} elseif (str_starts_with($repository, 'codeberg.org/')) {
$result = $this->getCodebergLatestVersion($repository, $currentTag);
} elseif (str_starts_with($repository, 'lscr.io/')) {
$result = $this->getDockerHubLatestVersion($repository, $currentTag);
} elseif ($this->isCustomRegistry($repository)) {
// Custom registries - skip for now, log warning
$this->warn(" Skipping custom registry: {$repository}");
$result = null;
} else {
// DockerHub (default registry - no prefix or docker.io/index.docker.io)
$result = $this->getDockerHubLatestVersion($repository, $currentTag);
}
return $result;
}
protected function isCustomRegistry(string $repository): bool
{
// List of custom/private registries that we can't query
$customRegistries = [
'docker.elastic.co/',
'docker.n8n.io/',
'docker.flipt.io/',
'docker.getoutline.com/',
'cr.weaviate.io/',
'downloads.unstructured.io/',
'budibase.docker.scarf.sh/',
'calcom.docker.scarf.sh/',
'code.forgejo.org/',
'registry.supertokens.io/',
'registry.rocket.chat/',
'nabo.codimd.dev/',
'gcr.io/',
];
foreach ($customRegistries as $registry) {
if (str_starts_with($repository, $registry)) {
return true;
}
}
return false;
}
protected function getRegistryUrl(string $image): ?string
{
[$repository] = $this->parseImage($image);
// GitHub Container Registry
if (str_starts_with($repository, 'ghcr.io/')) {
$parts = explode('/', str_replace('ghcr.io/', '', $repository));
if (count($parts) >= 2) {
return "https://github.com/{$parts[0]}/{$parts[1]}/pkgs/container/{$parts[1]}";
}
}
// Quay.io
if (str_starts_with($repository, 'quay.io/')) {
$repo = str_replace('quay.io/', '', $repository);
return "https://quay.io/repository/{$repo}?tab=tags";
}
// Codeberg
if (str_starts_with($repository, 'codeberg.org/')) {
$parts = explode('/', str_replace('codeberg.org/', '', $repository));
if (count($parts) >= 2) {
return "https://codeberg.org/{$parts[0]}/-/packages/container/{$parts[1]}";
}
}
// Docker Hub
$cleanRepo = str_replace(['index.docker.io/', 'docker.io/', 'lscr.io/'], '', $repository);
if (! str_contains($cleanRepo, '/')) {
// Official image
return "https://hub.docker.com/_/{$cleanRepo}/tags";
} else {
// User/org image
return "https://hub.docker.com/r/{$cleanRepo}/tags";
}
}
protected function parseImage(string $image): array
{
if (str_contains($image, ':')) {
[$repo, $tag] = explode(':', $image, 2);
} else {
$repo = $image;
$tag = 'latest';
}
// Handle variables in tags
if (str_contains($tag, '$')) {
$tag = 'latest'; // Default to latest for variable tags
}
return [$repo, $tag];
}
protected function getDockerHubLatestVersion(string $repository, string $currentTag): ?string
{
try {
// Check if we've already fetched tags for this repository
if (! isset($this->registryCache[$repository.'_tags'])) {
// Remove various registry prefixes
$cleanRepo = $repository;
$cleanRepo = str_replace('index.docker.io/', '', $cleanRepo);
$cleanRepo = str_replace('docker.io/', '', $cleanRepo);
$cleanRepo = str_replace('lscr.io/', '', $cleanRepo);
// For official images (no /) add library prefix
if (! str_contains($cleanRepo, '/')) {
$cleanRepo = "library/{$cleanRepo}";
}
$url = "https://hub.docker.com/v2/repositories/{$cleanRepo}/tags";
$response = Http::timeout(10)->get($url, [
'page_size' => 100,
'ordering' => 'last_updated',
]);
if (! $response->successful()) {
return null;
}
$data = $response->json();
$tags = $data['results'] ?? [];
// Cache the tags for this repository
$this->registryCache[$repository.'_tags'] = $tags;
} else {
$this->line(" [cached] Using cached tags for {$repository}");
$tags = $this->registryCache[$repository.'_tags'];
}
// Find the best matching tag
return $this->findBestTag($tags, $currentTag, $repository);
} catch (\Throwable $e) {
$this->warn(" DockerHub API error for {$repository}: {$e->getMessage()}");
return null;
}
}
protected function findLatestTagDigest(array $tags, string $targetTag = 'latest'): ?string
{
// Find the digest/sha for the target tag (usually 'latest')
foreach ($tags as $tag) {
if ($tag['name'] === $targetTag) {
return $tag['digest'] ?? $tag['images'][0]['digest'] ?? null;
}
}
return null;
}
protected function findVersionTagsForDigest(array $tags, string $digest): array
{
// Find all semantic version tags that share the same digest
$versionTags = [];
foreach ($tags as $tag) {
$tagDigest = $tag['digest'] ?? $tag['images'][0]['digest'] ?? null;
if ($tagDigest === $digest) {
$tagName = $tag['name'];
// Only include semantic version tags
if (preg_match('/^\d+\.\d+(\.\d+)?$/', $tagName)) {
$versionTags[] = $tagName;
}
}
}
return $versionTags;
}
protected function getGhcrLatestVersion(string $repository, string $currentTag): ?string
{
try {
// GHCR doesn't have a public API for listing tags without auth
// We'll try to fetch the package metadata via GitHub API
$parts = explode('/', str_replace('ghcr.io/', '', $repository));
if (count($parts) < 2) {
return null;
}
$owner = $parts[0];
$package = $parts[1];
// Try GitHub Container Registry API
$url = "https://api.github.com/users/{$owner}/packages/container/{$package}/versions";
$response = Http::timeout(10)
->withHeaders([
'Accept' => 'application/vnd.github.v3+json',
])
->get($url, ['per_page' => 100]);
if (! $response->successful()) {
// Most GHCR packages require authentication
if ($currentTag === 'latest') {
$this->warn(' ⚠ GHCR requires authentication - manual review needed');
}
return null;
}
$versions = $response->json();
$tags = [];
// Build tags array with digest information
foreach ($versions as $version) {
$digest = $version['name'] ?? null; // This is the SHA digest
if (isset($version['metadata']['container']['tags'])) {
foreach ($version['metadata']['container']['tags'] as $tag) {
$tags[] = [
'name' => $tag,
'digest' => $digest,
];
}
}
}
return $this->findBestTag($tags, $currentTag, $repository);
} catch (\Throwable $e) {
$this->warn(" GHCR API error for {$repository}: {$e->getMessage()}");
return null;
}
}
protected function getQuayLatestVersion(string $repository, string $currentTag): ?string
{
try {
// Check if we've already fetched tags for this repository
if (! isset($this->registryCache[$repository.'_tags'])) {
$cleanRepo = str_replace('quay.io/', '', $repository);
$url = "https://quay.io/api/v1/repository/{$cleanRepo}/tag/";
$response = Http::timeout(10)->get($url, ['limit' => 100]);
if (! $response->successful()) {
return null;
}
$data = $response->json();
$tags = array_map(fn ($tag) => ['name' => $tag['name']], $data['tags'] ?? []);
// Cache the tags for this repository
$this->registryCache[$repository.'_tags'] = $tags;
} else {
$this->line(" [cached] Using cached tags for {$repository}");
$tags = $this->registryCache[$repository.'_tags'];
}
return $this->findBestTag($tags, $currentTag, $repository);
} catch (\Throwable $e) {
$this->warn(" Quay API error for {$repository}: {$e->getMessage()}");
return null;
}
}
protected function getCodebergLatestVersion(string $repository, string $currentTag): ?string
{
try {
// Check if we've already fetched tags for this repository
if (! isset($this->registryCache[$repository.'_tags'])) {
// Codeberg uses Forgejo/Gitea, which has a container registry API
$cleanRepo = str_replace('codeberg.org/', '', $repository);
$parts = explode('/', $cleanRepo);
if (count($parts) < 2) {
return null;
}
$owner = $parts[0];
$package = $parts[1];
// Codeberg API endpoint for packages
$url = "https://codeberg.org/api/packages/{$owner}/container/{$package}";
$response = Http::timeout(10)->get($url);
if (! $response->successful()) {
return null;
}
$data = $response->json();
$tags = [];
if (isset($data['versions'])) {
foreach ($data['versions'] as $version) {
if (isset($version['name'])) {
$tags[] = ['name' => $version['name']];
}
}
}
// Cache the tags for this repository
$this->registryCache[$repository.'_tags'] = $tags;
} else {
$this->line(" [cached] Using cached tags for {$repository}");
$tags = $this->registryCache[$repository.'_tags'];
}
return $this->findBestTag($tags, $currentTag, $repository);
} catch (\Throwable $e) {
$this->warn(" Codeberg API error for {$repository}: {$e->getMessage()}");
return null;
}
}
protected function findBestTag(array $tags, string $currentTag, string $repository): ?string
{
if (empty($tags)) {
return null;
}
// If current tag is 'latest', find what version it actually points to
if ($currentTag === 'latest') {
// First, try to find the digest for 'latest' tag
$latestDigest = $this->findLatestTagDigest($tags, 'latest');
if ($latestDigest) {
// Find all semantic version tags that share the same digest
$versionTags = $this->findVersionTagsForDigest($tags, $latestDigest);
if (! empty($versionTags)) {
// Prefer shorter version tags (1.8 over 1.8.1)
$bestVersion = $this->preferShorterVersion($versionTags);
$this->info(" ✓ Found 'latest' points to: {$bestVersion}");
return $repository.':'.$bestVersion;
}
}
// Fallback: get the latest semantic version available (prefer shorter)
$semverTags = $this->filterSemanticVersionTags($tags);
if (! empty($semverTags)) {
$bestVersion = $this->preferShorterVersion($semverTags);
return $repository.':'.$bestVersion;
}
// If no semantic versions found, keep 'latest'
return null;
}
// Check for major version updates for reporting
$this->checkForMajorVersionUpdate($tags, $currentTag, $repository);
// If current tag is a major version (e.g., "8", "5", "16")
if (preg_match('/^\d+$/', $currentTag)) {
$majorVersion = (int) $currentTag;
$matchingTags = array_filter($tags, function ($tag) use ($majorVersion) {
$name = $tag['name'];
// Match tags that start with the major version
return preg_match("/^{$majorVersion}(\.\d+)?(\.\d+)?$/", $name);
});
if (! empty($matchingTags)) {
$versions = array_column($matchingTags, 'name');
$bestVersion = $this->preferShorterVersion($versions);
if ($bestVersion !== $currentTag) {
return $repository.':'.$bestVersion;
}
}
}
// If current tag is date-based version (e.g., "2025.06.02-sha-xxx")
if (preg_match('/^\d{4}\.\d{2}\.\d{2}/', $currentTag)) {
// Get all date-based tags
$dateTags = array_filter($tags, function ($tag) {
return preg_match('/^\d{4}\.\d{2}\.\d{2}/', $tag['name']);
});
if (! empty($dateTags)) {
$versions = array_column($dateTags, 'name');
$sorted = $this->sortSemanticVersions($versions);
$latestDate = $sorted[0];
// Compare dates
if ($latestDate !== $currentTag) {
return $repository.':'.$latestDate;
}
}
return null;
}
// If current tag is semantic version (e.g., "1.7.4", "8.0")
if (preg_match('/^\d+\.\d+(\.\d+)?$/', $currentTag)) {
$parts = explode('.', $currentTag);
$majorMinor = $parts[0].'.'.$parts[1];
$matchingTags = array_filter($tags, function ($tag) use ($majorMinor) {
$name = $tag['name'];
return str_starts_with($name, $majorMinor);
});
if (! empty($matchingTags)) {
$versions = array_column($matchingTags, 'name');
$bestVersion = $this->preferShorterVersion($versions);
if (version_compare($bestVersion, $currentTag, '>') || version_compare($bestVersion, $currentTag, '=')) {
// Only update if it's newer or if we can simplify (1.8.1 -> 1.8)
if ($bestVersion !== $currentTag) {
return $repository.':'.$bestVersion;
}
}
}
}
// If current tag is a named version (e.g., "stable")
if (in_array($currentTag, ['stable', 'lts', 'edge'])) {
// Check if the same tag exists in the list (it's up to date)
$exists = array_filter($tags, fn ($tag) => $tag['name'] === $currentTag);
if (! empty($exists)) {
return null; // Tag exists and is current
}
}
return null;
}
protected function filterSemanticVersionTags(array $tags): array
{
$semverTags = array_filter($tags, function ($tag) {
$name = $tag['name'];
// Accept semantic versions (1.2.3, v1.2.3)
if (preg_match('/^v?\d+\.\d+(\.\d+)?(\.\d+)?$/', $name)) {
// Exclude versions with suffixes like -rc, -beta, -alpha
if (preg_match('/-(rc|beta|alpha|dev|test|pre|snapshot)/i', $name)) {
return false;
}
return true;
}
// Accept date-based versions (2025.06.02, 2025.10.0, 2025.06.02-sha-xxx, RELEASE.2025-10-15T17-29-55Z)
if (preg_match('/^\d{4}\.\d{2}\.(\d{2}|\d)/', $name) || preg_match('/^RELEASE\.\d{4}-\d{2}-\d{2}/', $name)) {
return true;
}
return false;
});
return $this->sortSemanticVersions(array_column($semverTags, 'name'));
}
protected function sortSemanticVersions(array $versions): array
{
usort($versions, function ($a, $b) {
// Check if these are date-based versions (YYYY.MM.DD or YYYY.MM.D format)
$isDateA = preg_match('/^(\d{4})\.(\d{2})\.(\d{1,2})/', $a, $matchesA);
$isDateB = preg_match('/^(\d{4})\.(\d{2})\.(\d{1,2})/', $b, $matchesB);
if ($isDateA && $isDateB) {
// Both are date-based (YYYY.MM.DD), compare as dates
$dateA = $matchesA[1].$matchesA[2].str_pad($matchesA[3], 2, '0', STR_PAD_LEFT); // YYYYMMDD
$dateB = $matchesB[1].$matchesB[2].str_pad($matchesB[3], 2, '0', STR_PAD_LEFT); // YYYYMMDD
return strcmp($dateB, $dateA); // Descending order (newest first)
}
// Check if these are RELEASE date versions (RELEASE.YYYY-MM-DDTHH-MM-SSZ)
$isReleaseA = preg_match('/^RELEASE\.(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})Z/', $a, $matchesA);
$isReleaseB = preg_match('/^RELEASE\.(\d{4})-(\d{2})-(\d{2})T(\d{2})-(\d{2})-(\d{2})Z/', $b, $matchesB);
if ($isReleaseA && $isReleaseB) {
// Both are RELEASE format, compare as datetime
$dateTimeA = $matchesA[1].$matchesA[2].$matchesA[3].$matchesA[4].$matchesA[5].$matchesA[6]; // YYYYMMDDHHMMSS
$dateTimeB = $matchesB[1].$matchesB[2].$matchesB[3].$matchesB[4].$matchesB[5].$matchesB[6]; // YYYYMMDDHHMMSS
return strcmp($dateTimeB, $dateTimeA); // Descending order (newest first)
}
// Strip 'v' prefix for version comparison
$cleanA = ltrim($a, 'v');
$cleanB = ltrim($b, 'v');
// Fall back to semantic version comparison
return version_compare($cleanB, $cleanA); // Descending order
});
return $versions;
}
protected function preferShorterVersion(array $versions): string
{
if (empty($versions)) {
return '';
}
// Sort by version (highest first)
$sorted = $this->sortSemanticVersions($versions);
$highest = $sorted[0];
// Parse the highest version
$parts = explode('.', $highest);
// Look for shorter versions that match
// Priority: major (8) > major.minor (8.0) > major.minor.patch (8.0.39)
// Try to find just major.minor (e.g., 1.8 instead of 1.8.1)
if (count($parts) === 3) {
$majorMinor = $parts[0].'.'.$parts[1];
if (in_array($majorMinor, $versions)) {
return $majorMinor;
}
}
// Try to find just major (e.g., 8 instead of 8.0.39)
if (count($parts) >= 2) {
$major = $parts[0];
if (in_array($major, $versions)) {
return $major;
}
}
// Return the highest version we found
return $highest;
}
protected function updateYamlFile(string $filePath, string $originalContent, array $updatedYaml): void
{
// Preserve comments and formatting by updating the YAML content
$lines = explode("\n", $originalContent);
$updatedLines = [];
$inServices = false;
$currentService = null;
foreach ($lines as $line) {
// Detect if we're in the services section
if (preg_match('/^services:/', $line)) {
$inServices = true;
$updatedLines[] = $line;
continue;
}
// Detect service name (allow hyphens and underscores)
if ($inServices && preg_match('/^ ([\w-]+):/', $line, $matches)) {
$currentService = $matches[1];
$updatedLines[] = $line;
continue;
}
// Update image line
if ($currentService && preg_match('/^(\s+)image:\s*(.+)$/', $line, $matches)) {
$indent = $matches[1];
$newImage = $updatedYaml['services'][$currentService]['image'] ?? $matches[2];
$updatedLines[] = "{$indent}image: {$newImage}";
continue;
}
// If we hit a non-indented line, we're out of services
if ($inServices && preg_match('/^\S/', $line) && ! preg_match('/^services:/', $line)) {
$inServices = false;
$currentService = null;
}
$updatedLines[] = $line;
}
file_put_contents($filePath, implode("\n", $updatedLines));
}
protected function checkForMajorVersionUpdate(array $tags, string $currentTag, string $repository): void
{
// Only check semantic versions
if (! preg_match('/^v?(\d+)\./', $currentTag, $currentMatches)) {
return;
}
$currentMajor = (int) $currentMatches[1];
// Get all semantic version tags
$semverTags = $this->filterSemanticVersionTags($tags);
// Find the highest major version available
$highestMajor = $currentMajor;
foreach ($semverTags as $version) {
if (preg_match('/^v?(\d+)\./', $version, $matches)) {
$major = (int) $matches[1];
if ($major > $highestMajor) {
$highestMajor = $major;
}
}
}
// If there's a higher major version available, record it
if ($highestMajor > $currentMajor) {
$this->majorVersionUpdates[] = [
'repository' => $repository,
'current' => $currentTag,
'current_major' => $currentMajor,
'available_major' => $highestMajor,
'registry_url' => $this->getRegistryUrl($repository.':'.$currentTag),
];
}
}
protected function displayStats(): void
{
$this->info('Summary:');
$this->table(
['Metric', 'Count'],
[
['Total Templates', $this->stats['total']],
['Updated', $this->stats['updated']],
['Skipped (up to date)', $this->stats['skipped']],
['Failed', $this->stats['failed']],
]
);
// Display major version updates if any
if (! empty($this->majorVersionUpdates)) {
$this->newLine();
$this->warn('⚠ Services with available MAJOR version updates:');
$this->newLine();
$tableData = [];
foreach ($this->majorVersionUpdates as $update) {
$tableData[] = [
$update['repository'],
"v{$update['current_major']}.x",
"v{$update['available_major']}.x",
$update['registry_url'],
];
}
$this->table(
['Repository', 'Current', 'Available', 'Registry URL'],
$tableData
);
$this->newLine();
$this->comment('💡 Major version updates may include breaking changes. Review before upgrading.');
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/AdminDeleteUser.php | app/Console/Commands/AdminDeleteUser.php | <?php
namespace App\Console\Commands;
use App\Actions\Stripe\CancelSubscription;
use App\Actions\User\DeleteUserResources;
use App\Actions\User\DeleteUserServers;
use App\Actions\User\DeleteUserTeams;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
class AdminDeleteUser extends Command
{
protected $signature = 'admin:delete-user {email}
{--dry-run : Preview what will be deleted without actually deleting}
{--skip-stripe : Skip Stripe subscription cancellation}
{--skip-resources : Skip resource deletion}
{--auto-confirm : Skip all confirmation prompts between phases}
{--force : Bypass the lock check and force deletion (use with caution)}';
protected $description = 'Delete a user with comprehensive resource cleanup and phase-by-phase confirmation (works on cloud and self-hosted)';
private bool $isDryRun = false;
private bool $skipStripe = false;
private bool $skipResources = false;
private User $user;
private $lock;
private array $deletionState = [
'phase_1_overview' => false,
'phase_2_resources' => false,
'phase_3_servers' => false,
'phase_4_teams' => false,
'phase_5_user_profile' => false,
'phase_6_stripe' => false,
'db_committed' => false,
];
public function handle()
{
// Register signal handlers for graceful shutdown (Ctrl+C handling)
$this->registerSignalHandlers();
$email = $this->argument('email');
$this->isDryRun = $this->option('dry-run');
$this->skipStripe = $this->option('skip-stripe');
$this->skipResources = $this->option('skip-resources');
$force = $this->option('force');
if ($force) {
$this->warn('⚠️ FORCE MODE - Lock check will be bypassed');
$this->warn(' Use this flag only if you are certain no other deletion is running');
$this->newLine();
}
if ($this->isDryRun) {
$this->info('🔍 DRY RUN MODE - No data will be deleted');
$this->newLine();
}
if ($this->output->isVerbose()) {
$this->info('📊 VERBOSE MODE - Full stack traces will be shown on errors');
$this->newLine();
} else {
$this->comment('💡 Tip: Use -v flag for detailed error stack traces');
$this->newLine();
}
if (! $this->isDryRun && ! $this->option('auto-confirm')) {
$this->info('🔄 INTERACTIVE MODE - You will be asked to confirm after each phase');
$this->comment(' Use --auto-confirm to skip phase confirmations');
$this->newLine();
}
// Notify about instance type and Stripe
if (isCloud()) {
$this->comment('☁️ Cloud instance - Stripe subscriptions will be handled');
} else {
$this->comment('🏠 Self-hosted instance - Stripe operations will be skipped');
}
$this->newLine();
try {
$this->user = User::whereEmail($email)->firstOrFail();
} catch (\Exception $e) {
$this->error("User with email '{$email}' not found.");
return 1;
}
// Implement file lock to prevent concurrent deletions of the same user
$lockKey = "user_deletion_{$this->user->id}";
$this->lock = Cache::lock($lockKey, 600); // 10 minute lock
if (! $force) {
if (! $this->lock->get()) {
$this->error('Another deletion process is already running for this user.');
$this->error('Use --force to bypass this lock (use with extreme caution).');
$this->logAction("Deletion blocked for user {$email}: Another process is already running");
return 1;
}
} else {
// In force mode, try to get lock but continue even if it fails
if (! $this->lock->get()) {
$this->warn('⚠️ Lock exists but proceeding due to --force flag');
$this->warn(' There may be another deletion process running!');
$this->newLine();
}
}
try {
$this->logAction("Starting user deletion process for: {$email}");
// Phase 1: Show User Overview (outside transaction)
if (! $this->showUserOverview()) {
$this->info('User deletion cancelled by operator.');
return 0;
}
$this->deletionState['phase_1_overview'] = true;
// If not dry run, wrap DB operations in a transaction
// NOTE: Stripe cancellations happen AFTER commit to avoid inconsistent state
if (! $this->isDryRun) {
try {
DB::beginTransaction();
// Phase 2: Delete Resources
// WARNING: This triggers Docker container deletion via SSH which CANNOT be rolled back
if (! $this->skipResources) {
if (! $this->deleteResources()) {
DB::rollBack();
$this->displayErrorState('Phase 2: Resource Deletion');
$this->error('❌ User deletion failed at resource deletion phase.');
$this->warn('⚠️ Some Docker containers may have been deleted on remote servers and cannot be restored.');
$this->displayRecoverySteps();
return 1;
}
}
$this->deletionState['phase_2_resources'] = true;
// Confirmation to continue after Phase 2
if (! $this->skipResources && ! $this->option('auto-confirm')) {
$this->newLine();
if (! $this->confirm('Phase 2 completed. Continue to Phase 3 (Delete Servers)?', true)) {
DB::rollBack();
$this->info('User deletion cancelled by operator after Phase 2.');
$this->info('Database changes have been rolled back.');
return 0;
}
}
// Phase 3: Delete Servers
// WARNING: This may trigger cleanup operations on remote servers which CANNOT be rolled back
if (! $this->deleteServers()) {
DB::rollBack();
$this->displayErrorState('Phase 3: Server Deletion');
$this->error('❌ User deletion failed at server deletion phase.');
$this->warn('⚠️ Some server cleanup operations may have been performed and cannot be restored.');
$this->displayRecoverySteps();
return 1;
}
$this->deletionState['phase_3_servers'] = true;
// Confirmation to continue after Phase 3
if (! $this->option('auto-confirm')) {
$this->newLine();
if (! $this->confirm('Phase 3 completed. Continue to Phase 4 (Handle Teams)?', true)) {
DB::rollBack();
$this->info('User deletion cancelled by operator after Phase 3.');
$this->info('Database changes have been rolled back.');
return 0;
}
}
// Phase 4: Handle Teams
if (! $this->handleTeams()) {
DB::rollBack();
$this->displayErrorState('Phase 4: Team Handling');
$this->error('❌ User deletion failed at team handling phase.');
$this->displayRecoverySteps();
return 1;
}
$this->deletionState['phase_4_teams'] = true;
// Confirmation to continue after Phase 4
if (! $this->option('auto-confirm')) {
$this->newLine();
if (! $this->confirm('Phase 4 completed. Continue to Phase 5 (Delete User Profile)?', true)) {
DB::rollBack();
$this->info('User deletion cancelled by operator after Phase 4.');
$this->info('Database changes have been rolled back.');
return 0;
}
}
// Phase 5: Delete User Profile
if (! $this->deleteUserProfile()) {
DB::rollBack();
$this->displayErrorState('Phase 5: User Profile Deletion');
$this->error('❌ User deletion failed at user profile deletion phase.');
$this->displayRecoverySteps();
return 1;
}
$this->deletionState['phase_5_user_profile'] = true;
// CRITICAL CONFIRMATION: Database commit is next (PERMANENT)
if (! $this->option('auto-confirm')) {
$this->newLine();
$this->warn('⚠️ CRITICAL DECISION POINT');
$this->warn('Next step: COMMIT database changes (PERMANENT and IRREVERSIBLE)');
$this->warn('All resources, servers, teams, and user profile will be permanently deleted');
$this->newLine();
if (! $this->confirm('Phase 5 completed. Commit database changes? (THIS IS PERMANENT)', false)) {
DB::rollBack();
$this->info('User deletion cancelled by operator before commit.');
$this->info('Database changes have been rolled back.');
$this->warn('⚠️ Note: Some Docker containers may have been deleted on remote servers.');
return 0;
}
}
// Commit the database transaction
DB::commit();
$this->deletionState['db_committed'] = true;
$this->newLine();
$this->info('✅ Database operations completed successfully!');
$this->info('✅ Transaction committed - database changes are now PERMANENT.');
$this->logAction("Database deletion completed for: {$email}");
// Confirmation to continue to Stripe (after commit)
if (! $this->skipStripe && isCloud() && ! $this->option('auto-confirm')) {
$this->newLine();
$this->warn('⚠️ Database changes are committed (permanent)');
$this->info('Next: Cancel Stripe subscriptions');
if (! $this->confirm('Continue to Phase 6 (Cancel Stripe Subscriptions)?', true)) {
$this->warn('User deletion stopped after database commit.');
$this->error('⚠️ IMPORTANT: User deleted from database but Stripe subscriptions remain active!');
$this->error('You must cancel subscriptions manually in Stripe Dashboard.');
$this->error('Go to: https://dashboard.stripe.com/');
$this->error('Search for: '.$email);
return 1;
}
}
// Phase 6: Cancel Stripe Subscriptions (AFTER DB commit)
// This is done AFTER commit because Stripe API calls cannot be rolled back
// If this fails, DB changes are already committed but subscriptions remain active
if (! $this->skipStripe && isCloud()) {
if (! $this->cancelStripeSubscriptions()) {
$this->newLine();
$this->error('═══════════════════════════════════════');
$this->error('⚠️ CRITICAL: INCONSISTENT STATE DETECTED');
$this->error('═══════════════════════════════════════');
$this->error('✓ User data DELETED from database (committed)');
$this->error('✗ Stripe subscription cancellation FAILED');
$this->newLine();
$this->displayErrorState('Phase 6: Stripe Cancellation (Post-Commit)');
$this->newLine();
$this->error('MANUAL ACTION REQUIRED:');
$this->error('1. Go to Stripe Dashboard: https://dashboard.stripe.com/');
$this->error('2. Search for customer email: '.$email);
$this->error('3. Cancel all active subscriptions');
$this->error('4. Check storage/logs/user-deletions.log for subscription IDs');
$this->newLine();
$this->logAction("INCONSISTENT STATE: User {$email} deleted but Stripe cancellation failed");
return 1;
}
}
$this->deletionState['phase_6_stripe'] = true;
$this->newLine();
$this->info('✅ User deletion completed successfully!');
$this->logAction("User deletion completed for: {$email}");
} catch (\Exception $e) {
DB::rollBack();
$this->newLine();
$this->error('═══════════════════════════════════════');
$this->error('❌ EXCEPTION DURING USER DELETION');
$this->error('═══════════════════════════════════════');
$this->error('Exception: '.get_class($e));
$this->error('Message: '.$e->getMessage());
$this->error('File: '.$e->getFile().':'.$e->getLine());
$this->newLine();
if ($this->output->isVerbose()) {
$this->error('Stack Trace:');
$this->error($e->getTraceAsString());
$this->newLine();
} else {
$this->info('Run with -v for full stack trace');
$this->newLine();
}
$this->displayErrorState('Exception during execution');
$this->displayRecoverySteps();
$this->logAction("User deletion failed for {$email}: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}");
return 1;
}
} else {
// Dry run mode - just run through the phases without transaction
// Phase 2: Delete Resources
if (! $this->skipResources) {
if (! $this->deleteResources()) {
$this->info('User deletion would be cancelled at resource deletion phase.');
return 0;
}
}
// Phase 3: Delete Servers
if (! $this->deleteServers()) {
$this->info('User deletion would be cancelled at server deletion phase.');
return 0;
}
// Phase 4: Handle Teams
if (! $this->handleTeams()) {
$this->info('User deletion would be cancelled at team handling phase.');
return 0;
}
// Phase 5: Delete User Profile
if (! $this->deleteUserProfile()) {
$this->info('User deletion would be cancelled at user profile deletion phase.');
return 0;
}
// Phase 6: Cancel Stripe Subscriptions (shown after DB operations in dry run too)
if (! $this->skipStripe && isCloud()) {
if (! $this->cancelStripeSubscriptions()) {
$this->info('User deletion would be cancelled at Stripe cancellation phase.');
return 0;
}
}
$this->newLine();
$this->info('✅ DRY RUN completed successfully! No data was deleted.');
}
return 0;
} finally {
// Ensure lock is always released
$this->releaseLock();
}
}
private function showUserOverview(): bool
{
$this->info('═══════════════════════════════════════');
$this->info('PHASE 1: USER OVERVIEW');
$this->info('═══════════════════════════════════════');
$this->newLine();
$teams = $this->user->teams()->get();
$ownedTeams = $teams->filter(fn ($team) => $team->pivot->role === 'owner');
$memberTeams = $teams->filter(fn ($team) => $team->pivot->role !== 'owner');
// Collect servers and resources ONLY from teams that will be FULLY DELETED
// This means: user is owner AND is the ONLY member
//
// Resources from these teams will NOT be deleted:
// - Teams where user is just a member
// - Teams where user is owner but has other members (will be transferred/user removed)
$allServers = collect();
$allApplications = collect();
$allDatabases = collect();
$allServices = collect();
$activeSubscriptions = collect();
foreach ($teams as $team) {
$userRole = $team->pivot->role;
$memberCount = $team->members->count();
// Only show resources from teams where user is the ONLY member
// These are the teams that will be fully deleted
if ($userRole !== 'owner' || $memberCount > 1) {
continue;
}
$servers = $team->servers()->get();
$allServers = $allServers->merge($servers);
foreach ($servers as $server) {
$resources = $server->definedResources();
foreach ($resources as $resource) {
if ($resource instanceof \App\Models\Application) {
$allApplications->push($resource);
} elseif ($resource instanceof \App\Models\Service) {
$allServices->push($resource);
} else {
$allDatabases->push($resource);
}
}
}
// Only collect subscriptions on cloud instances
if (isCloud() && $team->subscription && $team->subscription->stripe_subscription_id) {
$activeSubscriptions->push($team->subscription);
}
}
// Build table data
$tableData = [
['User', $this->user->email],
['User ID', $this->user->id],
['Created', $this->user->created_at->format('Y-m-d H:i:s')],
['Last Login', $this->user->updated_at->format('Y-m-d H:i:s')],
['Teams (Total)', $teams->count()],
['Teams (Owner)', $ownedTeams->count()],
['Teams (Member)', $memberTeams->count()],
['Servers', $allServers->unique('id')->count()],
['Applications', $allApplications->count()],
['Databases', $allDatabases->count()],
['Services', $allServices->count()],
];
// Only show Stripe subscriptions on cloud instances
if (isCloud()) {
$tableData[] = ['Active Stripe Subscriptions', $activeSubscriptions->count()];
}
$this->table(['Property', 'Value'], $tableData);
$this->newLine();
$this->warn('⚠️ WARNING: This will permanently delete the user and all associated data!');
$this->newLine();
if (! $this->confirm('Do you want to continue with the deletion process?', false)) {
return false;
}
return true;
}
private function deleteResources(): bool
{
$this->newLine();
$this->info('═══════════════════════════════════════');
$this->info('PHASE 2: DELETE RESOURCES');
$this->info('═══════════════════════════════════════');
$this->newLine();
$action = new DeleteUserResources($this->user, $this->isDryRun);
$resources = $action->getResourcesPreview();
if ($resources['applications']->isEmpty() &&
$resources['databases']->isEmpty() &&
$resources['services']->isEmpty()) {
$this->info('No resources to delete.');
return true;
}
$this->info('Resources to be deleted:');
$this->newLine();
if ($resources['applications']->isNotEmpty()) {
$this->warn("Applications to be deleted ({$resources['applications']->count()}):");
$this->table(
['Name', 'UUID', 'Server', 'Status'],
$resources['applications']->map(function ($app) {
return [
$app->name,
$app->uuid,
$app->destination->server->name,
$app->status ?? 'unknown',
];
})->toArray()
);
$this->newLine();
}
if ($resources['databases']->isNotEmpty()) {
$this->warn("Databases to be deleted ({$resources['databases']->count()}):");
$this->table(
['Name', 'Type', 'UUID', 'Server'],
$resources['databases']->map(function ($db) {
return [
$db->name,
class_basename($db),
$db->uuid,
$db->destination->server->name,
];
})->toArray()
);
$this->newLine();
}
if ($resources['services']->isNotEmpty()) {
$this->warn("Services to be deleted ({$resources['services']->count()}):");
$this->table(
['Name', 'UUID', 'Server'],
$resources['services']->map(function ($service) {
return [
$service->name,
$service->uuid,
$service->server->name,
];
})->toArray()
);
$this->newLine();
}
$this->error('⚠️ THIS ACTION CANNOT BE UNDONE!');
if (! $this->confirm('Are you sure you want to delete all these resources?', false)) {
return false;
}
if (! $this->isDryRun) {
$this->info('Deleting resources...');
try {
$result = $action->execute();
$this->info("✓ Deleted: {$result['applications']} applications, {$result['databases']} databases, {$result['services']} services");
$this->logAction("Deleted resources for user {$this->user->email}: {$result['applications']} apps, {$result['databases']} databases, {$result['services']} services");
} catch (\Exception $e) {
$this->error('Failed to delete resources:');
$this->error('Exception: '.get_class($e));
$this->error('Message: '.$e->getMessage());
$this->error('File: '.$e->getFile().':'.$e->getLine());
if ($this->output->isVerbose()) {
$this->error('Stack Trace:');
$this->error($e->getTraceAsString());
}
throw $e; // Re-throw to trigger rollback
}
}
return true;
}
private function deleteServers(): bool
{
$this->newLine();
$this->info('═══════════════════════════════════════');
$this->info('PHASE 3: DELETE SERVERS');
$this->info('═══════════════════════════════════════');
$this->newLine();
$action = new DeleteUserServers($this->user, $this->isDryRun);
$servers = $action->getServersPreview();
if ($servers->isEmpty()) {
$this->info('No servers to delete.');
return true;
}
$this->warn("Servers to be deleted ({$servers->count()}):");
$this->table(
['ID', 'Name', 'IP', 'Description', 'Resources Count'],
$servers->map(function ($server) {
$resourceCount = $server->definedResources()->count();
return [
$server->id,
$server->name,
$server->ip,
$server->description ?? '-',
$resourceCount,
];
})->toArray()
);
$this->newLine();
$this->error('⚠️ WARNING: Deleting servers will remove all server configurations!');
if (! $this->confirm('Are you sure you want to delete all these servers?', false)) {
return false;
}
if (! $this->isDryRun) {
$this->info('Deleting servers...');
try {
$result = $action->execute();
$this->info("✓ Deleted {$result['servers']} servers");
$this->logAction("Deleted {$result['servers']} servers for user {$this->user->email}");
} catch (\Exception $e) {
$this->error('Failed to delete servers:');
$this->error('Exception: '.get_class($e));
$this->error('Message: '.$e->getMessage());
$this->error('File: '.$e->getFile().':'.$e->getLine());
if ($this->output->isVerbose()) {
$this->error('Stack Trace:');
$this->error($e->getTraceAsString());
}
throw $e; // Re-throw to trigger rollback
}
}
return true;
}
private function handleTeams(): bool
{
$this->newLine();
$this->info('═══════════════════════════════════════');
$this->info('PHASE 4: HANDLE TEAMS');
$this->info('═══════════════════════════════════════');
$this->newLine();
$action = new DeleteUserTeams($this->user, $this->isDryRun);
$preview = $action->getTeamsPreview();
// Check for edge cases first - EXIT IMMEDIATELY if found
if ($preview['edge_cases']->isNotEmpty()) {
$this->error('═══════════════════════════════════════');
$this->error('⚠️ EDGE CASES DETECTED - CANNOT PROCEED');
$this->error('═══════════════════════════════════════');
$this->newLine();
foreach ($preview['edge_cases'] as $edgeCase) {
$team = $edgeCase['team'];
$reason = $edgeCase['reason'];
$this->error("Team: {$team->name} (ID: {$team->id})");
$this->error("Issue: {$reason}");
// Show team members for context
$this->info('Current members:');
foreach ($team->members as $member) {
$role = $member->pivot->role;
$this->line(" - {$member->name} ({$member->email}) - Role: {$role}");
}
// Check for active resources
$resourceCount = 0;
foreach ($team->servers()->get() as $server) {
$resources = $server->definedResources();
$resourceCount += $resources->count();
}
if ($resourceCount > 0) {
$this->warn(" ⚠️ This team has {$resourceCount} active resources!");
}
// Show subscription details if relevant
if ($team->subscription && $team->subscription->stripe_subscription_id) {
$this->warn(' ⚠️ Active Stripe subscription details:');
$this->warn(" Subscription ID: {$team->subscription->stripe_subscription_id}");
$this->warn(" Customer ID: {$team->subscription->stripe_customer_id}");
// Show other owners who could potentially take over
$otherOwners = $team->members
->where('id', '!=', $this->user->id)
->filter(function ($member) {
return $member->pivot->role === 'owner';
});
if ($otherOwners->isNotEmpty()) {
$this->info(' Other owners who could take over billing:');
foreach ($otherOwners as $owner) {
$this->line(" - {$owner->name} ({$owner->email})");
}
}
}
$this->newLine();
}
$this->error('Please resolve these issues manually before retrying:');
// Check if any edge case involves subscription payment issues
$hasSubscriptionIssue = $preview['edge_cases']->contains(function ($edgeCase) {
return str_contains($edgeCase['reason'], 'Stripe subscription');
});
if ($hasSubscriptionIssue) {
$this->info('For teams with subscription payment issues:');
$this->info('1. Cancel the subscription through Stripe dashboard, OR');
$this->info('2. Transfer the subscription to another owner\'s payment method, OR');
$this->info('3. Have the other owner create a new subscription after cancelling this one');
$this->newLine();
}
$hasNoOwnerReplacement = $preview['edge_cases']->contains(function ($edgeCase) {
return str_contains($edgeCase['reason'], 'No suitable owner replacement');
});
if ($hasNoOwnerReplacement) {
$this->info('For teams with no suitable owner replacement:');
$this->info('1. Assign an admin role to a trusted member, OR');
$this->info('2. Transfer team resources to another team, OR');
$this->info('3. Delete the team manually if no longer needed');
$this->newLine();
}
$this->error('USER DELETION ABORTED DUE TO EDGE CASES');
$this->logAction("User deletion aborted for {$this->user->email}: Edge cases in team handling");
// Return false to trigger proper cleanup and lock release
return false;
}
if ($preview['to_delete']->isEmpty() &&
$preview['to_transfer']->isEmpty() &&
$preview['to_leave']->isEmpty()) {
$this->info('No team changes needed.');
return true;
}
if ($preview['to_delete']->isNotEmpty()) {
$this->warn('Teams to be DELETED (user is the only member):');
$this->table(
['ID', 'Name', 'Resources', 'Subscription'],
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/NotifyDemo.php | app/Console/Commands/NotifyDemo.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use function Termwind\ask;
use function Termwind\render;
use function Termwind\style;
class NotifyDemo extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'app:demo-notify {channel?}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send a demo notification, to a given channel. Run to see options.';
/**
* Execute the console command.
*/
public function handle()
{
$channel = $this->argument('channel');
if (blank($channel)) {
$this->showHelp();
return;
}
}
private function showHelp()
{
style('coolify')->color('#9333EA');
style('title-box')->apply('mt-1 px-2 py-1 bg-coolify');
render(
<<<'HTML'
<div>
<div class="title-box">
Coolify
</div>
<p class="mt-1 ml-1 ">
Demo Notify <strong class="text-coolify">=></strong> Send a demo notification to a given channel.
</p>
<p class="px-1 mt-1 ml-1 bg-coolify">
php artisan app:demo-notify {channel}
</p>
<div class="my-1">
<div class="text-warning-500"> Channels: </div>
<ul class="text-coolify">
<li>email</li>
<li>discord</li>
<li>telegram</li>
<li>slack</li>
<li>pushover</li>
</ul>
</div>
</div>
HTML
);
ask(<<<'HTML'
<div class="mr-1">
In which manner you wish a <strong class="text-coolify">coolified</strong> notification?
</div>
HTML, ['email', 'discord', 'telegram', 'slack', 'pushover']);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/RunScheduledJobsManually.php | app/Console/Commands/RunScheduledJobsManually.php | <?php
namespace App\Console\Commands;
use App\Jobs\DatabaseBackupJob;
use App\Jobs\ScheduledTaskJob;
use App\Models\ScheduledDatabaseBackup;
use App\Models\ScheduledTask;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class RunScheduledJobsManually extends Command
{
protected $signature = 'schedule:run-manual
{--type=all : Type of jobs to run (all, backups, tasks)}
{--frequency= : Filter by frequency (daily, hourly, weekly, monthly, yearly, or cron expression)}
{--chunk=5 : Number of jobs to process in each batch}
{--delay=30 : Delay in seconds between batches}
{--max= : Maximum number of jobs to process (useful for testing)}
{--dry-run : Show what would be executed without actually running jobs}';
protected $description = 'Manually run scheduled database backups and tasks when cron fails';
public function handle()
{
$type = $this->option('type');
$frequency = $this->option('frequency');
$chunkSize = (int) $this->option('chunk');
$delay = (int) $this->option('delay');
$maxJobs = $this->option('max') ? (int) $this->option('max') : null;
$dryRun = $this->option('dry-run');
$this->info('Starting manual execution of scheduled jobs...'.($dryRun ? ' (DRY RUN)' : ''));
$this->info("Type: {$type}".($frequency ? ", Frequency: {$frequency}" : '').", Chunk size: {$chunkSize}, Delay: {$delay}s".($maxJobs ? ", Max jobs: {$maxJobs}" : '').($dryRun ? ', Dry run: enabled' : ''));
if ($dryRun) {
$this->warn('DRY RUN MODE: No jobs will actually be dispatched');
}
if ($type === 'all' || $type === 'backups') {
$this->runScheduledBackups($chunkSize, $delay, $maxJobs, $dryRun, $frequency);
}
if ($type === 'all' || $type === 'tasks') {
$this->runScheduledTasks($chunkSize, $delay, $maxJobs, $dryRun, $frequency);
}
$this->info('Completed manual execution of scheduled jobs.'.($dryRun ? ' (DRY RUN)' : ''));
}
private function runScheduledBackups(int $chunkSize, int $delay, ?int $maxJobs = null, bool $dryRun = false, ?string $frequency = null): void
{
$this->info('Processing scheduled database backups...');
$query = ScheduledDatabaseBackup::where('enabled', true);
if ($frequency) {
$query->where(function ($q) use ($frequency) {
// Handle human-readable frequency strings
if (in_array($frequency, ['daily', 'hourly', 'weekly', 'monthly', 'yearly', 'every_minute'])) {
$q->where('frequency', $frequency);
} else {
// Handle cron expressions
$q->where('frequency', $frequency);
}
});
}
$scheduled_backups = $query->get();
if ($scheduled_backups->isEmpty()) {
$this->info('No enabled scheduled backups found'.($frequency ? " with frequency '{$frequency}'" : '').'.');
return;
}
$finalScheduledBackups = collect();
foreach ($scheduled_backups as $scheduled_backup) {
if (blank(data_get($scheduled_backup, 'database'))) {
$this->warn("Deleting backup {$scheduled_backup->id} - missing database");
$scheduled_backup->delete();
continue;
}
$server = $scheduled_backup->server();
if (blank($server)) {
$this->warn("Deleting backup {$scheduled_backup->id} - missing server");
$scheduled_backup->delete();
continue;
}
if ($server->isFunctional() === false) {
$this->warn("Skipping backup {$scheduled_backup->id} - server not functional");
continue;
}
if (isCloud() && data_get($server->team->subscription, 'stripe_invoice_paid', false) === false && $server->team->id !== 0) {
$this->warn("Skipping backup {$scheduled_backup->id} - subscription not paid");
continue;
}
$finalScheduledBackups->push($scheduled_backup);
}
if ($maxJobs && $finalScheduledBackups->count() > $maxJobs) {
$finalScheduledBackups = $finalScheduledBackups->take($maxJobs);
$this->info("Limited to {$maxJobs} scheduled backups for testing");
}
$this->info("Found {$finalScheduledBackups->count()} valid scheduled backups to process".($frequency ? " with frequency '{$frequency}'" : ''));
$chunks = $finalScheduledBackups->chunk($chunkSize);
foreach ($chunks as $index => $chunk) {
$this->info('Processing backup batch '.($index + 1).' of '.$chunks->count()." ({$chunk->count()} items)");
foreach ($chunk as $scheduled_backup) {
try {
if ($dryRun) {
$this->info("🔍 Would dispatch backup job for: {$scheduled_backup->name} (ID: {$scheduled_backup->id}, Frequency: {$scheduled_backup->frequency})");
} else {
DatabaseBackupJob::dispatch($scheduled_backup);
$this->info("✓ Dispatched backup job for: {$scheduled_backup->name} (ID: {$scheduled_backup->id}, Frequency: {$scheduled_backup->frequency})");
}
} catch (\Exception $e) {
$this->error("✗ Failed to dispatch backup job for {$scheduled_backup->id}: ".$e->getMessage());
Log::error('Error dispatching backup job: '.$e->getMessage());
}
}
if ($index < $chunks->count() - 1 && ! $dryRun) {
$this->info("Waiting {$delay} seconds before next batch...");
sleep($delay);
}
}
}
private function runScheduledTasks(int $chunkSize, int $delay, ?int $maxJobs = null, bool $dryRun = false, ?string $frequency = null): void
{
$this->info('Processing scheduled tasks...');
$query = ScheduledTask::where('enabled', true);
if ($frequency) {
$query->where(function ($q) use ($frequency) {
// Handle human-readable frequency strings
if (in_array($frequency, ['daily', 'hourly', 'weekly', 'monthly', 'yearly', 'every_minute'])) {
$q->where('frequency', $frequency);
} else {
// Handle cron expressions
$q->where('frequency', $frequency);
}
});
}
$scheduled_tasks = $query->get();
if ($scheduled_tasks->isEmpty()) {
$this->info('No enabled scheduled tasks found'.($frequency ? " with frequency '{$frequency}'" : '').'.');
return;
}
$finalScheduledTasks = collect();
foreach ($scheduled_tasks as $scheduled_task) {
$service = $scheduled_task->service;
$application = $scheduled_task->application;
$server = $scheduled_task->server();
if (blank($server)) {
$this->warn("Deleting task {$scheduled_task->id} - missing server");
$scheduled_task->delete();
continue;
}
if ($server->isFunctional() === false) {
$this->warn("Skipping task {$scheduled_task->id} - server not functional");
continue;
}
if (isCloud() && data_get($server->team->subscription, 'stripe_invoice_paid', false) === false && $server->team->id !== 0) {
$this->warn("Skipping task {$scheduled_task->id} - subscription not paid");
continue;
}
if (! $service && ! $application) {
$this->warn("Deleting task {$scheduled_task->id} - missing service and application");
$scheduled_task->delete();
continue;
}
if ($application && str($application->status)->contains('running') === false) {
$this->warn("Skipping task {$scheduled_task->id} - application not running");
continue;
}
if ($service && str($service->status)->contains('running') === false) {
$this->warn("Skipping task {$scheduled_task->id} - service not running");
continue;
}
$finalScheduledTasks->push($scheduled_task);
}
if ($maxJobs && $finalScheduledTasks->count() > $maxJobs) {
$finalScheduledTasks = $finalScheduledTasks->take($maxJobs);
$this->info("Limited to {$maxJobs} scheduled tasks for testing");
}
$this->info("Found {$finalScheduledTasks->count()} valid scheduled tasks to process".($frequency ? " with frequency '{$frequency}'" : ''));
$chunks = $finalScheduledTasks->chunk($chunkSize);
foreach ($chunks as $index => $chunk) {
$this->info('Processing task batch '.($index + 1).' of '.$chunks->count()." ({$chunk->count()} items)");
foreach ($chunk as $scheduled_task) {
try {
if ($dryRun) {
$this->info("🔍 Would dispatch task job for: {$scheduled_task->name} (ID: {$scheduled_task->id}, Frequency: {$scheduled_task->frequency})");
} else {
ScheduledTaskJob::dispatch($scheduled_task);
$this->info("✓ Dispatched task job for: {$scheduled_task->name} (ID: {$scheduled_task->id}, Frequency: {$scheduled_task->frequency})");
}
} catch (\Exception $e) {
$this->error("✗ Failed to dispatch task job for {$scheduled_task->id}: ".$e->getMessage());
Log::error('Error dispatching task job: '.$e->getMessage());
}
}
if ($index < $chunks->count() - 1 && ! $dryRun) {
$this->info("Waiting {$delay} seconds before next batch...");
sleep($delay);
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CleanupNames.php | app/Console/Commands/CleanupNames.php | <?php
namespace App\Console\Commands;
use App\Models\Application;
use App\Models\Environment;
use App\Models\PrivateKey;
use App\Models\Project;
use App\Models\S3Storage;
use App\Models\ScheduledTask;
use App\Models\Server;
use App\Models\Service;
use App\Models\StandaloneClickhouse;
use App\Models\StandaloneDragonfly;
use App\Models\StandaloneKeydb;
use App\Models\StandaloneMariadb;
use App\Models\StandaloneMongodb;
use App\Models\StandaloneMysql;
use App\Models\StandalonePostgresql;
use App\Models\StandaloneRedis;
use App\Models\Tag;
use App\Models\Team;
use App\Support\ValidationPatterns;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
class CleanupNames extends Command
{
protected $signature = 'cleanup:names
{--dry-run : Preview changes without applying them}
{--model= : Clean specific model (e.g., Project, Server)}
{--backup : Create database backup before changes}
{--force : Skip confirmation prompt}';
protected $description = 'Sanitize name fields by removing invalid characters (keeping only letters, numbers, spaces, dashes, underscores, dots, slashes, colons, parentheses)';
protected array $modelsToClean = [
'Project' => Project::class,
'Environment' => Environment::class,
'Application' => Application::class,
'Service' => Service::class,
'Server' => Server::class,
'Team' => Team::class,
'StandalonePostgresql' => StandalonePostgresql::class,
'StandaloneMysql' => StandaloneMysql::class,
'StandaloneRedis' => StandaloneRedis::class,
'StandaloneMongodb' => StandaloneMongodb::class,
'StandaloneMariadb' => StandaloneMariadb::class,
'StandaloneKeydb' => StandaloneKeydb::class,
'StandaloneDragonfly' => StandaloneDragonfly::class,
'StandaloneClickhouse' => StandaloneClickhouse::class,
'S3Storage' => S3Storage::class,
'Tag' => Tag::class,
'PrivateKey' => PrivateKey::class,
'ScheduledTask' => ScheduledTask::class,
];
protected array $changes = [];
protected int $totalProcessed = 0;
protected int $totalCleaned = 0;
public function handle(): int
{
if ($this->option('backup') && ! $this->option('dry-run')) {
$this->createBackup();
}
$modelFilter = $this->option('model');
$modelsToProcess = $modelFilter
? [$modelFilter => $this->modelsToClean[$modelFilter] ?? null]
: $this->modelsToClean;
if ($modelFilter && ! isset($this->modelsToClean[$modelFilter])) {
$this->error("Unknown model: {$modelFilter}");
$this->info('Available models: '.implode(', ', array_keys($this->modelsToClean)));
return self::FAILURE;
}
foreach ($modelsToProcess as $modelName => $modelClass) {
if (! $modelClass) {
continue;
}
$this->processModel($modelName, $modelClass);
}
if (! $this->option('dry-run') && $this->totalCleaned > 0) {
$this->logChanges();
}
if ($this->option('dry-run')) {
$this->info("Name cleanup: would sanitize {$this->totalCleaned} records");
} else {
$this->info("Name cleanup: sanitized {$this->totalCleaned} records");
}
return self::SUCCESS;
}
protected function processModel(string $modelName, string $modelClass): void
{
try {
$records = $modelClass::all(['id', 'name']);
$cleaned = 0;
foreach ($records as $record) {
$this->totalProcessed++;
$originalName = $record->name;
$sanitizedName = $this->sanitizeName($originalName);
if ($sanitizedName !== $originalName) {
$this->changes[] = [
'model' => $modelName,
'id' => $record->id,
'original' => $originalName,
'sanitized' => $sanitizedName,
'timestamp' => now(),
];
if (! $this->option('dry-run')) {
// Update without triggering events/mutators to avoid conflicts
$modelClass::where('id', $record->id)->update(['name' => $sanitizedName]);
}
$cleaned++;
$this->totalCleaned++;
// Only log in dry-run mode to preview changes
if ($this->option('dry-run')) {
$this->warn(" 🧹 {$modelName} #{$record->id}:");
$this->line(' From: '.$this->truncate($originalName, 80));
$this->line(' To: '.$this->truncate($sanitizedName, 80));
}
}
}
} catch (\Exception $e) {
$this->error("Error processing {$modelName}: ".$e->getMessage());
}
}
protected function sanitizeName(string $name): string
{
// Remove all characters that don't match the allowed pattern
// Use the shared ValidationPatterns to ensure consistency
$allowedPattern = str_replace(['/', '^', '$'], '', ValidationPatterns::NAME_PATTERN);
$sanitized = preg_replace('/[^'.$allowedPattern.']+/', '', $name);
// Clean up excessive whitespace but preserve other allowed characters
$sanitized = preg_replace('/\s+/', ' ', $sanitized);
$sanitized = trim($sanitized);
// If result is empty, provide a default name
if (empty($sanitized)) {
$sanitized = 'sanitized-item';
}
return $sanitized;
}
protected function logChanges(): void
{
$logFile = storage_path('logs/name-cleanup.log');
$logData = [
'timestamp' => now()->toISOString(),
'total_processed' => $this->totalProcessed,
'total_cleaned' => $this->totalCleaned,
'changes' => $this->changes,
];
file_put_contents($logFile, json_encode($logData, JSON_PRETTY_PRINT)."\n", FILE_APPEND);
Log::info('Name Sanitization completed', [
'total_processed' => $this->totalProcessed,
'total_sanitized' => $this->totalCleaned,
'changes_count' => count($this->changes),
]);
}
protected function createBackup(): void
{
try {
$backupFile = storage_path('backups/name-cleanup-backup-'.now()->format('Y-m-d-H-i-s').'.sql');
// Ensure backup directory exists
if (! file_exists(dirname($backupFile))) {
mkdir(dirname($backupFile), 0755, true);
}
$dbConfig = config('database.connections.'.config('database.default'));
$command = sprintf(
'pg_dump -h %s -p %s -U %s -d %s > %s',
$dbConfig['host'],
$dbConfig['port'],
$dbConfig['username'],
$dbConfig['database'],
$backupFile
);
exec($command, $output, $returnCode);
} catch (\Exception $e) {
// Log failure but continue - backup is optional safeguard
Log::warning('Name cleanup backup failed', ['error' => $e->getMessage()]);
}
}
protected function truncate(string $text, int $length): string
{
return strlen($text) > $length ? substr($text, 0, $length).'...' : $text;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Emails.php | app/Console/Commands/Emails.php | <?php
namespace App\Console\Commands;
use App\Models\Application;
use App\Models\ApplicationPreview;
use App\Models\ScheduledDatabaseBackup;
use App\Models\Server;
use App\Models\StandalonePostgresql;
use App\Models\Team;
use App\Notifications\Application\DeploymentFailed;
use App\Notifications\Application\DeploymentSuccess;
use App\Notifications\Application\StatusChanged;
use App\Notifications\Database\BackupFailed;
use App\Notifications\Database\BackupSuccess;
use App\Notifications\Test;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Mail\Message;
use Illuminate\Notifications\Messages\MailMessage;
use Mail;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\select;
use function Laravel\Prompts\text;
class Emails extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'emails';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Send out test / prod emails';
/**
* Execute the console command.
*/
private ?MailMessage $mail = null;
private ?string $email = null;
public function handle()
{
$type = select(
'Which Email should be sent?',
options: [
'updates' => 'Send Update Email to all users',
'emails-test' => 'Test',
'database-backup-statuses-daily' => 'Database - Backup Statuses (Daily)',
'application-deployment-success-daily' => 'Application - Deployment Success (Daily)',
'application-deployment-success' => 'Application - Deployment Success',
'application-deployment-failed' => 'Application - Deployment Failed',
'application-status-changed' => 'Application - Status Changed',
'backup-success' => 'Database - Backup Success',
'backup-failed' => 'Database - Backup Failed',
// 'invitation-link' => 'Invitation Link',
'realusers-before-trial' => 'REAL - Registered Users Before Trial without Subscription',
'realusers-server-lost-connection' => 'REAL - Server Lost Connection',
],
);
$emailsGathered = ['realusers-before-trial', 'realusers-server-lost-connection'];
if (isDev()) {
$this->email = 'test@example.com';
} else {
if (! in_array($type, $emailsGathered)) {
$this->email = text('Email Address to send to:');
}
}
set_transanctional_email_settings();
$this->mail = new MailMessage;
$this->mail->subject('Test Email');
switch ($type) {
case 'updates':
$teams = Team::all();
if (! $teams || $teams->isEmpty()) {
echo 'No teams found.'.PHP_EOL;
return;
}
$emails = [];
foreach ($teams as $team) {
foreach ($team->members as $member) {
if ($member->email && $member->marketing_emails) {
$emails[] = $member->email;
}
}
}
$emails = array_unique($emails);
$this->info('Sending to '.count($emails).' emails.');
foreach ($emails as $email) {
$this->info($email);
}
$confirmed = confirm('Are you sure?');
if ($confirmed) {
foreach ($emails as $email) {
$this->mail = new MailMessage;
$this->mail->subject('One-click Services, Docker Compose support');
$unsubscribeUrl = route('unsubscribe.marketing.emails', [
'token' => encrypt($email),
]);
$this->mail->view('emails.updates', ['unsubscribeUrl' => $unsubscribeUrl]);
$this->sendEmail($email);
}
}
break;
case 'emails-test':
$this->mail = (new Test)->toMail();
$this->sendEmail();
break;
case 'application-deployment-success-daily':
$applications = Application::all();
foreach ($applications as $application) {
$deployments = $application->get_last_days_deployments();
if ($deployments->isEmpty()) {
continue;
}
$this->mail = (new DeploymentSuccess($application, 'test'))->toMail();
$this->sendEmail();
}
break;
case 'application-deployment-success':
$application = Application::all()->first();
$this->mail = (new DeploymentSuccess($application, 'test'))->toMail();
$this->sendEmail();
break;
case 'application-deployment-failed':
$application = Application::all()->first();
$preview = ApplicationPreview::all()->first();
if (! $preview) {
$preview = ApplicationPreview::create([
'application_id' => $application->id,
'pull_request_id' => 1,
'pull_request_html_url' => 'http://example.com',
'fqdn' => $application->fqdn,
]);
}
$this->mail = (new DeploymentFailed($application, 'test'))->toMail();
$this->sendEmail();
$this->mail = (new DeploymentFailed($application, 'test', $preview))->toMail();
$this->sendEmail();
break;
case 'application-status-changed':
$application = Application::all()->first();
$this->mail = (new StatusChanged($application))->toMail();
$this->sendEmail();
break;
case 'backup-failed':
$backup = ScheduledDatabaseBackup::all()->first();
$db = StandalonePostgresql::all()->first();
if (! $backup) {
$backup = ScheduledDatabaseBackup::create([
'enabled' => true,
'frequency' => 'daily',
'save_s3' => false,
'database_id' => $db->id,
'database_type' => $db->getMorphClass(),
'team_id' => 0,
]);
}
$output = 'Because of an error, the backup of the database '.$db->name.' failed.';
$this->mail = (new BackupFailed($backup, $db, $output, $backup->database_name ?? 'unknown'))->toMail();
$this->sendEmail();
break;
case 'backup-success':
$backup = ScheduledDatabaseBackup::all()->first();
$db = StandalonePostgresql::all()->first();
if (! $backup) {
$backup = ScheduledDatabaseBackup::create([
'enabled' => true,
'frequency' => 'daily',
'save_s3' => false,
'database_id' => $db->id,
'database_type' => $db->getMorphClass(),
'team_id' => 0,
]);
}
// $this->mail = (new BackupSuccess($backup->frequency, $db->name))->toMail();
$this->sendEmail();
break;
// case 'invitation-link':
// $user = User::all()->first();
// $invitation = TeamInvitation::whereEmail($user->email)->first();
// if (!$invitation) {
// $invitation = TeamInvitation::create([
// 'uuid' => Str::uuid(),
// 'email' => $user->email,
// 'team_id' => 1,
// 'link' => 'http://example.com',
// ]);
// }
// $this->mail = (new InvitationLink($user))->toMail();
// $this->sendEmail();
// break;
case 'realusers-before-trial':
$this->mail = new MailMessage;
$this->mail->view('emails.before-trial-conversion');
$this->mail->subject('Trial period has been added for all subscription plans.');
$teams = Team::doesntHave('subscription')->where('id', '!=', 0)->get();
if (! $teams || $teams->isEmpty()) {
echo 'No teams found.'.PHP_EOL;
return;
}
$emails = [];
foreach ($teams as $team) {
foreach ($team->members as $member) {
if ($member->email) {
$emails[] = $member->email;
}
}
}
$emails = array_unique($emails);
$this->info('Sending to '.count($emails).' emails.');
foreach ($emails as $email) {
$this->info($email);
}
$confirmed = confirm('Are you sure?');
if ($confirmed) {
foreach ($emails as $email) {
$this->sendEmail($email);
}
}
break;
case 'realusers-server-lost-connection':
$serverId = text('Server Id');
$server = Server::find($serverId);
if (! $server) {
throw new Exception('Server not found');
}
$admins = [];
$members = $server->team->members;
foreach ($members as $member) {
if ($member->isAdmin()) {
$admins[] = $member->email;
}
}
$this->info('Sending to '.count($admins).' admins.');
foreach ($admins as $admin) {
$this->info($admin);
}
$this->mail = new MailMessage;
$this->mail->view('emails.server-lost-connection', [
'name' => $server->name,
]);
$this->mail->subject('Action required: Server '.$server->name.' lost connection.');
foreach ($admins as $email) {
$this->sendEmail($email);
}
break;
}
}
private function sendEmail(?string $email = null)
{
if ($email) {
$this->email = $email;
}
Mail::send(
[],
[],
fn (Message $message) => $message
->to($this->email)
->subject($this->mail->subject)
->html((string) $this->mail->render())
);
$this->info("Email sent to $this->email successfully. 📧");
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Scheduler.php | app/Console/Commands/Scheduler.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Scheduler extends Command
{
protected $signature = 'start:scheduler';
protected $description = 'Start Scheduler';
public function handle()
{
if (config('constants.horizon.is_scheduler_enabled')) {
$this->info('Scheduler is enabled on this server.');
$this->call('schedule:work');
exit(0);
} else {
exit(0);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/ClearGlobalSearchCache.php | app/Console/Commands/ClearGlobalSearchCache.php | <?php
namespace App\Console\Commands;
use App\Livewire\GlobalSearch;
use App\Models\Team;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
class ClearGlobalSearchCache extends Command
{
/**
* The name and signature of the console command.
*/
protected $signature = 'search:clear {--team= : Clear cache for specific team ID} {--all : Clear cache for all teams}';
/**
* The console command description.
*/
protected $description = 'Clear the global search cache for testing or manual refresh';
/**
* Execute the console command.
*/
public function handle(): int
{
if ($this->option('all')) {
return $this->clearAllTeamsCache();
}
if ($teamId = $this->option('team')) {
return $this->clearTeamCache($teamId);
}
// If no options provided, clear cache for current user's team
if (! auth()->check()) {
$this->error('No authenticated user found. Use --team=ID or --all option.');
return Command::FAILURE;
}
$teamId = auth()->user()->currentTeam()->id;
return $this->clearTeamCache($teamId);
}
private function clearTeamCache(int $teamId): int
{
$team = Team::find($teamId);
if (! $team) {
$this->error("Team with ID {$teamId} not found.");
return Command::FAILURE;
}
GlobalSearch::clearTeamCache($teamId);
$this->info("✓ Cleared global search cache for team: {$team->name} (ID: {$teamId})");
return Command::SUCCESS;
}
private function clearAllTeamsCache(): int
{
$teams = Team::all();
if ($teams->isEmpty()) {
$this->warn('No teams found.');
return Command::SUCCESS;
}
$count = 0;
foreach ($teams as $team) {
GlobalSearch::clearTeamCache($team->id);
$count++;
}
$this->info("✓ Cleared global search cache for {$count} team(s)");
return Command::SUCCESS;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CheckTraefikVersionCommand.php | app/Console/Commands/CheckTraefikVersionCommand.php | <?php
namespace App\Console\Commands;
use App\Jobs\CheckTraefikVersionJob;
use Illuminate\Console\Command;
class CheckTraefikVersionCommand extends Command
{
protected $signature = 'traefik:check-version';
protected $description = 'Check Traefik proxy versions on all servers and send notifications for outdated versions';
public function handle(): int
{
$this->info('Checking Traefik versions on all servers...');
try {
CheckTraefikVersionJob::dispatch();
$this->info('Traefik version check job dispatched successfully.');
$this->info('Notifications will be sent to teams with outdated Traefik versions.');
return Command::SUCCESS;
} catch (\Exception $e) {
$this->error('Failed to dispatch Traefik version check job: '.$e->getMessage());
return Command::FAILURE;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/SyncBunny.php | app/Console/Commands/SyncBunny.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Pool;
use Illuminate\Support\Facades\Http;
use function Laravel\Prompts\confirm;
class SyncBunny extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'sync:bunny {--templates} {--release} {--github-releases} {--github-versions} {--nightly}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Sync files to BunnyCDN';
/**
* Fetch GitHub releases and sync to GitHub repository
*/
private function syncReleasesToGitHubRepo(): bool
{
$this->info('Fetching releases from GitHub...');
try {
$response = Http::timeout(30)
->get('https://api.github.com/repos/coollabsio/coolify/releases', [
'per_page' => 30, // Fetch more releases for better changelog
]);
if (! $response->successful()) {
$this->error('Failed to fetch releases from GitHub: '.$response->status());
return false;
}
$releases = $response->json();
$timestamp = time();
$tmpDir = sys_get_temp_dir().'/coolify-cdn-'.$timestamp;
$branchName = 'update-releases-'.$timestamp;
// Clone the repository
$this->info('Cloning coolify-cdn repository...');
$output = [];
exec('gh repo clone coollabsio/coolify-cdn '.escapeshellarg($tmpDir).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to clone repository: '.implode("\n", $output));
return false;
}
// Create feature branch
$this->info('Creating feature branch...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git checkout -b '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to create branch: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Write releases.json
$this->info('Writing releases.json...');
$releasesPath = "$tmpDir/json/releases.json";
$releasesDir = dirname($releasesPath);
// Ensure directory exists
if (! is_dir($releasesDir)) {
$this->info("Creating directory: $releasesDir");
if (! mkdir($releasesDir, 0755, true)) {
$this->error("Failed to create directory: $releasesDir");
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
}
$jsonContent = json_encode($releases, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$bytesWritten = file_put_contents($releasesPath, $jsonContent);
if ($bytesWritten === false) {
$this->error("Failed to write releases.json to: $releasesPath");
$this->error('Possible reasons: permission denied or disk full.');
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Stage and commit
$this->info('Committing changes...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git add json/releases.json 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to stage changes: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
$this->info('Checking for changes...');
$statusOutput = [];
exec('cd '.escapeshellarg($tmpDir).' && git status --porcelain json/releases.json 2>&1', $statusOutput, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to check repository status: '.implode("\n", $statusOutput));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
if (empty(array_filter($statusOutput))) {
$this->info('Releases are already up to date. No changes to commit.');
exec('rm -rf '.escapeshellarg($tmpDir));
return true;
}
$commitMessage = 'Update releases.json with latest releases - '.date('Y-m-d H:i:s');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git commit -m '.escapeshellarg($commitMessage).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to commit changes: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Push to remote
$this->info('Pushing branch to remote...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git push origin '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to push branch: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Create pull request
$this->info('Creating pull request...');
$prTitle = 'Update releases.json - '.date('Y-m-d H:i:s');
$prBody = 'Automated update of releases.json with latest '.count($releases).' releases from GitHub API';
$prCommand = 'gh pr create --repo coollabsio/coolify-cdn --title '.escapeshellarg($prTitle).' --body '.escapeshellarg($prBody).' --base main --head '.escapeshellarg($branchName).' 2>&1';
$output = [];
exec($prCommand, $output, $returnCode);
// Clean up
exec('rm -rf '.escapeshellarg($tmpDir));
if ($returnCode !== 0) {
$this->error('Failed to create PR: '.implode("\n", $output));
return false;
}
$this->info('Pull request created successfully!');
if (! empty($output)) {
$this->info('PR Output: '.implode("\n", $output));
}
$this->info('Total releases synced: '.count($releases));
return true;
} catch (\Throwable $e) {
$this->error('Error syncing releases: '.$e->getMessage());
return false;
}
}
/**
* Sync both releases.json and versions.json to GitHub repository in one PR
*/
private function syncReleasesAndVersionsToGitHubRepo(string $versionsLocation, bool $nightly = false): bool
{
$this->info('Syncing releases.json and versions.json to GitHub repository...');
try {
// 1. Fetch releases from GitHub API
$this->info('Fetching releases from GitHub API...');
$response = Http::timeout(30)
->get('https://api.github.com/repos/coollabsio/coolify/releases', [
'per_page' => 30,
]);
if (! $response->successful()) {
$this->error('Failed to fetch releases from GitHub: '.$response->status());
return false;
}
$releases = $response->json();
// 2. Read versions.json
if (! file_exists($versionsLocation)) {
$this->error("versions.json not found at: $versionsLocation");
return false;
}
$file = file_get_contents($versionsLocation);
$versionsJson = json_decode($file, true);
$actualVersion = data_get($versionsJson, 'coolify.v4.version');
$timestamp = time();
$tmpDir = sys_get_temp_dir().'/coolify-cdn-combined-'.$timestamp;
$branchName = 'update-releases-and-versions-'.$timestamp;
$versionsTargetPath = $nightly ? 'json/versions-nightly.json' : 'json/versions.json';
// 3. Clone the repository
$this->info('Cloning coolify-cdn repository...');
$output = [];
exec('gh repo clone coollabsio/coolify-cdn '.escapeshellarg($tmpDir).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to clone repository: '.implode("\n", $output));
return false;
}
// 4. Create feature branch
$this->info('Creating feature branch...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git checkout -b '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to create branch: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// 5. Write releases.json
$this->info('Writing releases.json...');
$releasesPath = "$tmpDir/json/releases.json";
$releasesDir = dirname($releasesPath);
if (! is_dir($releasesDir)) {
if (! mkdir($releasesDir, 0755, true)) {
$this->error("Failed to create directory: $releasesDir");
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
}
$releasesJsonContent = json_encode($releases, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if (file_put_contents($releasesPath, $releasesJsonContent) === false) {
$this->error("Failed to write releases.json to: $releasesPath");
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// 6. Write versions.json
$this->info('Writing versions.json...');
$versionsPath = "$tmpDir/$versionsTargetPath";
$versionsDir = dirname($versionsPath);
if (! is_dir($versionsDir)) {
if (! mkdir($versionsDir, 0755, true)) {
$this->error("Failed to create directory: $versionsDir");
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
}
$versionsJsonContent = json_encode($versionsJson, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
if (file_put_contents($versionsPath, $versionsJsonContent) === false) {
$this->error("Failed to write versions.json to: $versionsPath");
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// 7. Stage both files
$this->info('Staging changes...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git add json/releases.json '.escapeshellarg($versionsTargetPath).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to stage changes: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// 8. Check for changes
$this->info('Checking for changes...');
$statusOutput = [];
exec('cd '.escapeshellarg($tmpDir).' && git status --porcelain 2>&1', $statusOutput, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to check repository status: '.implode("\n", $statusOutput));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
if (empty(array_filter($statusOutput))) {
$this->info('Both files are already up to date. No changes to commit.');
exec('rm -rf '.escapeshellarg($tmpDir));
return true;
}
// 9. Commit changes
$envLabel = $nightly ? 'NIGHTLY' : 'PRODUCTION';
$commitMessage = "Update releases.json and $envLabel versions.json to $actualVersion - ".date('Y-m-d H:i:s');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git commit -m '.escapeshellarg($commitMessage).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to commit changes: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// 10. Push to remote
$this->info('Pushing branch to remote...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git push origin '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to push branch: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// 11. Create pull request
$this->info('Creating pull request...');
$prTitle = "Update releases.json and $envLabel versions.json to $actualVersion - ".date('Y-m-d H:i:s');
$prBody = "Automated update:\n- releases.json with latest ".count($releases)." releases from GitHub API\n- $envLabel versions.json to version $actualVersion";
$prCommand = 'gh pr create --repo coollabsio/coolify-cdn --title '.escapeshellarg($prTitle).' --body '.escapeshellarg($prBody).' --base main --head '.escapeshellarg($branchName).' 2>&1';
$output = [];
exec($prCommand, $output, $returnCode);
// 12. Clean up
exec('rm -rf '.escapeshellarg($tmpDir));
if ($returnCode !== 0) {
$this->error('Failed to create PR: '.implode("\n", $output));
return false;
}
$this->info('Pull request created successfully!');
if (! empty($output)) {
$this->info('PR URL: '.implode("\n", $output));
}
$this->info("Version synced: $actualVersion");
$this->info('Total releases synced: '.count($releases));
return true;
} catch (\Throwable $e) {
$this->error('Error syncing to GitHub: '.$e->getMessage());
return false;
}
}
/**
* Sync versions.json to GitHub repository via PR
*/
private function syncVersionsToGitHubRepo(string $versionsLocation, bool $nightly = false): bool
{
$this->info('Syncing versions.json to GitHub repository...');
try {
if (! file_exists($versionsLocation)) {
$this->error("versions.json not found at: $versionsLocation");
return false;
}
$file = file_get_contents($versionsLocation);
$json = json_decode($file, true);
$actualVersion = data_get($json, 'coolify.v4.version');
$timestamp = time();
$tmpDir = sys_get_temp_dir().'/coolify-cdn-versions-'.$timestamp;
$branchName = 'update-versions-'.$timestamp;
$targetPath = $nightly ? 'json/versions-nightly.json' : 'json/versions.json';
// Clone the repository
$this->info('Cloning coolify-cdn repository...');
exec('gh repo clone coollabsio/coolify-cdn '.escapeshellarg($tmpDir).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to clone repository: '.implode("\n", $output));
return false;
}
// Create feature branch
$this->info('Creating feature branch...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git checkout -b '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to create branch: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Write versions.json
$this->info('Writing versions.json...');
$versionsPath = "$tmpDir/$targetPath";
$versionsDir = dirname($versionsPath);
// Ensure directory exists
if (! is_dir($versionsDir)) {
$this->info("Creating directory: $versionsDir");
if (! mkdir($versionsDir, 0755, true)) {
$this->error("Failed to create directory: $versionsDir");
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
}
$jsonContent = json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
$bytesWritten = file_put_contents($versionsPath, $jsonContent);
if ($bytesWritten === false) {
$this->error("Failed to write versions.json to: $versionsPath");
$this->error('Possible reasons: permission denied or disk full.');
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Stage and commit
$this->info('Committing changes...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git add '.escapeshellarg($targetPath).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to stage changes: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
$this->info('Checking for changes...');
$statusOutput = [];
exec('cd '.escapeshellarg($tmpDir).' && git status --porcelain '.escapeshellarg($targetPath).' 2>&1', $statusOutput, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to check repository status: '.implode("\n", $statusOutput));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
if (empty(array_filter($statusOutput))) {
$this->info('versions.json is already up to date. No changes to commit.');
exec('rm -rf '.escapeshellarg($tmpDir));
return true;
}
$envLabel = $nightly ? 'NIGHTLY' : 'PRODUCTION';
$commitMessage = "Update $envLabel versions.json to $actualVersion - ".date('Y-m-d H:i:s');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git commit -m '.escapeshellarg($commitMessage).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to commit changes: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Push to remote
$this->info('Pushing branch to remote...');
$output = [];
exec('cd '.escapeshellarg($tmpDir).' && git push origin '.escapeshellarg($branchName).' 2>&1', $output, $returnCode);
if ($returnCode !== 0) {
$this->error('Failed to push branch: '.implode("\n", $output));
exec('rm -rf '.escapeshellarg($tmpDir));
return false;
}
// Create pull request
$this->info('Creating pull request...');
$prTitle = "Update $envLabel versions.json to $actualVersion - ".date('Y-m-d H:i:s');
$prBody = "Automated update of $envLabel versions.json to version $actualVersion";
$output = [];
$prCommand = 'gh pr create --repo coollabsio/coolify-cdn --title '.escapeshellarg($prTitle).' --body '.escapeshellarg($prBody).' --base main --head '.escapeshellarg($branchName).' 2>&1';
exec($prCommand, $output, $returnCode);
// Clean up
exec('rm -rf '.escapeshellarg($tmpDir));
if ($returnCode !== 0) {
$this->error('Failed to create PR: '.implode("\n", $output));
return false;
}
$this->info('Pull request created successfully!');
if (! empty($output)) {
$this->info('PR URL: '.implode("\n", $output));
}
$this->info("Version synced: $actualVersion");
return true;
} catch (\Throwable $e) {
$this->error('Error syncing versions.json: '.$e->getMessage());
return false;
}
}
/**
* Execute the console command.
*/
public function handle()
{
$that = $this;
$only_template = $this->option('templates');
$only_version = $this->option('release');
$only_github_releases = $this->option('github-releases');
$only_github_versions = $this->option('github-versions');
$nightly = $this->option('nightly');
$bunny_cdn = 'https://cdn.coollabs.io';
$bunny_cdn_path = 'coolify';
$bunny_cdn_storage_name = 'coolcdn';
$parent_dir = realpath(dirname(__FILE__).'/../../..');
$compose_file = 'docker-compose.yml';
$compose_file_prod = 'docker-compose.prod.yml';
$install_script = 'install.sh';
$upgrade_script = 'upgrade.sh';
$production_env = '.env.production';
$service_template = config('constants.services.file_name');
$versions = 'versions.json';
$compose_file_location = "$parent_dir/$compose_file";
$compose_file_prod_location = "$parent_dir/$compose_file_prod";
$install_script_location = "$parent_dir/scripts/install.sh";
$upgrade_script_location = "$parent_dir/scripts/upgrade.sh";
$production_env_location = "$parent_dir/.env.production";
$versions_location = "$parent_dir/$versions";
PendingRequest::macro('storage', function ($fileName) use ($that) {
$headers = [
'AccessKey' => config('constants.bunny.storage_api_key'),
'Accept' => 'application/json',
'Content-Type' => 'application/octet-stream',
];
$fileStream = fopen($fileName, 'r');
$file = fread($fileStream, filesize($fileName));
$that->info('Uploading: '.$fileName);
return PendingRequest::baseUrl('https://storage.bunnycdn.com')->withHeaders($headers)->withBody($file)->throw();
});
PendingRequest::macro('purge', function ($url) use ($that) {
$headers = [
'AccessKey' => config('constants.bunny.api_key'),
'Accept' => 'application/json',
];
$that->info('Purging: '.$url);
return PendingRequest::withHeaders($headers)->get('https://api.bunny.net/purge', [
'url' => $url,
'async' => false,
]);
});
try {
if ($nightly) {
$bunny_cdn_path = 'coolify-nightly';
$compose_file_location = "$parent_dir/other/nightly/$compose_file";
$compose_file_prod_location = "$parent_dir/other/nightly/$compose_file_prod";
$production_env_location = "$parent_dir/other/nightly/$production_env";
$upgrade_script_location = "$parent_dir/other/nightly/$upgrade_script";
$install_script_location = "$parent_dir/other/nightly/$install_script";
$versions_location = "$parent_dir/other/nightly/$versions";
}
if (! $only_template && ! $only_version && ! $only_github_releases && ! $only_github_versions) {
if ($nightly) {
$this->info('About to sync files NIGHTLY (docker-compose.prod.yaml, upgrade.sh, install.sh, etc) to BunnyCDN.');
} else {
$this->info('About to sync files PRODUCTION (docker-compose.yml, docker-compose.prod.yml, upgrade.sh, install.sh, etc) to BunnyCDN.');
}
$confirmed = confirm('Are you sure you want to sync?');
if (! $confirmed) {
return;
}
}
if ($only_template) {
$this->info('About to sync '.config('constants.services.file_name').' to BunnyCDN.');
$confirmed = confirm('Are you sure you want to sync?');
if (! $confirmed) {
return;
}
Http::pool(fn (Pool $pool) => [
$pool->storage(fileName: "$parent_dir/templates/$service_template")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$service_template"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$service_template"),
]);
$this->info('Service template uploaded & purged...');
return;
} elseif ($only_version) {
if ($nightly) {
$this->info('About to sync NIGHTLY versions.json to BunnyCDN and create GitHub PR.');
} else {
$this->info('About to sync PRODUCTION versions.json to BunnyCDN and create GitHub PR.');
}
$file = file_get_contents($versions_location);
$json = json_decode($file, true);
$actual_version = data_get($json, 'coolify.v4.version');
$this->info("Version: {$actual_version}");
$this->info('This will:');
$this->info(' 1. Sync versions.json to BunnyCDN (deprecated but still supported)');
$this->info(' 2. Create ONE GitHub PR with both releases.json and versions.json');
$this->newLine();
$confirmed = confirm('Are you sure you want to proceed?');
if (! $confirmed) {
return;
}
// 1. Sync versions.json to BunnyCDN (deprecated but still needed)
$this->info('Step 1/2: Syncing versions.json to BunnyCDN...');
Http::pool(fn (Pool $pool) => [
$pool->storage(fileName: $versions_location)->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$versions"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$versions"),
]);
$this->info('✓ versions.json uploaded & purged to BunnyCDN');
$this->newLine();
// 2. Create GitHub PR with both releases.json and versions.json
$this->info('Step 2/2: Creating GitHub PR with releases.json and versions.json...');
$githubSuccess = $this->syncReleasesAndVersionsToGitHubRepo($versions_location, $nightly);
if ($githubSuccess) {
$this->info('✓ GitHub PR created successfully with both files');
} else {
$this->error('✗ Failed to create GitHub PR');
}
$this->newLine();
$this->info('=== Summary ===');
$this->info('BunnyCDN sync: ✓ Complete');
$this->info('GitHub PR: '.($githubSuccess ? '✓ Created (releases.json + versions.json)' : '✗ Failed'));
return;
} elseif ($only_github_releases) {
$this->info('About to sync GitHub releases to GitHub repository.');
$confirmed = confirm('Are you sure you want to sync GitHub releases?');
if (! $confirmed) {
return;
}
// Sync releases to GitHub repository
$this->syncReleasesToGitHubRepo();
return;
} elseif ($only_github_versions) {
$envLabel = $nightly ? 'NIGHTLY' : 'PRODUCTION';
$file = file_get_contents($versions_location);
$json = json_decode($file, true);
$actual_version = data_get($json, 'coolify.v4.version');
$this->info("About to sync $envLabel versions.json ($actual_version) to GitHub repository.");
$confirmed = confirm('Are you sure you want to sync versions.json via GitHub PR?');
if (! $confirmed) {
return;
}
// Sync versions.json to GitHub repository
$this->syncVersionsToGitHubRepo($versions_location, $nightly);
return;
}
Http::pool(fn (Pool $pool) => [
$pool->storage(fileName: "$compose_file_location")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$compose_file"),
$pool->storage(fileName: "$compose_file_prod_location")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$compose_file_prod"),
$pool->storage(fileName: "$production_env_location")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$production_env"),
$pool->storage(fileName: "$upgrade_script_location")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$upgrade_script"),
$pool->storage(fileName: "$install_script_location")->put("/$bunny_cdn_storage_name/$bunny_cdn_path/$install_script"),
]);
Http::pool(fn (Pool $pool) => [
$pool->purge("$bunny_cdn/$bunny_cdn_path/$compose_file"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$compose_file_prod"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$production_env"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$upgrade_script"),
$pool->purge("$bunny_cdn/$bunny_cdn_path/$install_script"),
]);
$this->info('All files uploaded & purged...');
} catch (\Throwable $e) {
$this->error('Error: '.$e->getMessage());
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CleanupDatabase.php | app/Console/Commands/CleanupDatabase.php | <?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class CleanupDatabase extends Command
{
protected $signature = 'cleanup:database {--yes} {--keep-days=}';
protected $description = 'Cleanup database';
public function handle()
{
if ($this->option('yes')) {
echo "Running database cleanup...\n";
} else {
echo "Running database cleanup in dry-run mode...\n";
}
if (isCloud()) {
// Later on we can increase this to 180 days or dynamically set
$keep_days = $this->option('keep-days') ?? 60;
} else {
$keep_days = $this->option('keep-days') ?? 60;
}
echo "Keep days: $keep_days\n";
// Cleanup failed jobs table
$failed_jobs = DB::table('failed_jobs')->where('failed_at', '<', now()->subDays(1));
$count = $failed_jobs->count();
echo "Delete $count entries from failed_jobs.\n";
if ($this->option('yes')) {
$failed_jobs->delete();
}
// Cleanup sessions table
$sessions = DB::table('sessions')->where('last_activity', '<', now()->subDays($keep_days)->timestamp);
$count = $sessions->count();
echo "Delete $count entries from sessions.\n";
if ($this->option('yes')) {
$sessions->delete();
}
// Cleanup activity_log table
$activity_log = DB::table('activity_log')->where('created_at', '<', now()->subDays($keep_days))->orderBy('created_at', 'desc')->skip(10);
$count = $activity_log->count();
echo "Delete $count entries from activity_log.\n";
if ($this->option('yes')) {
$activity_log->delete();
}
// Cleanup application_deployment_queues table
$application_deployment_queues = DB::table('application_deployment_queues')->where('created_at', '<', now()->subDays($keep_days))->orderBy('created_at', 'desc')->skip(10);
$count = $application_deployment_queues->count();
echo "Delete $count entries from application_deployment_queues.\n";
if ($this->option('yes')) {
$application_deployment_queues->delete();
}
// Cleanup scheduled_task_executions table
$scheduled_task_executions = DB::table('scheduled_task_executions')->where('created_at', '<', now()->subDays($keep_days))->orderBy('created_at', 'desc');
$count = $scheduled_task_executions->count();
echo "Delete $count entries from scheduled_task_executions.\n";
if ($this->option('yes')) {
$scheduled_task_executions->delete();
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/CheckApplicationDeploymentQueue.php | app/Console/Commands/CheckApplicationDeploymentQueue.php | <?php
namespace App\Console\Commands;
use App\Enums\ApplicationDeploymentStatus;
use App\Models\ApplicationDeploymentQueue;
use Illuminate\Console\Command;
class CheckApplicationDeploymentQueue extends Command
{
protected $signature = 'check:deployment-queue {--force} {--seconds=3600}';
protected $description = 'Check application deployment queue.';
public function handle()
{
$seconds = $this->option('seconds');
$deployments = ApplicationDeploymentQueue::whereIn('status', [
ApplicationDeploymentStatus::IN_PROGRESS,
ApplicationDeploymentStatus::QUEUED,
])->where('created_at', '<=', now()->subSeconds($seconds))->get();
if ($deployments->isEmpty()) {
$this->info('No deployments found in the last '.$seconds.' seconds.');
return;
}
$this->info('Found '.$deployments->count().' deployments created in the last '.$seconds.' seconds.');
foreach ($deployments as $deployment) {
if ($this->option('force')) {
$this->info('Deployment '.$deployment->id.' created at '.$deployment->created_at.' is older than '.$seconds.' seconds. Setting status to failed.');
$this->cancelDeployment($deployment);
} else {
$this->info('Deployment '.$deployment->id.' created at '.$deployment->created_at.' is older than '.$seconds.' seconds. Setting status to failed.');
if ($this->confirm('Do you want to cancel this deployment?', true)) {
$this->cancelDeployment($deployment);
}
}
}
}
private function cancelDeployment(ApplicationDeploymentQueue $deployment)
{
$deployment->update(['status' => ApplicationDeploymentStatus::FAILED]);
if ($deployment->server?->isFunctional()) {
remote_process(['docker rm -f '.$deployment->deployment_uuid], $deployment->server, false);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Dev.php | app/Console/Commands/Dev.php | <?php
namespace App\Console\Commands;
use App\Jobs\CheckHelperImageJob;
use App\Models\InstanceSettings;
use App\Models\ScheduledDatabaseBackupExecution;
use App\Models\ScheduledTaskExecution;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
class Dev extends Command
{
protected $signature = 'dev {--init}';
protected $description = 'Helper commands for development.';
public function handle()
{
if ($this->option('init')) {
$this->init();
return;
}
}
public function init()
{
// Generate APP_KEY if not exists
if (empty(config('app.key'))) {
echo "Generating APP_KEY.\n";
Artisan::call('key:generate');
}
// Generate STORAGE link if not exists
if (! file_exists(public_path('storage'))) {
echo "Generating STORAGE link.\n";
Artisan::call('storage:link');
}
// Seed database if it's empty
$settings = InstanceSettings::find(0);
if (! $settings) {
echo "Initializing instance, seeding database.\n";
Artisan::call('migrate --seed');
} else {
echo "Instance already initialized.\n";
}
// Clean up stuck jobs and stale locks on development startup
try {
echo "Cleaning up Redis (stuck jobs and stale locks)...\n";
Artisan::call('cleanup:redis', ['--restart' => true, '--clear-locks' => true]);
echo "Redis cleanup completed.\n";
} catch (\Throwable $e) {
echo "Error in cleanup:redis: {$e->getMessage()}\n";
}
try {
$updatedTaskCount = ScheduledTaskExecution::where('status', 'running')->update([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
]);
if ($updatedTaskCount > 0) {
echo "Marked {$updatedTaskCount} stuck scheduled task executions as failed\n";
}
} catch (\Throwable $e) {
echo "Could not cleanup stuck scheduled task executions: {$e->getMessage()}\n";
}
try {
$updatedBackupCount = ScheduledDatabaseBackupExecution::where('status', 'running')->update([
'status' => 'failed',
'message' => 'Marked as failed during Coolify startup - job was interrupted',
'finished_at' => Carbon::now(),
]);
if ($updatedBackupCount > 0) {
echo "Marked {$updatedBackupCount} stuck database backup executions as failed\n";
}
} catch (\Throwable $e) {
echo "Could not cleanup stuck database backup executions: {$e->getMessage()}\n";
}
CheckHelperImageJob::dispatch();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Cloud/RestoreDatabase.php | app/Console/Commands/Cloud/RestoreDatabase.php | <?php
namespace App\Console\Commands\Cloud;
use Illuminate\Console\Command;
class RestoreDatabase extends Command
{
protected $signature = 'cloud:restore-database {file : Path to the database dump file} {--debug : Show detailed debug output}';
protected $description = 'Restore a PostgreSQL database from a dump file (development mode only)';
private bool $debug = false;
public function handle(): int
{
$this->debug = $this->option('debug');
if (! $this->isDevelopment()) {
$this->error('This command can only be run in development mode.');
return 1;
}
$filePath = $this->argument('file');
if (! file_exists($filePath)) {
$this->error("File not found: {$filePath}");
return 1;
}
if (! is_readable($filePath)) {
$this->error("File is not readable: {$filePath}");
return 1;
}
try {
$this->info('Starting database restoration...');
$database = config('database.connections.pgsql.database');
$host = config('database.connections.pgsql.host');
$port = config('database.connections.pgsql.port');
$username = config('database.connections.pgsql.username');
$password = config('database.connections.pgsql.password');
if (! $database || ! $username) {
$this->error('Database configuration is incomplete.');
return 1;
}
$this->info("Restoring to database: {$database}");
// Drop all tables
if (! $this->dropAllTables($database, $host, $port, $username, $password)) {
return 1;
}
// Restore the database dump
if (! $this->restoreDatabaseDump($filePath, $database, $host, $port, $username, $password)) {
return 1;
}
$this->info('Database restoration completed successfully!');
return 0;
} catch (\Exception $e) {
$this->error("An error occurred: {$e->getMessage()}");
return 1;
}
}
private function dropAllTables(string $database, string $host, string $port, string $username, string $password): bool
{
$this->info('Dropping all tables...');
// SQL to drop all tables
$dropTablesSQL = <<<'SQL'
DO $$ DECLARE
r RECORD;
BEGIN
FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = 'public') LOOP
EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
END LOOP;
END $$;
SQL;
// Build the psql command to drop all tables
$command = sprintf(
'PGPASSWORD=%s psql -h %s -p %s -U %s -d %s -c %s',
escapeshellarg($password),
escapeshellarg($host),
escapeshellarg($port),
escapeshellarg($username),
escapeshellarg($database),
escapeshellarg($dropTablesSQL)
);
if ($this->debug) {
$this->line('<comment>Executing drop command:</comment>');
$this->line($command);
}
$output = shell_exec($command.' 2>&1');
if ($this->debug) {
$this->line("<comment>Output:</comment> {$output}");
}
$this->info('All tables dropped successfully.');
return true;
}
private function restoreDatabaseDump(string $filePath, string $database, string $host, string $port, string $username, string $password): bool
{
$this->info('Restoring database from dump file...');
// Handle gzipped files by decompressing first
$actualFile = $filePath;
if (str_ends_with($filePath, '.gz')) {
$actualFile = rtrim($filePath, '.gz');
$this->info('Decompressing gzipped dump file...');
$decompressCommand = sprintf(
'gunzip -c %s > %s',
escapeshellarg($filePath),
escapeshellarg($actualFile)
);
if ($this->debug) {
$this->line('<comment>Executing decompress command:</comment>');
$this->line($decompressCommand);
}
$decompressOutput = shell_exec($decompressCommand.' 2>&1');
if ($this->debug && $decompressOutput) {
$this->line("<comment>Decompress output:</comment> {$decompressOutput}");
}
}
// Use pg_restore for custom format dumps
$command = sprintf(
'PGPASSWORD=%s pg_restore -h %s -p %s -U %s -d %s -v %s',
escapeshellarg($password),
escapeshellarg($host),
escapeshellarg($port),
escapeshellarg($username),
escapeshellarg($database),
escapeshellarg($actualFile)
);
if ($this->debug) {
$this->line('<comment>Executing restore command:</comment>');
$this->line($command);
}
// Execute the restore command
$process = proc_open(
$command,
[
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
],
$pipes
);
if (! is_resource($process)) {
$this->error('Failed to start restoration process.');
return false;
}
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
$exitCode = proc_close($process);
// Clean up decompressed file if we created one
if ($actualFile !== $filePath && file_exists($actualFile)) {
unlink($actualFile);
}
if ($this->debug) {
if ($output) {
$this->line('<comment>Output:</comment>');
$this->line($output);
}
if ($error) {
$this->line('<comment>Error output:</comment>');
$this->line($error);
}
$this->line("<comment>Exit code:</comment> {$exitCode}");
}
if ($exitCode !== 0) {
$this->error("Restoration failed with exit code: {$exitCode}");
if ($error) {
$this->error('Error details:');
$this->error($error);
}
return false;
}
if ($output && ! $this->debug) {
$this->line($output);
}
return true;
}
private function isDevelopment(): bool
{
return app()->environment(['local', 'development', 'dev']);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Cloud/CloudFixSubscription.php | app/Console/Commands/Cloud/CloudFixSubscription.php | <?php
namespace App\Console\Commands\Cloud;
use App\Models\Team;
use Illuminate\Console\Command;
class CloudFixSubscription extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'cloud:fix-subscription
{--fix-canceled-subs : Fix canceled subscriptions in database}
{--verify-all : Verify all active subscriptions against Stripe}
{--fix-verified : Fix discrepancies found during verification}
{--dry-run : Show what would be fixed without making changes}
{--one : Only fix the first found subscription}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Fix Cloud subscriptions';
/**
* Execute the console command.
*/
public function handle()
{
$stripe = new \Stripe\StripeClient(config('subscription.stripe_api_key'));
if ($this->option('verify-all')) {
return $this->verifyAllActiveSubscriptions($stripe);
}
if ($this->option('fix-canceled-subs') || $this->option('dry-run')) {
return $this->fixCanceledSubscriptions($stripe);
}
$activeSubscribers = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->get();
$out = fopen('php://output', 'w');
// CSV header
fputcsv($out, [
'team_id',
'invoice_status',
'stripe_customer_url',
'stripe_subscription_id',
'subscription_status',
'subscription_url',
'note',
]);
foreach ($activeSubscribers as $team) {
$stripeSubscriptionId = $team->subscription->stripe_subscription_id;
$stripeInvoicePaid = $team->subscription->stripe_invoice_paid;
$stripeCustomerId = $team->subscription->stripe_customer_id;
if (! $stripeSubscriptionId && str($stripeInvoicePaid)->lower() != 'past_due') {
fputcsv($out, [
$team->id,
$stripeInvoicePaid,
$stripeCustomerId ? "https://dashboard.stripe.com/customers/{$stripeCustomerId}" : null,
null,
null,
null,
'Missing subscription ID while invoice not past_due',
]);
continue;
}
if (! $stripeSubscriptionId) {
// No subscription ID and invoice is past_due, still record for visibility
fputcsv($out, [
$team->id,
$stripeInvoicePaid,
$stripeCustomerId ? "https://dashboard.stripe.com/customers/{$stripeCustomerId}" : null,
null,
null,
null,
'Missing subscription ID',
]);
continue;
}
$subscription = $stripe->subscriptions->retrieve($stripeSubscriptionId);
if ($subscription->status === 'active') {
continue;
}
fputcsv($out, [
$team->id,
$stripeInvoicePaid,
$stripeCustomerId ? "https://dashboard.stripe.com/customers/{$stripeCustomerId}" : null,
$stripeSubscriptionId,
$subscription->status,
"https://dashboard.stripe.com/subscriptions/{$stripeSubscriptionId}",
'Subscription not active',
]);
}
fclose($out);
}
/**
* Fix canceled subscriptions in the database
*/
private function fixCanceledSubscriptions(\Stripe\StripeClient $stripe)
{
$isDryRun = $this->option('dry-run');
$checkOne = $this->option('one');
if ($isDryRun) {
$this->info('DRY RUN MODE - No changes will be made');
if ($checkOne) {
$this->info('Checking only the first canceled subscription...');
} else {
$this->info('Checking for canceled subscriptions...');
}
} else {
if ($checkOne) {
$this->info('Checking and fixing only the first canceled subscription...');
} else {
$this->info('Checking and fixing canceled subscriptions...');
}
}
$teamsWithSubscriptions = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->get();
$toFixCount = 0;
$fixedCount = 0;
$errors = [];
$canceledSubscriptions = [];
foreach ($teamsWithSubscriptions as $team) {
$subscription = $team->subscription;
if (! $subscription->stripe_subscription_id) {
continue;
}
try {
$stripeSubscription = $stripe->subscriptions->retrieve(
$subscription->stripe_subscription_id
);
if ($stripeSubscription->status === 'canceled') {
$toFixCount++;
// Get team members' emails
$memberEmails = $team->members->pluck('email')->toArray();
$canceledSubscriptions[] = [
'team_id' => $team->id,
'team_name' => $team->name,
'customer_id' => $subscription->stripe_customer_id,
'subscription_id' => $subscription->stripe_subscription_id,
'status' => 'canceled',
'member_emails' => $memberEmails,
'subscription_model' => $subscription->toArray(),
];
if ($isDryRun) {
$this->warn('Would fix canceled subscription:');
$this->line(" Team ID: {$team->id}");
$this->line(" Team Name: {$team->name}");
$this->line(' Team Members: '.implode(', ', $memberEmails));
$this->line(" Customer URL: https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}");
$this->line(" Subscription URL: https://dashboard.stripe.com/subscriptions/{$subscription->stripe_subscription_id}");
$this->line(' Current Subscription Data:');
foreach ($subscription->getAttributes() as $key => $value) {
if (is_null($value)) {
$this->line(" - {$key}: null");
} elseif (is_bool($value)) {
$this->line(" - {$key}: ".($value ? 'true' : 'false'));
} else {
$this->line(" - {$key}: {$value}");
}
}
$this->newLine();
} else {
$this->warn("Found canceled subscription for Team ID: {$team->id}");
// Send internal notification with all details before fixing
$notificationMessage = "Fixing canceled subscription:\n";
$notificationMessage .= "Team ID: {$team->id}\n";
$notificationMessage .= "Team Name: {$team->name}\n";
$notificationMessage .= 'Team Members: '.implode(', ', $memberEmails)."\n";
$notificationMessage .= "Customer URL: https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}\n";
$notificationMessage .= "Subscription URL: https://dashboard.stripe.com/subscriptions/{$subscription->stripe_subscription_id}\n";
$notificationMessage .= "Subscription Data:\n";
foreach ($subscription->getAttributes() as $key => $value) {
if (is_null($value)) {
$notificationMessage .= " - {$key}: null\n";
} elseif (is_bool($value)) {
$notificationMessage .= " - {$key}: ".($value ? 'true' : 'false')."\n";
} else {
$notificationMessage .= " - {$key}: {$value}\n";
}
}
send_internal_notification($notificationMessage);
// Apply the same logic as customer.subscription.deleted webhook
$team->subscriptionEnded();
$fixedCount++;
$this->info(" ✓ Fixed subscription for Team ID: {$team->id}");
$this->line(' Team Members: '.implode(', ', $memberEmails));
$this->line(" Customer URL: https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}");
$this->line(" Subscription URL: https://dashboard.stripe.com/subscriptions/{$subscription->stripe_subscription_id}");
}
// Break if --one flag is set
if ($checkOne) {
break;
}
}
} catch (\Stripe\Exception\InvalidRequestException $e) {
if ($e->getStripeCode() === 'resource_missing') {
$toFixCount++;
// Get team members' emails
$memberEmails = $team->members->pluck('email')->toArray();
$canceledSubscriptions[] = [
'team_id' => $team->id,
'team_name' => $team->name,
'customer_id' => $subscription->stripe_customer_id,
'subscription_id' => $subscription->stripe_subscription_id,
'status' => 'missing',
'member_emails' => $memberEmails,
'subscription_model' => $subscription->toArray(),
];
if ($isDryRun) {
$this->error('Would fix missing subscription (not found in Stripe):');
$this->line(" Team ID: {$team->id}");
$this->line(" Team Name: {$team->name}");
$this->line(' Team Members: '.implode(', ', $memberEmails));
$this->line(" Customer URL: https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}");
$this->line(" Subscription ID (missing): {$subscription->stripe_subscription_id}");
$this->line(' Current Subscription Data:');
foreach ($subscription->getAttributes() as $key => $value) {
if (is_null($value)) {
$this->line(" - {$key}: null");
} elseif (is_bool($value)) {
$this->line(" - {$key}: ".($value ? 'true' : 'false'));
} else {
$this->line(" - {$key}: {$value}");
}
}
$this->newLine();
} else {
$this->error("Subscription not found in Stripe for Team ID: {$team->id}");
// Send internal notification with all details before fixing
$notificationMessage = "Fixing missing subscription (not found in Stripe):\n";
$notificationMessage .= "Team ID: {$team->id}\n";
$notificationMessage .= "Team Name: {$team->name}\n";
$notificationMessage .= 'Team Members: '.implode(', ', $memberEmails)."\n";
$notificationMessage .= "Customer URL: https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}\n";
$notificationMessage .= "Subscription ID (missing): {$subscription->stripe_subscription_id}\n";
$notificationMessage .= "Subscription Data:\n";
foreach ($subscription->getAttributes() as $key => $value) {
if (is_null($value)) {
$notificationMessage .= " - {$key}: null\n";
} elseif (is_bool($value)) {
$notificationMessage .= " - {$key}: ".($value ? 'true' : 'false')."\n";
} else {
$notificationMessage .= " - {$key}: {$value}\n";
}
}
send_internal_notification($notificationMessage);
// Apply the same logic as customer.subscription.deleted webhook
$team->subscriptionEnded();
$fixedCount++;
$this->info(" ✓ Fixed missing subscription for Team ID: {$team->id}");
$this->line(' Team Members: '.implode(', ', $memberEmails));
$this->line(" Customer URL: https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}");
}
// Break if --one flag is set
if ($checkOne) {
break;
}
} else {
$errors[] = "Team ID {$team->id}: ".$e->getMessage();
}
} catch (\Exception $e) {
$errors[] = "Team ID {$team->id}: ".$e->getMessage();
}
}
$this->newLine();
$this->info('Summary:');
if ($isDryRun) {
$this->info(" - Found {$toFixCount} canceled/missing subscriptions that would be fixed");
if ($toFixCount > 0) {
$this->newLine();
$this->comment('Run with --fix-canceled-subs to apply these changes');
}
} else {
$this->info(" - Fixed {$fixedCount} canceled/missing subscriptions");
}
if (! empty($errors)) {
$this->newLine();
$this->error('Errors encountered:');
foreach ($errors as $error) {
$this->error(" - {$error}");
}
}
return 0;
}
/**
* Verify all active subscriptions against Stripe API
*/
private function verifyAllActiveSubscriptions(\Stripe\StripeClient $stripe)
{
$isDryRun = $this->option('dry-run');
$shouldFix = $this->option('fix-verified');
$this->info('Verifying all active subscriptions against Stripe...');
if ($isDryRun) {
$this->info('DRY RUN MODE - No changes will be made');
}
if ($shouldFix && ! $isDryRun) {
$this->warn('FIX MODE - Discrepancies will be corrected');
}
// Get all teams with active subscriptions
$teamsWithActiveSubscriptions = Team::whereRelation('subscription', 'stripe_invoice_paid', true)->get();
$totalCount = $teamsWithActiveSubscriptions->count();
$this->info("Found {$totalCount} teams with active subscriptions in database");
$this->newLine();
$out = fopen('php://output', 'w');
// CSV header
fputcsv($out, [
'team_id',
'team_name',
'customer_id',
'subscription_id',
'db_status',
'stripe_status',
'action',
'member_emails',
'customer_url',
'subscription_url',
]);
$stats = [
'total' => $totalCount,
'valid_active' => 0,
'valid_past_due' => 0,
'canceled' => 0,
'missing' => 0,
'invalid' => 0,
'fixed' => 0,
'errors' => 0,
];
$processedCount = 0;
foreach ($teamsWithActiveSubscriptions as $team) {
$subscription = $team->subscription;
$memberEmails = $team->members->pluck('email')->toArray();
// Database state
$dbStatus = 'active';
if ($subscription->stripe_past_due) {
$dbStatus = 'past_due';
}
$stripeStatus = null;
$action = 'none';
if (! $subscription->stripe_subscription_id) {
$this->line("Team {$team->id}: Missing subscription ID, searching in Stripe...");
$foundResult = null;
$searchMethod = null;
// Search by customer ID
if ($subscription->stripe_customer_id) {
$this->line(" → Searching by customer ID: {$subscription->stripe_customer_id}");
$foundResult = $this->searchSubscriptionsByCustomer($stripe, $subscription->stripe_customer_id);
if ($foundResult) {
$searchMethod = $foundResult['method'];
}
} else {
$this->line(' → No customer ID available');
}
// Search by emails if not found
if (! $foundResult && count($memberEmails) > 0) {
$foundResult = $this->searchSubscriptionsByEmails($stripe, $memberEmails);
if ($foundResult) {
$searchMethod = $foundResult['method'];
// Update customer ID if different
if (isset($foundResult['customer_id']) && $subscription->stripe_customer_id !== $foundResult['customer_id']) {
if ($isDryRun) {
$this->warn(" ⚠ Would update customer ID from {$subscription->stripe_customer_id} to {$foundResult['customer_id']}");
} elseif ($shouldFix) {
$subscription->update(['stripe_customer_id' => $foundResult['customer_id']]);
$this->info(" ✓ Updated customer ID to {$foundResult['customer_id']}");
}
}
}
}
if ($foundResult && isset($foundResult['subscription'])) {
// Check if it's an active/past_due subscription
if (in_array($foundResult['status'], ['active', 'past_due'])) {
// Found an active subscription, handle update
$result = $this->handleFoundSubscription(
$team,
$subscription,
$foundResult['subscription'],
$searchMethod,
$isDryRun,
$shouldFix,
$stats
);
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
$result['id'],
$dbStatus,
$result['status'],
$result['action'],
implode(', ', $memberEmails),
$subscription->stripe_customer_id ? "https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}" : 'N/A',
$result['url'],
]);
} else {
// Found subscription but it's canceled/expired - needs to be deactivated
$this->warn(" → Found {$foundResult['status']} subscription {$foundResult['subscription']->id} - needs deactivation");
$result = $this->handleMissingSubscription($team, $subscription, $foundResult['status'], $isDryRun, $shouldFix, $stats);
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
$foundResult['subscription']->id,
$dbStatus,
$foundResult['status'],
'needs_fix',
implode(', ', $memberEmails),
$subscription->stripe_customer_id ? "https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}" : 'N/A',
"https://dashboard.stripe.com/subscriptions/{$foundResult['subscription']->id}",
]);
}
} else {
// No subscription found at all
$this->line(' → No subscription found');
$stripeStatus = 'not_found';
$result = $this->handleMissingSubscription($team, $subscription, $stripeStatus, $isDryRun, $shouldFix, $stats);
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
'N/A',
$dbStatus,
$result['status'],
$result['action'],
implode(', ', $memberEmails),
$subscription->stripe_customer_id ? "https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}" : 'N/A',
'N/A',
]);
}
} else {
// First validate the subscription ID format
if (! str_starts_with($subscription->stripe_subscription_id, 'sub_')) {
$this->warn(" ⚠ Invalid subscription ID format (doesn't start with 'sub_')");
}
try {
$stripeSubscription = $stripe->subscriptions->retrieve(
$subscription->stripe_subscription_id
);
$stripeStatus = $stripeSubscription->status;
// Determine if action is needed
switch ($stripeStatus) {
case 'active':
$stats['valid_active']++;
$action = 'valid';
break;
case 'past_due':
$stats['valid_past_due']++;
$action = 'valid';
// Ensure past_due flag is set
if (! $subscription->stripe_past_due) {
if ($isDryRun) {
$this->info("Would set stripe_past_due=true for Team {$team->id}");
} elseif ($shouldFix) {
$subscription->update(['stripe_past_due' => true]);
}
}
break;
case 'canceled':
case 'incomplete_expired':
case 'unpaid':
case 'incomplete':
$stats['canceled']++;
$action = 'needs_fix';
// Only output problematic subscriptions
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
$subscription->stripe_subscription_id,
$dbStatus,
$stripeStatus,
$action,
implode(', ', $memberEmails),
"https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}",
"https://dashboard.stripe.com/subscriptions/{$subscription->stripe_subscription_id}",
]);
if ($isDryRun) {
$this->info("Would deactivate subscription for Team {$team->id} - status: {$stripeStatus}");
} elseif ($shouldFix) {
$this->fixSubscription($team, $subscription, $stripeStatus);
$stats['fixed']++;
}
break;
default:
$stats['invalid']++;
$action = 'unknown';
// Only output problematic subscriptions
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
$subscription->stripe_subscription_id,
$dbStatus,
$stripeStatus,
$action,
implode(', ', $memberEmails),
"https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}",
"https://dashboard.stripe.com/subscriptions/{$subscription->stripe_subscription_id}",
]);
break;
}
} catch (\Stripe\Exception\InvalidRequestException $e) {
$this->error(' → Error: '.$e->getMessage());
if ($e->getStripeCode() === 'resource_missing' || $e->getHttpStatus() === 404) {
// Subscription doesn't exist, try to find by customer ID
$this->warn(" → Subscription not found, checking customer's subscriptions...");
$foundResult = null;
if ($subscription->stripe_customer_id) {
$foundResult = $this->searchSubscriptionsByCustomer($stripe, $subscription->stripe_customer_id);
}
if ($foundResult && isset($foundResult['subscription']) && in_array($foundResult['status'], ['active', 'past_due'])) {
// Found an active subscription with different ID
$this->warn(" → ID mismatch! DB: {$subscription->stripe_subscription_id}, Stripe: {$foundResult['subscription']->id}");
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
"WRONG ID: {$subscription->stripe_subscription_id} → {$foundResult['subscription']->id}",
$dbStatus,
$foundResult['status'],
'id_mismatch',
implode(', ', $memberEmails),
"https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}",
"https://dashboard.stripe.com/subscriptions/{$foundResult['subscription']->id}",
]);
if ($isDryRun) {
$this->warn(" → Would update subscription ID to {$foundResult['subscription']->id}");
} elseif ($shouldFix) {
$subscription->update([
'stripe_subscription_id' => $foundResult['subscription']->id,
'stripe_invoice_paid' => true,
'stripe_past_due' => $foundResult['status'] === 'past_due',
]);
$stats['fixed']++;
$this->info(' → Updated subscription ID');
}
$stats[$foundResult['status'] === 'active' ? 'valid_active' : 'valid_past_due']++;
} else {
// No active subscription found
$stripeStatus = $foundResult ? $foundResult['status'] : 'not_found';
$result = $this->handleMissingSubscription($team, $subscription, $stripeStatus, $isDryRun, $shouldFix, $stats);
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
$subscription->stripe_subscription_id,
$dbStatus,
$result['status'],
$result['action'],
implode(', ', $memberEmails),
$subscription->stripe_customer_id ? "https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}" : 'N/A',
$foundResult && isset($foundResult['subscription']) ? "https://dashboard.stripe.com/subscriptions/{$foundResult['subscription']->id}" : 'N/A',
]);
}
} else {
// Other API error
$stats['errors']++;
$this->error(' → API Error - not marking as deleted');
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
$subscription->stripe_subscription_id,
$dbStatus,
'error: '.$e->getStripeCode(),
'error',
implode(', ', $memberEmails),
$subscription->stripe_customer_id ? "https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}" : 'N/A',
$subscription->stripe_subscription_id ? "https://dashboard.stripe.com/subscriptions/{$subscription->stripe_subscription_id}" : 'N/A',
]);
}
} catch (\Exception $e) {
$this->error(' → Unexpected error: '.$e->getMessage());
$stats['errors']++;
fputcsv($out, [
$team->id,
$team->name,
$subscription->stripe_customer_id,
$subscription->stripe_subscription_id,
$dbStatus,
'error',
'error',
implode(', ', $memberEmails),
$subscription->stripe_customer_id ? "https://dashboard.stripe.com/customers/{$subscription->stripe_customer_id}" : 'N/A',
$subscription->stripe_subscription_id ? "https://dashboard.stripe.com/subscriptions/{$subscription->stripe_subscription_id}" : 'N/A',
]);
}
}
$processedCount++;
if ($processedCount % 100 === 0) {
$this->info("Processed {$processedCount}/{$totalCount} subscriptions...");
}
}
fclose($out);
// Print summary
$this->newLine(2);
$this->info('=== Verification Summary ===');
$this->info("Total subscriptions checked: {$stats['total']}");
$this->newLine();
$this->info('Valid subscriptions in Stripe:');
$this->line(" - Active: {$stats['valid_active']}");
$this->line(" - Past Due: {$stats['valid_past_due']}");
$validTotal = $stats['valid_active'] + $stats['valid_past_due'];
$this->info(" Total valid: {$validTotal}");
$this->newLine();
$this->warn('Invalid subscriptions:');
$this->line(" - Canceled/Expired: {$stats['canceled']}");
$this->line(" - Missing/Not Found: {$stats['missing']}");
$this->line(" - Unknown status: {$stats['invalid']}");
$invalidTotal = $stats['canceled'] + $stats['missing'] + $stats['invalid'];
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | true |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Cloud/SyncStripeSubscriptions.php | app/Console/Commands/Cloud/SyncStripeSubscriptions.php | <?php
namespace App\Console\Commands\Cloud;
use App\Jobs\SyncStripeSubscriptionsJob;
use Illuminate\Console\Command;
class SyncStripeSubscriptions extends Command
{
protected $signature = 'cloud:sync-stripe-subscriptions {--fix : Actually fix discrepancies (default is check only)}';
protected $description = 'Sync subscription status with Stripe. By default only checks, use --fix to apply changes.';
public function handle(): int
{
if (! isCloud()) {
$this->error('This command can only be run on Coolify Cloud.');
return 1;
}
if (! isStripe()) {
$this->error('Stripe is not configured.');
return 1;
}
$fix = $this->option('fix');
if ($fix) {
$this->warn('Running with --fix: discrepancies will be corrected.');
} else {
$this->info('Running in check mode (no changes will be made). Use --fix to apply corrections.');
}
$this->newLine();
$job = new SyncStripeSubscriptionsJob($fix);
$result = $job->handle();
if (isset($result['error'])) {
$this->error($result['error']);
return 1;
}
$this->info("Total subscriptions checked: {$result['total_checked']}");
$this->newLine();
if (count($result['discrepancies']) > 0) {
$this->warn('Discrepancies found: '.count($result['discrepancies']));
$this->newLine();
foreach ($result['discrepancies'] as $discrepancy) {
$this->line(" - Subscription ID: {$discrepancy['subscription_id']}");
$this->line(" Team ID: {$discrepancy['team_id']}");
$this->line(" Stripe ID: {$discrepancy['stripe_subscription_id']}");
$this->line(" Stripe Status: {$discrepancy['stripe_status']}");
$this->newLine();
}
if ($fix) {
$this->info('All discrepancies have been fixed.');
} else {
$this->comment('Run with --fix to correct these discrepancies.');
}
} else {
$this->info('No discrepancies found. All subscriptions are in sync.');
}
if (count($result['errors']) > 0) {
$this->newLine();
$this->error('Errors encountered: '.count($result['errors']));
foreach ($result['errors'] as $error) {
$this->line(" - Subscription {$error['subscription_id']}: {$error['error']}");
}
}
return 0;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Generate/OpenApi.php | app/Console/Commands/Generate/OpenApi.php | <?php
namespace App\Console\Commands\Generate;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Process;
use Symfony\Component\Yaml\Yaml;
class OpenApi extends Command
{
protected $signature = 'generate:openapi';
protected $description = 'Generate OpenApi file.';
public function handle()
{
// Generate OpenAPI documentation
echo "Generating OpenAPI documentation.\n";
// https://github.com/OAI/OpenAPI-Specification/releases
$process = Process::run([
'./vendor/bin/openapi',
'app',
'-o',
'openapi.yaml',
'--version',
'3.1.0',
]);
$error = $process->errorOutput();
$error = preg_replace('/^.*an object literal,.*$/m', '', $error);
$error = preg_replace('/^\h*\v+/m', '', $error);
echo $error;
echo $process->output();
$yaml = file_get_contents('openapi.yaml');
$json = json_encode(Yaml::parse($yaml), JSON_PRETTY_PRINT);
file_put_contents('openapi.json', $json);
echo "Converted OpenAPI YAML to JSON.\n";
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Console/Commands/Generate/Services.php | app/Console/Commands/Generate/Services.php | <?php
namespace App\Console\Commands\Generate;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Symfony\Component\Yaml\Yaml;
class Services extends Command
{
/**
* {@inheritdoc}
*/
protected $signature = 'generate:services';
/**
* {@inheritdoc}
*/
protected $description = 'Generates service-templates json file based on /templates/compose directory';
public function handle(): int
{
$serviceTemplatesJson = collect(array_merge(
glob(base_path('templates/compose/*.yaml')),
glob(base_path('templates/compose/*.yml'))
))
->mapWithKeys(function ($file): array {
$file = basename($file);
$parsed = $this->processFile($file);
return $parsed === false ? [] : [
Arr::pull($parsed, 'name') => $parsed,
];
})->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents(base_path('templates/'.config('constants.services.file_name')), $serviceTemplatesJson.PHP_EOL);
// Generate service-templates.json with SERVICE_URL changed to SERVICE_FQDN
$this->generateServiceTemplatesWithFqdn();
return self::SUCCESS;
}
private function processFile(string $file): false|array
{
$content = file_get_contents(base_path("templates/compose/$file"));
$data = collect(explode(PHP_EOL, $content))->mapWithKeys(function ($line): array {
preg_match('/^#(?<key>.*):(?<value>.*)$/U', $line, $m);
return $m ? [trim($m['key']) => trim($m['value'])] : [];
});
if (str($data->get('ignore'))->toBoolean()) {
$this->info("Ignoring $file");
return false;
}
$this->info("Processing $file");
$documentation = $data->get('documentation');
$documentation = $documentation ? $documentation.'?utm_source=coolify.io' : 'https://coolify.io/docs';
$json = Yaml::parse($content);
$compose = base64_encode(Yaml::dump($json, 10, 2));
$tags = str($data->get('tags'))->lower()->explode(',')->map(fn ($tag) => trim($tag))->filter();
$tags = $tags->isEmpty() ? null : $tags->all();
$payload = [
'name' => pathinfo($file, PATHINFO_FILENAME),
'documentation' => $documentation,
'slogan' => $data->get('slogan', str($file)->headline()),
'compose' => $compose,
'tags' => $tags,
'category' => $data->get('category'),
'logo' => $data->get('logo', 'svgs/default.webp'),
'minversion' => $data->get('minversion', '0.0.0'),
];
if ($port = $data->get('port')) {
$payload['port'] = $port;
}
if ($envFile = $data->get('env_file')) {
$envFileContent = file_get_contents(base_path("templates/compose/$envFile"));
$payload['envs'] = base64_encode($envFileContent);
}
return $payload;
}
private function generateServiceTemplatesWithFqdn(): void
{
$serviceTemplatesWithFqdn = collect(array_merge(
glob(base_path('templates/compose/*.yaml')),
glob(base_path('templates/compose/*.yml'))
))
->mapWithKeys(function ($file): array {
$file = basename($file);
$parsed = $this->processFileWithFqdn($file);
return $parsed === false ? [] : [
Arr::pull($parsed, 'name') => $parsed,
];
})->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents(base_path('templates/service-templates.json'), $serviceTemplatesWithFqdn.PHP_EOL);
// Generate service-templates-raw.json with non-base64 encoded compose content
// $this->generateServiceTemplatesRaw();
}
private function processFileWithFqdn(string $file): false|array
{
$content = file_get_contents(base_path("templates/compose/$file"));
$data = collect(explode(PHP_EOL, $content))->mapWithKeys(function ($line): array {
preg_match('/^#(?<key>.*):(?<value>.*)$/U', $line, $m);
return $m ? [trim($m['key']) => trim($m['value'])] : [];
});
if (str($data->get('ignore'))->toBoolean()) {
return false;
}
$documentation = $data->get('documentation');
$documentation = $documentation ? $documentation.'?utm_source=coolify.io' : 'https://coolify.io/docs';
// Replace SERVICE_URL with SERVICE_FQDN in the content
$modifiedContent = str_replace('SERVICE_URL', 'SERVICE_FQDN', $content);
$json = Yaml::parse($modifiedContent);
$compose = base64_encode(Yaml::dump($json, 10, 2));
$tags = str($data->get('tags'))->lower()->explode(',')->map(fn ($tag) => trim($tag))->filter();
$tags = $tags->isEmpty() ? null : $tags->all();
$payload = [
'name' => pathinfo($file, PATHINFO_FILENAME),
'documentation' => $documentation,
'slogan' => $data->get('slogan', str($file)->headline()),
'compose' => $compose,
'tags' => $tags,
'category' => $data->get('category'),
'logo' => $data->get('logo', 'svgs/default.webp'),
'minversion' => $data->get('minversion', '0.0.0'),
];
if ($port = $data->get('port')) {
$payload['port'] = $port;
}
if ($envFile = $data->get('env_file')) {
$envFileContent = file_get_contents(base_path("templates/compose/$envFile"));
// Also replace SERVICE_URL with SERVICE_FQDN in env file content
$modifiedEnvContent = str_replace('SERVICE_URL', 'SERVICE_FQDN', $envFileContent);
$payload['envs'] = base64_encode($modifiedEnvContent);
}
return $payload;
}
private function generateServiceTemplatesRaw(): void
{
$serviceTemplatesRaw = collect(array_merge(
glob(base_path('templates/compose/*.yaml')),
glob(base_path('templates/compose/*.yml'))
))
->mapWithKeys(function ($file): array {
$file = basename($file);
$parsed = $this->processFileWithFqdnRaw($file);
return $parsed === false ? [] : [
Arr::pull($parsed, 'name') => $parsed,
];
})->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents(base_path('templates/service-templates-raw.json'), $serviceTemplatesRaw.PHP_EOL);
}
private function processFileWithFqdnRaw(string $file): false|array
{
$content = file_get_contents(base_path("templates/compose/$file"));
$data = collect(explode(PHP_EOL, $content))->mapWithKeys(function ($line): array {
preg_match('/^#(?<key>.*):(?<value>.*)$/U', $line, $m);
return $m ? [trim($m['key']) => trim($m['value'])] : [];
});
if (str($data->get('ignore'))->toBoolean()) {
return false;
}
$documentation = $data->get('documentation');
$documentation = $documentation ? $documentation.'?utm_source=coolify.io' : 'https://coolify.io/docs';
// Replace SERVICE_URL with SERVICE_FQDN in the content
$modifiedContent = str_replace('SERVICE_URL', 'SERVICE_FQDN', $content);
$json = Yaml::parse($modifiedContent);
$compose = Yaml::dump($json, 10, 2); // Not base64 encoded
$tags = str($data->get('tags'))->lower()->explode(',')->map(fn ($tag) => trim($tag))->filter();
$tags = $tags->isEmpty() ? null : $tags->all();
$payload = [
'name' => pathinfo($file, PATHINFO_FILENAME),
'documentation' => $documentation,
'slogan' => $data->get('slogan', str($file)->headline()),
'compose' => $compose,
'tags' => $tags,
'category' => $data->get('category'),
'logo' => $data->get('logo', 'svgs/default.webp'),
'minversion' => $data->get('minversion', '0.0.0'),
];
if ($port = $data->get('port')) {
$payload['port'] = $port;
}
if ($envFile = $data->get('env_file')) {
$envFileContent = file_get_contents(base_path("templates/compose/$envFile"));
// Also replace SERVICE_URL with SERVICE_FQDN in env file content (not base64 encoded)
$modifiedEnvContent = str_replace('SERVICE_URL', 'SERVICE_FQDN', $envFileContent);
$payload['envs'] = $modifiedEnvContent;
}
return $payload;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/ApplicationDeploymentStatus.php | app/Enums/ApplicationDeploymentStatus.php | <?php
namespace App\Enums;
enum ApplicationDeploymentStatus: string
{
case QUEUED = 'queued';
case IN_PROGRESS = 'in_progress';
case FINISHED = 'finished';
case FAILED = 'failed';
case CANCELLED_BY_USER = 'cancelled-by-user';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/ActivityTypes.php | app/Enums/ActivityTypes.php | <?php
namespace App\Enums;
enum ActivityTypes: string
{
case INLINE = 'inline';
case COMMAND = 'command';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/StaticImageTypes.php | app/Enums/StaticImageTypes.php | <?php
namespace App\Enums;
enum StaticImageTypes: string
{
case NGINX_ALPINE = 'nginx:alpine';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/BuildPackTypes.php | app/Enums/BuildPackTypes.php | <?php
namespace App\Enums;
enum BuildPackTypes: string
{
case NIXPACKS = 'nixpacks';
case STATIC = 'static';
case DOCKERFILE = 'dockerfile';
case DOCKERCOMPOSE = 'dockercompose';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/ProxyTypes.php | app/Enums/ProxyTypes.php | <?php
namespace App\Enums;
enum ProxyTypes: string
{
case NONE = 'NONE';
case TRAEFIK = 'TRAEFIK';
case NGINX = 'NGINX';
case CADDY = 'CADDY';
}
enum ProxyStatus: string
{
case EXITED = 'exited';
case RUNNING = 'running';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/NewResourceTypes.php | app/Enums/NewResourceTypes.php | <?php
namespace App\Enums;
enum NewResourceTypes: string
{
case PUBLIC = 'public';
case PRIVATE_GH_APP = 'private-gh-app';
case PRIVATE_DEPLOY_KEY = 'private-deploy-key';
case DOCKERFILE = 'dockerfile';
case DOCKERCOMPOSE = 'dockercompose';
case DOCKER_IMAGE = 'docker-image';
case SERVICE = 'service';
case POSTGRESQL = 'postgresql';
case MYSQL = 'mysql';
case MONGODB = 'mongodb';
case REDIS = 'redis';
case MARIADB = 'mariadb';
case KEYDB = 'keydb';
case DRAGONFLY = 'dragonfly';
case CLICKHOUSE = 'clickhouse';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/ContainerStatusTypes.php | app/Enums/ContainerStatusTypes.php | <?php
namespace App\Enums;
enum ContainerStatusTypes: string
{
case PAUSED = 'paused';
case RESTARTING = 'restarting';
case REMOVING = 'removing';
case RUNNING = 'running';
case DEAD = 'dead';
case CREATED = 'created';
case EXITED = 'exited';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/Role.php | app/Enums/Role.php | <?php
namespace App\Enums;
enum Role: string
{
case MEMBER = 'member';
case ADMIN = 'admin';
case OWNER = 'owner';
public function rank(): int
{
return match ($this) {
self::MEMBER => 1,
self::ADMIN => 2,
self::OWNER => 3,
};
}
public function lt(Role|string $role): bool
{
if (is_string($role)) {
$role = Role::from($role);
}
return $this->rank() < $role->rank();
}
public function gt(Role|string $role): bool
{
if (is_string($role)) {
$role = Role::from($role);
}
return $this->rank() > $role->rank();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/ProcessStatus.php | app/Enums/ProcessStatus.php | <?php
namespace App\Enums;
enum ProcessStatus: string
{
case QUEUED = 'queued';
case IN_PROGRESS = 'in_progress';
case FINISHED = 'finished';
case ERROR = 'error';
case KILLED = 'killed';
case CANCELLED = 'cancelled';
case CLOSED = 'closed';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/NewDatabaseTypes.php | app/Enums/NewDatabaseTypes.php | <?php
namespace App\Enums;
enum NewDatabaseTypes: string
{
case POSTGRESQL = 'postgresql';
case MYSQL = 'mysql';
case MONGODB = 'mongodb';
case REDIS = 'redis';
case MARIADB = 'mariadb';
case KEYDB = 'keydb';
case DRAGONFLY = 'dragonfly';
case CLICKHOUSE = 'clickhouse';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Enums/RedirectTypes.php | app/Enums/RedirectTypes.php | <?php
namespace App\Enums;
enum RedirectTypes: string
{
case BOTH = 'both';
case WWW = 'www';
case NON_WWW = 'non-www';
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/DiscordNotificationSettings.php | app/Models/DiscordNotificationSettings.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class DiscordNotificationSettings extends Model
{
use Notifiable;
public $timestamps = false;
protected $fillable = [
'team_id',
'discord_enabled',
'discord_webhook_url',
'deployment_success_discord_notifications',
'deployment_failure_discord_notifications',
'status_change_discord_notifications',
'backup_success_discord_notifications',
'backup_failure_discord_notifications',
'scheduled_task_success_discord_notifications',
'scheduled_task_failure_discord_notifications',
'docker_cleanup_discord_notifications',
'server_disk_usage_discord_notifications',
'server_reachable_discord_notifications',
'server_unreachable_discord_notifications',
'server_patch_discord_notifications',
'traefik_outdated_discord_notifications',
'discord_ping_enabled',
];
protected $casts = [
'discord_enabled' => 'boolean',
'discord_webhook_url' => 'encrypted',
'deployment_success_discord_notifications' => 'boolean',
'deployment_failure_discord_notifications' => 'boolean',
'status_change_discord_notifications' => 'boolean',
'backup_success_discord_notifications' => 'boolean',
'backup_failure_discord_notifications' => 'boolean',
'scheduled_task_success_discord_notifications' => 'boolean',
'scheduled_task_failure_discord_notifications' => 'boolean',
'docker_cleanup_discord_notifications' => 'boolean',
'server_disk_usage_discord_notifications' => 'boolean',
'server_reachable_discord_notifications' => 'boolean',
'server_unreachable_discord_notifications' => 'boolean',
'server_patch_discord_notifications' => 'boolean',
'traefik_outdated_discord_notifications' => 'boolean',
'discord_ping_enabled' => 'boolean',
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function isEnabled()
{
return $this->discord_enabled;
}
public function isPingEnabled()
{
return $this->discord_ping_enabled;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ServerSetting.php | app/Models/ServerSetting.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
use OpenApi\Attributes as OA;
#[OA\Schema(
description: 'Server Settings model',
type: 'object',
properties: [
'id' => ['type' => 'integer'],
'concurrent_builds' => ['type' => 'integer'],
'deployment_queue_limit' => ['type' => 'integer'],
'dynamic_timeout' => ['type' => 'integer'],
'force_disabled' => ['type' => 'boolean'],
'force_server_cleanup' => ['type' => 'boolean'],
'is_build_server' => ['type' => 'boolean'],
'is_cloudflare_tunnel' => ['type' => 'boolean'],
'is_jump_server' => ['type' => 'boolean'],
'is_logdrain_axiom_enabled' => ['type' => 'boolean'],
'is_logdrain_custom_enabled' => ['type' => 'boolean'],
'is_logdrain_highlight_enabled' => ['type' => 'boolean'],
'is_logdrain_newrelic_enabled' => ['type' => 'boolean'],
'is_metrics_enabled' => ['type' => 'boolean'],
'is_reachable' => ['type' => 'boolean'],
'is_sentinel_enabled' => ['type' => 'boolean'],
'is_swarm_manager' => ['type' => 'boolean'],
'is_swarm_worker' => ['type' => 'boolean'],
'is_terminal_enabled' => ['type' => 'boolean'],
'is_usable' => ['type' => 'boolean'],
'logdrain_axiom_api_key' => ['type' => 'string'],
'logdrain_axiom_dataset_name' => ['type' => 'string'],
'logdrain_custom_config' => ['type' => 'string'],
'logdrain_custom_config_parser' => ['type' => 'string'],
'logdrain_highlight_project_id' => ['type' => 'string'],
'logdrain_newrelic_base_uri' => ['type' => 'string'],
'logdrain_newrelic_license_key' => ['type' => 'string'],
'sentinel_metrics_history_days' => ['type' => 'integer'],
'sentinel_metrics_refresh_rate_seconds' => ['type' => 'integer'],
'sentinel_token' => ['type' => 'string'],
'docker_cleanup_frequency' => ['type' => 'string'],
'docker_cleanup_threshold' => ['type' => 'integer'],
'server_id' => ['type' => 'integer'],
'wildcard_domain' => ['type' => 'string'],
'created_at' => ['type' => 'string'],
'updated_at' => ['type' => 'string'],
'delete_unused_volumes' => ['type' => 'boolean', 'description' => 'The flag to indicate if the unused volumes should be deleted.'],
'delete_unused_networks' => ['type' => 'boolean', 'description' => 'The flag to indicate if the unused networks should be deleted.'],
]
)]
class ServerSetting extends Model
{
protected $guarded = [];
protected $casts = [
'force_docker_cleanup' => 'boolean',
'docker_cleanup_threshold' => 'integer',
'sentinel_token' => 'encrypted',
'is_reachable' => 'boolean',
'is_usable' => 'boolean',
'is_terminal_enabled' => 'boolean',
'disable_application_image_retention' => 'boolean',
];
protected static function booted()
{
static::creating(function ($setting) {
try {
if (str($setting->sentinel_token)->isEmpty()) {
$setting->generateSentinelToken(save: false, ignoreEvent: true);
}
if (str($setting->sentinel_custom_url)->isEmpty()) {
$setting->generateSentinelUrl(save: false, ignoreEvent: true);
}
} catch (\Throwable $e) {
Log::error('Error creating server setting: '.$e->getMessage());
}
});
static::updated(function ($settings) {
if (
$settings->wasChanged('sentinel_token') ||
$settings->wasChanged('sentinel_custom_url') ||
$settings->wasChanged('sentinel_metrics_refresh_rate_seconds') ||
$settings->wasChanged('sentinel_metrics_history_days') ||
$settings->wasChanged('sentinel_push_interval_seconds')
) {
$settings->server->restartSentinel();
}
});
}
public function generateSentinelToken(bool $save = true, bool $ignoreEvent = false)
{
$data = [
'server_uuid' => $this->server->uuid,
];
$token = json_encode($data);
$encrypted = encrypt($token);
$this->sentinel_token = $encrypted;
if ($save) {
if ($ignoreEvent) {
$this->saveQuietly();
} else {
$this->save();
}
}
return $token;
}
public function generateSentinelUrl(bool $save = true, bool $ignoreEvent = false)
{
$domain = null;
$settings = InstanceSettings::get();
if ($this->server->isLocalhost()) {
$domain = 'http://host.docker.internal:8000';
} elseif ($settings->fqdn) {
$domain = $settings->fqdn;
} elseif ($settings->public_ipv4) {
$domain = 'http://'.$settings->public_ipv4.':8000';
} elseif ($settings->public_ipv6) {
$domain = 'http://'.$settings->public_ipv6.':8000';
}
$this->sentinel_custom_url = $domain;
if ($save) {
if ($ignoreEvent) {
$this->saveQuietly();
} else {
$this->save();
}
}
return $domain;
}
public function server()
{
return $this->belongsTo(Server::class);
}
public function dockerCleanupFrequency(): Attribute
{
return Attribute::make(
set: function ($value) {
return translate_cron_expression($value);
},
get: function ($value) {
return translate_cron_expression($value);
}
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/InstanceSettings.php | app/Models/InstanceSettings.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Spatie\Url\Url;
class InstanceSettings extends Model
{
protected $guarded = [];
protected $casts = [
'smtp_enabled' => 'boolean',
'smtp_from_address' => 'encrypted',
'smtp_from_name' => 'encrypted',
'smtp_recipients' => 'encrypted',
'smtp_host' => 'encrypted',
'smtp_port' => 'integer',
'smtp_username' => 'encrypted',
'smtp_password' => 'encrypted',
'smtp_timeout' => 'integer',
'resend_enabled' => 'boolean',
'resend_api_key' => 'encrypted',
'allowed_ip_ranges' => 'array',
'is_auto_update_enabled' => 'boolean',
'auto_update_frequency' => 'string',
'update_check_frequency' => 'string',
'sentinel_token' => 'encrypted',
'is_wire_navigate_enabled' => 'boolean',
];
protected static function booted(): void
{
static::updated(function ($settings) {
// Clear trusted hosts cache when FQDN changes
if ($settings->wasChanged('fqdn')) {
\Cache::forget('instance_settings_fqdn_host');
}
});
}
public function fqdn(): Attribute
{
return Attribute::make(
set: function ($value) {
if ($value) {
$url = Url::fromString($value);
$host = $url->getHost();
return $url->getScheme().'://'.$host;
}
}
);
}
public function updateCheckFrequency(): Attribute
{
return Attribute::make(
set: function ($value) {
return translate_cron_expression($value);
},
get: function ($value) {
return translate_cron_expression($value);
}
);
}
public function autoUpdateFrequency(): Attribute
{
return Attribute::make(
set: function ($value) {
return translate_cron_expression($value);
},
get: function ($value) {
return translate_cron_expression($value);
}
);
}
public static function get()
{
return InstanceSettings::findOrFail(0);
}
// public function getRecipients($notification)
// {
// $recipients = data_get($notification, 'emails', null);
// if (is_null($recipients) || $recipients === '') {
// return [];
// }
// return explode(',', $recipients);
// }
public function getTitleDisplayName(): string
{
$instanceName = $this->instance_name;
if (! $instanceName) {
return '';
}
return "[{$instanceName}]";
}
// public function helperVersion(): Attribute
// {
// return Attribute::make(
// get: function ($value) {
// if (isDev()) {
// return 'latest';
// }
// return $value;
// }
// );
// }
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ProjectSetting.php | app/Models/ProjectSetting.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class ProjectSetting extends Model
{
protected $guarded = [];
public function project()
{
return $this->belongsTo(Project::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneDocker.php | app/Models/StandaloneDocker.php | <?php
namespace App\Models;
use App\Jobs\ConnectProxyToNetworksJob;
use App\Traits\HasSafeStringAttribute;
class StandaloneDocker extends BaseModel
{
use HasSafeStringAttribute;
protected $guarded = [];
protected static function boot()
{
parent::boot();
static::created(function ($newStandaloneDocker) {
$server = $newStandaloneDocker->server;
instant_remote_process([
"docker network inspect $newStandaloneDocker->network >/dev/null 2>&1 || docker network create --driver overlay --attachable $newStandaloneDocker->network >/dev/null",
], $server, false);
ConnectProxyToNetworksJob::dispatchSync($server);
});
}
public function applications()
{
return $this->morphMany(Application::class, 'destination');
}
public function postgresqls()
{
return $this->morphMany(StandalonePostgresql::class, 'destination');
}
public function redis()
{
return $this->morphMany(StandaloneRedis::class, 'destination');
}
public function mongodbs()
{
return $this->morphMany(StandaloneMongodb::class, 'destination');
}
public function mysqls()
{
return $this->morphMany(StandaloneMysql::class, 'destination');
}
public function mariadbs()
{
return $this->morphMany(StandaloneMariadb::class, 'destination');
}
public function keydbs()
{
return $this->morphMany(StandaloneKeydb::class, 'destination');
}
public function dragonflies()
{
return $this->morphMany(StandaloneDragonfly::class, 'destination');
}
public function clickhouses()
{
return $this->morphMany(StandaloneClickhouse::class, 'destination');
}
public function server()
{
return $this->belongsTo(Server::class);
}
public function services()
{
return $this->morphMany(Service::class, 'destination');
}
public function databases()
{
$postgresqls = $this->postgresqls;
$redis = $this->redis;
$mongodbs = $this->mongodbs;
$mysqls = $this->mysqls;
$mariadbs = $this->mariadbs;
return $postgresqls->concat($redis)->concat($mongodbs)->concat($mysqls)->concat($mariadbs);
}
public function attachedTo()
{
return $this->applications?->count() > 0 || $this->databases()->count() > 0;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/CloudProviderToken.php | app/Models/CloudProviderToken.php | <?php
namespace App\Models;
class CloudProviderToken extends BaseModel
{
protected $guarded = [];
protected $casts = [
'token' => 'encrypted',
];
public function team()
{
return $this->belongsTo(Team::class);
}
public function servers()
{
return $this->hasMany(Server::class);
}
public function hasServers(): bool
{
return $this->servers()->exists();
}
public static function ownedByCurrentTeam(array $select = ['*'])
{
$selectArray = collect($select)->concat(['id']);
return self::whereTeamId(currentTeam()->id)->select($selectArray->all());
}
public function scopeForProvider($query, string $provider)
{
return $query->where('provider', $provider);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/SwarmDocker.php | app/Models/SwarmDocker.php | <?php
namespace App\Models;
class SwarmDocker extends BaseModel
{
protected $guarded = [];
public function applications()
{
return $this->morphMany(Application::class, 'destination');
}
public function postgresqls()
{
return $this->morphMany(StandalonePostgresql::class, 'destination');
}
public function redis()
{
return $this->morphMany(StandaloneRedis::class, 'destination');
}
public function keydbs()
{
return $this->morphMany(StandaloneKeydb::class, 'destination');
}
public function dragonflies()
{
return $this->morphMany(StandaloneDragonfly::class, 'destination');
}
public function clickhouses()
{
return $this->morphMany(StandaloneClickhouse::class, 'destination');
}
public function mongodbs()
{
return $this->morphMany(StandaloneMongodb::class, 'destination');
}
public function mysqls()
{
return $this->morphMany(StandaloneMysql::class, 'destination');
}
public function mariadbs()
{
return $this->morphMany(StandaloneMariadb::class, 'destination');
}
public function server()
{
return $this->belongsTo(Server::class);
}
public function services()
{
return $this->morphMany(Service::class, 'destination');
}
public function databases()
{
$postgresqls = $this->postgresqls;
$redis = $this->redis;
$mongodbs = $this->mongodbs;
$mysqls = $this->mysqls;
$mariadbs = $this->mariadbs;
$keydbs = $this->keydbs;
$dragonflies = $this->dragonflies;
$clickhouses = $this->clickhouses;
return $postgresqls->concat($redis)->concat($mongodbs)->concat($mysqls)->concat($mariadbs)->concat($keydbs)->concat($dragonflies)->concat($clickhouses);
}
public function attachedTo()
{
return $this->applications?->count() > 0 || $this->databases()->count() > 0;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Tag.php | app/Models/Tag.php | <?php
namespace App\Models;
use App\Traits\HasSafeStringAttribute;
class Tag extends BaseModel
{
use HasSafeStringAttribute;
protected $guarded = [];
protected function customizeName($value)
{
return strtolower($value);
}
public static function ownedByCurrentTeam()
{
return Tag::whereTeamId(currentTeam()->id)->orderBy('name');
}
public function applications()
{
return $this->morphedByMany(Application::class, 'taggable');
}
public function services()
{
return $this->morphedByMany(Service::class, 'taggable');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/Team.php | app/Models/Team.php | <?php
namespace App\Models;
use App\Events\ServerReachabilityChanged;
use App\Notifications\Channels\SendsDiscord;
use App\Notifications\Channels\SendsEmail;
use App\Notifications\Channels\SendsPushover;
use App\Notifications\Channels\SendsSlack;
use App\Traits\HasNotificationSettings;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use OpenApi\Attributes as OA;
#[OA\Schema(
description: 'Team model',
type: 'object',
properties: [
'id' => ['type' => 'integer', 'description' => 'The unique identifier of the team.'],
'name' => ['type' => 'string', 'description' => 'The name of the team.'],
'description' => ['type' => 'string', 'description' => 'The description of the team.'],
'personal_team' => ['type' => 'boolean', 'description' => 'Whether the team is personal or not.'],
'created_at' => ['type' => 'string', 'description' => 'The date and time the team was created.'],
'updated_at' => ['type' => 'string', 'description' => 'The date and time the team was last updated.'],
'show_boarding' => ['type' => 'boolean', 'description' => 'Whether to show the boarding screen or not.'],
'custom_server_limit' => ['type' => 'string', 'description' => 'The custom server limit.'],
'members' => new OA\Property(
property: 'members',
type: 'array',
items: new OA\Items(ref: '#/components/schemas/User'),
description: 'The members of the team.'
),
]
)]
class Team extends Model implements SendsDiscord, SendsEmail, SendsPushover, SendsSlack
{
use HasFactory, HasNotificationSettings, HasSafeStringAttribute, Notifiable;
protected $guarded = [];
protected $casts = [
'personal_team' => 'boolean',
];
protected static function booted()
{
static::created(function ($team) {
$team->emailNotificationSettings()->create([
'use_instance_email_settings' => isDev(),
]);
$team->discordNotificationSettings()->create();
$team->slackNotificationSettings()->create();
$team->telegramNotificationSettings()->create();
$team->pushoverNotificationSettings()->create();
$team->webhookNotificationSettings()->create();
});
static::saving(function ($team) {
if (auth()->user()?->isMember()) {
throw new \Exception('You are not allowed to update this team.');
}
});
static::deleting(function ($team) {
$keys = $team->privateKeys;
foreach ($keys as $key) {
$key->delete();
}
$sources = $team->sources();
foreach ($sources as $source) {
$source->delete();
}
$tags = Tag::whereTeamId($team->id)->get();
foreach ($tags as $tag) {
$tag->delete();
}
$shared_variables = $team->environment_variables();
foreach ($shared_variables as $shared_variable) {
$shared_variable->delete();
}
$s3s = $team->s3s;
foreach ($s3s as $s3) {
$s3->delete();
}
});
}
public static function serverLimitReached()
{
$serverLimit = Team::serverLimit();
$team = currentTeam();
$servers = $team->servers->count();
return $servers >= $serverLimit;
}
public function subscriptionPastOverDue()
{
if (isCloud()) {
return $this->subscription?->stripe_past_due;
}
return false;
}
public function serverOverflow()
{
if ($this->serverLimit() < $this->servers->count()) {
return true;
}
return false;
}
public static function serverLimit()
{
if (currentTeam()->id === 0 && isDev()) {
return 9999999;
}
$team = Team::find(currentTeam()->id);
if (! $team) {
return 0;
}
return data_get($team, 'limits', 0);
}
public function limits(): Attribute
{
return Attribute::make(
get: function () {
if (config('constants.coolify.self_hosted') || $this->id === 0) {
return 999999999999;
}
return $this->custom_server_limit ?? 2;
}
);
}
public function routeNotificationForDiscord()
{
return data_get($this, 'discord_webhook_url', null);
}
public function routeNotificationForTelegram()
{
return [
'token' => data_get($this, 'telegram_token', null),
'chat_id' => data_get($this, 'telegram_chat_id', null),
];
}
public function routeNotificationForSlack()
{
return data_get($this, 'slack_webhook_url', null);
}
public function routeNotificationForPushover()
{
return [
'user' => data_get($this, 'pushover_user_key', null),
'token' => data_get($this, 'pushover_api_token', null),
];
}
public function getRecipients(): array
{
$recipients = $this->members()->pluck('email')->toArray();
$validatedEmails = array_filter($recipients, function ($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
});
if (is_null($validatedEmails)) {
return [];
}
return array_values($validatedEmails);
}
public function isAnyNotificationEnabled()
{
if (isCloud()) {
return true;
}
return $this->getNotificationSettings('email')?->isEnabled() ||
$this->getNotificationSettings('discord')?->isEnabled() ||
$this->getNotificationSettings('slack')?->isEnabled() ||
$this->getNotificationSettings('telegram')?->isEnabled() ||
$this->getNotificationSettings('pushover')?->isEnabled();
}
public function subscriptionEnded()
{
$this->subscription->update([
'stripe_subscription_id' => null,
'stripe_cancel_at_period_end' => false,
'stripe_invoice_paid' => false,
'stripe_trial_already_ended' => false,
'stripe_past_due' => false,
]);
foreach ($this->servers as $server) {
$server->settings()->update([
'is_usable' => false,
'is_reachable' => false,
]);
ServerReachabilityChanged::dispatch($server);
}
}
public function environment_variables()
{
return $this->hasMany(SharedEnvironmentVariable::class)->whereNull('project_id')->whereNull('environment_id');
}
public function members()
{
return $this->belongsToMany(User::class, 'team_user', 'team_id', 'user_id')->withPivot('role');
}
public function subscription()
{
return $this->hasOne(Subscription::class);
}
public function applications()
{
return $this->hasManyThrough(Application::class, Project::class);
}
public function invitations()
{
return $this->hasMany(TeamInvitation::class);
}
public function isEmpty()
{
if ($this->projects()->count() === 0 && $this->servers()->count() === 0 && $this->privateKeys()->count() === 0 && $this->sources()->count() === 0) {
return true;
}
return false;
}
public function projects()
{
return $this->hasMany(Project::class);
}
public function servers()
{
return $this->hasMany(Server::class);
}
public function privateKeys()
{
return $this->hasMany(PrivateKey::class);
}
public function cloudProviderTokens()
{
return $this->hasMany(CloudProviderToken::class);
}
public function sources()
{
$sources = collect([]);
$github_apps = GithubApp::where(function ($query) {
$query->where(function ($q) {
$q->where('team_id', $this->id)
->orWhere('is_system_wide', true);
})->where('is_public', false);
})->get();
$gitlab_apps = GitlabApp::where(function ($query) {
$query->where(function ($q) {
$q->where('team_id', $this->id)
->orWhere('is_system_wide', true);
})->where('is_public', false);
})->get();
return $sources->merge($github_apps)->merge($gitlab_apps);
}
public function s3s()
{
return $this->hasMany(S3Storage::class)->where('is_usable', true);
}
public function emailNotificationSettings()
{
return $this->hasOne(EmailNotificationSettings::class);
}
public function discordNotificationSettings()
{
return $this->hasOne(DiscordNotificationSettings::class);
}
public function telegramNotificationSettings()
{
return $this->hasOne(TelegramNotificationSettings::class);
}
public function slackNotificationSettings()
{
return $this->hasOne(SlackNotificationSettings::class);
}
public function pushoverNotificationSettings()
{
return $this->hasOne(PushoverNotificationSettings::class);
}
public function webhookNotificationSettings()
{
return $this->hasOne(WebhookNotificationSettings::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/ApplicationSetting.php | app/Models/ApplicationSetting.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class ApplicationSetting extends Model
{
protected $casts = [
'is_static' => 'boolean',
'is_spa' => 'boolean',
'is_build_server_enabled' => 'boolean',
'is_preserve_repository_enabled' => 'boolean',
'is_container_label_escape_enabled' => 'boolean',
'is_container_label_readonly_enabled' => 'boolean',
'use_build_secrets' => 'boolean',
'inject_build_args_to_dockerfile' => 'boolean',
'include_source_commit_in_build' => 'boolean',
'is_auto_deploy_enabled' => 'boolean',
'is_force_https_enabled' => 'boolean',
'is_debug_enabled' => 'boolean',
'is_preview_deployments_enabled' => 'boolean',
'is_pr_deployments_public_enabled' => 'boolean',
'is_git_submodules_enabled' => 'boolean',
'is_git_lfs_enabled' => 'boolean',
'is_git_shallow_clone_enabled' => 'boolean',
'docker_images_to_keep' => 'integer',
];
protected $guarded = [];
public function isStatic(): Attribute
{
return Attribute::make(
set: function ($value) {
if ($value) {
$this->application->ports_exposes = 80;
}
$this->application->save();
return $value;
}
);
}
public function application()
{
return $this->belongsTo(Application::class);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/TeamInvitation.php | app/Models/TeamInvitation.php | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class TeamInvitation extends Model
{
protected $fillable = [
'team_id',
'uuid',
'email',
'role',
'link',
'via',
];
/**
* Set the email attribute to lowercase.
*/
public function setEmailAttribute(string $value): void
{
$this->attributes['email'] = strtolower($value);
}
public function team()
{
return $this->belongsTo(Team::class);
}
public static function ownedByCurrentTeam()
{
return TeamInvitation::whereTeamId(currentTeam()->id);
}
public function isValid()
{
$createdAt = $this->created_at;
$diff = $createdAt->diffInDays(now());
if ($diff <= config('constants.invitation.link.expiration_days')) {
return true;
} else {
$this->delete();
$user = User::whereEmail($this->email)->first();
if (filled($user)) {
$user->deleteIfNotVerifiedAndForcePasswordReset();
}
return false;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/User.php | app/Models/User.php | <?php
namespace App\Models;
use App\Notifications\Channels\SendsEmail;
use App\Notifications\TransactionalEmails\ResetPassword as TransactionalEmailsResetPassword;
use App\Traits\DeletesUserSessions;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;
use Laravel\Fortify\TwoFactorAuthenticatable;
use Laravel\Sanctum\HasApiTokens;
use Laravel\Sanctum\NewAccessToken;
use OpenApi\Attributes as OA;
#[OA\Schema(
description: 'User model',
type: 'object',
properties: [
'id' => ['type' => 'integer', 'description' => 'The user identifier in the database.'],
'name' => ['type' => 'string', 'description' => 'The user name.'],
'email' => ['type' => 'string', 'description' => 'The user email.'],
'email_verified_at' => ['type' => 'string', 'description' => 'The date when the user email was verified.'],
'created_at' => ['type' => 'string', 'description' => 'The date when the user was created.'],
'updated_at' => ['type' => 'string', 'description' => 'The date when the user was updated.'],
'two_factor_confirmed_at' => ['type' => 'string', 'description' => 'The date when the user two factor was confirmed.'],
'force_password_reset' => ['type' => 'boolean', 'description' => 'The flag to force the user to reset the password.'],
'marketing_emails' => ['type' => 'boolean', 'description' => 'The flag to receive marketing emails.'],
],
)]
class User extends Authenticatable implements SendsEmail
{
use DeletesUserSessions, HasApiTokens, HasFactory, Notifiable, TwoFactorAuthenticatable;
protected $guarded = [];
protected $hidden = [
'password',
'remember_token',
'two_factor_recovery_codes',
'two_factor_secret',
];
protected $casts = [
'email_verified_at' => 'datetime',
'force_password_reset' => 'boolean',
'show_boarding' => 'boolean',
'email_change_code_expires_at' => 'datetime',
];
/**
* Set the email attribute to lowercase.
*/
public function setEmailAttribute($value)
{
$this->attributes['email'] = strtolower($value);
}
/**
* Set the pending_email attribute to lowercase.
*/
public function setPendingEmailAttribute($value)
{
$this->attributes['pending_email'] = $value ? strtolower($value) : null;
}
protected static function boot()
{
parent::boot();
static::created(function (User $user) {
$team = [
'name' => $user->name."'s Team",
'personal_team' => true,
'show_boarding' => true,
];
if ($user->id === 0) {
$team['id'] = 0;
$team['name'] = 'Root Team';
}
$new_team = Team::create($team);
$user->teams()->attach($new_team, ['role' => 'owner']);
});
static::deleting(function (User $user) {
\DB::transaction(function () use ($user) {
$teams = $user->teams;
foreach ($teams as $team) {
$user_alone_in_team = $team->members->count() === 1;
// Prevent deletion if user is alone in root team
if ($team->id === 0 && $user_alone_in_team) {
throw new \Exception('User is alone in the root team, cannot delete');
}
if ($user_alone_in_team) {
static::finalizeTeamDeletion($user, $team);
// Delete any pending team invitations for this user
TeamInvitation::whereEmail($user->email)->delete();
continue;
}
// Load the user's role for this team
$userRole = $team->members->where('id', $user->id)->first()?->pivot?->role;
if ($userRole === 'owner') {
$found_other_owner_or_admin = $team->members->filter(function ($member) use ($user) {
return ($member->pivot->role === 'owner' || $member->pivot->role === 'admin') && $member->id !== $user->id;
})->first();
if ($found_other_owner_or_admin) {
$team->members()->detach($user->id);
continue;
} else {
$found_other_member_who_is_not_owner = $team->members->filter(function ($member) {
return $member->pivot->role === 'member';
})->first();
if ($found_other_member_who_is_not_owner) {
$found_other_member_who_is_not_owner->pivot->role = 'owner';
$found_other_member_who_is_not_owner->pivot->save();
$team->members()->detach($user->id);
} else {
static::finalizeTeamDeletion($user, $team);
}
continue;
}
} else {
$team->members()->detach($user->id);
}
}
});
});
}
/**
* Finalize team deletion by cleaning up all associated resources
*/
private static function finalizeTeamDeletion(User $user, Team $team)
{
$servers = $team->servers;
foreach ($servers as $server) {
$resources = $server->definedResources();
foreach ($resources as $resource) {
$resource->forceDelete();
}
$server->forceDelete();
}
$projects = $team->projects;
foreach ($projects as $project) {
$project->forceDelete();
}
$team->members()->detach($user->id);
$team->delete();
}
/**
* Delete the user if they are not verified and have a force password reset.
* This is used to clean up users that have been invited, did not accept the invitation (and did not verify their email and have a force password reset).
*/
public function deleteIfNotVerifiedAndForcePasswordReset()
{
if ($this->hasVerifiedEmail() === false && $this->force_password_reset === true) {
$this->delete();
}
}
public function recreate_personal_team()
{
$team = [
'name' => $this->name."'s Team",
'personal_team' => true,
'show_boarding' => true,
];
if ($this->id === 0) {
$team['id'] = 0;
$team['name'] = 'Root Team';
}
$new_team = Team::create($team);
$this->teams()->attach($new_team, ['role' => 'owner']);
return $new_team;
}
public function createToken(string $name, array $abilities = ['*'], ?DateTimeInterface $expiresAt = null)
{
$plainTextToken = sprintf(
'%s%s%s',
config('sanctum.token_prefix', ''),
$tokenEntropy = Str::random(40),
hash('crc32b', $tokenEntropy)
);
$token = $this->tokens()->create([
'name' => $name,
'token' => hash('sha256', $plainTextToken),
'abilities' => $abilities,
'expires_at' => $expiresAt,
'team_id' => session('currentTeam')->id,
]);
return new NewAccessToken($token, $token->getKey().'|'.$plainTextToken);
}
public function teams()
{
return $this->belongsToMany(Team::class)->withPivot('role');
}
public function changelogReads()
{
return $this->hasMany(UserChangelogRead::class);
}
public function getUnreadChangelogCount(): int
{
return app(\App\Services\ChangelogService::class)->getUnreadCountForUser($this);
}
public function getRecipients(): array
{
return [$this->email];
}
public function sendVerificationEmail()
{
$mail = new MailMessage;
$url = Url::temporarySignedRoute(
'verify.verify',
Carbon::now()->addMinutes(Config::get('auth.verification.expire', 60)),
[
'id' => $this->getKey(),
'hash' => sha1($this->getEmailForVerification()),
]
);
$mail->view('emails.email-verification', [
'url' => $url,
]);
$mail->subject('Coolify: Verify your email.');
send_user_an_email($mail, $this->email);
}
public function sendPasswordResetNotification($token): void
{
$this?->notify(new TransactionalEmailsResetPassword($token));
}
public function isAdmin()
{
return $this->role() === 'admin' || $this->role() === 'owner';
}
public function isOwner()
{
return $this->role() === 'owner';
}
public function isMember()
{
return $this->role() === 'member';
}
public function isAdminFromSession()
{
if (Auth::id() === 0) {
return true;
}
$teams = $this->teams()->get();
$is_part_of_root_team = $teams->where('id', 0)->first();
$is_admin_of_root_team = $is_part_of_root_team &&
($is_part_of_root_team->pivot->role === 'admin' || $is_part_of_root_team->pivot->role === 'owner');
if ($is_part_of_root_team && $is_admin_of_root_team) {
return true;
}
$team = $teams->where('id', session('currentTeam')->id)->first();
$role = data_get($team, 'pivot.role');
return $role === 'admin' || $role === 'owner';
}
public function isInstanceAdmin()
{
$found_root_team = Auth::user()->teams->filter(function ($team) {
if ($team->id == 0) {
if (! Auth::user()->isAdmin()) {
return false;
}
return true;
}
return false;
});
return $found_root_team->count() > 0;
}
public function currentTeam()
{
return Cache::remember('team:'.Auth::id(), 3600, function () {
if (is_null(data_get(session('currentTeam'), 'id')) && Auth::user()->teams->count() > 0) {
return Auth::user()->teams[0];
}
return Team::find(session('currentTeam')->id);
});
}
public function otherTeams()
{
return Auth::user()->teams->filter(function ($team) {
return $team->id != currentTeam()->id;
});
}
public function role()
{
if (data_get($this, 'pivot')) {
return $this->pivot->role;
}
$user = Auth::user()->teams->where('id', currentTeam()->id)->first();
return data_get($user, 'pivot.role');
}
/**
* Check if the user is an admin or owner of a specific team
*/
public function isAdminOfTeam(int $teamId): bool
{
$team = $this->teams->where('id', $teamId)->first();
if (! $team) {
return false;
}
$role = $team->pivot->role ?? null;
return $role === 'admin' || $role === 'owner';
}
/**
* Check if the user can access system resources (team_id=0)
* Must be admin/owner of root team
*/
public function canAccessSystemResources(): bool
{
// Check if user is member of root team
$rootTeam = $this->teams->where('id', 0)->first();
if (! $rootTeam) {
return false;
}
// Check if user is admin or owner of root team
return $this->isAdminOfTeam(0);
}
public function requestEmailChange(string $newEmail): void
{
// Generate 6-digit code
$code = sprintf('%06d', mt_rand(0, 999999));
// Set expiration using config value
$expiryMinutes = config('constants.email_change.verification_code_expiry_minutes', 10);
$expiresAt = Carbon::now()->addMinutes($expiryMinutes);
$this->update([
'pending_email' => $newEmail,
'email_change_code' => $code,
'email_change_code_expires_at' => $expiresAt,
]);
// Send verification email to new address
$this->notify(new \App\Notifications\TransactionalEmails\EmailChangeVerification($this, $code, $newEmail, $expiresAt));
}
public function isEmailChangeCodeValid(string $code): bool
{
return $this->email_change_code === $code
&& $this->email_change_code_expires_at
&& Carbon::now()->lessThan($this->email_change_code_expires_at);
}
public function confirmEmailChange(string $code): bool
{
if (! $this->isEmailChangeCodeValid($code)) {
return false;
}
$oldEmail = $this->email;
$newEmail = $this->pending_email;
// Update email and clear change request fields
$this->update([
'email' => $newEmail,
'pending_email' => null,
'email_change_code' => null,
'email_change_code_expires_at' => null,
]);
// For cloud users, dispatch job to update Stripe customer email asynchronously
if (isCloud() && $this->currentTeam()->subscription) {
dispatch(new \App\Jobs\UpdateStripeCustomerEmailJob(
$this->currentTeam(),
$this->id,
$newEmail,
$oldEmail
));
}
return true;
}
public function clearEmailChangeRequest(): void
{
$this->update([
'pending_email' => null,
'email_change_code' => null,
'email_change_code_expires_at' => null,
]);
}
public function hasEmailChangeRequest(): bool
{
return ! is_null($this->pending_email)
&& ! is_null($this->email_change_code)
&& $this->email_change_code_expires_at
&& Carbon::now()->lessThan($this->email_change_code_expires_at);
}
/**
* Check if the user has a password set.
* OAuth users are created without passwords.
*/
public function hasPassword(): bool
{
return ! empty($this->password);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Models/StandaloneKeydb.php | app/Models/StandaloneKeydb.php | <?php
namespace App\Models;
use App\Traits\ClearsGlobalSearchCache;
use App\Traits\HasSafeStringAttribute;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
class StandaloneKeydb extends BaseModel
{
use ClearsGlobalSearchCache, HasFactory, HasSafeStringAttribute, SoftDeletes;
protected $guarded = [];
protected $appends = ['internal_db_url', 'external_db_url', 'server_status'];
protected $casts = [
'keydb_password' => 'encrypted',
'restart_count' => 'integer',
'last_restart_at' => 'datetime',
'last_restart_type' => 'string',
];
protected static function booted()
{
static::created(function ($database) {
LocalPersistentVolume::create([
'name' => 'keydb-data-'.$database->uuid,
'mount_path' => '/data',
'host_path' => null,
'resource_id' => $database->id,
'resource_type' => $database->getMorphClass(),
]);
});
static::forceDeleting(function ($database) {
$database->persistentStorages()->delete();
$database->scheduledBackups()->delete();
$database->environment_variables()->delete();
$database->tags()->detach();
});
static::saving(function ($database) {
if ($database->isDirty('status')) {
$database->forceFill(['last_online_at' => now()]);
}
});
}
/**
* Get query builder for KeyDB databases owned by current team.
* If you need all databases without further query chaining, use ownedByCurrentTeamCached() instead.
*/
public static function ownedByCurrentTeam()
{
return StandaloneKeydb::whereRelation('environment.project.team', 'id', currentTeam()->id)->orderBy('name');
}
/**
* Get all KeyDB databases owned by current team (cached for request duration).
*/
public static function ownedByCurrentTeamCached()
{
return once(function () {
return StandaloneKeydb::ownedByCurrentTeam()->get();
});
}
protected function serverStatus(): Attribute
{
return Attribute::make(
get: function () {
return $this->destination->server->isFunctional();
}
);
}
public function isConfigurationChanged(bool $save = false)
{
$newConfigHash = $this->image.$this->ports_mappings.$this->keydb_conf;
$newConfigHash .= json_encode($this->environment_variables()->get('value')->sort());
$newConfigHash = md5($newConfigHash);
$oldConfigHash = data_get($this, 'config_hash');
if ($oldConfigHash === null) {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
if ($oldConfigHash === $newConfigHash) {
return false;
} else {
if ($save) {
$this->config_hash = $newConfigHash;
$this->save();
}
return true;
}
}
public function isRunning()
{
return (bool) str($this->status)->contains('running');
}
public function isExited()
{
return (bool) str($this->status)->startsWith('exited');
}
public function workdir()
{
return database_configuration_dir()."/{$this->uuid}";
}
public function deleteConfigurations()
{
$server = data_get($this, 'destination.server');
$workdir = $this->workdir();
if (str($workdir)->endsWith($this->uuid)) {
instant_remote_process(['rm -rf '.$this->workdir()], $server, false);
}
}
public function deleteVolumes()
{
$persistentStorages = $this->persistentStorages()->get() ?? collect();
if ($persistentStorages->count() === 0) {
return;
}
$server = data_get($this, 'destination.server');
foreach ($persistentStorages as $storage) {
instant_remote_process(["docker volume rm -f $storage->name"], $server, false);
}
}
public function realStatus()
{
return $this->getRawOriginal('status');
}
public function status(): Attribute
{
return Attribute::make(
set: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
get: function ($value) {
if (str($value)->contains('(')) {
$status = str($value)->before('(')->trim()->value();
$health = str($value)->after('(')->before(')')->trim()->value() ?? 'unhealthy';
} elseif (str($value)->contains(':')) {
$status = str($value)->before(':')->trim()->value();
$health = str($value)->after(':')->trim()->value() ?? 'unhealthy';
} else {
$status = $value;
$health = 'unhealthy';
}
return "$status:$health";
},
);
}
public function tags()
{
return $this->morphToMany(Tag::class, 'taggable');
}
public function project()
{
return data_get($this, 'environment.project');
}
public function team()
{
return data_get($this, 'environment.project.team');
}
public function sslCertificates()
{
return $this->morphMany(SslCertificate::class, 'resource');
}
public function link()
{
if (data_get($this, 'environment.project.uuid')) {
return route('project.database.configuration', [
'project_uuid' => data_get($this, 'environment.project.uuid'),
'environment_uuid' => data_get($this, 'environment.uuid'),
'database_uuid' => data_get($this, 'uuid'),
]);
}
return null;
}
public function isLogDrainEnabled()
{
return data_get($this, 'is_log_drain_enabled', false);
}
public function portsMappings(): Attribute
{
return Attribute::make(
set: fn ($value) => $value === '' ? null : $value,
);
}
public function portsMappingsArray(): Attribute
{
return Attribute::make(
get: fn () => is_null($this->ports_mappings)
? []
: explode(',', $this->ports_mappings),
);
}
public function databaseType(): Attribute
{
return new Attribute(
get: fn () => $this->type(),
);
}
public function type(): string
{
return 'standalone-keydb';
}
protected function internalDbUrl(): Attribute
{
return new Attribute(
get: function () {
$scheme = $this->enable_ssl ? 'rediss' : 'redis';
$port = $this->enable_ssl ? 6380 : 6379;
$encodedPass = rawurlencode($this->keydb_password);
$url = "{$scheme}://:{$encodedPass}@{$this->uuid}:{$port}/0";
if ($this->enable_ssl && $this->ssl_mode === 'verify-ca') {
$url .= '?cacert=/etc/ssl/certs/coolify-ca.crt';
}
return $url;
}
);
}
protected function externalDbUrl(): Attribute
{
return new Attribute(
get: function () {
if ($this->is_public && $this->public_port) {
$serverIp = $this->destination->server->getIp;
if (empty($serverIp)) {
return null;
}
$scheme = $this->enable_ssl ? 'rediss' : 'redis';
$encodedPass = rawurlencode($this->keydb_password);
$url = "{$scheme}://:{$encodedPass}@{$serverIp}:{$this->public_port}/0";
if ($this->enable_ssl && $this->ssl_mode === 'verify-ca') {
$url .= '?cacert=/etc/ssl/certs/coolify-ca.crt';
}
return $url;
}
return null;
}
);
}
public function environment()
{
return $this->belongsTo(Environment::class);
}
public function fileStorages()
{
return $this->morphMany(LocalFileVolume::class, 'resource');
}
public function destination()
{
return $this->morphTo();
}
public function runtime_environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable');
}
public function persistentStorages()
{
return $this->morphMany(LocalPersistentVolume::class, 'resource');
}
public function scheduledBackups()
{
return $this->morphMany(ScheduledDatabaseBackup::class, 'database');
}
public function getCpuMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/cpu/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['percent']];
});
return $parsedCollection->toArray();
}
public function getMemoryMetrics(int $mins = 5)
{
$server = $this->destination->server;
$container_name = $this->uuid;
$from = now()->subMinutes($mins)->toIso8601ZuluString();
$metrics = instant_remote_process(["docker exec coolify-sentinel sh -c 'curl -H \"Authorization: Bearer {$server->settings->sentinel_token}\" http://localhost:8888/api/container/{$container_name}/memory/history?from=$from'"], $server, false);
if (str($metrics)->contains('error')) {
$error = json_decode($metrics, true);
$error = data_get($error, 'error', 'Something is not okay, are you okay?');
if ($error === 'Unauthorized') {
$error = 'Unauthorized, please check your metrics token or restart Sentinel to set a new token.';
}
throw new \Exception($error);
}
$metrics = json_decode($metrics, true);
$parsedCollection = collect($metrics)->map(function ($metric) {
return [(int) $metric['time'], (float) $metric['used']];
});
return $parsedCollection->toArray();
}
public function isBackupSolutionAvailable()
{
return false;
}
public function environment_variables()
{
return $this->morphMany(EnvironmentVariable::class, 'resourceable')
->orderByRaw("
CASE
WHEN LOWER(key) LIKE 'service_%' THEN 1
WHEN is_required = true AND (value IS NULL OR value = '') THEN 2
ELSE 3
END,
LOWER(key) ASC
");
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.