Skip to content

Commit

Permalink
fixes and check for valid cron expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
peaklabs-dev committed Aug 5, 2024
1 parent 27e82f0 commit 38976da
Show file tree
Hide file tree
Showing 9 changed files with 124 additions and 27 deletions.
2 changes: 0 additions & 2 deletions app/Actions/Server/UpdateCoolify.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public function handle($manual_update = false)
{
try {
$settings = InstanceSettings::get();
ray('Running InstanceAutoUpdateJob');
$this->server = Server::find(0);
if (! $this->server) {
return;
Expand Down Expand Up @@ -48,7 +47,6 @@ public function handle($manual_update = false)
private function update()
{
if (isDev()) {
ray('Running in dev mode');
remote_process([
'sleep 10',
], $this->server);
Expand Down
45 changes: 33 additions & 12 deletions app/Console/Kernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
use App\Jobs\PullTemplatesFromCDN;
use App\Jobs\ScheduledTaskJob;
use App\Jobs\ServerStatusJob;
use App\Jobs\UpdateCoolifyJob;
use App\Jobs\CheckForUpdatesJob;
use App\Models\InstanceSettings;
use App\Models\ScheduledDatabaseBackup;
use App\Models\ScheduledTask;
Expand All @@ -31,10 +33,6 @@ protected function schedule(Schedule $schedule): void
$settings = InstanceSettings::get();

if (isDev()) {
// Instance Jobs
$schedule->command('horizon:snapshot')->everyMinute();
$schedule->job(new CleanupInstanceStuffsJob)->everyMinute()->onOneServer();
$schedule->job(new PullTemplatesFromCDN)->everyTwoHours()->onOneServer();
// Server Jobs
$this->check_scheduled_backups($schedule);
$this->check_resources($schedule);
Expand All @@ -45,18 +43,23 @@ protected function schedule(Schedule $schedule): void
// Instance Jobs
$schedule->command('horizon:snapshot')->everyFiveMinutes();
$schedule->command('cleanup:unreachable-servers')->daily();
$schedule->job(new PullCoolifyImageJob)->cron($settings->update_check_frequency)->onOneServer();
$schedule->job(new PullTemplatesFromCDN)->everyThirtyMinutes()->onOneServer();
$schedule->job(new CleanupInstanceStuffsJob)->everyTwoMinutes()->onOneServer();

$schedule->job(new PullTemplatesFromCDN)->daily()->onOneServer();
$schedule->job(new CleanupInstanceStuffsJob)->everyFiveMinutes()->onOneServer();

if ($settings->update_check_frequency && $this->isValidCronExpression($settings->update_check_frequency)) {
$schedule->job(new PullCoolifyImageJob)->cron($settings->update_check_frequency)->onOneServer();
} else {
// Default to every 12 hours if not set or invalid
$schedule->job(new PullCoolifyImageJob)->twiceDaily()->onOneServer();
}

// Server Jobs
$this->scheduleUpdates($schedule);
$this->pull_images($schedule);
$this->check_resources($schedule);
$this->check_scheduled_tasks($schedule);
$this->check_scheduled_backups($schedule);


$schedule->command('cleanup:database --yes')->daily();
$schedule->command('uploads:clear')->everyTwoMinutes();
}
Expand All @@ -79,13 +82,31 @@ private function scheduleUpdates($schedule)
$settings = InstanceSettings::get();

// Schedule update check
if ($settings->update_check_frequency) {
if ($settings->update_check_frequency && $this->isValidCronExpression($settings->update_check_frequency)) {
$schedule->job(new CheckForUpdatesJob())->cron($settings->update_check_frequency)->onOneServer();
} else {
// Default to every 12 hours if not set or invalid
$schedule->job(new CheckForUpdatesJob())->twiceDaily()->onOneServer();
}

// Schedule auto-update
if ($settings->is_auto_update_enabled && $settings->auto_update_frequency) {
$schedule->job(new UpdateCoolifyJob())->cron($settings->auto_update_frequency)->onOneServer();
if ($settings->is_auto_update_enabled) {
if ($settings->auto_update_frequency && $this->isValidCronExpression($settings->auto_update_frequency)) {
$schedule->job(new UpdateCoolifyJob())->cron($settings->auto_update_frequency)->onOneServer();
} else {
// Default to every 24 hours if not set or invalid
$schedule->job(new UpdateCoolifyJob())->daily()->onOneServer();
}
}
}

private function isValidCronExpression($expression)
{
try {
new \Cron\CronExpression($expression);
return true;
} catch (\Exception $e) {
return false;
}
}

Expand Down
4 changes: 1 addition & 3 deletions app/Jobs/CheckForUpdatesJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@ public function handle(): void
if (version_compare($latest_version, $current_version, '>')) {
// New version available
$settings->update(['new_version_available' => true]);
// Optionally, you can trigger a notification here
} else {
$settings->update(['new_version_available' => false]);
}
}
} catch (\Throwable $e) {
// Log the error or send a notification
ray('CheckForUpdatesJob failed: ' . $e->getMessage());
// Consider implementing a notification to administrators
}
}
}
1 change: 0 additions & 1 deletion app/Jobs/PullCoolifyImageJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public function handle(): void
if (version_compare($latest_version, $current_version, '<')) {
return;
}
// The actual update process will be handled by the UpdateCoolifyJob
} catch (\Throwable $e) {
throw $e;
}
Expand Down
19 changes: 14 additions & 5 deletions app/Jobs/UpdateCoolifyJob.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace App\Jobs;

use App\Actions\Server\UpdateCoolify;
use App\Models\InstanceSettings;
use App\Models\Server;
use Illuminate\Bus\Queueable;
Expand All @@ -11,6 +10,8 @@
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Actions\Server\UpdateCoolify;
use Illuminate\Support\Facades\Log;

class UpdateCoolifyJob implements ShouldBeEncrypted, ShouldQueue
{
Expand All @@ -22,23 +23,31 @@ public function handle(): void
{
try {
$settings = InstanceSettings::get();
if (!$settings->is_auto_update_enabled || !$settings->new_version_available) {
if (!$settings->is_auto_update_enabled) {
Log::info('Auto-update is disabled. Skipping update check.');
return;
}

if (!$settings->new_version_available) {
Log::info('No new version available. Skipping update.');
return;
}

$server = Server::findOrFail(0);
if (!$server) {
Log::error('Server not found. Cannot proceed with update.');
return;
}

Log::info('Starting Coolify update process...');
UpdateCoolify::run(false); // false means it's not a manual update

// After successful update, reset the new_version_available flag
$settings->update(['new_version_available' => false]);
Log::info('Coolify update completed successfully.');

} catch (\Throwable $e) {
// Log the error or send a notification
ray('UpdateCoolifyJob failed: ' . $e->getMessage());
Log::error('UpdateCoolifyJob failed: ' . $e->getMessage());
// Consider implementing a notification to administrators
}
}
}
69 changes: 68 additions & 1 deletion app/Livewire/Settings/Configuration.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use App\Models\InstanceSettings as ModelsInstanceSettings;
use App\Models\Server;
use Livewire\Component;
use Cron\CronExpression;

class Configuration extends Component
{
Expand All @@ -20,6 +21,10 @@ class Configuration extends Component

public bool $is_api_enabled;

public ?string $auto_update_frequency;

public ?string $update_check_frequency;

protected string $dynamic_config_path = '/data/coolify/proxy/dynamic';

protected Server $server;
Expand All @@ -32,6 +37,9 @@ class Configuration extends Component
'settings.custom_dns_servers' => 'nullable',
'settings.instance_name' => 'nullable',
'settings.allowed_ips' => 'nullable',
'settings.is_auto_update_enabled' => 'boolean',
'auto_update_frequency' => 'nullable|string',
'update_check_frequency' => 'required|string',
];

protected $validationAttributes = [
Expand All @@ -41,6 +49,9 @@ class Configuration extends Component
'settings.public_port_max' => 'Public port max',
'settings.custom_dns_servers' => 'Custom DNS servers',
'settings.allowed_ips' => 'Allowed IPs',
'settings.is_auto_update_enabled' => 'Auto Update Enabled',
'auto_update_frequency' => 'Auto Update Frequency',
'update_check_frequency' => 'Update Check Frequency',
];

public function mount()
Expand All @@ -50,6 +61,8 @@ public function mount()
$this->is_registration_enabled = $this->settings->is_registration_enabled;
$this->is_dns_validation_enabled = $this->settings->is_dns_validation_enabled;
$this->is_api_enabled = $this->settings->is_api_enabled;
$this->auto_update_frequency = $this->settings->auto_update_frequency;
$this->update_check_frequency = $this->settings->update_check_frequency;
}

public function instantSave()
Expand All @@ -59,6 +72,8 @@ public function instantSave()
$this->settings->is_registration_enabled = $this->is_registration_enabled;
$this->settings->is_dns_validation_enabled = $this->is_dns_validation_enabled;
$this->settings->is_api_enabled = $this->is_api_enabled;
$this->settings->auto_update_frequency = $this->auto_update_frequency;
$this->settings->update_check_frequency = $this->update_check_frequency;
$this->settings->save();
$this->dispatch('success', 'Settings updated!');
}
Expand All @@ -76,6 +91,16 @@ public function submit()
}
$this->validate();

if ($this->is_auto_update_enabled && !$this->validateCronExpression($this->auto_update_frequency)) {
$this->dispatch('error', 'Invalid Cron / Human expression for Auto Update Frequency.');
return;
}

if (!$this->validateCronExpression($this->update_check_frequency)) {
$this->dispatch('error', 'Invalid Cron / Human expression for Update Check Frequency.');
return;
}

if ($this->settings->is_dns_validation_enabled && $this->settings->fqdn) {
if (! validate_dns_entry($this->settings->fqdn, $this->server)) {
$this->dispatch('error', "Validating DNS failed.<br><br>Make sure you have added the DNS records correctly.<br><br>{$this->settings->fqdn}->{$this->server->ip}<br><br>Check this <a target='_blank' class='underline dark:text-white' href='https://coolify.io/docs/knowledge-base/dns-configuration'>documentation</a> for further help.");
Expand All @@ -99,6 +124,14 @@ public function submit()
$this->settings->allowed_ips = $this->settings->allowed_ips->unique();
$this->settings->allowed_ips = $this->settings->allowed_ips->implode(',');

$this->settings->do_not_track = $this->do_not_track;
$this->settings->is_auto_update_enabled = $this->is_auto_update_enabled;
$this->settings->is_registration_enabled = $this->is_registration_enabled;
$this->settings->is_dns_validation_enabled = $this->is_dns_validation_enabled;
$this->settings->is_api_enabled = $this->is_api_enabled;
$this->settings->auto_update_frequency = $this->auto_update_frequency;
$this->settings->update_check_frequency = $this->update_check_frequency;

$this->settings->save();
$this->server->setupDynamicProxyConfiguration();
if (! $error_show) {
Expand All @@ -108,4 +141,38 @@ public function submit()
return handleError($e, $this);
}
}
}

private function validateCronExpression($expression): bool
{
if (empty($expression)) {
return false;
}
$isValid = false;
try {
$cronExpression = new CronExpression($expression);
$isValid = $cronExpression->getNextRunDate() !== false;
} catch (\Exception $e) {
$isValid = false;
}

if (isset(VALID_CRON_STRINGS[$expression])) {
$isValid = true;
}

return $isValid;
}

public function updatedAutoUpdateFrequency()
{
if (!$this->validateCronExpression($this->auto_update_frequency)) {
$this->dispatch('error', 'Invalid Cron / Human expression.');
}
}

public function updatedUpdateCheckFrequency()
{
if (!$this->validateCronExpression($this->update_check_frequency)) {
$this->dispatch('error', 'Invalid Cron / Human expression.');
}
}
}
3 changes: 3 additions & 0 deletions app/Models/InstanceSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ class InstanceSettings extends Model implements SendsEmail
'resale_license' => 'encrypted',
'smtp_password' => 'encrypted',
'allowed_ip_ranges' => 'array',
'is_auto_update_enabled' => 'boolean',
'auto_update_frequency' => 'string',
'update_check_frequency' => 'string',
];

public function fqdn(): Attribute
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
public function up(): void
{
Schema::table('instance_settings', function (Blueprint $table) {
$table->string('update_check_frequency')->nullable();
$table->string('auto_update_frequency')->nullable();
$table->string('update_check_frequency')->default('0 */12 * * *')->nullable();
$table->string('auto_update_frequency')->default('0 0 * * *')->nullable();
});
}

Expand Down
4 changes: 3 additions & 1 deletion resources/views/livewire/settings/configuration.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,10 @@
<x-forms.checkbox instantSave id="is_auto_update_enabled" label="Auto Update Coolify" />
@if($is_auto_update_enabled)
<x-forms.input id="auto_update_frequency" label="Auto Update Frequency" placeholder="0 0 * * *" helper="Cron expression for auto update frequency" />
@error('settings.auto_update_frequency') <span class="text-error">{{ $message }}</span> @enderror
@endif
<x-forms.input id="update_check_frequency" label="Update Check Frequency" placeholder="0 0 * * *" helper="Cron expression for update check frequency" />
<x-forms.input id="update_check_frequency" label="Update Check Frequency" placeholder="0 */12 * * *" helper="Cron expression for update check frequency" />
@error('settings.update_check_frequency') <span class="text-error">{{ $message }}</span> @enderror
@endif
<x-forms.checkbox instantSave id="is_registration_enabled" label="Registration Allowed" />
<x-forms.checkbox instantSave id="do_not_track" label="Do Not Track" />
Expand Down

0 comments on commit 38976da

Please sign in to comment.