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/Http/Middleware/RedirectIfAuthenticated.php | app/Http/Middleware/RedirectIfAuthenticated.php | <?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/TrustProxies.php | app/Http/Middleware/TrustProxies.php | <?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies = '*';
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/ValidateSignature.php | app/Http/Middleware/ValidateSignature.php | <?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/CanUpdateResource.php | app/Http/Middleware/CanUpdateResource.php | <?php
namespace App\Http\Middleware;
use App\Models\Application;
use App\Models\Environment;
use App\Models\Project;
use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
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 Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;
class CanUpdateResource
{
public function handle(Request $request, Closure $next): Response
{
return $next($request);
// Get resource from route parameters
// $resource = null;
// if ($request->route('application_uuid')) {
// $resource = Application::where('uuid', $request->route('application_uuid'))->first();
// } elseif ($request->route('service_uuid')) {
// $resource = Service::where('uuid', $request->route('service_uuid'))->first();
// } elseif ($request->route('stack_service_uuid')) {
// // Handle ServiceApplication or ServiceDatabase
// $stack_service_uuid = $request->route('stack_service_uuid');
// $resource = ServiceApplication::where('uuid', $stack_service_uuid)->first() ??
// ServiceDatabase::where('uuid', $stack_service_uuid)->first();
// } elseif ($request->route('database_uuid')) {
// // Try different database types
// $database_uuid = $request->route('database_uuid');
// $resource = StandalonePostgresql::where('uuid', $database_uuid)->first() ??
// StandaloneMysql::where('uuid', $database_uuid)->first() ??
// StandaloneMariadb::where('uuid', $database_uuid)->first() ??
// StandaloneRedis::where('uuid', $database_uuid)->first() ??
// StandaloneKeydb::where('uuid', $database_uuid)->first() ??
// StandaloneDragonfly::where('uuid', $database_uuid)->first() ??
// StandaloneClickhouse::where('uuid', $database_uuid)->first() ??
// StandaloneMongodb::where('uuid', $database_uuid)->first();
// } elseif ($request->route('server_uuid')) {
// // For server routes, check if user can manage servers
// if (! auth()->user()->isAdmin()) {
// abort(403, 'You do not have permission to access this resource.');
// }
// return $next($request);
// } elseif ($request->route('environment_uuid')) {
// $resource = Environment::where('uuid', $request->route('environment_uuid'))->first();
// } elseif ($request->route('project_uuid')) {
// $resource = Project::ownedByCurrentTeam()->where('uuid', $request->route('project_uuid'))->first();
// }
// if (! $resource) {
// abort(404, 'Resource not found.');
// }
// if (! Gate::allows('update', $resource)) {
// abort(403, 'You do not have permission to update this resource.');
// }
// return $next($request);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/CanCreateResources.php | app/Http/Middleware/CanCreateResources.php | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Symfony\Component\HttpFoundation\Response;
class CanCreateResources
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
return $next($request);
// if (! Gate::allows('createAnyResource')) {
// abort(403, 'You do not have permission to create resources.');
// }
// return $next($request);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/ApiAbility.php | app/Http/Middleware/ApiAbility.php | <?php
namespace App\Http\Middleware;
use Laravel\Sanctum\Http\Middleware\CheckForAnyAbility;
class ApiAbility extends CheckForAnyAbility
{
public function handle($request, $next, ...$abilities)
{
try {
if ($request->user()->tokenCan('root')) {
return $next($request);
}
return parent::handle($request, $next, ...$abilities);
} catch (\Illuminate\Auth\AuthenticationException $e) {
return response()->json([
'message' => 'Unauthenticated.',
], 401);
} catch (\Exception $e) {
return response()->json([
'message' => 'Missing required permissions: '.implode(', ', $abilities),
], 403);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/CheckForcePasswordReset.php | app/Http/Middleware/CheckForcePasswordReset.php | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CheckForcePasswordReset
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (auth()->user()) {
if ($request->path() === 'auth/link') {
auth()->logout();
request()->session()->invalidate();
request()->session()->regenerateToken();
return $next($request);
}
$force_password_reset = auth()->user()->force_password_reset;
if ($force_password_reset) {
if ($request->routeIs('auth.force-password-reset') || $request->path() === 'force-password-reset' || $request->path() === 'livewire/update' || $request->path() === 'logout') {
return $next($request);
}
return redirect()->route('auth.force-password-reset');
}
}
return $next($request);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/PreventRequestsDuringMaintenance.php | app/Http/Middleware/PreventRequestsDuringMaintenance.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
'webhooks/*',
'/api/health',
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/CanAccessTerminal.php | app/Http/Middleware/CanAccessTerminal.php | <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class CanAccessTerminal
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (! auth()->check()) {
abort(401, 'Authentication required');
}
// Only admins/owners can access terminal functionality
if (! auth()->user()->can('canAccessTerminal')) {
abort(403, 'Access to terminal functionality is restricted to team administrators');
}
return $next($request);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/TrimStrings.php | app/Http/Middleware/TrimStrings.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/TrustHosts.php | app/Http/Middleware/TrustHosts.php | <?php
namespace App\Http\Middleware;
use App\Models\InstanceSettings;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Spatie\Url\Url;
class TrustHosts extends Middleware
{
/**
* Handle the incoming request.
*
* Skip host validation for certain routes:
* - Terminal auth routes (called by realtime container)
* - API routes (use token-based authentication, not host validation)
* - Webhook endpoints (use cryptographic signature validation)
*/
public function handle(Request $request, $next)
{
// Skip host validation for these routes
if ($request->is(
'terminal/auth',
'terminal/auth/ips',
'api/*',
'webhooks/*'
)) {
return $next($request);
}
// Skip host validation if no FQDN is configured (initial setup)
$fqdnHost = Cache::get('instance_settings_fqdn_host');
if ($fqdnHost === '' || $fqdnHost === null) {
return $next($request);
}
// For all other routes, use parent's host validation
return parent::handle($request, $next);
}
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
$trustedHosts = [];
// Trust the configured FQDN from InstanceSettings (cached to avoid DB query on every request)
// Use empty string as sentinel value instead of null so negative results are cached
$fqdnHost = Cache::remember('instance_settings_fqdn_host', 300, function () {
try {
$settings = InstanceSettings::get();
if ($settings && $settings->fqdn) {
$url = Url::fromString($settings->fqdn);
$host = $url->getHost();
return $host ?: '';
}
} catch (\Exception $e) {
// If instance settings table doesn't exist yet (during installation),
// return empty string (sentinel) so this result is cached
}
return '';
});
// Convert sentinel value back to null for consumption
$fqdnHost = $fqdnHost !== '' ? $fqdnHost : null;
if ($fqdnHost) {
$trustedHosts[] = $fqdnHost;
}
// Trust the APP_URL host itself (not just subdomains)
$appUrl = config('app.url');
if ($appUrl) {
try {
$appUrlHost = parse_url($appUrl, PHP_URL_HOST);
if ($appUrlHost && ! in_array($appUrlHost, $trustedHosts, true)) {
$trustedHosts[] = $appUrlHost;
}
} catch (\Exception $e) {
// Ignore parse errors
}
}
// Trust all subdomains of APP_URL as fallback
$trustedHosts[] = $this->allSubdomainsOfApplicationUrl();
return array_filter($trustedHosts);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/EncryptCookies.php | app/Http/Middleware/EncryptCookies.php | <?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Http/Middleware/VerifyCsrfToken.php | app/Http/Middleware/VerifyCsrfToken.php | <?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
'webhooks/*',
];
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/EnvironmentVariableProtection.php | app/Traits/EnvironmentVariableProtection.php | <?php
namespace App\Traits;
use Symfony\Component\Yaml\Yaml;
trait EnvironmentVariableProtection
{
/**
* Check if an environment variable is protected from deletion
*
* @param string $key The environment variable key to check
* @return bool True if the variable is protected, false otherwise
*/
protected function isProtectedEnvironmentVariable(string $key): bool
{
return str($key)->startsWith('SERVICE_FQDN_') || str($key)->startsWith('SERVICE_URL_') || str($key)->startsWith('SERVICE_NAME_');
}
/**
* Check if an environment variable is used in Docker Compose
*
* @param string $key The environment variable key to check
* @param string|null $dockerCompose The Docker Compose YAML content
* @return array [bool $isUsed, string $reason] Whether the variable is used and the reason if it is
*/
protected function isEnvironmentVariableUsedInDockerCompose(string $key, ?string $dockerCompose): array
{
if (empty($dockerCompose)) {
return [false, ''];
}
try {
$dockerComposeData = Yaml::parse($dockerCompose);
$dockerEnvVars = data_get($dockerComposeData, 'services.*.environment');
foreach ($dockerEnvVars as $serviceEnvs) {
if (! is_array($serviceEnvs)) {
continue;
}
// Check for direct variable usage
foreach ($serviceEnvs as $env => $value) {
if ($env === $key) {
return [true, "Environment variable '{$key}' is used directly in the Docker Compose file."];
}
}
// Check for variable references in values
foreach ($serviceEnvs as $env => $value) {
if (is_string($value) && str_contains($value, '$'.$key)) {
return [true, "Environment variable '{$key}' is referenced in the Docker Compose file."];
}
}
}
} catch (\Exception $e) {
// If there's an error parsing the Docker Compose file, we'll assume it's not used
return [false, ''];
}
return [false, ''];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/SaveFromRedirect.php | app/Traits/SaveFromRedirect.php | <?php
namespace App\Traits;
use Illuminate\Support\Collection;
trait SaveFromRedirect
{
public function saveFromRedirect(string $route, ?Collection $parameters = null)
{
session()->forget('from');
if (! $parameters || $parameters->count() === 0) {
$parameters = $this->parameters;
}
$parameters = collect($parameters) ?? collect([]);
$queries = collect($this->query) ?? collect([]);
$parameters = $parameters->merge($queries);
session(['from' => [
'back' => $this->currentRoute,
'route' => $route,
'parameters' => $parameters,
]]);
return redirect()->route($route);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/EnvironmentVariableAnalyzer.php | app/Traits/EnvironmentVariableAnalyzer.php | <?php
namespace App\Traits;
trait EnvironmentVariableAnalyzer
{
/**
* List of environment variables that commonly cause build issues when set to production values.
* Each entry contains the variable pattern and associated metadata.
*/
protected static function getProblematicBuildVariables(): array
{
return [
'NODE_ENV' => [
'problematic_values' => ['production', 'prod'],
'affects' => 'Node.js/npm/yarn/bun/pnpm',
'issue' => 'Skips devDependencies installation which are often required for building (webpack, typescript, etc.)',
'recommendation' => 'Uncheck "Available at Buildtime" or use "development" during build',
],
'NPM_CONFIG_PRODUCTION' => [
'problematic_values' => ['true', '1', 'yes'],
'affects' => 'npm/pnpm',
'issue' => 'Forces npm to skip devDependencies',
'recommendation' => 'Remove from build-time variables or set to false',
],
'YARN_PRODUCTION' => [
'problematic_values' => ['true', '1', 'yes'],
'affects' => 'Yarn/pnpm',
'issue' => 'Forces yarn to skip devDependencies',
'recommendation' => 'Remove from build-time variables or set to false',
],
'COMPOSER_NO_DEV' => [
'problematic_values' => ['1', 'true', 'yes'],
'affects' => 'PHP/Composer',
'issue' => 'Skips require-dev packages which may include build tools',
'recommendation' => 'Set as "Runtime only" or remove from build-time variables',
],
'MIX_ENV' => [
'problematic_values' => ['prod', 'production'],
'affects' => 'Elixir/Phoenix',
'issue' => 'Production mode may skip development dependencies needed for compilation',
'recommendation' => 'Use "dev" for build or set as "Runtime only"',
],
'RAILS_ENV' => [
'problematic_values' => ['production'],
'affects' => 'Ruby on Rails',
'issue' => 'May affect asset precompilation and dependency handling',
'recommendation' => 'Consider using "development" for build phase',
],
'RACK_ENV' => [
'problematic_values' => ['production'],
'affects' => 'Ruby/Rack',
'issue' => 'May affect dependency handling and build behavior',
'recommendation' => 'Consider using "development" for build phase',
],
'BUNDLE_WITHOUT' => [
'problematic_values' => ['development', 'test', 'development:test'],
'affects' => 'Ruby/Bundler',
'issue' => 'Excludes gem groups that may contain build dependencies',
'recommendation' => 'Remove from build-time variables or adjust groups',
],
'FLASK_ENV' => [
'problematic_values' => ['production'],
'affects' => 'Python/Flask',
'issue' => 'May affect debug mode and development tools availability',
'recommendation' => 'Usually safe, but consider "development" for complex builds',
],
'DJANGO_SETTINGS_MODULE' => [
'problematic_values' => [], // Check if contains 'production' or 'prod'
'affects' => 'Python/Django',
'issue' => 'Production settings may disable debug tools needed during build',
'recommendation' => 'Use development settings for build phase',
'check_function' => 'checkDjangoSettings',
],
'APP_ENV' => [
'problematic_values' => ['production', 'prod'],
'affects' => 'Laravel/Symfony',
'issue' => 'May affect dependency installation and build optimizations',
'recommendation' => 'Consider using "local" or "development" for build',
],
'ASPNETCORE_ENVIRONMENT' => [
'problematic_values' => ['Production'],
'affects' => '.NET/ASP.NET Core',
'issue' => 'May affect build-time configurations and optimizations',
'recommendation' => 'Usually safe, but verify build requirements',
],
'CI' => [
'problematic_values' => ['true', '1', 'yes'],
'affects' => 'Various tools',
'issue' => 'Changes behavior in many tools (disables interactivity, changes caching)',
'recommendation' => 'Usually beneficial for builds, but be aware of behavior changes',
],
];
}
/**
* Analyze an environment variable for potential build issues.
* Always returns a warning if the key is in our list, regardless of value.
*/
public static function analyzeBuildVariable(string $key, string $value): ?array
{
$problematicVars = self::getProblematicBuildVariables();
// Direct key match
if (isset($problematicVars[$key])) {
$config = $problematicVars[$key];
// Check if it has a custom check function
if (isset($config['check_function'])) {
$method = $config['check_function'];
if (method_exists(self::class, $method)) {
return self::{$method}($key, $value, $config);
}
}
// Always return warning for known problematic variables
return [
'variable' => $key,
'value' => $value,
'affects' => $config['affects'],
'issue' => $config['issue'],
'recommendation' => $config['recommendation'],
];
}
return null;
}
/**
* Analyze multiple environment variables for potential build issues.
*/
public static function analyzeBuildVariables(array $variables): array
{
$warnings = [];
foreach ($variables as $key => $value) {
$warning = self::analyzeBuildVariable($key, $value);
if ($warning) {
$warnings[] = $warning;
}
}
return $warnings;
}
/**
* Custom check for Django settings module.
*/
protected static function checkDjangoSettings(string $key, string $value, array $config): ?array
{
// Always return warning for DJANGO_SETTINGS_MODULE when it's set as build-time
return [
'variable' => $key,
'value' => $value,
'affects' => $config['affects'],
'issue' => $config['issue'],
'recommendation' => $config['recommendation'],
];
}
/**
* Generate a formatted warning message for deployment logs.
*/
public static function formatBuildWarning(array $warning): array
{
$messages = [
"β οΈ Build-time environment variable warning: {$warning['variable']}={$warning['value']}",
" Affects: {$warning['affects']}",
" Issue: {$warning['issue']}",
" Recommendation: {$warning['recommendation']}",
];
return $messages;
}
/**
* Check if a variable should show a warning in the UI.
*/
public static function shouldShowBuildWarning(string $key): bool
{
return isset(self::getProblematicBuildVariables()[$key]);
}
/**
* Get UI warning message for a specific variable.
*/
public static function getUIWarningMessage(string $key): ?string
{
$problematicVars = self::getProblematicBuildVariables();
if (! isset($problematicVars[$key])) {
return null;
}
$config = $problematicVars[$key];
$problematicValuesStr = implode(', ', $config['problematic_values']);
return "Setting {$key} to {$problematicValuesStr} as a build-time variable may cause issues. {$config['issue']} Consider: {$config['recommendation']}";
}
/**
* Get problematic variables configuration for frontend use.
*/
public static function getProblematicVariablesForFrontend(): array
{
$vars = self::getProblematicBuildVariables();
$result = [];
foreach ($vars as $key => $config) {
// Skip the check_function as it's PHP-specific
$result[$key] = [
'problematic_values' => $config['problematic_values'],
'affects' => $config['affects'],
'issue' => $config['issue'],
'recommendation' => $config['recommendation'],
];
}
return $result;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/DeletesUserSessions.php | app/Traits/DeletesUserSessions.php | <?php
namespace App\Traits;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
trait DeletesUserSessions
{
/**
* Delete all sessions for the current user.
* This will force the user to log in again on all devices.
*/
public function deleteAllSessions(): void
{
// Invalidate the current session
Session::invalidate();
Session::regenerateToken();
DB::table('sessions')->where('user_id', $this->id)->delete();
}
/**
* Boot the trait.
*/
protected static function bootDeletesUserSessions()
{
static::updated(function ($user) {
// Check if password was changed
if ($user->wasChanged('password')) {
$user->deleteAllSessions();
}
});
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/ClearsGlobalSearchCache.php | app/Traits/ClearsGlobalSearchCache.php | <?php
namespace App\Traits;
use App\Livewire\GlobalSearch;
use Illuminate\Database\Eloquent\Model;
trait ClearsGlobalSearchCache
{
protected static function bootClearsGlobalSearchCache()
{
static::saving(function ($model) {
try {
// Only clear cache if searchable fields are being changed
if ($model->hasSearchableChanges()) {
$teamId = $model->getTeamIdForCache();
if (filled($teamId)) {
GlobalSearch::clearTeamCache($teamId);
}
}
} catch (\Throwable $e) {
// Silently fail cache clearing - don't break the save operation
ray('Failed to clear global search cache on saving: '.$e->getMessage());
}
});
static::created(function ($model) {
try {
// Always clear cache when model is created
$teamId = $model->getTeamIdForCache();
if (filled($teamId)) {
GlobalSearch::clearTeamCache($teamId);
}
} catch (\Throwable $e) {
// Silently fail cache clearing - don't break the create operation
ray('Failed to clear global search cache on creation: '.$e->getMessage());
}
});
static::deleted(function ($model) {
try {
// Always clear cache when model is deleted
$teamId = $model->getTeamIdForCache();
if (filled($teamId)) {
GlobalSearch::clearTeamCache($teamId);
}
} catch (\Throwable $e) {
// Silently fail cache clearing - don't break the delete operation
ray('Failed to clear global search cache on deletion: '.$e->getMessage());
}
});
}
private function hasSearchableChanges(): bool
{
try {
// Define searchable fields based on model type
$searchableFields = ['name', 'description'];
// Add model-specific searchable fields
if ($this instanceof \App\Models\Application) {
$searchableFields[] = 'fqdn';
$searchableFields[] = 'docker_compose_domains';
} elseif ($this instanceof \App\Models\Server) {
$searchableFields[] = 'ip';
} elseif ($this instanceof \App\Models\Service) {
// Services don't have direct fqdn, but name and description are covered
} elseif ($this instanceof \App\Models\Project || $this instanceof \App\Models\Environment) {
// Projects and environments only have name and description as searchable
}
// Database models only have name and description as searchable
// Check if any searchable field is dirty
foreach ($searchableFields as $field) {
// Check if attribute exists before checking if dirty
if (array_key_exists($field, $this->getAttributes()) && $this->isDirty($field)) {
return true;
}
}
return false;
} catch (\Throwable $e) {
// If checking changes fails, assume changes exist to be safe
ray('Failed to check searchable changes: '.$e->getMessage());
return true;
}
}
private function getTeamIdForCache()
{
try {
// For Project models (has direct team_id)
if ($this instanceof \App\Models\Project) {
return $this->team_id ?? null;
}
// For Environment models (get team_id through project)
if ($this instanceof \App\Models\Environment) {
return $this->project?->team_id;
}
// For database models, team is accessed through environment.project.team
if (method_exists($this, 'team')) {
if ($this instanceof \App\Models\Server) {
$team = $this->team;
} else {
$team = $this->team();
}
if (filled($team)) {
return is_object($team) ? $team->id : null;
}
}
// For models with direct team_id property
if (property_exists($this, 'team_id') || isset($this->team_id)) {
return $this->team_id ?? null;
}
return null;
} catch (\Throwable $e) {
// If we can't determine team ID, return null
ray('Failed to get team ID for cache: '.$e->getMessage());
return null;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/HasConfiguration.php | app/Traits/HasConfiguration.php | <?php
namespace App\Traits;
use App\Services\ConfigurationGenerator;
trait HasConfiguration
{
public function generateConfigurationFiles(): void
{
$generator = new ConfigurationGenerator($this);
$configDir = base_configuration_dir()."/{$this->uuid}";
if (! is_dir($configDir)) {
mkdir($configDir, 0755, true);
}
$generator->saveJson($configDir.'/coolify.json');
$generator->saveYaml($configDir.'/coolify.yaml');
// Generate a README file with basic information
file_put_contents(
$configDir.'/README.md',
generate_readme_file($this->name, now()->toIso8601String())
);
}
public function getConfigurationAsJson(): string
{
return (new ConfigurationGenerator($this))->toJson();
}
public function getConfigurationAsYaml(): string
{
return (new ConfigurationGenerator($this))->toYaml();
}
public function getConfigurationAsArray(): array
{
return (new ConfigurationGenerator($this))->toArray();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/AuthorizesResourceCreation.php | app/Traits/AuthorizesResourceCreation.php | <?php
namespace App\Traits;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
trait AuthorizesResourceCreation
{
use AuthorizesRequests;
/**
* Authorize creation of all supported resources.
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function authorizeResourceCreation(): void
{
$this->authorize('createAnyResource');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/HasNotificationSettings.php | app/Traits/HasNotificationSettings.php | <?php
namespace App\Traits;
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 Illuminate\Database\Eloquent\Model;
trait HasNotificationSettings
{
protected $alwaysSendEvents = [
'server_force_enabled',
'server_force_disabled',
'general',
'test',
'ssl_certificate_renewal',
'hetzner_deletion_failure',
];
/**
* Get settings model for specific channel
*/
public function getNotificationSettings(string $channel): ?Model
{
return match ($channel) {
'email' => $this->emailNotificationSettings,
'discord' => $this->discordNotificationSettings,
'telegram' => $this->telegramNotificationSettings,
'slack' => $this->slackNotificationSettings,
'pushover' => $this->pushoverNotificationSettings,
'webhook' => $this->webhookNotificationSettings,
default => null,
};
}
/**
* Check if a notification channel is enabled
*/
public function isNotificationEnabled(string $channel): bool
{
$settings = $this->getNotificationSettings($channel);
return $settings?->isEnabled() ?? false;
}
/**
* Check if a specific notification type is enabled for a channel
*/
public function isNotificationTypeEnabled(string $channel, string $event): bool
{
$settings = $this->getNotificationSettings($channel);
if (! $settings || ! $this->isNotificationEnabled($channel)) {
return false;
}
if (in_array($event, $this->alwaysSendEvents)) {
return true;
}
$settingKey = "{$event}_{$channel}_notifications";
return (bool) $settings->$settingKey;
}
/**
* Get all enabled notification channels for an event
*/
public function getEnabledChannels(string $event): array
{
$channels = [];
$channelMap = [
'email' => EmailChannel::class,
'discord' => DiscordChannel::class,
'telegram' => TelegramChannel::class,
'slack' => SlackChannel::class,
'pushover' => PushoverChannel::class,
'webhook' => WebhookChannel::class,
];
if ($event === 'general') {
unset($channelMap['email']);
}
foreach ($channelMap as $channel => $channelClass) {
if ($this->isNotificationEnabled($channel) && $this->isNotificationTypeEnabled($channel, $event)) {
$channels[] = $channelClass;
}
}
return $channels;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/SshRetryable.php | app/Traits/SshRetryable.php | <?php
namespace App\Traits;
use Illuminate\Support\Facades\Log;
trait SshRetryable
{
/**
* Check if an error message indicates a retryable SSH connection error
*/
protected function isRetryableSshError(string $errorOutput): bool
{
$retryablePatterns = [
'kex_exchange_identification',
'Connection reset by peer',
'Connection refused',
'Connection timed out',
'Connection closed by remote host',
'ssh_exchange_identification',
'Bad file descriptor',
'Broken pipe',
'No route to host',
'Network is unreachable',
'Host is down',
'No buffer space available',
'Connection reset by',
'Permission denied, please try again',
'Received disconnect from',
'Disconnected from',
'Connection to .* closed',
'ssh: connect to host .* port .*: Connection',
'Lost connection',
'Timeout, server not responding',
'Cannot assign requested address',
'Network is down',
'Host key verification failed',
'Operation timed out',
'Connection closed unexpectedly',
'Remote host closed connection',
'Authentication failed',
'Too many authentication failures',
];
$lowerErrorOutput = strtolower($errorOutput);
foreach ($retryablePatterns as $pattern) {
if (str_contains($lowerErrorOutput, strtolower($pattern))) {
return true;
}
}
return false;
}
/**
* Calculate delay for exponential backoff
*/
protected function calculateRetryDelay(int $attempt): int
{
$baseDelay = config('constants.ssh.retry_base_delay');
$maxDelay = config('constants.ssh.retry_max_delay');
$multiplier = config('constants.ssh.retry_multiplier');
$delay = min($baseDelay * pow($multiplier, $attempt), $maxDelay);
return (int) $delay;
}
/**
* Execute a callback with SSH retry logic
*
* @param callable $callback The operation to execute
* @param array $context Context for logging (server, command, etc.)
* @param bool $throwError Whether to throw error on final failure
* @return mixed The result from the callback
*/
protected function executeWithSshRetry(callable $callback, array $context = [], bool $throwError = true)
{
$maxRetries = config('constants.ssh.max_retries');
$lastError = null;
$lastErrorMessage = '';
// Randomly fail the command with a key exchange error for testing
// if (random_int(1, 10) === 1) { // 10% chance to fail
// ray('SSH key exchange failed: kex_exchange_identification: read: Connection reset by peer');
// throw new \RuntimeException('SSH key exchange failed: kex_exchange_identification: read: Connection reset by peer');
// }
for ($attempt = 0; $attempt < $maxRetries; $attempt++) {
try {
return $callback();
} catch (\Throwable $e) {
$lastError = $e;
$lastErrorMessage = $e->getMessage();
// Check if it's retryable and not the last attempt
if ($this->isRetryableSshError($lastErrorMessage) && $attempt < $maxRetries - 1) {
$delay = $this->calculateRetryDelay($attempt);
// Track SSH retry event in Sentry
$this->trackSshRetryEvent($attempt + 1, $maxRetries, $delay, $lastErrorMessage, $context);
// Add deployment log if available (for ExecuteRemoteCommand trait)
if (isset($this->application_deployment_queue) && method_exists($this, 'addRetryLogEntry')) {
$this->addRetryLogEntry($attempt + 1, $maxRetries, $delay, $lastErrorMessage);
}
sleep($delay);
continue;
}
// Not retryable or max retries reached
break;
}
}
// All retries exhausted
if ($attempt >= $maxRetries) {
Log::error('SSH operation failed after all retries', array_merge($context, [
'attempts' => $attempt,
'error' => $lastErrorMessage,
]));
}
if ($throwError && $lastError) {
// If the error message is empty, provide a more meaningful one
if (empty($lastErrorMessage) || trim($lastErrorMessage) === '') {
$contextInfo = isset($context['server']) ? " to server {$context['server']}" : '';
$attemptInfo = $attempt > 1 ? " after {$attempt} attempts" : '';
throw new \RuntimeException("SSH connection failed{$contextInfo}{$attemptInfo}", $lastError->getCode());
}
throw $lastError;
}
return null;
}
/**
* Track SSH retry event in Sentry
*/
protected function trackSshRetryEvent(int $attempt, int $maxRetries, int $delay, string $errorMessage, array $context = []): void
{
// Only track in production/cloud instances
if (isDev() || ! config('constants.sentry.sentry_dsn')) {
return;
}
try {
app('sentry')->captureMessage(
'SSH connection retry triggered',
\Sentry\Severity::warning(),
[
'extra' => [
'attempt' => $attempt,
'max_retries' => $maxRetries,
'delay_seconds' => $delay,
'error_message' => $errorMessage,
'context' => $context,
'retryable_error' => true,
],
'tags' => [
'component' => 'ssh_retry',
'error_type' => 'connection_retry',
],
]
);
} catch (\Throwable $e) {
// Don't let Sentry tracking errors break the SSH retry flow
Log::warning('Failed to track SSH retry event in Sentry', [
'error' => $e->getMessage(),
'original_attempt' => $attempt,
]);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/HasSafeStringAttribute.php | app/Traits/HasSafeStringAttribute.php | <?php
namespace App\Traits;
trait HasSafeStringAttribute
{
/**
* Set the name attribute - strip any HTML tags for safety
*/
public function setNameAttribute($value)
{
$sanitized = strip_tags($value);
$this->attributes['name'] = $this->customizeName($sanitized);
}
protected function customizeName($value)
{
return $value; // Default: no customization
}
public function setDescriptionAttribute($value)
{
$this->attributes['description'] = strip_tags($value);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/CalculatesExcludedStatus.php | app/Traits/CalculatesExcludedStatus.php | <?php
namespace App\Traits;
use App\Services\ContainerStatusAggregator;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Symfony\Component\Yaml\Exception\ParseException;
trait CalculatesExcludedStatus
{
/**
* Calculate status for containers when all containers are excluded from health checks.
*
* This method processes excluded containers and returns a status with :excluded suffix
* to indicate that monitoring is disabled but still show the actual container state.
*
* @param Collection $containers Collection of container objects from Docker inspect
* @param Collection $excludedContainers Collection of container names that are excluded
* @return string Status string with :excluded suffix (e.g., 'running:unhealthy:excluded')
*/
protected function calculateExcludedStatus(Collection $containers, Collection $excludedContainers): string
{
// Filter to only excluded containers
$excludedOnly = $containers->filter(function ($container) use ($excludedContainers) {
$labels = data_get($container, 'Config.Labels', []);
$serviceName = data_get($labels, 'com.docker.compose.service');
return $serviceName && $excludedContainers->contains($serviceName);
});
// Use ContainerStatusAggregator service for state machine logic
$aggregator = new ContainerStatusAggregator;
$status = $aggregator->aggregateFromContainers($excludedOnly);
// Append :excluded suffix
return $this->appendExcludedSuffix($status);
}
/**
* Calculate status for containers when all containers are excluded (simplified version).
*
* This version works with status strings (e.g., "running:healthy") instead of full
* container objects, suitable for Sentinel updates that don't have full container data.
*
* @param Collection $containerStatuses Collection of status strings keyed by container name
* @return string Status string with :excluded suffix
*/
protected function calculateExcludedStatusFromStrings(Collection $containerStatuses): string
{
// Use ContainerStatusAggregator service for state machine logic
$aggregator = new ContainerStatusAggregator;
$status = $aggregator->aggregateFromStrings($containerStatuses);
// Append :excluded suffix
$finalStatus = $this->appendExcludedSuffix($status);
return $finalStatus;
}
/**
* Append :excluded suffix to a status string.
*
* Converts status formats like:
* - "running:healthy" β "running:healthy:excluded"
* - "degraded:unhealthy" β "degraded:excluded" (simplified)
* - "paused:unknown" β "paused:excluded" (simplified)
*
* @param string $status The base status string
* @return string Status with :excluded suffix
*/
private function appendExcludedSuffix(string $status): string
{
// For degraded states, simplify to just "degraded:excluded"
if (str($status)->startsWith('degraded')) {
return 'degraded:excluded';
}
// For paused/starting/exited states, simplify to just "state:excluded"
if (str($status)->startsWith('paused')) {
return 'paused:excluded';
}
if (str($status)->startsWith('starting')) {
return 'starting:excluded';
}
if (str($status)->startsWith('exited')) {
return 'exited';
}
// For running states, keep the health status: "running:healthy:excluded"
return "$status:excluded";
}
/**
* Get excluded containers from docker-compose YAML.
*
* Containers are excluded if:
* - They have exclude_from_hc: true label
* - They have restart: no policy
*
* @param string|null $dockerComposeRaw The raw docker-compose YAML content
* @return Collection Collection of excluded container names
*/
protected function getExcludedContainersFromDockerCompose(?string $dockerComposeRaw): Collection
{
$excludedContainers = collect();
if (! $dockerComposeRaw) {
return $excludedContainers;
}
try {
$dockerCompose = \Symfony\Component\Yaml\Yaml::parse($dockerComposeRaw);
// Validate structure
if (! is_array($dockerCompose)) {
Log::warning('Docker Compose YAML did not parse to array', [
'yaml_length' => strlen($dockerComposeRaw),
'parsed_type' => gettype($dockerCompose),
]);
return $excludedContainers;
}
$services = data_get($dockerCompose, 'services', []);
if (! is_array($services)) {
Log::warning('Docker Compose services is not an array', [
'services_type' => gettype($services),
]);
return $excludedContainers;
}
foreach ($services as $serviceName => $serviceConfig) {
$excludeFromHc = data_get($serviceConfig, 'exclude_from_hc', false);
$restartPolicy = data_get($serviceConfig, 'restart', 'always');
if ($excludeFromHc || $restartPolicy === 'no') {
$excludedContainers->push($serviceName);
}
}
} catch (ParseException $e) {
// Specific YAML parsing errors
Log::warning('Failed to parse Docker Compose YAML for health check exclusions', [
'error' => $e->getMessage(),
'line' => $e->getParsedLine(),
'snippet' => $e->getSnippet(),
]);
return $excludedContainers;
} catch (\Exception $e) {
// Unexpected errors
Log::error('Unexpected error parsing Docker Compose YAML', [
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
return $excludedContainers;
}
return $excludedContainers;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Traits/ExecuteRemoteCommand.php | app/Traits/ExecuteRemoteCommand.php | <?php
namespace App\Traits;
use App\Enums\ApplicationDeploymentStatus;
use App\Helpers\SshMultiplexingHelper;
use App\Models\Server;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Process;
trait ExecuteRemoteCommand
{
use SshRetryable;
public ?string $save = null;
public static int $batch_counter = 0;
private function redact_sensitive_info($text)
{
$text = remove_iip($text);
if (! isset($this->application)) {
return $text;
}
$lockedVars = collect([]);
if (isset($this->application->environment_variables)) {
$lockedVars = $lockedVars->merge(
$this->application->environment_variables
->where('is_shown_once', true)
->pluck('real_value', 'key')
->filter()
);
}
if (isset($this->pull_request_id) && $this->pull_request_id !== 0 && isset($this->application->environment_variables_preview)) {
$lockedVars = $lockedVars->merge(
$this->application->environment_variables_preview
->where('is_shown_once', true)
->pluck('real_value', 'key')
->filter()
);
}
foreach ($lockedVars as $key => $value) {
$escapedValue = preg_quote($value, '/');
$text = preg_replace(
'/'.$escapedValue.'/',
REDACTED,
$text
);
}
return $text;
}
public function execute_remote_command(...$commands)
{
static::$batch_counter++;
if ($commands instanceof Collection) {
$commandsText = $commands;
} else {
$commandsText = collect($commands);
}
if ($this->server instanceof Server === false) {
throw new \RuntimeException('Server is not set or is not an instance of Server model');
}
$commandsText->each(function ($single_command) {
$command = data_get($single_command, 'command') ?? $single_command[0] ?? null;
if ($command === null) {
throw new \RuntimeException('Command is not set');
}
$hidden = data_get($single_command, 'hidden', false);
$customType = data_get($single_command, 'type');
$ignore_errors = data_get($single_command, 'ignore_errors', false);
$append = data_get($single_command, 'append', true);
$this->save = data_get($single_command, 'save');
if ($this->server->isNonRoot()) {
if (str($command)->startsWith('docker exec')) {
$command = str($command)->replace('docker exec', 'sudo docker exec');
} else {
$command = parseLineForSudo($command, $this->server);
}
}
// Check for cancellation before executing commands
if (isset($this->application_deployment_queue)) {
$this->application_deployment_queue->refresh();
if ($this->application_deployment_queue->status === \App\Enums\ApplicationDeploymentStatus::CANCELLED_BY_USER->value) {
throw new \RuntimeException('Deployment cancelled by user', 69420);
}
}
$maxRetries = config('constants.ssh.max_retries');
$attempt = 0;
$lastError = null;
$commandExecuted = false;
while ($attempt < $maxRetries && ! $commandExecuted) {
try {
$this->executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors);
$commandExecuted = true;
} catch (\RuntimeException $e) {
$lastError = $e;
$errorMessage = $e->getMessage();
// Only retry if it's an SSH connection error and we haven't exhausted retries
if ($this->isRetryableSshError($errorMessage) && $attempt < $maxRetries - 1) {
$attempt++;
$delay = $this->calculateRetryDelay($attempt - 1);
// Track SSH retry event in Sentry
$this->trackSshRetryEvent($attempt, $maxRetries, $delay, $errorMessage, [
'server' => $this->server->name ?? $this->server->ip ?? 'unknown',
'command' => $this->redact_sensitive_info($command),
'trait' => 'ExecuteRemoteCommand',
]);
// Add log entry for the retry
if (isset($this->application_deployment_queue)) {
$this->addRetryLogEntry($attempt, $maxRetries, $delay, $errorMessage);
// Check for cancellation during retry wait
$this->application_deployment_queue->refresh();
if ($this->application_deployment_queue->status === \App\Enums\ApplicationDeploymentStatus::CANCELLED_BY_USER->value) {
throw new \RuntimeException('Deployment cancelled by user during retry', 69420);
}
}
sleep($delay);
} else {
// Not retryable or max retries reached
throw $e;
}
}
}
// If we exhausted all retries and still failed
if (! $commandExecuted && $lastError) {
// Now we can set the status to FAILED since all retries have been exhausted
// But only if the deployment hasn't already been marked as FINISHED
if (isset($this->application_deployment_queue)) {
// Avoid clobbering a deployment that may have just been marked FINISHED
$this->application_deployment_queue->newQuery()
->where('id', $this->application_deployment_queue->id)
->where('status', '!=', ApplicationDeploymentStatus::FINISHED->value)
->update([
'status' => ApplicationDeploymentStatus::FAILED->value,
]);
}
throw $lastError;
}
});
}
/**
* Execute the actual command with process handling
*/
private function executeCommandWithProcess($command, $hidden, $customType, $append, $ignore_errors)
{
$remote_command = SshMultiplexingHelper::generateSshCommand($this->server, $command);
$process = Process::timeout(config('constants.ssh.command_timeout'))->idleTimeout(3600)->start($remote_command, function (string $type, string $output) use ($command, $hidden, $customType, $append) {
$output = str($output)->trim();
if ($output->startsWith('β')) {
$output = "\n".$output;
}
// Sanitize output to ensure valid UTF-8 encoding before JSON encoding
$sanitized_output = sanitize_utf8_text($output);
$new_log_entry = [
'command' => $this->redact_sensitive_info($command),
'output' => $this->redact_sensitive_info($sanitized_output),
'type' => $customType ?? $type === 'err' ? 'stderr' : 'stdout',
'timestamp' => Carbon::now('UTC'),
'hidden' => $hidden,
'batch' => static::$batch_counter,
];
if (! $this->application_deployment_queue->logs) {
$new_log_entry['order'] = 1;
} else {
try {
$previous_logs = json_decode($this->application_deployment_queue->logs, associative: true, flags: JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
// If existing logs are corrupted, start fresh
$previous_logs = [];
$new_log_entry['order'] = 1;
}
if (is_array($previous_logs)) {
$new_log_entry['order'] = count($previous_logs) + 1;
} else {
$previous_logs = [];
$new_log_entry['order'] = 1;
}
}
$previous_logs[] = $new_log_entry;
try {
$this->application_deployment_queue->logs = json_encode($previous_logs, flags: JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
// If JSON encoding still fails, use fallback with invalid sequences replacement
$this->application_deployment_queue->logs = json_encode($previous_logs, flags: JSON_INVALID_UTF8_SUBSTITUTE);
}
$this->application_deployment_queue->save();
if ($this->save) {
if (data_get($this->saved_outputs, $this->save, null) === null) {
$this->saved_outputs->put($this->save, str());
}
if ($append) {
$current_value = $this->saved_outputs->get($this->save);
$this->saved_outputs->put($this->save, str($current_value.str($sanitized_output)->trim()));
} else {
$this->saved_outputs->put($this->save, str($sanitized_output)->trim());
}
}
});
$this->application_deployment_queue->update([
'current_process_id' => $process->id(),
]);
$process_result = $process->wait();
if ($process_result->exitCode() !== 0) {
if (! $ignore_errors) {
// Check if deployment was cancelled while command was running
if (isset($this->application_deployment_queue)) {
$this->application_deployment_queue->refresh();
if ($this->application_deployment_queue->status === \App\Enums\ApplicationDeploymentStatus::CANCELLED_BY_USER->value) {
throw new \RuntimeException('Deployment cancelled by user', 69420);
}
}
// Don't immediately set to FAILED - let the retry logic handle it
// This prevents premature status changes during retryable SSH errors
$error = $process_result->errorOutput();
if (empty($error)) {
$error = $process_result->output() ?: 'Command failed with no error output';
}
$redactedCommand = $this->redact_sensitive_info($command);
throw new \RuntimeException("Command execution failed (exit code {$process_result->exitCode()}): {$redactedCommand}\nError: {$error}");
}
}
}
/**
* Add a log entry for SSH retry attempts
*/
private function addRetryLogEntry(int $attempt, int $maxRetries, int $delay, string $errorMessage)
{
$retryMessage = "SSH connection failed. Retrying... (Attempt {$attempt}/{$maxRetries}, waiting {$delay}s)\nError: {$errorMessage}";
$new_log_entry = [
'output' => $this->redact_sensitive_info($retryMessage),
'type' => 'stdout',
'timestamp' => Carbon::now('UTC'),
'hidden' => false,
'batch' => static::$batch_counter,
];
if (! $this->application_deployment_queue->logs) {
$new_log_entry['order'] = 1;
$previous_logs = [];
} else {
try {
$previous_logs = json_decode($this->application_deployment_queue->logs, associative: true, flags: JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$previous_logs = [];
$new_log_entry['order'] = 1;
}
if (is_array($previous_logs)) {
$new_log_entry['order'] = count($previous_logs) + 1;
} else {
$previous_logs = [];
$new_log_entry['order'] = 1;
}
}
$previous_logs[] = $new_log_entry;
try {
$this->application_deployment_queue->logs = json_encode($previous_logs, flags: JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
$this->application_deployment_queue->logs = json_encode($previous_logs, flags: JSON_INVALID_UTF8_SUBSTITUTE);
}
$this->application_deployment_queue->save();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Listeners/ProxyStatusChangedNotification.php | app/Listeners/ProxyStatusChangedNotification.php | <?php
namespace App\Listeners;
use App\Enums\ProxyTypes;
use App\Events\ProxyStatusChanged;
use App\Events\ProxyStatusChangedUI;
use App\Jobs\CheckTraefikVersionForServerJob;
use App\Models\Server;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Support\Facades\Log;
class ProxyStatusChangedNotification implements ShouldQueueAfterCommit
{
public function __construct() {}
public function handle(ProxyStatusChanged $event)
{
$serverId = $event->data;
if (is_null($serverId)) {
return;
}
$server = Server::where('id', $serverId)->first();
if (is_null($server)) {
return;
}
$proxyContainerName = 'coolify-proxy';
$status = getContainerStatus($server, $proxyContainerName);
$server->proxy->set('status', $status);
$server->save();
$versionCheckDispatched = false;
if ($status === 'running') {
$server->setupDefaultRedirect();
$server->setupDynamicProxyConfiguration();
$server->proxy->force_stop = false;
$server->save();
// Check Traefik version after proxy is running
if ($server->proxyType() === ProxyTypes::TRAEFIK->value) {
$traefikVersions = get_traefik_versions();
if ($traefikVersions !== null) {
// Version check job will dispatch ProxyStatusChangedUI when complete
CheckTraefikVersionForServerJob::dispatch($server, $traefikVersions);
$versionCheckDispatched = true;
} else {
Log::warning('Traefik version check skipped after proxy status change: versions.json data unavailable', [
'server_id' => $server->id,
'server_name' => $server->name,
]);
}
}
}
// Only dispatch UI refresh if version check wasn't dispatched
// (version check job handles its own UI refresh with updated version data)
if (! $versionCheckDispatched) {
ProxyStatusChangedUI::dispatch($server->team_id);
}
if ($status === 'created') {
instant_remote_process([
'docker rm -f coolify-proxy',
], $server);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Listeners/CloudflareTunnelChangedNotification.php | app/Listeners/CloudflareTunnelChangedNotification.php | <?php
namespace App\Listeners;
use App\Events\CloudflareTunnelChanged;
use App\Events\CloudflareTunnelConfigured;
use App\Models\Server;
use Illuminate\Support\Sleep;
class CloudflareTunnelChangedNotification
{
public Server $server;
public function __construct() {}
public function handle(CloudflareTunnelChanged $event): void
{
$server_id = data_get($event, 'data.server_id');
$ssh_domain = data_get($event, 'data.ssh_domain');
$this->server = Server::where('id', $server_id)->firstOrFail();
// Check if cloudflare tunnel is running (container is healthy) - try 3 times with 5 second intervals
$cloudflareHealthy = false;
$attempts = 3;
for ($i = 1; $i <= $attempts; $i++) {
\Log::debug("Cloudflare health check attempt {$i}/{$attempts}", ['server_id' => $server_id]);
$result = instant_remote_process_with_timeout(['docker inspect coolify-cloudflared | jq -e ".[0].State.Health.Status == \"healthy\""'], $this->server, false, 10);
if (blank($result)) {
\Log::debug("Cloudflare Tunnels container not found on attempt {$i}", ['server_id' => $server_id]);
} elseif ($result === 'true') {
\Log::debug("Cloudflare Tunnels container healthy on attempt {$i}", ['server_id' => $server_id]);
$cloudflareHealthy = true;
break;
} else {
\Log::debug("Cloudflare Tunnels container not healthy on attempt {$i}", ['server_id' => $server_id, 'result' => $result]);
}
// Sleep between attempts (except after the last attempt)
if ($i < $attempts) {
Sleep::for(5)->seconds();
}
}
if (! $cloudflareHealthy) {
\Log::error('Cloudflare Tunnels container failed all health checks.', ['server_id' => $server_id, 'attempts' => $attempts]);
return;
}
$this->server->settings->update([
'is_cloudflare_tunnel' => true,
]);
// Only update IP if it's not already set to the ssh_domain or if it's empty
if ($this->server->ip !== $ssh_domain && ! empty($ssh_domain)) {
\Log::debug('Cloudflare Tunnels configuration updated - updating IP address.', ['old_ip' => $this->server->ip, 'new_ip' => $ssh_domain]);
$this->server->update(['ip' => $ssh_domain]);
} else {
\Log::debug('Cloudflare Tunnels configuration updated - IP address unchanged.', ['current_ip' => $this->server->ip]);
}
$teamId = $this->server->team_id;
CloudflareTunnelConfigured::dispatch($teamId);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Support/ValidationPatterns.php | app/Support/ValidationPatterns.php | <?php
namespace App\Support;
/**
* Shared validation patterns for consistent use across the application
*/
class ValidationPatterns
{
/**
* Pattern for names (allows letters, numbers, spaces, dashes, underscores, dots, slashes, colons, parentheses)
* Matches CleanupNames::sanitizeName() allowed characters
*/
public const NAME_PATTERN = '/^[a-zA-Z0-9\s\-_.:\/()]+$/';
/**
* Pattern for descriptions (allows more characters including quotes, commas, etc.)
* More permissive than names but still restricts dangerous characters
*/
public const DESCRIPTION_PATTERN = '/^[a-zA-Z0-9\s\-_.:\/()\'\",.!?@#%&+=\[\]{}|~`*]+$/';
/**
* Get validation rules for name fields
*/
public static function nameRules(bool $required = true, int $minLength = 3, int $maxLength = 255): array
{
$rules = [];
if ($required) {
$rules[] = 'required';
} else {
$rules[] = 'nullable';
}
$rules[] = 'string';
$rules[] = "min:$minLength";
$rules[] = "max:$maxLength";
$rules[] = 'regex:'.self::NAME_PATTERN;
return $rules;
}
/**
* Get validation rules for description fields
*/
public static function descriptionRules(bool $required = false, int $maxLength = 255): array
{
$rules = [];
if ($required) {
$rules[] = 'required';
} else {
$rules[] = 'nullable';
}
$rules[] = 'string';
$rules[] = "max:$maxLength";
$rules[] = 'regex:'.self::DESCRIPTION_PATTERN;
return $rules;
}
/**
* Get validation messages for name fields
*/
public static function nameMessages(): array
{
return [
'name.regex' => 'The name may only contain letters, numbers, spaces, dashes (-), underscores (_), dots (.), slashes (/), colons (:), and parentheses ().',
'name.min' => 'The name must be at least :min characters.',
'name.max' => 'The name may not be greater than :max characters.',
];
}
/**
* Get validation messages for description fields
*/
public static function descriptionMessages(): array
{
return [
'description.regex' => 'The description contains invalid characters. Only letters, numbers, spaces, and common punctuation (- _ . : / () \' " , ! ? @ # % & + = [] {} | ~ ` *) are allowed.',
'description.max' => 'The description may not be greater than :max characters.',
];
}
/**
* Get combined validation messages for both name and description fields
*/
public static function combinedMessages(): array
{
return array_merge(self::nameMessages(), self::descriptionMessages());
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Application/StopApplicationOneServer.php | app/Actions/Application/StopApplicationOneServer.php | <?php
namespace App\Actions\Application;
use App\Models\Application;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class StopApplicationOneServer
{
use AsAction;
public function handle(Application $application, Server $server)
{
if ($application->destination->server->isSwarm()) {
return;
}
if (! $server->isFunctional()) {
return 'Server is not functional';
}
try {
$containers = getCurrentApplicationContainerStatus($server, $application->id, 0);
if ($containers->count() > 0) {
foreach ($containers as $container) {
$containerName = data_get($container, 'Names');
if ($containerName) {
instant_remote_process(
[
"docker stop -t 30 $containerName",
"docker rm -f $containerName",
],
$server
);
}
}
}
} catch (\Exception $e) {
return $e->getMessage();
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Application/GenerateConfig.php | app/Actions/Application/GenerateConfig.php | <?php
namespace App\Actions\Application;
use App\Models\Application;
use Lorisleiva\Actions\Concerns\AsAction;
class GenerateConfig
{
use AsAction;
public function handle(Application $application, bool $is_json = false)
{
return $application->generateConfig(is_json: $is_json);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Application/IsHorizonQueueEmpty.php | app/Actions/Application/IsHorizonQueueEmpty.php | <?php
namespace App\Actions\Application;
use Laravel\Horizon\Contracts\JobRepository;
use Lorisleiva\Actions\Concerns\AsAction;
class IsHorizonQueueEmpty
{
use AsAction;
public function handle()
{
$hostname = gethostname();
$recent = app(JobRepository::class)->getRecent();
if ($recent) {
$running = $recent->filter(function ($job) use ($hostname) {
$payload = json_decode($job->payload);
$tags = data_get($payload, 'tags');
return $job->status != 'completed' &&
$job->status != 'failed' &&
isset($tags) &&
is_array($tags) &&
in_array('server:'.$hostname, $tags);
});
if ($running->count() > 0) {
echo 'false';
return false;
}
}
echo 'true';
return true;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Application/StopApplication.php | app/Actions/Application/StopApplication.php | <?php
namespace App\Actions\Application;
use App\Actions\Server\CleanupDocker;
use App\Events\ServiceStatusChanged;
use App\Models\Application;
use Lorisleiva\Actions\Concerns\AsAction;
class StopApplication
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Application $application, bool $previewDeployments = false, bool $dockerCleanup = true)
{
$servers = collect([$application->destination->server]);
if ($application?->additional_servers?->count() > 0) {
$servers = $servers->merge($application->additional_servers);
}
foreach ($servers as $server) {
try {
if (! $server->isFunctional()) {
return 'Server is not functional';
}
if ($server->isSwarm()) {
instant_remote_process(["docker stack rm {$application->uuid}"], $server);
return;
}
$containers = $previewDeployments
? getCurrentApplicationContainerStatus($server, $application->id, includePullrequests: true)
: getCurrentApplicationContainerStatus($server, $application->id, 0);
$containersToStop = $containers->pluck('Names')->toArray();
foreach ($containersToStop as $containerName) {
instant_remote_process(command: [
"docker stop -t 30 $containerName",
"docker rm -f $containerName",
], server: $server, throwError: false);
}
if ($application->build_pack === 'dockercompose') {
$application->deleteConnectedNetworks();
}
if ($dockerCleanup) {
CleanupDocker::dispatch($server, false, false);
}
} catch (\Exception $e) {
return $e->getMessage();
}
}
// Reset restart tracking when application is manually stopped
$application->update([
'restart_count' => 0,
'last_restart_at' => null,
'last_restart_type' => null,
]);
ServiceStatusChanged::dispatch($application->environment->project->team->id);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Application/LoadComposeFile.php | app/Actions/Application/LoadComposeFile.php | <?php
namespace App\Actions\Application;
use App\Models\Application;
use Lorisleiva\Actions\Concerns\AsAction;
class LoadComposeFile
{
use AsAction;
public function handle(Application $application)
{
$application->loadComposeFile();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Application/CleanupPreviewDeployment.php | app/Actions/Application/CleanupPreviewDeployment.php | <?php
namespace App\Actions\Application;
use App\Enums\ApplicationDeploymentStatus;
use App\Jobs\DeleteResourceJob;
use App\Models\Application;
use App\Models\ApplicationDeploymentQueue;
use App\Models\ApplicationPreview;
use Lorisleiva\Actions\Concerns\AsAction;
class CleanupPreviewDeployment
{
use AsAction;
public string $jobQueue = 'high';
/**
* Clean up a PR preview deployment completely.
*
* This handles:
* 1. Cancelling active deployments for the PR (QUEUED/IN_PROGRESS β CANCELLED_BY_USER)
* 2. Killing helper containers by deployment_uuid
* 3. Stopping/removing all running PR containers
* 4. Dispatching DeleteResourceJob for thorough cleanup (volumes, networks, database records)
*
* This unifies the cleanup logic from GitHub webhook handler to be used across all providers.
*/
public function handle(
Application $application,
int $pull_request_id,
?ApplicationPreview $preview = null
): array {
$result = [
'cancelled_deployments' => 0,
'killed_containers' => 0,
'status' => 'success',
];
$server = $application->destination->server;
if (! $server->isFunctional()) {
return [
...$result,
'status' => 'failed',
'message' => 'Server is not functional',
];
}
// Step 1: Cancel all active deployments for this PR and kill helper containers
$result['cancelled_deployments'] = $this->cancelActiveDeployments(
$application,
$pull_request_id,
$server
);
// Step 2: Stop and remove all running PR containers
$result['killed_containers'] = $this->stopRunningContainers(
$application,
$pull_request_id,
$server
);
// Step 3: Find or use provided preview, then dispatch cleanup job for thorough cleanup
if (! $preview) {
$preview = ApplicationPreview::where('application_id', $application->id)
->where('pull_request_id', $pull_request_id)
->first();
}
if ($preview) {
DeleteResourceJob::dispatch($preview);
}
return $result;
}
/**
* Cancel all active (QUEUED/IN_PROGRESS) deployments for this PR.
*/
private function cancelActiveDeployments(
Application $application,
int $pull_request_id,
$server
): int {
$activeDeployments = ApplicationDeploymentQueue::where('application_id', $application->id)
->where('pull_request_id', $pull_request_id)
->whereIn('status', [
ApplicationDeploymentStatus::QUEUED->value,
ApplicationDeploymentStatus::IN_PROGRESS->value,
])
->get();
$cancelled = 0;
foreach ($activeDeployments as $deployment) {
try {
// Mark deployment as cancelled
$deployment->update([
'status' => ApplicationDeploymentStatus::CANCELLED_BY_USER->value,
]);
// Add cancellation log entry
$deployment->addLogEntry('Deployment cancelled: Pull request closed.', 'stderr');
// Try to kill helper container if it exists
$this->killHelperContainer($deployment->deployment_uuid, $server);
$cancelled++;
} catch (\Throwable $e) {
\Log::warning("Failed to cancel deployment {$deployment->id}: {$e->getMessage()}");
}
}
return $cancelled;
}
/**
* Kill the helper container used during deployment.
*/
private function killHelperContainer(string $deployment_uuid, $server): void
{
try {
$escapedUuid = escapeshellarg($deployment_uuid);
$checkCommand = "docker ps -a --filter name={$escapedUuid} --format '{{.Names}}'";
$containerExists = instant_remote_process([$checkCommand], $server);
if ($containerExists && str($containerExists)->trim()->isNotEmpty()) {
instant_remote_process(["docker rm -f {$escapedUuid}"], $server);
}
} catch (\Throwable $e) {
// Silently handle - container may already be gone
}
}
/**
* Stop and remove all running containers for this PR.
*/
private function stopRunningContainers(
Application $application,
int $pull_request_id,
$server
): int {
$killed = 0;
try {
if ($server->isSwarm()) {
$escapedStackName = escapeshellarg("{$application->uuid}-{$pull_request_id}");
instant_remote_process(["docker stack rm {$escapedStackName}"], $server);
$killed++;
} else {
$containers = getCurrentApplicationContainerStatus(
$server,
$application->id,
$pull_request_id
);
if ($containers->isNotEmpty()) {
foreach ($containers as $container) {
$containerName = data_get($container, 'Names');
if ($containerName) {
$escapedContainerName = escapeshellarg($containerName);
instant_remote_process(
["docker rm -f {$escapedContainerName}"],
$server
);
$killed++;
}
}
}
}
} catch (\Throwable $e) {
\Log::warning("Error stopping containers for PR #{$pull_request_id}: {$e->getMessage()}");
}
return $killed;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Docker/GetContainersStatus.php | app/Actions/Docker/GetContainersStatus.php | <?php
namespace App\Actions\Docker;
use App\Actions\Database\StartDatabaseProxy;
use App\Actions\Shared\ComplexStatusCheck;
use App\Events\ServiceChecked;
use App\Models\ApplicationPreview;
use App\Models\Server;
use App\Models\ServiceDatabase;
use App\Services\ContainerStatusAggregator;
use App\Traits\CalculatesExcludedStatus;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Lorisleiva\Actions\Concerns\AsAction;
class GetContainersStatus
{
use AsAction;
use CalculatesExcludedStatus;
public string $jobQueue = 'high';
public $applications;
public ?Collection $containers;
public ?Collection $containerReplicates;
public $server;
protected ?Collection $applicationContainerStatuses;
protected ?Collection $applicationContainerRestartCounts;
protected ?Collection $serviceContainerStatuses;
public function handle(Server $server, ?Collection $containers = null, ?Collection $containerReplicates = null)
{
$this->containers = $containers;
$this->containerReplicates = $containerReplicates;
$this->server = $server;
if (! $this->server->isFunctional()) {
return 'Server is not functional.';
}
$this->applications = $this->server->applications();
$skip_these_applications = collect([]);
foreach ($this->applications as $application) {
if ($application->additional_servers->count() > 0) {
$skip_these_applications->push($application);
ComplexStatusCheck::run($application);
$this->applications = $this->applications->filter(function ($value, $key) use ($application) {
return $value->id !== $application->id;
});
}
}
$this->applications = $this->applications->filter(function ($value, $key) use ($skip_these_applications) {
return ! $skip_these_applications->pluck('id')->contains($value->id);
});
if ($this->containers === null) {
['containers' => $this->containers, 'containerReplicates' => $this->containerReplicates] = $this->server->getContainers();
}
if (is_null($this->containers)) {
return;
}
if ($this->containerReplicates) {
foreach ($this->containerReplicates as $containerReplica) {
$name = data_get($containerReplica, 'Name');
$this->containers = $this->containers->map(function ($container) use ($name, $containerReplica) {
if (data_get($container, 'Spec.Name') === $name) {
$replicas = data_get($containerReplica, 'Replicas');
$running = str($replicas)->explode('/')[0];
$total = str($replicas)->explode('/')[1];
if ($running === $total) {
data_set($container, 'State.Status', 'running');
data_set($container, 'State.Health.Status', 'healthy');
} else {
data_set($container, 'State.Status', 'starting');
data_set($container, 'State.Health.Status', 'unhealthy');
}
}
return $container;
});
}
}
$databases = $this->server->databases();
$services = $this->server->services()->get();
$previews = $this->server->previews();
$foundApplications = [];
$foundApplicationPreviews = [];
$foundDatabases = [];
$foundServices = [];
foreach ($this->containers as $container) {
if ($this->server->isSwarm()) {
$labels = data_get($container, 'Spec.Labels');
$uuid = data_get($labels, 'coolify.name');
} else {
$labels = data_get($container, 'Config.Labels');
}
$containerStatus = data_get($container, 'State.Status');
$containerHealth = data_get($container, 'State.Health.Status');
if ($containerStatus === 'restarting') {
$healthSuffix = $containerHealth ?? 'unknown';
$containerStatus = "restarting:$healthSuffix";
} elseif ($containerStatus === 'exited') {
// Keep as-is, no health suffix for exited containers
} else {
$healthSuffix = $containerHealth ?? 'unknown';
$containerStatus = "$containerStatus:$healthSuffix";
}
$labels = Arr::undot(format_docker_labels_to_json($labels));
$applicationId = data_get($labels, 'coolify.applicationId');
if ($applicationId) {
$pullRequestId = data_get($labels, 'coolify.pullRequestId');
if ($pullRequestId) {
if (str($applicationId)->contains('-')) {
$applicationId = str($applicationId)->before('-');
}
$preview = ApplicationPreview::where('application_id', $applicationId)->where('pull_request_id', $pullRequestId)->first();
if ($preview) {
$foundApplicationPreviews[] = $preview->id;
$statusFromDb = $preview->status;
if ($statusFromDb !== $containerStatus) {
$preview->update(['status' => $containerStatus]);
} else {
$preview->update(['last_online_at' => now()]);
}
} else {
// Notify user that this container should not be there.
}
} else {
$application = $this->applications->where('id', $applicationId)->first();
if ($application) {
$foundApplications[] = $application->id;
// Store container status for aggregation
if (! isset($this->applicationContainerStatuses)) {
$this->applicationContainerStatuses = collect();
}
if (! $this->applicationContainerStatuses->has($applicationId)) {
$this->applicationContainerStatuses->put($applicationId, collect());
}
$containerName = data_get($labels, 'com.docker.compose.service');
if ($containerName) {
$this->applicationContainerStatuses->get($applicationId)->put($containerName, $containerStatus);
}
// Track restart counts for applications
$restartCount = data_get($container, 'RestartCount', 0);
if (! isset($this->applicationContainerRestartCounts)) {
$this->applicationContainerRestartCounts = collect();
}
if (! $this->applicationContainerRestartCounts->has($applicationId)) {
$this->applicationContainerRestartCounts->put($applicationId, collect());
}
if ($containerName) {
$this->applicationContainerRestartCounts->get($applicationId)->put($containerName, $restartCount);
}
} else {
// Notify user that this container should not be there.
}
}
} else {
$uuid = data_get($labels, 'com.docker.compose.service');
$type = data_get($labels, 'coolify.type');
if ($uuid) {
if ($type === 'service') {
$database_id = data_get($labels, 'coolify.service.subId');
if ($database_id) {
$service_db = ServiceDatabase::where('id', $database_id)->first();
if ($service_db) {
$uuid = data_get($service_db, 'service.uuid');
if ($uuid) {
$isPublic = data_get($service_db, 'is_public');
if ($isPublic) {
$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
} else {
return data_get($value, 'Name') === "/$uuid-proxy";
}
})->first();
if (! $foundTcpProxy) {
StartDatabaseProxy::run($service_db);
// $this->server->team?->notify(new ContainerRestarted("TCP Proxy for {$service_db->service->name}", $this->server));
}
}
}
}
}
} else {
$database = $databases->where('uuid', $uuid)->first();
if ($database) {
$isPublic = data_get($database, 'is_public');
$foundDatabases[] = $database->id;
$statusFromDb = $database->status;
// Track restart count for databases (single-container)
$restartCount = data_get($container, 'RestartCount', 0);
$previousRestartCount = $database->restart_count ?? 0;
if ($statusFromDb !== $containerStatus) {
$updateData = ['status' => $containerStatus];
} else {
$updateData = ['last_online_at' => now()];
}
// Update restart tracking if restart count increased
if ($restartCount > $previousRestartCount) {
$updateData['restart_count'] = $restartCount;
$updateData['last_restart_at'] = now();
$updateData['last_restart_type'] = 'crash';
}
$database->update($updateData);
if ($isPublic) {
$foundTcpProxy = $this->containers->filter(function ($value, $key) use ($uuid) {
if ($this->server->isSwarm()) {
return data_get($value, 'Spec.Name') === "coolify-proxy_$uuid";
} else {
return data_get($value, 'Name') === "/$uuid-proxy";
}
})->first();
if (! $foundTcpProxy) {
StartDatabaseProxy::run($database);
// $this->server->team?->notify(new ContainerRestarted("TCP Proxy for database", $this->server));
}
}
} else {
// Notify user that this container should not be there.
}
}
}
if (data_get($container, 'Name') === '/coolify-db') {
$foundDatabases[] = 0;
}
}
$serviceLabelId = data_get($labels, 'coolify.serviceId');
if ($serviceLabelId) {
$subType = data_get($labels, 'coolify.service.subType');
$subId = data_get($labels, 'coolify.service.subId');
$parentService = $services->where('id', $serviceLabelId)->first();
if (! $parentService) {
continue;
}
// Store container status for aggregation
if (! isset($this->serviceContainerStatuses)) {
$this->serviceContainerStatuses = collect();
}
$key = $serviceLabelId.':'.$subType.':'.$subId;
if (! $this->serviceContainerStatuses->has($key)) {
$this->serviceContainerStatuses->put($key, collect());
}
$containerName = data_get($labels, 'com.docker.compose.service');
if ($containerName) {
$this->serviceContainerStatuses->get($key)->put($containerName, $containerStatus);
}
// Mark service as found
if ($subType === 'application') {
$service = $parentService->applications()->where('id', $subId)->first();
} else {
$service = $parentService->databases()->where('id', $subId)->first();
}
if ($service) {
$foundServices[] = "$service->id-$service->name";
}
}
}
$exitedServices = collect([]);
foreach ($services as $service) {
$apps = $service->applications()->get();
$dbs = $service->databases()->get();
foreach ($apps as $app) {
if (in_array("$app->id-$app->name", $foundServices)) {
continue;
} else {
$exitedServices->push($app);
}
}
foreach ($dbs as $db) {
if (in_array("$db->id-$db->name", $foundServices)) {
continue;
} else {
$exitedServices->push($db);
}
}
}
$exitedServices = $exitedServices->unique('uuid');
foreach ($exitedServices as $exitedService) {
if (str($exitedService->status)->startsWith('exited')) {
continue;
}
$name = data_get($exitedService, 'name');
$fqdn = data_get($exitedService, 'fqdn');
if ($name) {
if ($fqdn) {
$containerName = "$name, available at $fqdn";
} else {
$containerName = $name;
}
} else {
if ($fqdn) {
$containerName = $fqdn;
} else {
$containerName = null;
}
}
$projectUuid = data_get($service, 'environment.project.uuid');
$serviceUuid = data_get($service, 'uuid');
$environmentName = data_get($service, 'environment.name');
if ($projectUuid && $serviceUuid && $environmentName) {
$url = base_url().'/project/'.$projectUuid.'/'.$environmentName.'/service/'.$serviceUuid;
} else {
$url = null;
}
// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
$exitedService->update(['status' => 'exited']);
}
$notRunningApplications = $this->applications->pluck('id')->diff($foundApplications);
foreach ($notRunningApplications as $applicationId) {
$application = $this->applications->where('id', $applicationId)->first();
if (str($application->status)->startsWith('exited')) {
continue;
}
// Only protection: If no containers at all, Docker query might have failed
if ($this->containers->isEmpty()) {
continue;
}
// If container was recently restarting (crash loop), keep it as degraded for a grace period
// This prevents false "exited" status during the brief moment between container removal and recreation
$recentlyRestarted = $application->restart_count > 0 &&
$application->last_restart_at &&
$application->last_restart_at->greaterThan(now()->subSeconds(30));
if ($recentlyRestarted) {
// Keep it as degraded if it was recently in a crash loop
$application->update(['status' => 'degraded:unhealthy']);
} else {
// Reset restart count when application exits completely
$application->update([
'status' => 'exited',
'restart_count' => 0,
'last_restart_at' => null,
'last_restart_type' => null,
]);
}
}
$notRunningApplicationPreviews = $previews->pluck('id')->diff($foundApplicationPreviews);
foreach ($notRunningApplicationPreviews as $previewId) {
$preview = $previews->where('id', $previewId)->first();
if (str($preview->status)->startsWith('exited')) {
continue;
}
// Only protection: If no containers at all, Docker query might have failed
if ($this->containers->isEmpty()) {
continue;
}
$preview->update(['status' => 'exited']);
}
$notRunningDatabases = $databases->pluck('id')->diff($foundDatabases);
foreach ($notRunningDatabases as $database) {
$database = $databases->where('id', $database)->first();
if (str($database->status)->startsWith('exited')) {
continue;
}
// Reset restart tracking when database exits completely
$database->update([
'status' => 'exited',
'restart_count' => 0,
'last_restart_at' => null,
'last_restart_type' => null,
]);
$name = data_get($database, 'name');
$fqdn = data_get($database, 'fqdn');
$containerName = $name;
$projectUuid = data_get($database, 'environment.project.uuid');
$environmentName = data_get($database, 'environment.name');
$databaseUuid = data_get($database, 'uuid');
if ($projectUuid && $databaseUuid && $environmentName) {
$url = base_url().'/project/'.$projectUuid.'/'.$environmentName.'/database/'.$databaseUuid;
} else {
$url = null;
}
// $this->server->team?->notify(new ContainerStopped($containerName, $this->server, $url));
}
// Aggregate multi-container application statuses
if (isset($this->applicationContainerStatuses) && $this->applicationContainerStatuses->isNotEmpty()) {
foreach ($this->applicationContainerStatuses as $applicationId => $containerStatuses) {
$application = $this->applications->where('id', $applicationId)->first();
if (! $application) {
continue;
}
// Track restart counts first
$maxRestartCount = 0;
if (isset($this->applicationContainerRestartCounts) && $this->applicationContainerRestartCounts->has($applicationId)) {
$containerRestartCounts = $this->applicationContainerRestartCounts->get($applicationId);
$maxRestartCount = $containerRestartCounts->max() ?? 0;
}
// Wrap all database updates in a transaction to ensure consistency
DB::transaction(function () use ($application, $maxRestartCount, $containerStatuses) {
$previousRestartCount = $application->restart_count ?? 0;
if ($maxRestartCount > $previousRestartCount) {
// Restart count increased - this is a crash restart
$application->update([
'restart_count' => $maxRestartCount,
'last_restart_at' => now(),
'last_restart_type' => 'crash',
]);
// Send notification
$containerName = $application->name;
$projectUuid = data_get($application, 'environment.project.uuid');
$environmentName = data_get($application, 'environment.name');
$applicationUuid = data_get($application, 'uuid');
if ($projectUuid && $applicationUuid && $environmentName) {
$url = base_url().'/project/'.$projectUuid.'/'.$environmentName.'/application/'.$applicationUuid;
} else {
$url = null;
}
}
// Aggregate status after tracking restart counts
$aggregatedStatus = $this->aggregateApplicationStatus($application, $containerStatuses, $maxRestartCount);
if ($aggregatedStatus) {
$statusFromDb = $application->status;
if ($statusFromDb !== $aggregatedStatus) {
$application->update(['status' => $aggregatedStatus]);
} else {
$application->update(['last_online_at' => now()]);
}
}
});
}
}
// Aggregate multi-container service statuses
$this->aggregateServiceContainerStatuses($services);
ServiceChecked::dispatch($this->server->team->id);
}
private function aggregateApplicationStatus($application, Collection $containerStatuses, int $maxRestartCount = 0): ?string
{
// Parse docker compose to check for excluded containers
$dockerComposeRaw = data_get($application, 'docker_compose_raw');
$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);
// Filter out excluded containers
$relevantStatuses = $containerStatuses->filter(function ($status, $containerName) use ($excludedContainers) {
return ! $excludedContainers->contains($containerName);
});
// If all containers are excluded, calculate status from excluded containers
if ($relevantStatuses->isEmpty()) {
return $this->calculateExcludedStatusFromStrings($containerStatuses);
}
// Use ContainerStatusAggregator service for state machine logic
// Use preserveRestarting: true so applications show "Restarting" instead of "Degraded"
$aggregator = new ContainerStatusAggregator;
return $aggregator->aggregateFromStrings($relevantStatuses, $maxRestartCount, preserveRestarting: true);
}
private function aggregateServiceContainerStatuses($services)
{
if (! isset($this->serviceContainerStatuses) || $this->serviceContainerStatuses->isEmpty()) {
return;
}
foreach ($this->serviceContainerStatuses as $key => $containerStatuses) {
// Parse key: serviceId:subType:subId
[$serviceId, $subType, $subId] = explode(':', $key);
$service = $services->where('id', $serviceId)->first();
if (! $service) {
continue;
}
// Get the service sub-resource (ServiceApplication or ServiceDatabase)
$subResource = null;
if ($subType === 'application') {
$subResource = $service->applications()->where('id', $subId)->first();
} elseif ($subType === 'database') {
$subResource = $service->databases()->where('id', $subId)->first();
}
if (! $subResource) {
continue;
}
// Parse docker compose from service to check for excluded containers
$dockerComposeRaw = data_get($service, 'docker_compose_raw');
$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);
// Filter out excluded containers
$relevantStatuses = $containerStatuses->filter(function ($status, $containerName) use ($excludedContainers) {
return ! $excludedContainers->contains($containerName);
});
// If all containers are excluded, calculate status from excluded containers
if ($relevantStatuses->isEmpty()) {
$aggregatedStatus = $this->calculateExcludedStatusFromStrings($containerStatuses);
if ($aggregatedStatus) {
$statusFromDb = $subResource->status;
if ($statusFromDb !== $aggregatedStatus) {
$subResource->update(['status' => $aggregatedStatus]);
} else {
$subResource->update(['last_online_at' => now()]);
}
}
continue;
}
// Use ContainerStatusAggregator service for state machine logic
// Use preserveRestarting: true so individual sub-resources show "Restarting" instead of "Degraded"
$aggregator = new ContainerStatusAggregator;
$aggregatedStatus = $aggregator->aggregateFromStrings($relevantStatuses, preserveRestarting: true);
// Update service sub-resource status with aggregated result
if ($aggregatedStatus) {
$statusFromDb = $subResource->status;
if ($statusFromDb !== $aggregatedStatus) {
$subResource->update(['status' => $aggregatedStatus]);
} else {
$subResource->update(['last_online_at' => now()]);
}
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/User/DeleteUserServers.php | app/Actions/User/DeleteUserServers.php | <?php
namespace App\Actions\User;
use App\Models\Server;
use App\Models\User;
use Illuminate\Support\Collection;
class DeleteUserServers
{
private User $user;
private bool $isDryRun;
public function __construct(User $user, bool $isDryRun = false)
{
$this->user = $user;
$this->isDryRun = $isDryRun;
}
public function getServersPreview(): Collection
{
$servers = collect();
// Get all teams the user belongs to
$teams = $this->user->teams()->get();
foreach ($teams as $team) {
// Only include servers from teams where user is owner or admin
$userRole = $team->pivot->role;
if ($userRole === 'owner' || $userRole === 'admin') {
$teamServers = $team->servers()->get();
$servers = $servers->merge($teamServers);
}
}
// Return unique servers (in case same server is in multiple teams)
return $servers->unique('id');
}
public function execute(): array
{
if ($this->isDryRun) {
return [
'servers' => 0,
];
}
$deletedCount = 0;
$servers = $this->getServersPreview();
foreach ($servers as $server) {
try {
// Skip the default server (ID 0) which is the Coolify host
if ($server->id === 0) {
\Log::info('Skipping deletion of Coolify host server (ID: 0)');
continue;
}
// The Server model's forceDeleting event will handle cleanup of:
// - destinations
// - settings
$server->forceDelete();
$deletedCount++;
} catch (\Exception $e) {
\Log::error("Failed to delete server {$server->id}: ".$e->getMessage());
throw $e; // Re-throw to trigger rollback
}
}
return [
'servers' => $deletedCount,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/User/DeleteUserTeams.php | app/Actions/User/DeleteUserTeams.php | <?php
namespace App\Actions\User;
use App\Models\Team;
use App\Models\User;
class DeleteUserTeams
{
private User $user;
private bool $isDryRun;
public function __construct(User $user, bool $isDryRun = false)
{
$this->user = $user;
$this->isDryRun = $isDryRun;
}
public function getTeamsPreview(): array
{
$teamsToDelete = collect();
$teamsToTransfer = collect();
$teamsToLeave = collect();
$edgeCases = collect();
$teams = $this->user->teams;
foreach ($teams as $team) {
// Skip root team (ID 0)
if ($team->id === 0) {
continue;
}
$userRole = $team->pivot->role;
$memberCount = $team->members->count();
if ($memberCount === 1) {
// User is alone in the team - delete it
$teamsToDelete->push($team);
} elseif ($userRole === 'owner') {
// Check if there are other owners
$otherOwners = $team->members
->where('id', '!=', $this->user->id)
->filter(function ($member) {
return $member->pivot->role === 'owner';
});
if ($otherOwners->isNotEmpty()) {
// There are other owners, but check if this user is paying for the subscription
if ($this->isUserPayingForTeamSubscription($team)) {
// User is paying for the subscription - this is an edge case
$edgeCases->push([
'team' => $team,
'reason' => 'User is paying for the team\'s Stripe subscription but there are other owners. The subscription needs to be cancelled or transferred to another owner\'s payment method.',
]);
} else {
// There are other owners and user is not paying, just remove this user
$teamsToLeave->push($team);
}
} else {
// User is the only owner, check for replacement
$newOwner = $this->findNewOwner($team);
if ($newOwner) {
$teamsToTransfer->push([
'team' => $team,
'new_owner' => $newOwner,
]);
} else {
// No suitable replacement found - this is an edge case
$edgeCases->push([
'team' => $team,
'reason' => 'No suitable owner replacement found. Team has only regular members without admin privileges.',
]);
}
}
} else {
// User is just a member - remove them from the team
$teamsToLeave->push($team);
}
}
return [
'to_delete' => $teamsToDelete,
'to_transfer' => $teamsToTransfer,
'to_leave' => $teamsToLeave,
'edge_cases' => $edgeCases,
];
}
public function execute(): array
{
if ($this->isDryRun) {
return [
'deleted' => 0,
'transferred' => 0,
'left' => 0,
];
}
$counts = [
'deleted' => 0,
'transferred' => 0,
'left' => 0,
];
$preview = $this->getTeamsPreview();
// Check for edge cases - should not happen here as we check earlier, but be safe
if ($preview['edge_cases']->isNotEmpty()) {
throw new \Exception('Edge cases detected during execution. This should not happen.');
}
// Delete teams where user is alone
foreach ($preview['to_delete'] as $team) {
try {
// The Team model's deleting event will handle cleanup of:
// - private keys
// - sources
// - tags
// - environment variables
// - s3 storages
// - notification settings
$team->delete();
$counts['deleted']++;
} catch (\Exception $e) {
\Log::error("Failed to delete team {$team->id}: ".$e->getMessage());
throw $e; // Re-throw to trigger rollback
}
}
// Transfer ownership for teams where user is owner but not alone
foreach ($preview['to_transfer'] as $item) {
try {
$team = $item['team'];
$newOwner = $item['new_owner'];
// Update the new owner's role to owner
$team->members()->updateExistingPivot($newOwner->id, ['role' => 'owner']);
// Remove the current user from the team
$team->members()->detach($this->user->id);
$counts['transferred']++;
} catch (\Exception $e) {
\Log::error("Failed to transfer ownership of team {$item['team']->id}: ".$e->getMessage());
throw $e; // Re-throw to trigger rollback
}
}
// Remove user from teams where they're just a member
foreach ($preview['to_leave'] as $team) {
try {
$team->members()->detach($this->user->id);
$counts['left']++;
} catch (\Exception $e) {
\Log::error("Failed to remove user from team {$team->id}: ".$e->getMessage());
throw $e; // Re-throw to trigger rollback
}
}
return $counts;
}
private function findNewOwner(Team $team): ?User
{
// Only look for admins as potential new owners
// We don't promote regular members automatically
$otherAdmin = $team->members
->where('id', '!=', $this->user->id)
->filter(function ($member) {
return $member->pivot->role === 'admin';
})
->first();
return $otherAdmin;
}
private function isUserPayingForTeamSubscription(Team $team): bool
{
if (! $team->subscription || ! $team->subscription->stripe_customer_id) {
return false;
}
// In Stripe, we need to check if the customer email matches the user's email
// This would require a Stripe API call to get customer details
// For now, we'll check if the subscription was created by this user
// Alternative approach: Check if user is the one who initiated the subscription
// We could store this information when the subscription is created
// For safety, we'll assume if there's an active subscription and multiple owners,
// we should treat it as an edge case that needs manual review
if ($team->subscription->stripe_subscription_id &&
$team->subscription->stripe_invoice_paid) {
// Active subscription exists - we should be cautious
return true;
}
return false;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/User/DeleteUserResources.php | app/Actions/User/DeleteUserResources.php | <?php
namespace App\Actions\User;
use App\Models\User;
use Illuminate\Support\Collection;
class DeleteUserResources
{
private User $user;
private bool $isDryRun;
public function __construct(User $user, bool $isDryRun = false)
{
$this->user = $user;
$this->isDryRun = $isDryRun;
}
public function getResourcesPreview(): array
{
$applications = collect();
$databases = collect();
$services = collect();
// Get all teams the user belongs to
$teams = $this->user->teams()->get();
foreach ($teams as $team) {
// Only delete resources from teams that will be FULLY DELETED
// This means: user is the ONLY member of the team
//
// DO NOT delete resources if:
// - User is just a member (not owner)
// - Team has other members (ownership will be transferred or user just removed)
$userRole = $team->pivot->role;
$memberCount = $team->members->count();
// Skip if user is not owner
if ($userRole !== 'owner') {
continue;
}
// Skip if team has other members (will be transferred/user removed, not deleted)
if ($memberCount > 1) {
continue;
}
// Only delete resources from teams where user is the ONLY member
// These teams will be fully deleted
// Get all servers for this team
$servers = $team->servers()->get();
foreach ($servers as $server) {
// Get applications (custom method returns Collection)
$serverApplications = $server->applications();
$applications = $applications->merge($serverApplications);
// Get databases (custom method returns Collection)
$serverDatabases = $server->databases();
$databases = $databases->merge($serverDatabases);
// Get services (relationship needs ->get())
$serverServices = $server->services()->get();
$services = $services->merge($serverServices);
}
}
return [
'applications' => $applications->unique('id'),
'databases' => $databases->unique('id'),
'services' => $services->unique('id'),
];
}
public function execute(): array
{
if ($this->isDryRun) {
return [
'applications' => 0,
'databases' => 0,
'services' => 0,
];
}
$deletedCounts = [
'applications' => 0,
'databases' => 0,
'services' => 0,
];
$resources = $this->getResourcesPreview();
// Delete applications
foreach ($resources['applications'] as $application) {
try {
$application->forceDelete();
$deletedCounts['applications']++;
} catch (\Exception $e) {
\Log::error("Failed to delete application {$application->id}: ".$e->getMessage());
throw $e; // Re-throw to trigger rollback
}
}
// Delete databases
foreach ($resources['databases'] as $database) {
try {
$database->forceDelete();
$deletedCounts['databases']++;
} catch (\Exception $e) {
\Log::error("Failed to delete database {$database->id}: ".$e->getMessage());
throw $e; // Re-throw to trigger rollback
}
}
// Delete services
foreach ($resources['services'] as $service) {
try {
$service->forceDelete();
$deletedCounts['services']++;
} catch (\Exception $e) {
\Log::error("Failed to delete service {$service->id}: ".$e->getMessage());
throw $e; // Re-throw to trigger rollback
}
}
return $deletedCounts;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartMysql.php | app/Actions/Database/StartMysql.php | <?php
namespace App\Actions\Database;
use App\Helpers\SslHelper;
use App\Models\SslCertificate;
use App\Models\StandaloneMysql;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartMysql
{
use AsAction;
public StandaloneMysql $database;
public array $commands = [];
public string $configuration_dir;
private ?SslCertificate $ssl_certificate = null;
public function handle(StandaloneMysql $database)
{
$this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$this->commands = [
"echo 'Starting database.'",
"echo 'Creating directories.'",
"mkdir -p $this->configuration_dir",
"echo 'Directories created successfully.'",
];
if (! $this->database->enable_ssl) {
$this->commands[] = "rm -rf $this->configuration_dir/ssl";
$this->database->sslCertificates()->delete();
$this->database->fileStorages()
->where('resource_type', $this->database->getMorphClass())
->where('resource_id', $this->database->id)
->get()
->filter(function ($storage) {
return in_array($storage->mount_path, [
'/etc/mysql/certs/server.crt',
'/etc/mysql/certs/server.key',
]);
})
->each(function ($storage) {
$storage->delete();
});
} else {
$this->commands[] = "echo 'Setting up SSL for this database.'";
$this->commands[] = "mkdir -p $this->configuration_dir/ssl";
$server = $this->database->destination->server;
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
if (! $caCert) {
$server->generateCaCertificate();
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
}
if (! $caCert) {
$this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
return;
}
$this->ssl_certificate = $this->database->sslCertificates()->first();
if (! $this->ssl_certificate) {
$this->commands[] = "echo 'No SSL certificate found, generating new SSL certificate for this database.'";
$this->ssl_certificate = SslHelper::generateSslCertificate(
commonName: $this->database->uuid,
resourceType: $this->database->getMorphClass(),
resourceId: $this->database->id,
serverId: $server->id,
caCert: $caCert->ssl_certificate,
caKey: $caCert->ssl_private_key,
configurationDir: $this->configuration_dir,
mountPath: '/etc/mysql/certs',
);
}
}
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$this->add_custom_mysql();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => ['CMD', 'mysqladmin', 'ping', '-h', 'localhost', '-u', 'root', "-p{$this->database->mysql_root_password}"],
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (! is_null($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
$docker_compose['services'][$container_name]['volumes'] ??= [];
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
$persistent_storages
);
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
$persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray()
);
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => '/data/coolify/ssl/coolify-ca.crt',
'target' => '/etc/mysql/certs/coolify-ca.crt',
'read_only' => true,
],
]
);
}
if (! is_null($this->database->mysql_conf) || ! empty($this->database->mysql_conf)) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => $this->configuration_dir.'/custom-config.cnf',
'target' => '/etc/mysql/conf.d/custom-config.cnf',
'read_only' => true,
],
]
);
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['command'] = [
'mysqld',
'--ssl-cert=/etc/mysql/certs/server.crt',
'--ssl-key=/etc/mysql/certs/server.key',
'--ssl-ca=/etc/mysql/certs/coolify-ca.crt',
'--require-secure-transport=1',
];
}
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
if ($this->database->enable_ssl) {
$this->commands[] = executeInDocker($this->database->uuid, "chown {$this->database->mysql_user}:{$this->database->mysql_user} /etc/mysql/certs/server.crt /etc/mysql/certs/server.key");
}
$this->commands[] = "echo 'Database started.'";
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->real_value");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MYSQL_ROOT_PASSWORD'))->isEmpty()) {
$environment_variables->push("MYSQL_ROOT_PASSWORD={$this->database->mysql_root_password}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MYSQL_DATABASE'))->isEmpty()) {
$environment_variables->push("MYSQL_DATABASE={$this->database->mysql_database}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MYSQL_USER'))->isEmpty()) {
$environment_variables->push("MYSQL_USER={$this->database->mysql_user}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MYSQL_PASSWORD'))->isEmpty()) {
$environment_variables->push("MYSQL_PASSWORD={$this->database->mysql_password}");
}
add_coolify_default_environment_variables($this->database, $environment_variables, $environment_variables);
return $environment_variables->all();
}
private function add_custom_mysql()
{
if (is_null($this->database->mysql_conf) || empty($this->database->mysql_conf)) {
return;
}
$filename = 'custom-config.cnf';
$content = $this->database->mysql_conf;
$content_base64 = base64_encode($content);
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $this->configuration_dir/{$filename} > /dev/null";
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartRedis.php | app/Actions/Database/StartRedis.php | <?php
namespace App\Actions\Database;
use App\Helpers\SslHelper;
use App\Models\SslCertificate;
use App\Models\StandaloneRedis;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartRedis
{
use AsAction;
public StandaloneRedis $database;
public array $commands = [];
public string $configuration_dir;
private ?SslCertificate $ssl_certificate = null;
public function handle(StandaloneRedis $database)
{
$this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$this->commands = [
"echo 'Starting database.'",
"echo 'Creating directories.'",
"mkdir -p $this->configuration_dir",
"echo 'Directories created successfully.'",
];
if (! $this->database->enable_ssl) {
$this->commands[] = "rm -rf $this->configuration_dir/ssl";
$this->database->sslCertificates()->delete();
$this->database->fileStorages()
->where('resource_type', $this->database->getMorphClass())
->where('resource_id', $this->database->id)
->get()
->filter(function ($storage) {
return in_array($storage->mount_path, [
'/etc/redis/certs/server.crt',
'/etc/redis/certs/server.key',
]);
})
->each(function ($storage) {
$storage->delete();
});
} else {
$this->commands[] = "echo 'Setting up SSL for this database.'";
$this->commands[] = "mkdir -p $this->configuration_dir/ssl";
$server = $this->database->destination->server;
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
if (! $caCert) {
$server->generateCaCertificate();
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
}
if (! $caCert) {
$this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
return;
}
$this->ssl_certificate = $this->database->sslCertificates()->first();
if (! $this->ssl_certificate) {
$this->commands[] = "echo 'No SSL certificate found, generating new SSL certificate for this database.'";
$this->ssl_certificate = SslHelper::generateSslCertificate(
commonName: $this->database->uuid,
resourceType: $this->database->getMorphClass(),
resourceId: $this->database->id,
serverId: $server->id,
caCert: $caCert->ssl_certificate,
caKey: $caCert->ssl_private_key,
configurationDir: $this->configuration_dir,
mountPath: '/etc/redis/certs',
);
}
}
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$this->add_custom_redis();
$startCommand = $this->buildStartCommand();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'command' => $startCommand,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => [
'CMD-SHELL',
'redis-cli',
'ping',
],
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (! is_null($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
$docker_compose['services'][$container_name]['volumes'] ??= [];
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_storages
);
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray()
);
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => '/data/coolify/ssl/coolify-ca.crt',
'target' => '/etc/redis/certs/coolify-ca.crt',
'read_only' => true,
],
]
);
}
if (! is_null($this->database->redis_conf) || ! empty($this->database->redis_conf)) {
$docker_compose['services'][$container_name]['volumes'][] = [
'type' => 'bind',
'source' => $this->configuration_dir.'/redis.conf',
'target' => '/usr/local/etc/redis/redis.conf',
'read_only' => true,
];
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
if ($this->database->enable_ssl) {
$this->commands[] = "chown -R 999:999 $this->configuration_dir/ssl/server.key $this->configuration_dir/ssl/server.crt";
}
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
if ($env->is_shared) {
$environment_variables->push("$env->key=$env->real_value");
if ($env->key === 'REDIS_PASSWORD') {
$this->database->update(['redis_password' => $env->real_value]);
}
if ($env->key === 'REDIS_USERNAME') {
$this->database->update(['redis_username' => $env->real_value]);
}
} else {
if ($env->key === 'REDIS_PASSWORD') {
$env->update(['value' => $this->database->redis_password]);
} elseif ($env->key === 'REDIS_USERNAME') {
$env->update(['value' => $this->database->redis_username]);
}
$environment_variables->push("$env->key=$env->real_value");
}
}
add_coolify_default_environment_variables($this->database, $environment_variables, $environment_variables);
return $environment_variables->all();
}
private function buildStartCommand(): string
{
$hasRedisConf = ! is_null($this->database->redis_conf) && ! empty($this->database->redis_conf);
$redisConfPath = '/usr/local/etc/redis/redis.conf';
if ($hasRedisConf) {
$confContent = $this->database->redis_conf;
$hasRequirePass = str_contains($confContent, 'requirepass');
if ($hasRequirePass) {
$command = "redis-server $redisConfPath";
} else {
$command = "redis-server $redisConfPath --requirepass {$this->database->redis_password}";
}
} else {
$command = "redis-server --requirepass {$this->database->redis_password} --appendonly yes";
}
if ($this->database->enable_ssl) {
$sslArgs = [
'--tls-port 6380',
'--tls-cert-file /etc/redis/certs/server.crt',
'--tls-key-file /etc/redis/certs/server.key',
'--tls-ca-cert-file /etc/redis/certs/coolify-ca.crt',
'--tls-auth-clients optional',
];
}
if (! empty($sslArgs)) {
$command .= ' '.implode(' ', $sslArgs);
}
return $command;
}
private function add_custom_redis()
{
if (is_null($this->database->redis_conf) || empty($this->database->redis_conf)) {
return;
}
$filename = 'redis.conf';
$content = $this->database->redis_conf;
$content_base64 = base64_encode($content);
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $this->configuration_dir/{$filename} > /dev/null";
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartDragonfly.php | app/Actions/Database/StartDragonfly.php | <?php
namespace App\Actions\Database;
use App\Helpers\SslHelper;
use App\Models\SslCertificate;
use App\Models\StandaloneDragonfly;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartDragonfly
{
use AsAction;
public StandaloneDragonfly $database;
public array $commands = [];
public string $configuration_dir;
private ?SslCertificate $ssl_certificate = null;
public function handle(StandaloneDragonfly $database)
{
$this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$this->commands = [
"echo 'Starting database.'",
"echo 'Creating directories.'",
"mkdir -p $this->configuration_dir",
"echo 'Directories created successfully.'",
];
if (! $this->database->enable_ssl) {
$this->commands[] = "rm -rf $this->configuration_dir/ssl";
$this->database->sslCertificates()->delete();
$this->database->fileStorages()
->where('resource_type', $this->database->getMorphClass())
->where('resource_id', $this->database->id)
->get()
->filter(function ($storage) {
return in_array($storage->mount_path, [
'/etc/dragonfly/certs/server.crt',
'/etc/dragonfly/certs/server.key',
]);
})
->each(function ($storage) {
$storage->delete();
});
} else {
$this->commands[] = "echo 'Setting up SSL for this database.'";
$this->commands[] = "mkdir -p $this->configuration_dir/ssl";
$server = $this->database->destination->server;
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
if (! $caCert) {
$server->generateCaCertificate();
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
}
if (! $caCert) {
$this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
return;
}
$this->ssl_certificate = $this->database->sslCertificates()->first();
if (! $this->ssl_certificate) {
$this->commands[] = "echo 'No SSL certificate found, generating new SSL certificate for this database.'";
$this->ssl_certificate = SslHelper::generateSslCertificate(
commonName: $this->database->uuid,
resourceType: $this->database->getMorphClass(),
resourceId: $this->database->id,
serverId: $server->id,
caCert: $caCert->ssl_certificate,
caKey: $caCert->ssl_private_key,
configurationDir: $this->configuration_dir,
mountPath: '/etc/dragonfly/certs',
);
}
}
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$startCommand = $this->buildStartCommand();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'command' => $startCommand,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => "redis-cli -a {$this->database->dragonfly_password} ping",
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (! is_null($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
$docker_compose['services'][$container_name]['volumes'] ??= [];
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_storages
);
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray()
);
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => '/data/coolify/ssl/coolify-ca.crt',
'target' => '/etc/dragonfly/certs/coolify-ca.crt',
'read_only' => true,
],
]
);
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
if ($this->database->enable_ssl) {
$this->commands[] = "chown -R 999:999 $this->configuration_dir/ssl/server.key $this->configuration_dir/ssl/server.crt";
}
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function buildStartCommand(): string
{
$command = "dragonfly --requirepass {$this->database->dragonfly_password}";
if ($this->database->enable_ssl) {
$sslArgs = [
'--tls',
'--tls_cert_file /etc/dragonfly/certs/server.crt',
'--tls_key_file /etc/dragonfly/certs/server.key',
'--tls_ca_cert_file /etc/dragonfly/certs/coolify-ca.crt',
];
$command .= ' '.implode(' ', $sslArgs);
}
return $command;
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->real_value");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('REDIS_PASSWORD'))->isEmpty()) {
$environment_variables->push("REDIS_PASSWORD={$this->database->dragonfly_password}");
}
return $environment_variables->all();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartMongodb.php | app/Actions/Database/StartMongodb.php | <?php
namespace App\Actions\Database;
use App\Helpers\SslHelper;
use App\Models\SslCertificate;
use App\Models\StandaloneMongodb;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartMongodb
{
use AsAction;
public StandaloneMongodb $database;
public array $commands = [];
public string $configuration_dir;
private ?SslCertificate $ssl_certificate = null;
public function handle(StandaloneMongodb $database)
{
$this->database = $database;
$startCommand = 'mongod';
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
if (isDev()) {
$this->configuration_dir = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/databases/'.$container_name;
}
$this->commands = [
"echo 'Starting database.'",
"echo 'Creating directories.'",
"mkdir -p $this->configuration_dir",
"echo 'Directories created successfully.'",
];
if (! $this->database->enable_ssl) {
$this->commands[] = "rm -rf $this->configuration_dir/ssl";
$this->database->sslCertificates()->delete();
$this->database->fileStorages()
->where('resource_type', $this->database->getMorphClass())
->where('resource_id', $this->database->id)
->get()
->filter(function ($storage) {
return in_array($storage->mount_path, [
'/etc/mongo/certs/server.pem',
]);
})
->each(function ($storage) {
$storage->delete();
});
} else {
$this->commands[] = "echo 'Setting up SSL for this database.'";
$this->commands[] = "mkdir -p $this->configuration_dir/ssl";
$server = $this->database->destination->server;
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
if (! $caCert) {
$server->generateCaCertificate();
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
}
if (! $caCert) {
$this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
return;
}
$this->ssl_certificate = $this->database->sslCertificates()->first();
if (! $this->ssl_certificate) {
$this->commands[] = "echo 'No SSL certificate found, generating new SSL certificate for this database.'";
$this->ssl_certificate = SslHelper::generateSslCertificate(
commonName: $this->database->uuid,
resourceType: $this->database->getMorphClass(),
resourceId: $this->database->id,
serverId: $server->id,
caCert: $caCert->ssl_certificate,
caKey: $caCert->ssl_private_key,
configurationDir: $this->configuration_dir,
mountPath: '/etc/mongo/certs',
isPemKeyFileRequired: true,
);
}
}
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$this->add_custom_mongo_conf();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'command' => $startCommand,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => [
'CMD',
'echo',
'ok',
],
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (! is_null($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
$docker_compose['services'][$container_name]['volumes'] ??= [];
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
$persistent_storages
);
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
$persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray()
);
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
if (! empty($this->database->mongo_conf)) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[[
'type' => 'bind',
'source' => $this->configuration_dir.'/mongod.conf',
'target' => '/etc/mongo/mongod.conf',
'read_only' => true,
]]
);
$docker_compose['services'][$container_name]['command'] = ['mongod', '--config', '/etc/mongo/mongod.conf'];
}
$this->add_default_database();
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[[
'type' => 'bind',
'source' => $this->configuration_dir.'/docker-entrypoint-initdb.d',
'target' => '/docker-entrypoint-initdb.d',
'read_only' => true,
]]
);
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => '/data/coolify/ssl/coolify-ca.crt',
'target' => '/etc/mongo/certs/ca.pem',
'read_only' => true,
],
]
);
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
if ($this->database->enable_ssl) {
$commandParts = ['mongod'];
if (! empty($this->database->mongo_conf)) {
$commandParts = ['mongod', '--config', '/etc/mongo/mongod.conf'];
}
$sslConfig = match ($this->database->ssl_mode) {
'allow' => [
'--tlsMode=allowTLS',
'--tlsAllowConnectionsWithoutCertificates',
'--tlsAllowInvalidHostnames',
],
'prefer' => [
'--tlsMode=preferTLS',
'--tlsAllowConnectionsWithoutCertificates',
'--tlsAllowInvalidHostnames',
],
'require' => [
'--tlsMode=requireTLS',
'--tlsAllowConnectionsWithoutCertificates',
'--tlsAllowInvalidHostnames',
],
'verify-full' => [
'--tlsMode=requireTLS',
'--tlsAllowInvalidHostnames',
],
default => [],
};
$commandParts = [...$commandParts, ...$sslConfig];
$commandParts[] = '--tlsCAFile';
$commandParts[] = '/etc/mongo/certs/ca.pem';
$commandParts[] = '--tlsCertificateKeyFile';
$commandParts[] = '/etc/mongo/certs/server.pem';
$docker_compose['services'][$container_name]['command'] = $commandParts;
}
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
if ($this->database->enable_ssl) {
$this->commands[] = executeInDocker($this->database->uuid, 'chown mongodb:mongodb /etc/mongo/certs/server.pem');
}
$this->commands[] = "echo 'Database started.'";
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->real_value");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MONGO_INITDB_ROOT_USERNAME'))->isEmpty()) {
$environment_variables->push("MONGO_INITDB_ROOT_USERNAME={$this->database->mongo_initdb_root_username}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MONGO_INITDB_ROOT_PASSWORD'))->isEmpty()) {
$environment_variables->push("MONGO_INITDB_ROOT_PASSWORD={$this->database->mongo_initdb_root_password}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MONGO_INITDB_DATABASE'))->isEmpty()) {
$environment_variables->push("MONGO_INITDB_DATABASE={$this->database->mongo_initdb_database}");
}
add_coolify_default_environment_variables($this->database, $environment_variables, $environment_variables);
return $environment_variables->all();
}
private function add_custom_mongo_conf()
{
if (is_null($this->database->mongo_conf) || empty($this->database->mongo_conf)) {
return;
}
$filename = 'mongod.conf';
$content = $this->database->mongo_conf;
$content_base64 = base64_encode($content);
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $this->configuration_dir/{$filename} > /dev/null";
}
private function add_default_database()
{
$content = "db = db.getSiblingDB(\"{$this->database->mongo_initdb_database}\");db.createCollection('init_collection');db.createUser({user: \"{$this->database->mongo_initdb_root_username}\", pwd: \"{$this->database->mongo_initdb_root_password}\",roles: [{role:\"readWrite\",db:\"{$this->database->mongo_initdb_database}\"}]});";
$content_base64 = base64_encode($content);
$this->commands[] = "mkdir -p $this->configuration_dir/docker-entrypoint-initdb.d";
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $this->configuration_dir/docker-entrypoint-initdb.d/01-default-database.js > /dev/null";
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartDatabase.php | app/Actions/Database/StartDatabase.php | <?php
namespace App\Actions\Database;
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 Lorisleiva\Actions\Concerns\AsAction;
class StartDatabase
{
use AsAction;
public string $jobQueue = 'high';
public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $database)
{
$server = $database->destination->server;
if (! $server->isFunctional()) {
return 'Server is not functional';
}
switch ($database->getMorphClass()) {
case \App\Models\StandalonePostgresql::class:
$activity = StartPostgresql::run($database);
break;
case \App\Models\StandaloneRedis::class:
$activity = StartRedis::run($database);
break;
case \App\Models\StandaloneMongodb::class:
$activity = StartMongodb::run($database);
break;
case \App\Models\StandaloneMysql::class:
$activity = StartMysql::run($database);
break;
case \App\Models\StandaloneMariadb::class:
$activity = StartMariadb::run($database);
break;
case \App\Models\StandaloneKeydb::class:
$activity = StartKeydb::run($database);
break;
case \App\Models\StandaloneDragonfly::class:
$activity = StartDragonfly::run($database);
break;
case \App\Models\StandaloneClickhouse::class:
$activity = StartClickhouse::run($database);
break;
}
if ($database->is_public && $database->public_port) {
StartDatabaseProxy::dispatch($database);
}
return $activity;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/RestartDatabase.php | app/Actions/Database/RestartDatabase.php | <?php
namespace App\Actions\Database;
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 Lorisleiva\Actions\Concerns\AsAction;
class RestartDatabase
{
use AsAction;
public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $database)
{
$server = $database->destination->server;
if (! $server->isFunctional()) {
return 'Server is not functional';
}
StopDatabase::run($database, dockerCleanup: false);
return StartDatabase::run($database);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartClickhouse.php | app/Actions/Database/StartClickhouse.php | <?php
namespace App\Actions\Database;
use App\Models\StandaloneClickhouse;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartClickhouse
{
use AsAction;
public StandaloneClickhouse $database;
public array $commands = [];
public string $configuration_dir;
public function handle(StandaloneClickhouse $database)
{
$this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$this->commands = [
"echo 'Starting database.'",
"mkdir -p $this->configuration_dir",
];
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'ulimits' => [
'nofile' => [
'soft' => 262144,
'hard' => 262144,
],
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => "clickhouse-client --user {$this->database->clickhouse_admin_user} --password {$this->database->clickhouse_admin_password} --query 'SELECT 1'",
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (! is_null($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = $persistent_storages;
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = $persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray();
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->real_value");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('CLICKHOUSE_USER'))->isEmpty()) {
$environment_variables->push("CLICKHOUSE_USER={$this->database->clickhouse_admin_user}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('CLICKHOUSE_PASSWORD'))->isEmpty()) {
$environment_variables->push("CLICKHOUSE_PASSWORD={$this->database->clickhouse_admin_password}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('CLICKHOUSE_DB'))->isEmpty()) {
$environment_variables->push("CLICKHOUSE_DB={$this->database->clickhouse_db}");
}
add_coolify_default_environment_variables($this->database, $environment_variables, $environment_variables);
return $environment_variables->all();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartKeydb.php | app/Actions/Database/StartKeydb.php | <?php
namespace App\Actions\Database;
use App\Helpers\SslHelper;
use App\Models\SslCertificate;
use App\Models\StandaloneKeydb;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartKeydb
{
use AsAction;
public StandaloneKeydb $database;
public array $commands = [];
public string $configuration_dir;
private ?SslCertificate $ssl_certificate = null;
public function handle(StandaloneKeydb $database)
{
$this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$this->commands = [
"echo 'Starting database.'",
"echo 'Creating directories.'",
"mkdir -p $this->configuration_dir",
"echo 'Directories created successfully.'",
];
if (! $this->database->enable_ssl) {
$this->commands[] = "rm -rf $this->configuration_dir/ssl";
$this->database->sslCertificates()->delete();
$this->database->fileStorages()
->where('resource_type', $this->database->getMorphClass())
->where('resource_id', $this->database->id)
->get()
->filter(function ($storage) {
return in_array($storage->mount_path, [
'/etc/keydb/certs/server.crt',
'/etc/keydb/certs/server.key',
]);
})
->each(function ($storage) {
$storage->delete();
});
} else {
$this->commands[] = "echo 'Setting up SSL for this database.'";
$this->commands[] = "mkdir -p $this->configuration_dir/ssl";
$server = $this->database->destination->server;
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
if (! $caCert) {
$server->generateCaCertificate();
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
}
if (! $caCert) {
$this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
return;
}
$this->ssl_certificate = $this->database->sslCertificates()->first();
if (! $this->ssl_certificate) {
$this->commands[] = "echo 'No SSL certificate found, generating new SSL certificate for this database.'";
$this->ssl_certificate = SslHelper::generateSslCertificate(
commonName: $this->database->uuid,
resourceType: $this->database->getMorphClass(),
resourceId: $this->database->id,
serverId: $server->id,
caCert: $caCert->ssl_certificate,
caKey: $caCert->ssl_private_key,
configurationDir: $this->configuration_dir,
mountPath: '/etc/keydb/certs',
);
}
}
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$this->add_custom_keydb();
$startCommand = $this->buildStartCommand();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'command' => $startCommand,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => "keydb-cli --pass {$this->database->keydb_password} ping",
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (! is_null($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
$docker_compose['services'][$container_name]['volumes'] ??= [];
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
$persistent_storages
);
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
$persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray()
);
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
if (! is_null($this->database->keydb_conf) || ! empty($this->database->keydb_conf)) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => $this->configuration_dir.'/keydb.conf',
'target' => '/etc/keydb/keydb.conf',
'read_only' => true,
],
]
);
}
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => '/data/coolify/ssl/coolify-ca.crt',
'target' => '/etc/keydb/certs/coolify-ca.crt',
'read_only' => true,
],
]
);
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
if ($this->database->enable_ssl) {
$this->commands[] = "chown -R 999:999 $this->configuration_dir/ssl/server.key $this->configuration_dir/ssl/server.crt";
}
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->real_value");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('REDIS_PASSWORD'))->isEmpty()) {
$environment_variables->push("REDIS_PASSWORD={$this->database->keydb_password}");
}
add_coolify_default_environment_variables($this->database, $environment_variables, $environment_variables);
return $environment_variables->all();
}
private function add_custom_keydb()
{
if (is_null($this->database->keydb_conf) || empty($this->database->keydb_conf)) {
return;
}
$filename = 'keydb.conf';
$content = $this->database->keydb_conf;
$content_base64 = base64_encode($content);
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $this->configuration_dir/{$filename} > /dev/null";
}
private function buildStartCommand(): string
{
$hasKeydbConf = ! is_null($this->database->keydb_conf) && ! empty($this->database->keydb_conf);
$keydbConfPath = '/etc/keydb/keydb.conf';
if ($hasKeydbConf) {
$confContent = $this->database->keydb_conf;
$hasRequirePass = str_contains($confContent, 'requirepass');
if ($hasRequirePass) {
$command = "keydb-server $keydbConfPath";
} else {
$command = "keydb-server $keydbConfPath --requirepass {$this->database->keydb_password}";
}
} else {
$command = "keydb-server --requirepass {$this->database->keydb_password} --appendonly yes";
}
if ($this->database->enable_ssl) {
$sslArgs = [
'--tls-port 6380',
'--tls-cert-file /etc/keydb/certs/server.crt',
'--tls-key-file /etc/keydb/certs/server.key',
'--tls-ca-cert-file /etc/keydb/certs/coolify-ca.crt',
'--tls-auth-clients optional',
];
$command .= ' '.implode(' ', $sslArgs);
}
return $command;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartDatabaseProxy.php | app/Actions/Database/StartDatabaseProxy.php | <?php
namespace App\Actions\Database;
use App\Models\ServiceDatabase;
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 Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartDatabaseProxy
{
use AsAction;
public string $jobQueue = 'high';
public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse|ServiceDatabase $database)
{
$databaseType = $database->database_type;
$network = data_get($database, 'destination.network');
$server = data_get($database, 'destination.server');
$containerName = data_get($database, 'uuid');
$proxyContainerName = "{$database->uuid}-proxy";
$isSSLEnabled = $database->enable_ssl ?? false;
if ($database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$databaseType = $database->databaseType();
$network = $database->service->uuid;
$server = data_get($database, 'service.destination.server');
$proxyContainerName = "{$database->service->uuid}-proxy";
$containerName = "{$database->name}-{$database->service->uuid}";
}
$internalPort = match ($databaseType) {
'standalone-mariadb', 'standalone-mysql' => 3306,
'standalone-postgresql', 'standalone-supabase/postgres' => 5432,
'standalone-redis', 'standalone-keydb', 'standalone-dragonfly' => 6379,
'standalone-clickhouse' => 9000,
'standalone-mongodb' => 27017,
default => throw new \Exception("Unsupported database type: $databaseType"),
};
if ($isSSLEnabled) {
$internalPort = match ($databaseType) {
'standalone-redis', 'standalone-keydb', 'standalone-dragonfly' => 6380,
default => $internalPort,
};
}
$configuration_dir = database_proxy_dir($database->uuid);
if (isDev()) {
$configuration_dir = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/databases/'.$database->uuid.'/proxy';
}
$nginxconf = <<<EOF
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
events {
worker_connections 1024;
}
stream {
server {
listen $database->public_port;
proxy_pass $containerName:$internalPort;
}
}
EOF;
$docker_compose = [
'services' => [
$proxyContainerName => [
'image' => 'nginx:stable-alpine',
'container_name' => $proxyContainerName,
'restart' => RESTART_MODE,
'ports' => [
"$database->public_port:$database->public_port",
],
'networks' => [
$network,
],
'volumes' => [
[
'type' => 'bind',
'source' => "$configuration_dir/nginx.conf",
'target' => '/etc/nginx/nginx.conf',
],
],
'healthcheck' => [
'test' => [
'CMD-SHELL',
'stat /etc/nginx/nginx.conf || exit 1',
],
'interval' => '5s',
'timeout' => '5s',
'retries' => 3,
'start_period' => '1s',
],
],
],
'networks' => [
$network => [
'external' => true,
'name' => $network,
'attachable' => true,
],
],
];
$dockercompose_base64 = base64_encode(Yaml::dump($docker_compose, 4, 2));
$nginxconf_base64 = base64_encode($nginxconf);
instant_remote_process(["docker rm -f $proxyContainerName"], $server, false);
instant_remote_process([
"mkdir -p $configuration_dir",
"echo '{$nginxconf_base64}' | base64 -d | tee $configuration_dir/nginx.conf > /dev/null",
"echo '{$dockercompose_base64}' | base64 -d | tee $configuration_dir/docker-compose.yaml > /dev/null",
"docker compose --project-directory {$configuration_dir} pull",
"docker compose --project-directory {$configuration_dir} up -d",
], $server);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StopDatabase.php | app/Actions/Database/StopDatabase.php | <?php
namespace App\Actions\Database;
use App\Actions\Server\CleanupDocker;
use App\Events\ServiceStatusChanged;
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 Lorisleiva\Actions\Concerns\AsAction;
class StopDatabase
{
use AsAction;
public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|StandaloneDragonfly|StandaloneClickhouse $database, bool $dockerCleanup = true)
{
try {
$server = $database->destination->server;
if (! $server->isFunctional()) {
return 'Server is not functional';
}
$this->stopContainer($database, $database->uuid, 30);
// Reset restart tracking when database is manually stopped
$database->update([
'restart_count' => 0,
'last_restart_at' => null,
'last_restart_type' => null,
]);
if ($dockerCleanup) {
CleanupDocker::dispatch($server, false, false);
}
if ($database->is_public) {
StopDatabaseProxy::run($database);
}
return 'Database stopped successfully';
} catch (\Exception $e) {
return 'Database stop failed: '.$e->getMessage();
} finally {
ServiceStatusChanged::dispatch($database->environment->project->team->id);
}
}
private function stopContainer($database, string $containerName, int $timeout = 30): void
{
$server = $database->destination->server;
instant_remote_process(command: [
"docker stop -t $timeout $containerName",
"docker rm -f $containerName",
], server: $server, throwError: false);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartMariadb.php | app/Actions/Database/StartMariadb.php | <?php
namespace App\Actions\Database;
use App\Helpers\SslHelper;
use App\Models\SslCertificate;
use App\Models\StandaloneMariadb;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartMariadb
{
use AsAction;
public StandaloneMariadb $database;
public array $commands = [];
public string $configuration_dir;
private ?SslCertificate $ssl_certificate = null;
public function handle(StandaloneMariadb $database)
{
$this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
$this->commands = [
"echo 'Starting database.'",
"echo 'Creating directories.'",
"mkdir -p $this->configuration_dir",
"echo 'Directories created successfully.'",
];
if (! $this->database->enable_ssl) {
$this->commands[] = "rm -rf $this->configuration_dir/ssl";
$this->database->sslCertificates()->delete();
$this->database->fileStorages()
->where('resource_type', $this->database->getMorphClass())
->where('resource_id', $this->database->id)
->get()
->filter(function ($storage) {
return in_array($storage->mount_path, [
'/etc/mysql/certs/server.crt',
'/etc/mysql/certs/server.key',
]);
})
->each(function ($storage) {
$storage->delete();
});
} else {
$this->commands[] = "echo 'Setting up SSL for this database.'";
$this->commands[] = "mkdir -p $this->configuration_dir/ssl";
$server = $this->database->destination->server;
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
if (! $caCert) {
$server->generateCaCertificate();
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
}
if (! $caCert) {
$this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
return;
}
$this->ssl_certificate = $this->database->sslCertificates()->first();
if (! $this->ssl_certificate) {
$this->commands[] = "echo 'No SSL certificate found, generating new SSL certificate for this database.'";
$this->ssl_certificate = SslHelper::generateSslCertificate(
commonName: $this->database->uuid,
resourceType: $this->database->getMorphClass(),
resourceId: $this->database->id,
serverId: $server->id,
caCert: $caCert->ssl_certificate,
caKey: $caCert->ssl_private_key,
configurationDir: $this->configuration_dir,
mountPath: '/etc/mysql/certs',
);
}
}
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$this->add_custom_mysql();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => ['CMD', 'healthcheck.sh', '--connect', '--innodb_initialized'],
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (! is_null($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
$docker_compose['services'][$container_name]['volumes'] ??= [];
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_storages
);
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray()
);
}
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'] ?? [],
[
[
'type' => 'bind',
'source' => '/data/coolify/ssl/coolify-ca.crt',
'target' => '/etc/mysql/certs/coolify-ca.crt',
'read_only' => true,
],
]
);
}
if (! is_null($this->database->mariadb_conf) || ! empty($this->database->mariadb_conf)) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
[
[
'type' => 'bind',
'source' => $this->configuration_dir.'/custom-config.cnf',
'target' => '/etc/mysql/conf.d/custom-config.cnf',
'read_only' => true,
],
]
);
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
if ($this->database->enable_ssl) {
$docker_compose['services'][$container_name]['command'] = [
'mariadbd',
'--ssl-cert=/etc/mysql/certs/server.crt',
'--ssl-key=/etc/mysql/certs/server.key',
'--ssl-ca=/etc/mysql/certs/coolify-ca.crt',
'--require-secure-transport=1',
];
}
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
$this->commands[] = "echo 'Database started.'";
if ($this->database->enable_ssl) {
$this->commands[] = executeInDocker($this->database->uuid, 'chown mysql:mysql /etc/mysql/certs/server.crt /etc/mysql/certs/server.key');
}
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->real_value");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MARIADB_ROOT_PASSWORD'))->isEmpty()) {
$environment_variables->push("MARIADB_ROOT_PASSWORD={$this->database->mariadb_root_password}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MARIADB_DATABASE'))->isEmpty()) {
$environment_variables->push("MARIADB_DATABASE={$this->database->mariadb_database}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MARIADB_USER'))->isEmpty()) {
$environment_variables->push("MARIADB_USER={$this->database->mariadb_user}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('MARIADB_PASSWORD'))->isEmpty()) {
$environment_variables->push("MARIADB_PASSWORD={$this->database->mariadb_password}");
}
add_coolify_default_environment_variables($this->database, $environment_variables, $environment_variables);
return $environment_variables->all();
}
private function add_custom_mysql()
{
if (is_null($this->database->mariadb_conf) || empty($this->database->mariadb_conf)) {
return;
}
$filename = 'custom-config.cnf';
$content = $this->database->mariadb_conf;
$content_base64 = base64_encode($content);
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $this->configuration_dir/{$filename} > /dev/null";
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StartPostgresql.php | app/Actions/Database/StartPostgresql.php | <?php
namespace App\Actions\Database;
use App\Helpers\SslHelper;
use App\Models\SslCertificate;
use App\Models\StandalonePostgresql;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartPostgresql
{
use AsAction;
public StandalonePostgresql $database;
public array $commands = [];
public array $init_scripts = [];
public string $configuration_dir;
private ?SslCertificate $ssl_certificate = null;
public function handle(StandalonePostgresql $database)
{
$this->database = $database;
$container_name = $this->database->uuid;
$this->configuration_dir = database_configuration_dir().'/'.$container_name;
if (isDev()) {
$this->configuration_dir = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/databases/'.$container_name;
}
$this->commands = [
"echo 'Starting database.'",
"echo 'Creating directories.'",
"mkdir -p $this->configuration_dir",
"mkdir -p $this->configuration_dir/docker-entrypoint-initdb.d/",
"echo 'Directories created successfully.'",
];
if (! $this->database->enable_ssl) {
$this->commands[] = "rm -rf $this->configuration_dir/ssl";
$this->database->sslCertificates()->delete();
$this->database->fileStorages()
->where('resource_type', $this->database->getMorphClass())
->where('resource_id', $this->database->id)
->get()
->filter(function ($storage) {
return in_array($storage->mount_path, [
'/var/lib/postgresql/certs/server.crt',
'/var/lib/postgresql/certs/server.key',
]);
})
->each(function ($storage) {
$storage->delete();
});
} else {
$this->commands[] = "echo 'Setting up SSL for this database.'";
$this->commands[] = "mkdir -p $this->configuration_dir/ssl";
$server = $this->database->destination->server;
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
if (! $caCert) {
$server->generateCaCertificate();
$caCert = $server->sslCertificates()->where('is_ca_certificate', true)->first();
}
if (! $caCert) {
$this->dispatch('error', 'No CA certificate found for this database. Please generate a CA certificate for this server in the server/advanced page.');
return;
}
$this->ssl_certificate = $this->database->sslCertificates()->first();
if (! $this->ssl_certificate) {
$this->commands[] = "echo 'No SSL certificate found, generating new SSL certificate for this database.'";
$this->ssl_certificate = SslHelper::generateSslCertificate(
commonName: $this->database->uuid,
resourceType: $this->database->getMorphClass(),
resourceId: $this->database->id,
serverId: $server->id,
caCert: $caCert->ssl_certificate,
caKey: $caCert->ssl_private_key,
configurationDir: $this->configuration_dir,
mountPath: '/var/lib/postgresql/certs',
);
}
}
$persistent_storages = $this->generate_local_persistent_volumes();
$persistent_file_volumes = $this->database->fileStorages()->get();
$volume_names = $this->generate_local_persistent_volumes_only_volume_names();
$environment_variables = $this->generate_environment_variables();
$this->generate_init_scripts();
$this->add_custom_conf();
$docker_compose = [
'services' => [
$container_name => [
'image' => $this->database->image,
'container_name' => $container_name,
'environment' => $environment_variables,
'restart' => RESTART_MODE,
'networks' => [
$this->database->destination->network,
],
'labels' => defaultDatabaseLabels($this->database)->toArray(),
'healthcheck' => [
'test' => [
'CMD-SHELL',
"psql -U {$this->database->postgres_user} -d {$this->database->postgres_db} -c 'SELECT 1' || exit 1",
],
'interval' => '5s',
'timeout' => '5s',
'retries' => 10,
'start_period' => '5s',
],
'mem_limit' => $this->database->limits_memory,
'memswap_limit' => $this->database->limits_memory_swap,
'mem_swappiness' => $this->database->limits_memory_swappiness,
'mem_reservation' => $this->database->limits_memory_reservation,
'cpus' => (float) $this->database->limits_cpus,
'cpu_shares' => $this->database->limits_cpu_shares,
],
],
'networks' => [
$this->database->destination->network => [
'external' => true,
'name' => $this->database->destination->network,
'attachable' => true,
],
],
];
if (filled($this->database->limits_cpuset)) {
data_set($docker_compose, "services.{$container_name}.cpuset", $this->database->limits_cpuset);
}
if ($this->database->destination->server->isLogDrainEnabled() && $this->database->isLogDrainEnabled()) {
$docker_compose['services'][$container_name]['logging'] = generate_fluentd_configuration();
}
if (count($this->database->ports_mappings_array) > 0) {
$docker_compose['services'][$container_name]['ports'] = $this->database->ports_mappings_array;
}
$docker_compose['services'][$container_name]['volumes'] ??= [];
if (count($persistent_storages) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_storages
);
}
if (count($persistent_file_volumes) > 0) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
$persistent_file_volumes->map(function ($item) {
return "$item->fs_path:$item->mount_path";
})->toArray()
);
}
if (count($volume_names) > 0) {
$docker_compose['volumes'] = $volume_names;
}
if (count($this->init_scripts) > 0) {
foreach ($this->init_scripts as $init_script) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
[[
'type' => 'bind',
'source' => $init_script,
'target' => '/docker-entrypoint-initdb.d/'.basename($init_script),
'read_only' => true,
]]
);
}
}
$command = ['postgres'];
if (filled($this->database->postgres_conf)) {
$docker_compose['services'][$container_name]['volumes'] = array_merge(
$docker_compose['services'][$container_name]['volumes'],
[[
'type' => 'bind',
'source' => $this->configuration_dir.'/custom-postgres.conf',
'target' => '/etc/postgresql/postgresql.conf',
'read_only' => true,
]]
);
$command = array_merge($command, ['-c', 'config_file=/etc/postgresql/postgresql.conf']);
}
if ($this->database->enable_ssl) {
$command = array_merge($command, [
'-c', 'ssl=on',
'-c', 'ssl_cert_file=/var/lib/postgresql/certs/server.crt',
'-c', 'ssl_key_file=/var/lib/postgresql/certs/server.key',
]);
}
// Add custom docker run options
$docker_run_options = convertDockerRunToCompose($this->database->custom_docker_run_options);
$docker_compose = generateCustomDockerRunOptionsForDatabases($docker_run_options, $docker_compose, $container_name, $this->database->destination->network);
if (count($command) > 1) {
$docker_compose['services'][$container_name]['command'] = $command;
}
$docker_compose = Yaml::dump($docker_compose, 10);
$docker_compose_base64 = base64_encode($docker_compose);
$this->commands[] = "echo '{$docker_compose_base64}' | base64 -d | tee $this->configuration_dir/docker-compose.yml > /dev/null";
$readme = generate_readme_file($this->database->name, now());
$this->commands[] = "echo '{$readme}' > $this->configuration_dir/README.md";
$this->commands[] = "echo 'Pulling {$database->image} image.'";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml pull";
$this->commands[] = "docker stop -t 10 $container_name 2>/dev/null || true";
$this->commands[] = "docker rm -f $container_name 2>/dev/null || true";
$this->commands[] = "docker compose -f $this->configuration_dir/docker-compose.yml up -d";
if ($this->database->enable_ssl) {
$this->commands[] = executeInDocker($this->database->uuid, "chown {$this->database->postgres_user}:{$this->database->postgres_user} /var/lib/postgresql/certs/server.key /var/lib/postgresql/certs/server.crt");
}
$this->commands[] = "echo 'Database started.'";
return remote_process($this->commands, $database->destination->server, callEventOnFinish: 'DatabaseStatusChanged');
}
private function generate_local_persistent_volumes()
{
$local_persistent_volumes = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path !== '' && $persistentStorage->host_path !== null) {
$local_persistent_volumes[] = $persistentStorage->host_path.':'.$persistentStorage->mount_path;
} else {
$volume_name = $persistentStorage->name;
$local_persistent_volumes[] = $volume_name.':'.$persistentStorage->mount_path;
}
}
return $local_persistent_volumes;
}
private function generate_local_persistent_volumes_only_volume_names()
{
$local_persistent_volumes_names = [];
foreach ($this->database->persistentStorages as $persistentStorage) {
if ($persistentStorage->host_path) {
continue;
}
$name = $persistentStorage->name;
$local_persistent_volumes_names[$name] = [
'name' => $name,
'external' => false,
];
}
return $local_persistent_volumes_names;
}
private function generate_environment_variables()
{
$environment_variables = collect();
foreach ($this->database->runtime_environment_variables as $env) {
$environment_variables->push("$env->key=$env->real_value");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('POSTGRES_USER'))->isEmpty()) {
$environment_variables->push("POSTGRES_USER={$this->database->postgres_user}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('PGUSER'))->isEmpty()) {
$environment_variables->push("PGUSER={$this->database->postgres_user}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('POSTGRES_PASSWORD'))->isEmpty()) {
$environment_variables->push("POSTGRES_PASSWORD={$this->database->postgres_password}");
}
if ($environment_variables->filter(fn ($env) => str($env)->contains('POSTGRES_DB'))->isEmpty()) {
$environment_variables->push("POSTGRES_DB={$this->database->postgres_db}");
}
add_coolify_default_environment_variables($this->database, $environment_variables, $environment_variables);
return $environment_variables->all();
}
private function generate_init_scripts()
{
$this->commands[] = "rm -rf $this->configuration_dir/docker-entrypoint-initdb.d/*";
if (blank($this->database->init_scripts) || count($this->database->init_scripts) === 0) {
return;
}
foreach ($this->database->init_scripts as $init_script) {
$filename = data_get($init_script, 'filename');
$content = data_get($init_script, 'content');
$content_base64 = base64_encode($content);
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $this->configuration_dir/docker-entrypoint-initdb.d/{$filename} > /dev/null";
$this->init_scripts[] = "$this->configuration_dir/docker-entrypoint-initdb.d/{$filename}";
}
}
private function add_custom_conf()
{
$filename = 'custom-postgres.conf';
$config_file_path = "$this->configuration_dir/$filename";
if (blank($this->database->postgres_conf)) {
$this->commands[] = "rm -f $config_file_path";
return;
}
$content = $this->database->postgres_conf;
if (! str($content)->contains('listen_addresses')) {
$content .= "\nlisten_addresses = '*'";
$this->database->postgres_conf = $content;
$this->database->save();
}
$content_base64 = base64_encode($content);
$this->commands[] = "echo '{$content_base64}' | base64 -d | tee $config_file_path > /dev/null";
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Database/StopDatabaseProxy.php | app/Actions/Database/StopDatabaseProxy.php | <?php
namespace App\Actions\Database;
use App\Events\DatabaseProxyStopped;
use App\Models\ServiceDatabase;
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 Lorisleiva\Actions\Concerns\AsAction;
class StopDatabaseProxy
{
use AsAction;
public string $jobQueue = 'high';
public function handle(StandaloneRedis|StandalonePostgresql|StandaloneMongodb|StandaloneMysql|StandaloneMariadb|StandaloneKeydb|ServiceDatabase|StandaloneDragonfly|StandaloneClickhouse $database)
{
$server = data_get($database, 'destination.server');
$uuid = $database->uuid;
if ($database->getMorphClass() === \App\Models\ServiceDatabase::class) {
$uuid = $database->service->uuid;
$server = data_get($database, 'service.server');
}
instant_remote_process(["docker rm -f {$uuid}-proxy"], $server);
$database->save();
DatabaseProxyStopped::dispatch();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/StopLogDrain.php | app/Actions/Server/StopLogDrain.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class StopLogDrain
{
use AsAction;
public function handle(Server $server)
{
try {
return instant_remote_process(['docker rm -f coolify-log-drain'], $server, false);
} catch (\Throwable $e) {
return handleError($e);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/StartLogDrain.php | app/Actions/Server/StartLogDrain.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class StartLogDrain
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Server $server)
{
if ($server->settings->is_logdrain_newrelic_enabled) {
$type = 'newrelic';
} elseif ($server->settings->is_logdrain_highlight_enabled) {
$type = 'highlight';
} elseif ($server->settings->is_logdrain_axiom_enabled) {
$type = 'axiom';
} elseif ($server->settings->is_logdrain_custom_enabled) {
$type = 'custom';
} else {
$type = 'none';
}
if ($type !== 'none') {
StopLogDrain::run($server);
}
try {
if ($type === 'none') {
return 'No log drain is enabled.';
} elseif ($type === 'newrelic') {
if (! $server->settings->is_logdrain_newrelic_enabled) {
throw new \Exception('New Relic log drain is not enabled.');
}
$config = base64_encode("
[SERVICE]
Flush 5
Daemon off
Tag container_logs
Log_Level debug
Parsers_File parsers.conf
[INPUT]
Name forward
Buffer_Chunk_Size 1M
Buffer_Max_Size 6M
[FILTER]
Name grep
Match *
Exclude log 127.0.0.1
[FILTER]
Name modify
Match *
Set coolify.server_name {$server->name}
Rename COOLIFY_APP_NAME coolify.app_name
Rename COOLIFY_PROJECT_NAME coolify.project_name
Rename COOLIFY_SERVER_IP coolify.server_ip
Rename COOLIFY_ENVIRONMENT_NAME coolify.environment_name
[OUTPUT]
Name nrlogs
Match *
license_key \${LICENSE_KEY}
# https://log-api.eu.newrelic.com/log/v1 - EU
# https://log-api.newrelic.com/log/v1 - US
base_uri \${BASE_URI}
");
} elseif ($type === 'highlight') {
if (! $server->settings->is_logdrain_highlight_enabled) {
throw new \Exception('Highlight log drain is not enabled.');
}
$config = base64_encode('
[SERVICE]
Flush 5
Daemon off
Log_Level debug
Parsers_File parsers.conf
[INPUT]
Name forward
tag ${HIGHLIGHT_PROJECT_ID}
Buffer_Chunk_Size 1M
Buffer_Max_Size 6M
[OUTPUT]
Name forward
Match *
Host otel.highlight.io
Port 24224
');
} elseif ($type === 'axiom') {
if (! $server->settings->is_logdrain_axiom_enabled) {
throw new \Exception('Axiom log drain is not enabled.');
}
$config = base64_encode("
[SERVICE]
Flush 5
Daemon off
Log_Level debug
Parsers_File parsers.conf
[INPUT]
Name forward
Buffer_Chunk_Size 1M
Buffer_Max_Size 6M
[FILTER]
Name grep
Match *
Exclude log 127.0.0.1
[FILTER]
Name modify
Match *
Set coolify.server_name {$server->name}
Rename COOLIFY_APP_NAME coolify.app_name
Rename COOLIFY_PROJECT_NAME coolify.project_name
Rename COOLIFY_SERVER_IP coolify.server_ip
Rename COOLIFY_ENVIRONMENT_NAME coolify.environment_name
[OUTPUT]
Name http
Match *
Host api.axiom.co
Port 443
URI /v1/datasets/\${AXIOM_DATASET_NAME}/ingest
# Authorization Bearer should be an API token
Header Authorization Bearer \${AXIOM_API_KEY}
compress gzip
format json
json_date_key _time
json_date_format iso8601
tls On
");
} elseif ($type === 'custom') {
if (! $server->settings->is_logdrain_custom_enabled) {
throw new \Exception('Custom log drain is not enabled.');
}
$config = base64_encode($server->settings->logdrain_custom_config);
$parsers = base64_encode($server->settings->logdrain_custom_config_parser);
} else {
throw new \Exception('Unknown log drain type.');
}
if ($type !== 'custom') {
$parsers = base64_encode("
[PARSER]
Name empty_line_skipper
Format regex
Regex /^(?!\s*$).+/
");
}
$compose = base64_encode('
services:
coolify-log-drain:
image: cr.fluentbit.io/fluent/fluent-bit:2.0
container_name: coolify-log-drain
command: -c /fluent-bit.conf
env_file:
- .env
volumes:
- ./fluent-bit.conf:/fluent-bit.conf
- ./parsers.conf:/parsers.conf
ports:
- 127.0.0.1:24224:24224
labels:
- coolify.managed=true
restart: unless-stopped
');
$readme = base64_encode('# New Relic Log Drain
This log drain is based on [Fluent Bit](https://fluentbit.io/) and New Relic Log Forwarder.
Files:
- `fluent-bit.conf` - configuration file for Fluent Bit
- `docker-compose.yml` - docker-compose file to run Fluent Bit
- `.env` - environment variables for Fluent Bit
');
$license_key = $server->settings->logdrain_newrelic_license_key;
$base_uri = $server->settings->logdrain_newrelic_base_uri;
$base_path = config('constants.coolify.base_config_path');
$config_path = $base_path.'/log-drains';
$fluent_bit_config = $config_path.'/fluent-bit.conf';
$parsers_config = $config_path.'/parsers.conf';
$compose_path = $config_path.'/docker-compose.yml';
$readme_path = $config_path.'/README.md';
$command = [
"echo 'Saving configuration'",
"mkdir -p $config_path",
"echo '{$parsers}' | base64 -d | tee $parsers_config > /dev/null",
"echo '{$config}' | base64 -d | tee $fluent_bit_config > /dev/null",
"echo '{$compose}' | base64 -d | tee $compose_path > /dev/null",
"echo '{$readme}' | base64 -d | tee $readme_path > /dev/null",
"test -f $config_path/.env && rm $config_path/.env",
];
if ($type === 'newrelic') {
$add_envs_command = [
"echo LICENSE_KEY=$license_key >> $config_path/.env",
"echo BASE_URI=$base_uri >> $config_path/.env",
];
} elseif ($type === 'highlight') {
$add_envs_command = [
"echo HIGHLIGHT_PROJECT_ID={$server->settings->logdrain_highlight_project_id} >> $config_path/.env",
];
} elseif ($type === 'axiom') {
$add_envs_command = [
"echo AXIOM_DATASET_NAME={$server->settings->logdrain_axiom_dataset_name} >> $config_path/.env",
"echo AXIOM_API_KEY={$server->settings->logdrain_axiom_api_key} >> $config_path/.env",
];
} elseif ($type === 'custom') {
$add_envs_command = [
"touch $config_path/.env",
];
} else {
throw new \Exception('Unknown log drain type.');
}
$restart_command = [
"echo 'Starting Fluent Bit'",
"cd $config_path && docker compose up -d",
];
$command = array_merge($command, $add_envs_command, $restart_command);
return instant_remote_process($command, $server);
} catch (\Throwable $e) {
return handleError($e);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/DeleteServer.php | app/Actions/Server/DeleteServer.php | <?php
namespace App\Actions\Server;
use App\Models\CloudProviderToken;
use App\Models\Server;
use App\Models\Team;
use App\Notifications\Server\HetznerDeletionFailed;
use App\Services\HetznerService;
use Lorisleiva\Actions\Concerns\AsAction;
class DeleteServer
{
use AsAction;
public function handle(int $serverId, bool $deleteFromHetzner = false, ?int $hetznerServerId = null, ?int $cloudProviderTokenId = null, ?int $teamId = null)
{
$server = Server::withTrashed()->find($serverId);
// Delete from Hetzner even if server is already gone from Coolify
if ($deleteFromHetzner && ($hetznerServerId || ($server && $server->hetzner_server_id))) {
$this->deleteFromHetznerById(
$hetznerServerId ?? $server->hetzner_server_id,
$cloudProviderTokenId ?? $server->cloud_provider_token_id,
$teamId ?? $server->team_id
);
}
ray($server ? 'Deleting server from Coolify' : 'Server already deleted from Coolify, skipping Coolify deletion');
// If server is already deleted from Coolify, skip this part
if (! $server) {
return; // Server already force deleted from Coolify
}
ray('force deleting server from Coolify', ['server_id' => $server->id]);
try {
$server->forceDelete();
} catch (\Throwable $e) {
ray('Failed to force delete server from Coolify', [
'error' => $e->getMessage(),
'server_id' => $server->id,
]);
logger()->error('Failed to force delete server from Coolify', [
'error' => $e->getMessage(),
'server_id' => $server->id,
]);
}
}
private function deleteFromHetznerById(int $hetznerServerId, ?int $cloudProviderTokenId, int $teamId): void
{
try {
// Use the provided token, or fallback to first available team token
$token = null;
if ($cloudProviderTokenId) {
$token = CloudProviderToken::find($cloudProviderTokenId);
}
if (! $token) {
$token = CloudProviderToken::where('team_id', $teamId)
->where('provider', 'hetzner')
->first();
}
if (! $token) {
ray('No Hetzner token found for team, skipping Hetzner deletion', [
'team_id' => $teamId,
'hetzner_server_id' => $hetznerServerId,
]);
return;
}
$hetznerService = new HetznerService($token->token);
$hetznerService->deleteServer($hetznerServerId);
ray('Deleted server from Hetzner', [
'hetzner_server_id' => $hetznerServerId,
'team_id' => $teamId,
]);
} catch (\Throwable $e) {
ray('Failed to delete server from Hetzner', [
'error' => $e->getMessage(),
'hetzner_server_id' => $hetznerServerId,
'team_id' => $teamId,
]);
// Log the error but don't prevent the server from being deleted from Coolify
logger()->error('Failed to delete server from Hetzner', [
'error' => $e->getMessage(),
'hetzner_server_id' => $hetznerServerId,
'team_id' => $teamId,
]);
// Notify the team about the failure
$team = Team::find($teamId);
$team?->notify(new HetznerDeletionFailed($hetznerServerId, $teamId, $e->getMessage()));
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/ValidateServer.php | app/Actions/Server/ValidateServer.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class ValidateServer
{
use AsAction;
public string $jobQueue = 'high';
public ?string $uptime = null;
public ?string $error = null;
public ?string $supported_os_type = null;
public ?string $docker_installed = null;
public ?string $docker_compose_installed = null;
public ?string $docker_version = null;
public function handle(Server $server)
{
$server->update([
'validation_logs' => null,
]);
['uptime' => $this->uptime, 'error' => $error] = $server->validateConnection();
if (! $this->uptime) {
$this->error = 'Server is not reachable. Please validate your configuration and connection.<br>Check this <a target="_blank" class="text-black underline dark:text-white" href="https://coolify.io/docs/knowledge-base/server/openssh">documentation</a> for further help. <br><br><div class="text-error">Error: '.$error.'</div>';
$server->update([
'validation_logs' => $this->error,
]);
throw new \Exception($this->error);
}
$this->supported_os_type = $server->validateOS();
if (! $this->supported_os_type) {
$this->error = 'Server OS type is not supported. Please install Docker manually before continuing: <a target="_blank" class="text-black underline dark:text-white" href="https://docs.docker.com/engine/install/#server">documentation</a>.';
$server->update([
'validation_logs' => $this->error,
]);
throw new \Exception($this->error);
}
$validationResult = $server->validatePrerequisites();
if (! $validationResult['success']) {
$missingCommands = implode(', ', $validationResult['missing']);
$this->error = "Prerequisites ({$missingCommands}) are not installed. Please install them before continuing or use the validation with installation endpoint.";
$server->update([
'validation_logs' => $this->error,
]);
throw new \Exception($this->error);
}
$this->docker_installed = $server->validateDockerEngine();
$this->docker_compose_installed = $server->validateDockerCompose();
if (! $this->docker_installed || ! $this->docker_compose_installed) {
$this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: <a target="_blank" class="text-black underline dark:text-white" href="https://docs.docker.com/engine/install/#server">documentation</a>.';
$server->update([
'validation_logs' => $this->error,
]);
throw new \Exception($this->error);
}
$this->docker_version = $server->validateDockerEngineVersion();
if ($this->docker_version) {
return 'OK';
} else {
$this->error = 'Docker Engine is not installed. Please install Docker manually before continuing: <a target="_blank" class="text-black underline dark:text-white" href="https://docs.docker.com/engine/install/#server">documentation</a>.';
$server->update([
'validation_logs' => $this->error,
]);
throw new \Exception($this->error);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/UpdatePackage.php | app/Actions/Server/UpdatePackage.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
use Spatie\Activitylog\Contracts\Activity;
class UpdatePackage
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Server $server, string $osId, ?string $package = null, ?string $packageManager = null, bool $all = false): Activity|array
{
try {
if ($server->serverStatus() === false) {
return [
'error' => 'Server is not reachable or not ready.',
];
}
// Validate that package name is provided when not updating all packages
if (! $all && ($package === null || $package === '')) {
return [
'error' => "Package name required when 'all' is false.",
];
}
// Sanitize package name to prevent command injection
// Only allow alphanumeric characters, hyphens, underscores, periods, plus signs, and colons
// These are valid characters in package names across most package managers
$sanitizedPackage = '';
if ($package !== null && ! $all) {
if (! preg_match('/^[a-zA-Z0-9._+:-]+$/', $package)) {
return [
'error' => 'Invalid package name. Package names can only contain alphanumeric characters, hyphens, underscores, periods, plus signs, and colons.',
];
}
$sanitizedPackage = escapeshellarg($package);
}
switch ($packageManager) {
case 'zypper':
$commandAll = 'zypper update -y';
$commandInstall = 'zypper install -y '.$sanitizedPackage;
break;
case 'dnf':
$commandAll = 'dnf update -y';
$commandInstall = 'dnf update -y '.$sanitizedPackage;
break;
case 'apt':
$commandAll = 'apt update && apt upgrade -y';
$commandInstall = 'apt install -y '.$sanitizedPackage;
break;
case 'pacman':
$commandAll = 'pacman -Syu --noconfirm';
$commandInstall = 'pacman -S --noconfirm '.$sanitizedPackage;
break;
default:
return [
'error' => 'OS not supported',
];
}
if ($all) {
return remote_process([$commandAll], $server);
}
return remote_process([$commandInstall], $server);
} catch (\Exception $e) {
return [
'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/Actions/Server/StopSentinel.php | app/Actions/Server/StopSentinel.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class StopSentinel
{
use AsAction;
public function handle(Server $server)
{
instant_remote_process(['docker rm -f coolify-sentinel'], $server, false);
$server->sentinelHeartbeat(isReset: true);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/InstallPrerequisites.php | app/Actions/Server/InstallPrerequisites.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class InstallPrerequisites
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Server $server)
{
$supported_os_type = $server->validateOS();
if (! $supported_os_type) {
throw new \Exception('Server OS type is not supported for automated installation. Please install prerequisites manually.');
}
$command = collect([]);
if ($supported_os_type->contains('debian')) {
$command = $command->merge([
"echo 'Installing Prerequisites...'",
'apt-get update -y',
'command -v curl >/dev/null || apt install -y curl',
'command -v wget >/dev/null || apt install -y wget',
'command -v git >/dev/null || apt install -y git',
'command -v jq >/dev/null || apt install -y jq',
]);
} elseif ($supported_os_type->contains('rhel')) {
$command = $command->merge([
"echo 'Installing Prerequisites...'",
'command -v curl >/dev/null || dnf install -y curl',
'command -v wget >/dev/null || dnf install -y wget',
'command -v git >/dev/null || dnf install -y git',
'command -v jq >/dev/null || dnf install -y jq',
]);
} elseif ($supported_os_type->contains('sles')) {
$command = $command->merge([
"echo 'Installing Prerequisites...'",
'zypper update -y',
'command -v curl >/dev/null || zypper install -y curl',
'command -v wget >/dev/null || zypper install -y wget',
'command -v git >/dev/null || zypper install -y git',
'command -v jq >/dev/null || zypper install -y jq',
]);
} elseif ($supported_os_type->contains('arch')) {
// Use -Syu for full system upgrade to avoid partial upgrade issues on Arch Linux
// --needed flag skips packages that are already installed and up-to-date
$command = $command->merge([
"echo 'Installing Prerequisites for Arch Linux...'",
'pacman -Syu --noconfirm --needed curl wget git jq',
]);
} else {
throw new \Exception('Unsupported OS type for prerequisites installation');
}
$command->push("echo 'Prerequisites installed successfully.'");
return remote_process($command, $server);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/StartSentinel.php | app/Actions/Server/StartSentinel.php | <?php
namespace App\Actions\Server;
use App\Events\SentinelRestarted;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class StartSentinel
{
use AsAction;
public function handle(Server $server, bool $restart = false, ?string $latestVersion = null, ?string $customImage = null)
{
if ($server->isSwarm() || $server->isBuildServer()) {
return;
}
if ($restart) {
StopSentinel::run($server);
}
$version = $latestVersion ?? get_latest_sentinel_version();
$metricsHistory = data_get($server, 'settings.sentinel_metrics_history_days');
$refreshRate = data_get($server, 'settings.sentinel_metrics_refresh_rate_seconds');
$pushInterval = data_get($server, 'settings.sentinel_push_interval_seconds');
$token = data_get($server, 'settings.sentinel_token');
$endpoint = data_get($server, 'settings.sentinel_custom_url');
$debug = data_get($server, 'settings.is_sentinel_debug_enabled');
$mountDir = '/data/coolify/sentinel';
$image = config('constants.coolify.registry_url').'/coollabsio/sentinel:'.$version;
if (! $endpoint) {
throw new \RuntimeException('You should set FQDN in Instance Settings.');
}
$environments = [
'TOKEN' => $token,
'DEBUG' => $debug ? 'true' : 'false',
'PUSH_ENDPOINT' => $endpoint,
'PUSH_INTERVAL_SECONDS' => $pushInterval,
'COLLECTOR_ENABLED' => $server->isMetricsEnabled() ? 'true' : 'false',
'COLLECTOR_REFRESH_RATE_SECONDS' => $refreshRate,
'COLLECTOR_RETENTION_PERIOD_DAYS' => $metricsHistory,
];
$labels = [
'coolify.managed' => 'true',
];
if (isDev()) {
// data_set($environments, 'DEBUG', 'true');
if ($customImage && ! empty($customImage)) {
$image = $customImage;
}
$mountDir = '/var/lib/docker/volumes/coolify_dev_coolify_data/_data/sentinel';
}
$dockerEnvironments = '-e "'.implode('" -e "', array_map(fn ($key, $value) => "$key=$value", array_keys($environments), $environments)).'"';
$dockerLabels = implode(' ', array_map(fn ($key, $value) => "$key=$value", array_keys($labels), $labels));
$dockerCommand = "docker run -d $dockerEnvironments --name coolify-sentinel -v /var/run/docker.sock:/var/run/docker.sock -v $mountDir:/app/db --pid host --health-cmd \"curl --fail http://127.0.0.1:8888/api/health || exit 1\" --health-interval 10s --health-retries 3 --add-host=host.docker.internal:host-gateway --label $dockerLabels $image";
instant_remote_process([
'docker rm -f coolify-sentinel || true',
"mkdir -p $mountDir",
$dockerCommand,
"chown -R 9999:root $mountDir",
"chmod -R 700 $mountDir",
], $server);
$server->settings->is_sentinel_enabled = true;
$server->settings->save();
$server->sentinelHeartbeat();
// Dispatch event to notify UI components
SentinelRestarted::dispatch($server, $version);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/ValidatePrerequisites.php | app/Actions/Server/ValidatePrerequisites.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class ValidatePrerequisites
{
use AsAction;
public string $jobQueue = 'high';
/**
* Validate that required commands are available on the server.
*
* @return array{success: bool, missing: array<string>, found: array<string>}
*/
public function handle(Server $server): array
{
$requiredCommands = ['git', 'curl', 'jq'];
$missing = [];
$found = [];
foreach ($requiredCommands as $cmd) {
$result = instant_remote_process(["command -v {$cmd}"], $server, false);
if (! $result) {
$missing[] = $cmd;
} else {
$found[] = $cmd;
}
}
return [
'success' => empty($missing),
'missing' => $missing,
'found' => $found,
];
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/UpdateCoolify.php | app/Actions/Server/UpdateCoolify.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Sleep;
use Lorisleiva\Actions\Concerns\AsAction;
class UpdateCoolify
{
use AsAction;
public ?Server $server = null;
public ?string $latestVersion = null;
public ?string $currentVersion = null;
public function handle($manual_update = false)
{
if (isDev()) {
Sleep::for(10)->seconds();
return;
}
$settings = instanceSettings();
$this->server = Server::find(0);
if (! $this->server) {
return;
}
// Fetch fresh version from CDN instead of using cache
try {
$response = Http::retry(3, 1000)->timeout(10)
->get(config('constants.coolify.versions_url'));
if ($response->successful()) {
$versions = $response->json();
$this->latestVersion = data_get($versions, 'coolify.v4.version');
} else {
// Fallback to cache if CDN unavailable
$cacheVersion = get_latest_version_of_coolify();
// Validate cache version against current running version
if ($cacheVersion && version_compare($cacheVersion, config('constants.coolify.version'), '<')) {
Log::error('Failed to fetch fresh version from CDN and cache is corrupted/outdated', [
'cached_version' => $cacheVersion,
'current_version' => config('constants.coolify.version'),
]);
throw new \Exception(
'Cannot determine latest version: CDN unavailable and cache version '.
"({$cacheVersion}) is older than running version (".config('constants.coolify.version').')'
);
}
$this->latestVersion = $cacheVersion;
Log::warning('Failed to fetch fresh version from CDN (unsuccessful response), using validated cache', [
'version' => $cacheVersion,
]);
}
} catch (\Throwable $e) {
$cacheVersion = get_latest_version_of_coolify();
// Validate cache version against current running version
if ($cacheVersion && version_compare($cacheVersion, config('constants.coolify.version'), '<')) {
Log::error('Failed to fetch fresh version from CDN and cache is corrupted/outdated', [
'error' => $e->getMessage(),
'cached_version' => $cacheVersion,
'current_version' => config('constants.coolify.version'),
]);
throw new \Exception(
'Cannot determine latest version: CDN unavailable and cache version '.
"({$cacheVersion}) is older than running version (".config('constants.coolify.version').')'
);
}
$this->latestVersion = $cacheVersion;
Log::warning('Failed to fetch fresh version from CDN, using validated cache', [
'error' => $e->getMessage(),
'version' => $cacheVersion,
]);
}
$this->currentVersion = config('constants.coolify.version');
if (! $manual_update) {
if (! $settings->is_auto_update_enabled) {
return;
}
if ($this->latestVersion === $this->currentVersion) {
return;
}
if (version_compare($this->latestVersion, $this->currentVersion, '<')) {
return;
}
}
// ALWAYS check for downgrades (even for manual updates)
if (version_compare($this->latestVersion, $this->currentVersion, '<')) {
Log::error('Downgrade prevented', [
'target_version' => $this->latestVersion,
'current_version' => $this->currentVersion,
'manual_update' => $manual_update,
]);
throw new \Exception(
"Cannot downgrade from {$this->currentVersion} to {$this->latestVersion}. ".
'If you need to downgrade, please do so manually via Docker commands.'
);
}
$this->update();
$settings->new_version_available = false;
$settings->save();
}
private function update()
{
$latestHelperImageVersion = getHelperVersion();
$upgradeScriptUrl = config('constants.coolify.upgrade_script_url');
remote_process([
"curl -fsSL {$upgradeScriptUrl} -o /data/coolify/source/upgrade.sh",
"bash /data/coolify/source/upgrade.sh $this->latestVersion $latestHelperImageVersion",
], $this->server);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/CheckUpdates.php | app/Actions/Server/CheckUpdates.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class CheckUpdates
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Server $server)
{
$osId = 'unknown';
$packageManager = null;
try {
if ($server->serverStatus() === false) {
return [
'error' => 'Server is not reachable or not ready.',
];
}
// Try first method - using instant_remote_process
$output = instant_remote_process(['cat /etc/os-release'], $server);
// Parse os-release into an associative array
$osInfo = [];
foreach (explode("\n", $output) as $line) {
if (empty($line)) {
continue;
}
if (strpos($line, '=') === false) {
continue;
}
[$key, $value] = explode('=', $line, 2);
$osInfo[$key] = trim($value, '"');
}
// Get the main OS identifier
$osId = $osInfo['ID'] ?? '';
// $osIdLike = $osInfo['ID_LIKE'] ?? '';
// $versionId = $osInfo['VERSION_ID'] ?? '';
// Normalize OS types based on install.sh logic
switch ($osId) {
case 'manjaro':
case 'manjaro-arm':
case 'endeavouros':
$osType = 'arch';
break;
case 'pop':
case 'linuxmint':
case 'zorin':
$osType = 'ubuntu';
break;
case 'fedora-asahi-remix':
$osType = 'fedora';
break;
default:
$osType = $osId;
}
// Determine package manager based on OS type
$packageManager = match ($osType) {
'arch' => 'pacman',
'alpine' => 'apk',
'ubuntu', 'debian', 'raspbian' => 'apt',
'centos', 'fedora', 'rhel', 'ol', 'rocky', 'almalinux', 'amzn' => 'dnf',
'sles', 'opensuse-leap', 'opensuse-tumbleweed' => 'zypper',
default => null
};
switch ($packageManager) {
case 'zypper':
$output = instant_remote_process(['LANG=C zypper -tx list-updates'], $server);
$out = $this->parseZypperOutput($output);
$out['osId'] = $osId;
$out['package_manager'] = $packageManager;
return $out;
case 'dnf':
$output = instant_remote_process(['LANG=C dnf list -q --updates --refresh'], $server);
$out = $this->parseDnfOutput($output);
$out['osId'] = $osId;
$out['package_manager'] = $packageManager;
return $out;
case 'apt':
instant_remote_process(['apt-get update -qq'], $server);
$output = instant_remote_process(['LANG=C apt list --upgradable 2>/dev/null'], $server);
$out = $this->parseAptOutput($output);
$out['osId'] = $osId;
$out['package_manager'] = $packageManager;
return $out;
case 'pacman':
// Sync database first, then check for updates
// Using -Sy to refresh package database before querying available updates
instant_remote_process(['pacman -Sy'], $server);
$output = instant_remote_process(['pacman -Qu 2>/dev/null'], $server);
$out = $this->parsePacmanOutput($output);
$out['osId'] = $osId;
$out['package_manager'] = $packageManager;
return $out;
default:
return [
'osId' => $osId,
'error' => 'Unsupported package manager',
'package_manager' => $packageManager,
];
}
} catch (\Throwable $e) {
return [
'osId' => $osId,
'package_manager' => $packageManager,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
];
}
}
private function parseZypperOutput(string $output): array
{
$updates = [];
try {
$xml = simplexml_load_string($output);
if ($xml === false) {
return [
'total_updates' => 0,
'updates' => [],
'error' => 'Failed to parse XML output',
];
}
// Navigate to the update-list node
$updateList = $xml->xpath('//update-list/update');
foreach ($updateList as $update) {
$updates[] = [
'package' => (string) $update['name'],
'new_version' => (string) $update['edition'],
'current_version' => (string) $update['edition-old'],
'architecture' => (string) $update['arch'],
'repository' => (string) $update->source['alias'],
'summary' => (string) $update->summary,
'description' => (string) $update->description,
];
}
return [
'total_updates' => count($updates),
'updates' => $updates,
];
} catch (\Throwable $e) {
return [
'total_updates' => 0,
'updates' => [],
'error' => 'Error parsing zypper output: '.$e->getMessage(),
];
}
}
private function parseDnfOutput(string $output): array
{
$updates = [];
$lines = explode("\n", $output);
foreach ($lines as $line) {
if (empty($line)) {
continue;
}
// Split by multiple spaces/tabs and filter out empty elements
$parts = array_values(array_filter(preg_split('/\s+/', $line)));
if (count($parts) >= 3) {
$package = $parts[0];
$new_version = $parts[1];
$repository = $parts[2];
// Extract architecture from package name (e.g., "cloud-init.noarch" -> "noarch")
$architecture = str_contains($package, '.') ? explode('.', $package)[1] : 'noarch';
$updates[] = [
'package' => $package,
'new_version' => $new_version,
'repository' => $repository,
'architecture' => $architecture,
'current_version' => 'unknown', // DNF doesn't show current version in check-update output
];
}
}
return [
'total_updates' => count($updates),
'updates' => $updates,
];
}
private function parseAptOutput(string $output): array
{
$updates = [];
$lines = explode("\n", $output);
foreach ($lines as $line) {
// Skip the "Listing... Done" line and empty lines
if (empty($line) || str_contains($line, 'Listing...')) {
continue;
}
// Example line: package/stable 2.0-1 amd64 [upgradable from: 1.0-1]
if (preg_match('/^(.+?)\/(\S+)\s+(\S+)\s+(\S+)\s+\[upgradable from: (.+?)\]/', $line, $matches)) {
$updates[] = [
'package' => $matches[1],
'repository' => $matches[2],
'new_version' => $matches[3],
'architecture' => $matches[4],
'current_version' => $matches[5],
];
}
}
return [
'total_updates' => count($updates),
'updates' => $updates,
];
}
private function parsePacmanOutput(string $output): array
{
$updates = [];
$unparsedLines = [];
$lines = explode("\n", $output);
foreach ($lines as $line) {
if (empty($line)) {
continue;
}
// Format: package current_version -> new_version
if (preg_match('/^(\S+)\s+(\S+)\s+->\s+(\S+)$/', $line, $matches)) {
$updates[] = [
'package' => $matches[1],
'current_version' => $matches[2],
'new_version' => $matches[3],
'architecture' => 'unknown',
'repository' => 'unknown',
];
} else {
// Log unmatched lines for debugging purposes
$unparsedLines[] = $line;
}
}
$result = [
'total_updates' => count($updates),
'updates' => $updates,
];
// Include unparsed lines in the result for debugging if any exist
if (! empty($unparsedLines)) {
$result['unparsed_lines'] = $unparsedLines;
\Illuminate\Support\Facades\Log::debug('Pacman output contained unparsed lines', [
'unparsed_lines' => $unparsedLines,
]);
}
return $result;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/CleanupDocker.php | app/Actions/Server/CleanupDocker.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class CleanupDocker
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Server $server, bool $deleteUnusedVolumes = false, bool $deleteUnusedNetworks = false)
{
$realtimeImage = config('constants.coolify.realtime_image');
$realtimeImageVersion = config('constants.coolify.realtime_version');
$realtimeImageWithVersion = "$realtimeImage:$realtimeImageVersion";
$realtimeImageWithoutPrefix = 'coollabsio/coolify-realtime';
$realtimeImageWithoutPrefixVersion = "coollabsio/coolify-realtime:$realtimeImageVersion";
$helperImageVersion = getHelperVersion();
$helperImage = config('constants.coolify.helper_image');
$helperImageWithVersion = "$helperImage:$helperImageVersion";
$helperImageWithoutPrefix = 'coollabsio/coolify-helper';
$helperImageWithoutPrefixVersion = "coollabsio/coolify-helper:$helperImageVersion";
$cleanupLog = [];
// Get all application image repositories to exclude from prune
$applications = $server->applications();
$applicationImageRepos = collect($applications)->map(function ($app) {
return $app->docker_registry_image_name ?? $app->uuid;
})->unique()->values();
// Clean up old application images while preserving N most recent for rollback
$applicationCleanupLog = $this->cleanupApplicationImages($server, $applications);
$cleanupLog = array_merge($cleanupLog, $applicationCleanupLog);
// Build image prune command that excludes application images and current Coolify infrastructure images
// This ensures we clean up non-Coolify images while preserving rollback images and current helper/realtime images
// Note: Only the current version is protected; old versions will be cleaned up by explicit commands below
// We pass the version strings so all registry variants are protected (ghcr.io, docker.io, no prefix)
$imagePruneCmd = $this->buildImagePruneCommand(
$applicationImageRepos,
$helperImageVersion,
$realtimeImageVersion
);
$commands = [
'docker container prune -f --filter "label=coolify.managed=true" --filter "label!=coolify.proxy=true"',
$imagePruneCmd,
'docker builder prune -af',
"docker images --filter before=$helperImageWithVersion --filter reference=$helperImage | grep $helperImage | awk '{print $3}' | xargs -r docker rmi -f",
"docker images --filter before=$realtimeImageWithVersion --filter reference=$realtimeImage | grep $realtimeImage | awk '{print $3}' | xargs -r docker rmi -f",
"docker images --filter before=$helperImageWithoutPrefixVersion --filter reference=$helperImageWithoutPrefix | grep $helperImageWithoutPrefix | awk '{print $3}' | xargs -r docker rmi -f",
"docker images --filter before=$realtimeImageWithoutPrefixVersion --filter reference=$realtimeImageWithoutPrefix | grep $realtimeImageWithoutPrefix | awk '{print $3}' | xargs -r docker rmi -f",
];
if ($deleteUnusedVolumes) {
$commands[] = 'docker volume prune -af';
}
if ($deleteUnusedNetworks) {
$commands[] = 'docker network prune -f';
}
foreach ($commands as $command) {
$commandOutput = instant_remote_process([$command], $server, false);
if ($commandOutput !== null) {
$cleanupLog[] = [
'command' => $command,
'output' => $commandOutput,
];
}
}
return $cleanupLog;
}
/**
* Build a docker image prune command that excludes application image repositories.
*
* Since docker image prune doesn't support excluding by repository name directly,
* we use a shell script approach to delete unused images while preserving application images.
*/
private function buildImagePruneCommand(
$applicationImageRepos,
string $helperImageVersion,
string $realtimeImageVersion
): string {
// Step 1: Always prune dangling images (untagged)
$commands = ['docker image prune -f'];
// Build grep pattern to exclude application image repositories (matches repo:tag and repo_service:tag)
$appExcludePatterns = $applicationImageRepos->map(function ($repo) {
// Escape special characters for grep extended regex (ERE)
// ERE special chars: . \ + * ? [ ^ ] $ ( ) { } |
return preg_replace('/([.\\\\+*?\[\]^$(){}|])/', '\\\\$1', $repo);
})->implode('|');
// Build grep pattern to exclude Coolify infrastructure images (current version only)
// This pattern matches the image name regardless of registry prefix:
// - ghcr.io/coollabsio/coolify-helper:1.0.12
// - docker.io/coollabsio/coolify-helper:1.0.12
// - coollabsio/coolify-helper:1.0.12
// Pattern: (^|/)coollabsio/coolify-(helper|realtime):VERSION$
$escapedHelperVersion = preg_replace('/([.\\\\+*?\[\]^$(){}|])/', '\\\\$1', $helperImageVersion);
$escapedRealtimeVersion = preg_replace('/([.\\\\+*?\[\]^$(){}|])/', '\\\\$1', $realtimeImageVersion);
$infraExcludePattern = "(^|/)coollabsio/coolify-helper:{$escapedHelperVersion}$|(^|/)coollabsio/coolify-realtime:{$escapedRealtimeVersion}$";
// Delete unused images that:
// - Are not application images (don't match app repos)
// - Are not current Coolify infrastructure images (any registry)
// - Don't have coolify.managed=true label
// Images in use by containers will fail silently with docker rmi
// Pattern matches both uuid:tag and uuid_servicename:tag (Docker Compose with build)
$grepCommands = "grep -v '<none>'";
// Add application repo exclusion if there are applications
if ($applicationImageRepos->isNotEmpty()) {
$grepCommands .= " | grep -v -E '^({$appExcludePatterns})[_:].+'";
}
// Add infrastructure image exclusion (matches any registry prefix)
$grepCommands .= " | grep -v -E '{$infraExcludePattern}'";
$commands[] = "docker images --format '{{.Repository}}:{{.Tag}}' | ".
$grepCommands.' | '.
"xargs -r -I {} sh -c 'docker inspect --format \"{{{{index .Config.Labels \\\"coolify.managed\\\"}}}}\" \"{}\" 2>/dev/null | grep -q true || docker rmi \"{}\" 2>/dev/null' || true";
return implode(' && ', $commands);
}
private function cleanupApplicationImages(Server $server, $applications = null): array
{
$cleanupLog = [];
if ($applications === null) {
$applications = $server->applications();
}
$disableRetention = $server->settings->disable_application_image_retention ?? false;
foreach ($applications as $application) {
$imagesToKeep = $disableRetention ? 0 : ($application->settings->docker_images_to_keep ?? 2);
$imageRepository = $application->docker_registry_image_name ?? $application->uuid;
// Get the currently running image tag
$currentTagCommand = "docker inspect --format='{{.Config.Image}}' {$application->uuid} 2>/dev/null | grep -oP '(?<=:)[^:]+$' || true";
$currentTag = instant_remote_process([$currentTagCommand], $server, false);
$currentTag = trim($currentTag ?? '');
// List all images for this application with their creation timestamps
// Use wildcard to match both uuid:tag and uuid_servicename:tag (Docker Compose with build)
$listCommand = "docker images --format '{{.Repository}}:{{.Tag}}#{{.CreatedAt}}' --filter reference='{$imageRepository}*' 2>/dev/null || true";
$output = instant_remote_process([$listCommand], $server, false);
if (empty($output)) {
continue;
}
$images = collect(explode("\n", trim($output)))
->filter()
->map(function ($line) {
$parts = explode('#', $line);
$imageRef = $parts[0] ?? '';
$tagParts = explode(':', $imageRef);
return [
'repository' => $tagParts[0] ?? '',
'tag' => $tagParts[1] ?? '',
'created_at' => $parts[1] ?? '',
'image_ref' => $imageRef,
];
})
->filter(fn ($image) => ! empty($image['tag']));
// Separate images into categories
// PR images (pr-*) and build images (*-build) are excluded from retention
// Build images will be cleaned up by docker image prune -af
$prImages = $images->filter(fn ($image) => str_starts_with($image['tag'], 'pr-'));
$regularImages = $images->filter(fn ($image) => ! str_starts_with($image['tag'], 'pr-') && ! str_ends_with($image['tag'], '-build'));
// Always delete all PR images
foreach ($prImages as $image) {
$deleteCommand = "docker rmi {$image['image_ref']} 2>/dev/null || true";
$deleteOutput = instant_remote_process([$deleteCommand], $server, false);
$cleanupLog[] = [
'command' => $deleteCommand,
'output' => $deleteOutput ?? 'PR image removed or was in use',
];
}
// Filter out current running image from regular images and sort by creation date
$sortedRegularImages = $regularImages
->filter(fn ($image) => $image['tag'] !== $currentTag)
->sortByDesc('created_at')
->values();
// Keep only N images (imagesToKeep), delete the rest
$imagesToDelete = $sortedRegularImages->skip($imagesToKeep);
foreach ($imagesToDelete as $image) {
$deleteCommand = "docker rmi {$image['image_ref']} 2>/dev/null || true";
$deleteOutput = instant_remote_process([$deleteCommand], $server, false);
$cleanupLog[] = [
'command' => $deleteCommand,
'output' => $deleteOutput ?? 'Image removed or was in use',
];
}
}
return $cleanupLog;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/ResourcesCheck.php | app/Actions/Server/ResourcesCheck.php | <?php
namespace App\Actions\Server;
use App\Models\Application;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
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 Lorisleiva\Actions\Concerns\AsAction;
class ResourcesCheck
{
use AsAction;
public function handle()
{
$seconds = 60;
try {
Application::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
ServiceApplication::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
ServiceDatabase::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandalonePostgresql::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandaloneRedis::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandaloneMongodb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandaloneMysql::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandaloneMariadb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandaloneKeydb::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandaloneDragonfly::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
StandaloneClickhouse::where('last_online_at', '<', now()->subSeconds($seconds))->update(['status' => 'exited']);
} catch (\Throwable $e) {
return handleError($e);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/ConfigureCloudflared.php | app/Actions/Server/ConfigureCloudflared.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
use Spatie\Activitylog\Models\Activity;
use Symfony\Component\Yaml\Yaml;
class ConfigureCloudflared
{
use AsAction;
public function handle(Server $server, string $cloudflare_token, string $ssh_domain): Activity
{
try {
$config = [
'services' => [
'coolify-cloudflared' => [
'container_name' => 'coolify-cloudflared',
'image' => 'cloudflare/cloudflared:latest',
'restart' => RESTART_MODE,
'network_mode' => 'host',
'command' => 'tunnel run',
'environment' => [
"TUNNEL_TOKEN={$cloudflare_token}",
'TUNNEL_METRICS=127.0.0.1:60123',
],
'healthcheck' => [
'test' => ['CMD', 'cloudflared', 'tunnel', '--metrics', '127.0.0.1:60123', 'ready'],
'interval' => '5s',
'timeout' => '30s',
'retries' => 5,
],
],
],
];
$config = Yaml::dump($config, 12, 2);
$docker_compose_yml_base64 = base64_encode($config);
$commands = collect([
'mkdir -p /tmp/cloudflared',
'cd /tmp/cloudflared',
"echo '$docker_compose_yml_base64' | base64 -d | tee docker-compose.yml > /dev/null",
'echo Pulling latest Cloudflare Tunnel image.',
'docker compose pull',
'echo Stopping existing Cloudflare Tunnel container.',
'docker rm -f coolify-cloudflared || true',
'echo Starting new Cloudflare Tunnel container.',
'docker compose up --wait --wait-timeout 15 --remove-orphans || docker logs coolify-cloudflared',
]);
return remote_process($commands, $server, callEventOnFinish: 'CloudflareTunnelChanged', callEventData: [
'server_id' => $server->id,
'ssh_domain' => $ssh_domain,
]);
} catch (\Throwable $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/Actions/Server/RunCommand.php | app/Actions/Server/RunCommand.php | <?php
namespace App\Actions\Server;
use App\Enums\ActivityTypes;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class RunCommand
{
use AsAction;
public function handle(Server $server, $command)
{
return remote_process(command: [$command], server: $server, ignore_errors: true, type: ActivityTypes::COMMAND->value);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/RestartContainer.php | app/Actions/Server/RestartContainer.php | <?php
namespace App\Actions\Server;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class RestartContainer
{
use AsAction;
public function handle(Server $server, string $containerName)
{
$server->restartContainer($containerName);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Server/InstallDocker.php | app/Actions/Server/InstallDocker.php | <?php
namespace App\Actions\Server;
use App\Helpers\SslHelper;
use App\Models\Server;
use App\Models\StandaloneDocker;
use Lorisleiva\Actions\Concerns\AsAction;
class InstallDocker
{
use AsAction;
private string $dockerVersion;
public function handle(Server $server)
{
$this->dockerVersion = config('constants.docker.minimum_required_version');
$supported_os_type = $server->validateOS();
if (! $supported_os_type) {
throw new \Exception('Server OS type is not supported for automated installation. Please install Docker manually before continuing: <a target="_blank" class="underline" href="https://coolify.io/docs/installation#manually">documentation</a>.');
}
if (! $server->sslCertificates()->where('is_ca_certificate', true)->exists()) {
$serverCert = SslHelper::generateSslCertificate(
commonName: 'Coolify CA Certificate',
serverId: $server->id,
isCaCertificate: true,
validityDays: 10 * 365
);
$caCertPath = config('constants.coolify.base_config_path').'/ssl/';
$commands = collect([
"mkdir -p $caCertPath",
"chown -R 9999:root $caCertPath",
"chmod -R 700 $caCertPath",
"rm -rf $caCertPath/coolify-ca.crt",
"echo '{$serverCert->ssl_certificate}' > $caCertPath/coolify-ca.crt",
"chmod 644 $caCertPath/coolify-ca.crt",
]);
remote_process($commands, $server);
}
$config = base64_encode('{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}');
$found = StandaloneDocker::where('server_id', $server->id);
if ($found->count() == 0 && $server->id) {
StandaloneDocker::create([
'name' => 'coolify',
'network' => 'coolify',
'server_id' => $server->id,
]);
}
$command = collect([]);
if (isDev() && $server->id === 0) {
$command = $command->merge([
"echo 'Installing Docker Engine...'",
"echo 'Configuring Docker Engine (merging existing configuration with the required)...'",
'sleep 4',
"echo 'Restarting Docker Engine...'",
'ls -l /tmp',
]);
return remote_process($command, $server);
} else {
$command = $command->merge([
"echo 'Installing Docker Engine...'",
]);
if ($supported_os_type->contains('debian')) {
$command = $command->merge([$this->getDebianDockerInstallCommand()]);
} elseif ($supported_os_type->contains('rhel')) {
$command = $command->merge([$this->getRhelDockerInstallCommand()]);
} elseif ($supported_os_type->contains('sles')) {
$command = $command->merge([$this->getSuseDockerInstallCommand()]);
} elseif ($supported_os_type->contains('arch')) {
$command = $command->merge([$this->getArchDockerInstallCommand()]);
} else {
$command = $command->merge([$this->getGenericDockerInstallCommand()]);
}
$command = $command->merge([
"echo 'Configuring Docker Engine (merging existing configuration with the required)...'",
'test -s /etc/docker/daemon.json && cp /etc/docker/daemon.json "/etc/docker/daemon.json.original-$(date +"%Y%m%d-%H%M%S")"',
"test ! -s /etc/docker/daemon.json && echo '{$config}' | base64 -d | tee /etc/docker/daemon.json > /dev/null",
"echo '{$config}' | base64 -d | tee /etc/docker/daemon.json.coolify > /dev/null",
'jq . /etc/docker/daemon.json.coolify | tee /etc/docker/daemon.json.coolify.pretty > /dev/null',
'mv /etc/docker/daemon.json.coolify.pretty /etc/docker/daemon.json.coolify',
"jq -s '.[0] * .[1]' /etc/docker/daemon.json.coolify /etc/docker/daemon.json | tee /etc/docker/daemon.json.appended > /dev/null",
'mv /etc/docker/daemon.json.appended /etc/docker/daemon.json',
"echo 'Restarting Docker Engine...'",
'systemctl enable docker >/dev/null 2>&1 || true',
'systemctl restart docker',
]);
if ($server->isSwarm()) {
$command = $command->merge([
'docker network create --attachable --driver overlay coolify-overlay >/dev/null 2>&1 || true',
]);
} else {
$command = $command->merge([
'docker network create --attachable coolify >/dev/null 2>&1 || true',
]);
$command = $command->merge([
"echo 'Done!'",
]);
}
return remote_process($command, $server);
}
}
private function getDebianDockerInstallCommand(): string
{
return "curl --max-time 300 --retry 3 https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl --max-time 300 --retry 3 https://get.docker.com | sh -s -- --version {$this->dockerVersion} || (".
'install -m 0755 -d /etc/apt/keyrings && '.
'curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc && '.
'chmod a+r /etc/apt/keyrings/docker.asc && '.
'. /etc/os-release && '.
'echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian ${VERSION_CODENAME} stable" > /etc/apt/sources.list.d/docker.list && '.
'apt-get update && '.
'apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin'.
')';
}
private function getRhelDockerInstallCommand(): string
{
return "curl https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$this->dockerVersion} || (".
'dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo && '.
'dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin && '.
'systemctl start docker && '.
'systemctl enable docker'.
')';
}
private function getSuseDockerInstallCommand(): string
{
return "curl https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl https://get.docker.com | sh -s -- --version {$this->dockerVersion} || (".
'zypper addrepo https://download.docker.com/linux/sles/docker-ce.repo && '.
'zypper refresh && '.
'zypper install -y --no-confirm docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin && '.
'systemctl start docker && '.
'systemctl enable docker'.
')';
}
private function getArchDockerInstallCommand(): string
{
// Use -Syu to perform full system upgrade before installing Docker
// Partial upgrades (-Sy without -u) are discouraged on Arch Linux
// as they can lead to broken dependencies and system instability
// Use --needed to skip reinstalling packages that are already up-to-date (idempotent)
return 'pacman -Syu --noconfirm --needed docker docker-compose && '.
'systemctl enable docker.service && '.
'systemctl start docker.service';
}
private function getGenericDockerInstallCommand(): string
{
return "curl --max-time 300 --retry 3 https://releases.rancher.com/install-docker/{$this->dockerVersion}.sh | sh || curl --max-time 300 --retry 3 https://get.docker.com | sh -s -- --version {$this->dockerVersion}";
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/CoolifyTask/RunRemoteProcess.php | app/Actions/CoolifyTask/RunRemoteProcess.php | <?php
namespace App\Actions\CoolifyTask;
use App\Enums\ActivityTypes;
use App\Enums\ProcessStatus;
use App\Helpers\SshMultiplexingHelper;
use App\Jobs\ApplicationDeploymentJob;
use App\Models\Server;
use Illuminate\Process\ProcessResult;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Spatie\Activitylog\Models\Activity;
class RunRemoteProcess
{
public Activity $activity;
public bool $hide_from_output;
public bool $ignore_errors;
public $call_event_on_finish = null;
public $call_event_data = null;
protected $time_start;
protected $current_time;
protected $last_write_at = 0;
protected $throttle_interval_ms = 200;
protected int $counter = 1;
/**
* Create a new job instance.
*/
public function __construct(Activity $activity, bool $hide_from_output = false, bool $ignore_errors = false, $call_event_on_finish = null, $call_event_data = null)
{
if ($activity->getExtraProperty('type') !== ActivityTypes::INLINE->value && $activity->getExtraProperty('type') !== ActivityTypes::COMMAND->value) {
throw new \RuntimeException('Incompatible Activity to run a remote command.');
}
$this->activity = $activity;
$this->hide_from_output = $hide_from_output;
$this->ignore_errors = $ignore_errors;
$this->call_event_on_finish = $call_event_on_finish;
$this->call_event_data = $call_event_data;
}
public static function decodeOutput(?Activity $activity = null): string
{
if (is_null($activity)) {
return '';
}
try {
$decoded = json_decode(
data_get($activity, 'description'),
associative: true,
flags: JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE
);
} catch (\JsonException $exception) {
return '';
}
return collect($decoded)
->sortBy(fn ($i) => $i['order'])
->map(fn ($i) => $i['output'])
->implode('');
}
public function __invoke(): ProcessResult
{
$this->time_start = hrtime(true);
$status = ProcessStatus::IN_PROGRESS;
$timeout = config('constants.ssh.command_timeout');
$process = Process::timeout($timeout)->start($this->getCommand(), $this->handleOutput(...));
$this->activity->properties = $this->activity->properties->merge([
'process_id' => $process->id(),
]);
$processResult = $process->wait();
if ($this->activity->properties->get('status') === ProcessStatus::ERROR->value) {
$status = ProcessStatus::ERROR;
} else {
if ($processResult->exitCode() == 0) {
$status = ProcessStatus::FINISHED;
} else {
$status = ProcessStatus::ERROR;
}
}
$this->activity->properties = $this->activity->properties->merge([
'exitCode' => $processResult->exitCode(),
'stdout' => $processResult->output(),
'stderr' => $processResult->errorOutput(),
'status' => $status->value,
]);
$this->activity->save();
if ($this->call_event_on_finish) {
try {
$eventClass = "App\\Events\\$this->call_event_on_finish";
if (! is_null($this->call_event_data)) {
event(new $eventClass($this->call_event_data));
} else {
event(new $eventClass($this->activity->causer_id));
}
} catch (\Throwable $e) {
Log::error('Error calling event: '.$e->getMessage());
}
}
if ($processResult->exitCode() != 0 && ! $this->ignore_errors) {
throw new \RuntimeException($processResult->errorOutput(), $processResult->exitCode());
}
return $processResult;
}
protected function getCommand(): string
{
$server_uuid = $this->activity->getExtraProperty('server_uuid');
$command = $this->activity->getExtraProperty('command');
$server = Server::whereUuid($server_uuid)->firstOrFail();
return SshMultiplexingHelper::generateSshCommand($server, $command);
}
protected function handleOutput(string $type, string $output)
{
if ($this->hide_from_output) {
return;
}
$this->current_time = $this->elapsedTime();
$this->activity->description = $this->encodeOutput($type, $output);
if ($this->isAfterLastThrottle()) {
// Let's write to database.
DB::transaction(function () {
$this->activity->save();
$this->last_write_at = $this->current_time;
});
}
}
protected function elapsedTime(): int
{
$timeMs = (hrtime(true) - $this->time_start) / 1_000_000;
return intval($timeMs);
}
public function encodeOutput($type, $output)
{
$outputStack = json_decode($this->activity->description, associative: true, flags: JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
$outputStack[] = [
'type' => $type,
'output' => $output,
'timestamp' => hrtime(true),
'batch' => ApplicationDeploymentJob::$batch_counter,
'order' => $this->getLatestCounter(),
];
return json_encode($outputStack, flags: JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
}
protected function getLatestCounter(): int
{
$description = json_decode($this->activity->description, associative: true, flags: JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
if ($description === null || count($description) === 0) {
return 1;
}
return end($description)['order'] + 1;
}
/**
* Determines if it's time to write again to database.
*
* @return bool
*/
protected function isAfterLastThrottle()
{
// If DB was never written, then we immediately decide we have to write.
if ($this->last_write_at === 0) {
return true;
}
return ($this->current_time - $this->throttle_interval_ms) > $this->last_write_at;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/CoolifyTask/PrepareCoolifyTask.php | app/Actions/CoolifyTask/PrepareCoolifyTask.php | <?php
namespace App\Actions\CoolifyTask;
use App\Data\CoolifyTaskArgs;
use App\Jobs\CoolifyTask;
use Spatie\Activitylog\Models\Activity;
/**
* The initial step to run a `CoolifyTask`: a remote SSH process
* with monitoring/tracking/trace feature. Such thing is made
* possible using an Activity model and some attributes.
*/
class PrepareCoolifyTask
{
protected Activity $activity;
protected CoolifyTaskArgs $remoteProcessArgs;
public function __construct(CoolifyTaskArgs $remoteProcessArgs)
{
$this->remoteProcessArgs = $remoteProcessArgs;
if ($remoteProcessArgs->model) {
$properties = $remoteProcessArgs->toArray();
unset($properties['model']);
$this->activity = activity()
->withProperties($properties)
->performedOn($remoteProcessArgs->model)
->event($remoteProcessArgs->type)
->log('[]');
} else {
$this->activity = activity()
->withProperties($remoteProcessArgs->toArray())
->event($remoteProcessArgs->type)
->log('[]');
}
}
public function __invoke(): Activity
{
$job = new CoolifyTask(
activity: $this->activity,
ignore_errors: $this->remoteProcessArgs->ignore_errors,
call_event_on_finish: $this->remoteProcessArgs->call_event_on_finish,
call_event_data: $this->remoteProcessArgs->call_event_data,
);
dispatch($job);
$this->activity->refresh();
return $this->activity;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Fortify/UpdateUserProfileInformation.php | app/Actions/Fortify/UpdateUserProfileInformation.php | <?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\UpdatesUserProfileInformation;
class UpdateUserProfileInformation implements UpdatesUserProfileInformation
{
/**
* Validate and update the given user's profile information.
*
* @param array<string, string> $input
*/
public function update(User $user, array $input): void
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique('users')->ignore($user->id),
],
])->validateWithBag('updateProfileInformation');
if (
$input['email'] !== $user->email &&
$user instanceof MustVerifyEmail
) {
$this->updateVerifiedUser($user, $input);
} else {
$user->forceFill([
'name' => $input['name'],
'email' => $input['email'],
])->save();
}
}
/**
* Update the given verified user's profile information.
*
* @param array<string, string> $input
*/
protected function updateVerifiedUser(User $user, array $input): void
{
$user->forceFill([
'name' => $input['name'],
'email' => $input['email'],
'email_verified_at' => null,
])->save();
$user->sendEmailVerificationNotification();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Fortify/UpdateUserPassword.php | app/Actions/Fortify/UpdateUserPassword.php | <?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
use Laravel\Fortify\Contracts\UpdatesUserPasswords;
class UpdateUserPassword implements UpdatesUserPasswords
{
/**
* Validate and update the user's password.
*
* @param array<string, string> $input
*/
public function update(User $user, array $input): void
{
Validator::make($input, [
'current_password' => ['required', 'string', 'current_password:web'],
'password' => ['required', Password::defaults(), 'confirmed'],
], [
'current_password.current_password' => __('The provided password does not match your current password.'),
])->validateWithBag('updatePassword');
$user->forceFill([
'password' => Hash::make($input['password']),
])->save();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Fortify/CreateNewUser.php | app/Actions/Fortify/CreateNewUser.php | <?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Password;
use Laravel\Fortify\Contracts\CreatesNewUsers;
class CreateNewUser implements CreatesNewUsers
{
/**
* Validate and create a newly registered user.
*
* @param array<string, string> $input
*/
public function create(array $input): User
{
$settings = instanceSettings();
if (! $settings->is_registration_enabled) {
abort(403);
}
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'password' => ['required', Password::defaults(), 'confirmed'],
])->validate();
if (User::count() == 0) {
// If this is the first user, make them the root user
// Team is already created in the database/seeders/ProductionSeeder.php
$user = User::create([
'id' => 0,
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
$team = $user->teams()->first();
// Disable registration after first user is created
$settings = instanceSettings();
$settings->is_registration_enabled = false;
$settings->save();
} else {
$user = User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
$team = $user->teams()->first();
if (isCloud()) {
$user->sendVerificationEmail();
} else {
$user->markEmailAsVerified();
}
}
// Set session variable
session(['currentTeam' => $user->currentTeam = $team]);
return $user;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Fortify/ResetUserPassword.php | app/Actions/Fortify/ResetUserPassword.php | <?php
namespace App\Actions\Fortify;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;
use Laravel\Fortify\Contracts\ResetsUserPasswords;
class ResetUserPassword implements ResetsUserPasswords
{
/**
* Validate and reset the user's forgotten password.
*
* @param array<string, string> $input
*/
public function reset(User $user, array $input): void
{
Validator::make($input, [
'password' => ['required', Password::defaults(), 'confirmed'],
])->validate();
$user->forceFill([
'password' => Hash::make($input['password']),
])->save();
$user->deleteAllSessions();
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Shared/ComplexStatusCheck.php | app/Actions/Shared/ComplexStatusCheck.php | <?php
namespace App\Actions\Shared;
use App\Models\Application;
use App\Services\ContainerStatusAggregator;
use App\Traits\CalculatesExcludedStatus;
use Lorisleiva\Actions\Concerns\AsAction;
class ComplexStatusCheck
{
use AsAction;
use CalculatesExcludedStatus;
public function handle(Application $application)
{
$servers = $application->additional_servers;
$servers->push($application->destination->server);
foreach ($servers as $server) {
$is_main_server = $application->destination->server->id === $server->id;
if (! $server->isFunctional()) {
if ($is_main_server) {
$application->update(['status' => 'exited']);
continue;
} else {
$application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited']);
continue;
}
}
$containers = instant_remote_process(["docker container inspect $(docker container ls -q --filter 'label=coolify.applicationId={$application->id}' --filter 'label=coolify.pullRequestId=0') --format '{{json .}}'"], $server, false);
$containers = format_docker_command_output_to_json($containers);
if ($containers->count() > 0) {
$statusToSet = $this->aggregateContainerStatuses($application, $containers);
if ($is_main_server) {
$statusFromDb = $application->status;
if ($statusFromDb !== $statusToSet) {
$application->update(['status' => $statusToSet]);
}
} else {
$additional_server = $application->additional_servers()->wherePivot('server_id', $server->id);
$statusFromDb = $additional_server->first()->pivot->status;
if ($statusFromDb !== $statusToSet) {
$additional_server->updateExistingPivot($server->id, ['status' => $statusToSet]);
}
}
} else {
if ($is_main_server) {
$application->update(['status' => 'exited']);
continue;
} else {
$application->additional_servers()->updateExistingPivot($server->id, ['status' => 'exited']);
continue;
}
}
}
}
private function aggregateContainerStatuses($application, $containers)
{
$dockerComposeRaw = data_get($application, 'docker_compose_raw');
$excludedContainers = $this->getExcludedContainersFromDockerCompose($dockerComposeRaw);
// Filter non-excluded containers
$relevantContainers = collect($containers)->filter(function ($container) use ($excludedContainers) {
$labels = data_get($container, 'Config.Labels', []);
$serviceName = data_get($labels, 'com.docker.compose.service');
return ! ($serviceName && $excludedContainers->contains($serviceName));
});
// If all containers are excluded, calculate status from excluded containers
// but mark it with :excluded to indicate monitoring is disabled
if ($relevantContainers->isEmpty()) {
return $this->calculateExcludedStatus($containers, $excludedContainers);
}
// Use ContainerStatusAggregator service for state machine logic
$aggregator = new ContainerStatusAggregator;
return $aggregator->aggregateFromContainers($relevantContainers);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Stripe/CancelSubscription.php | app/Actions/Stripe/CancelSubscription.php | <?php
namespace App\Actions\Stripe;
use App\Models\Subscription;
use App\Models\User;
use Illuminate\Support\Collection;
use Stripe\StripeClient;
class CancelSubscription
{
private User $user;
private bool $isDryRun;
private ?StripeClient $stripe = null;
public function __construct(User $user, bool $isDryRun = false)
{
$this->user = $user;
$this->isDryRun = $isDryRun;
if (! $isDryRun && isCloud()) {
$this->stripe = new StripeClient(config('subscription.stripe_api_key'));
}
}
public function getSubscriptionsPreview(): Collection
{
$subscriptions = collect();
// Get all teams the user belongs to
$teams = $this->user->teams()->get();
foreach ($teams as $team) {
// Only include subscriptions from teams where user is owner
$userRole = $team->pivot->role;
if ($userRole === 'owner' && $team->subscription) {
$subscription = $team->subscription;
// Only include active subscriptions
if ($subscription->stripe_subscription_id &&
$subscription->stripe_invoice_paid) {
$subscriptions->push($subscription);
}
}
}
return $subscriptions;
}
/**
* Verify subscriptions exist and are active in Stripe API
*
* @return array ['verified' => Collection, 'not_found' => Collection, 'errors' => array]
*/
public function verifySubscriptionsInStripe(): array
{
if (! isCloud()) {
return [
'verified' => collect(),
'not_found' => collect(),
'errors' => [],
];
}
$stripe = new StripeClient(config('subscription.stripe_api_key'));
$subscriptions = $this->getSubscriptionsPreview();
$verified = collect();
$notFound = collect();
$errors = [];
foreach ($subscriptions as $subscription) {
try {
$stripeSubscription = $stripe->subscriptions->retrieve($subscription->stripe_subscription_id);
// Check if subscription is actually active in Stripe
if (in_array($stripeSubscription->status, ['active', 'trialing', 'past_due'])) {
$verified->push([
'subscription' => $subscription,
'stripe_status' => $stripeSubscription->status,
'current_period_end' => $stripeSubscription->current_period_end,
]);
} else {
$notFound->push([
'subscription' => $subscription,
'reason' => "Status in Stripe: {$stripeSubscription->status}",
]);
}
} catch (\Stripe\Exception\InvalidRequestException $e) {
// Subscription doesn't exist in Stripe
$notFound->push([
'subscription' => $subscription,
'reason' => 'Not found in Stripe',
]);
} catch (\Exception $e) {
$errors[] = "Error verifying subscription {$subscription->stripe_subscription_id}: ".$e->getMessage();
\Log::error("Error verifying subscription {$subscription->stripe_subscription_id}: ".$e->getMessage());
}
}
return [
'verified' => $verified,
'not_found' => $notFound,
'errors' => $errors,
];
}
public function execute(): array
{
if ($this->isDryRun) {
return [
'cancelled' => 0,
'failed' => 0,
'errors' => [],
];
}
$cancelledCount = 0;
$failedCount = 0;
$errors = [];
$subscriptions = $this->getSubscriptionsPreview();
foreach ($subscriptions as $subscription) {
try {
$this->cancelSingleSubscription($subscription);
$cancelledCount++;
} catch (\Exception $e) {
$failedCount++;
$errorMessage = "Failed to cancel subscription {$subscription->stripe_subscription_id}: ".$e->getMessage();
$errors[] = $errorMessage;
\Log::error($errorMessage);
}
}
return [
'cancelled' => $cancelledCount,
'failed' => $failedCount,
'errors' => $errors,
];
}
private function cancelSingleSubscription(Subscription $subscription): void
{
if (! $this->stripe) {
throw new \Exception('Stripe client not initialized');
}
$subscriptionId = $subscription->stripe_subscription_id;
// Cancel the subscription immediately (not at period end)
$this->stripe->subscriptions->cancel($subscriptionId, []);
// Update local database
$subscription->update([
'stripe_cancel_at_period_end' => false,
'stripe_invoice_paid' => false,
'stripe_trial_already_ended' => false,
'stripe_past_due' => false,
'stripe_feedback' => 'User account deleted',
'stripe_comment' => 'Subscription cancelled due to user account deletion at '.now()->toDateTimeString(),
]);
// Call the team's subscription ended method to handle cleanup
if ($subscription->team) {
$subscription->team->subscriptionEnded();
}
\Log::info("Cancelled Stripe subscription: {$subscriptionId} for team: {$subscription->team->name}");
}
/**
* Cancel a single subscription by ID (helper method for external use)
*/
public static function cancelById(string $subscriptionId): bool
{
try {
if (! isCloud()) {
return false;
}
$stripe = new StripeClient(config('subscription.stripe_api_key'));
$stripe->subscriptions->cancel($subscriptionId, []);
// Update local record if exists
$subscription = Subscription::where('stripe_subscription_id', $subscriptionId)->first();
if ($subscription) {
$subscription->update([
'stripe_cancel_at_period_end' => false,
'stripe_invoice_paid' => false,
'stripe_trial_already_ended' => false,
'stripe_past_due' => false,
]);
if ($subscription->team) {
$subscription->team->subscriptionEnded();
}
}
return true;
} catch (\Exception $e) {
\Log::error("Failed to cancel subscription {$subscriptionId}: ".$e->getMessage());
return false;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Service/StopService.php | app/Actions/Service/StopService.php | <?php
namespace App\Actions\Service;
use App\Actions\Server\CleanupDocker;
use App\Enums\ProcessStatus;
use App\Events\ServiceStatusChanged;
use App\Models\Server;
use App\Models\Service;
use Lorisleiva\Actions\Concerns\AsAction;
use Spatie\Activitylog\Models\Activity;
class StopService
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Service $service, bool $deleteConnectedNetworks = false, bool $dockerCleanup = true)
{
try {
// Cancel any in-progress deployment activities so status doesn't stay stuck at "starting"
Activity::where('properties->type_uuid', $service->uuid)
->where(function ($q) {
$q->where('properties->status', ProcessStatus::IN_PROGRESS->value)
->orWhere('properties->status', ProcessStatus::QUEUED->value);
})
->each(function ($activity) {
$activity->properties = $activity->properties->put('status', ProcessStatus::CANCELLED->value);
$activity->save();
});
$server = $service->destination->server;
if (! $server->isFunctional()) {
return 'Server is not functional';
}
$containersToStop = [];
$applications = $service->applications()->get();
foreach ($applications as $application) {
$containersToStop[] = "{$application->name}-{$service->uuid}";
}
$dbs = $service->databases()->get();
foreach ($dbs as $db) {
$containersToStop[] = "{$db->name}-{$service->uuid}";
}
if (! empty($containersToStop)) {
$this->stopContainersInParallel($containersToStop, $server);
}
if ($deleteConnectedNetworks) {
$service->deleteConnectedNetworks();
}
if ($dockerCleanup) {
CleanupDocker::dispatch($server, false, false);
}
} catch (\Exception $e) {
return $e->getMessage();
} finally {
ServiceStatusChanged::dispatch($service->environment->project->team->id);
}
}
private function stopContainersInParallel(array $containersToStop, Server $server): void
{
$timeout = count($containersToStop) > 5 ? 10 : 30;
$commands = [];
$containerList = implode(' ', $containersToStop);
$commands[] = "docker stop -t $timeout $containerList";
$commands[] = "docker rm -f $containerList";
instant_remote_process(
command: $commands,
server: $server,
throwError: false
);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Service/RestartService.php | app/Actions/Service/RestartService.php | <?php
namespace App\Actions\Service;
use App\Models\Service;
use Lorisleiva\Actions\Concerns\AsAction;
class RestartService
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Service $service, bool $pullLatestImages)
{
StopService::run($service);
return StartService::run($service, $pullLatestImages);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Service/StartService.php | app/Actions/Service/StartService.php | <?php
namespace App\Actions\Service;
use App\Models\Service;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class StartService
{
use AsAction;
public string $jobQueue = 'high';
public function handle(Service $service, bool $pullLatestImages = false, bool $stopBeforeStart = false)
{
$service->parse();
if ($stopBeforeStart) {
StopService::run(service: $service, dockerCleanup: false);
}
$service->saveComposeConfigs();
$service->isConfigurationChanged(save: true);
$workdir = $service->workdir();
// $commands[] = "cd {$workdir}";
$commands[] = "echo 'Saved configuration files to {$workdir}.'";
// Ensure .env exists in the correct directory before docker compose tries to load it
// This is defensive programming - saveComposeConfigs() already creates it,
// but we guarantee it here in case of any edge cases or manual deployments
$commands[] = "touch {$workdir}/.env";
if ($pullLatestImages) {
$commands[] = "echo 'Pulling images.'";
$commands[] = "docker compose --project-directory {$workdir} pull";
}
if ($service->networks()->count() > 0) {
$commands[] = "echo 'Creating Docker network.'";
$commands[] = "docker network inspect $service->uuid >/dev/null 2>&1 || docker network create --attachable $service->uuid";
}
$commands[] = 'echo Starting service.';
$commands[] = "docker compose --project-directory {$workdir} -f {$workdir}/docker-compose.yml --project-name {$service->uuid} up -d --remove-orphans --force-recreate --build";
$commands[] = "docker network connect $service->uuid coolify-proxy >/dev/null 2>&1 || true";
if (data_get($service, 'connect_to_docker_network')) {
$compose = data_get($service, 'docker_compose', []);
$network = $service->destination->network;
$serviceNames = data_get(Yaml::parse($compose), 'services', []);
foreach ($serviceNames as $serviceName => $serviceConfig) {
$commands[] = "docker network connect --alias {$serviceName}-{$service->uuid} $network {$serviceName}-{$service->uuid} >/dev/null 2>&1 || true";
}
}
return remote_process($commands, $service->server, type_uuid: $service->uuid, callEventOnFinish: 'ServiceStatusChanged');
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Service/DeleteService.php | app/Actions/Service/DeleteService.php | <?php
namespace App\Actions\Service;
use App\Actions\Server\CleanupDocker;
use App\Models\Service;
use Illuminate\Support\Facades\Log;
use Lorisleiva\Actions\Concerns\AsAction;
class DeleteService
{
use AsAction;
public function handle(Service $service, bool $deleteVolumes, bool $deleteConnectedNetworks, bool $deleteConfigurations, bool $dockerCleanup)
{
try {
$server = data_get($service, 'server');
if ($deleteVolumes && $server->isFunctional()) {
$storagesToDelete = collect([]);
$service->environment_variables()->delete();
$commands = [];
foreach ($service->applications()->get() as $application) {
$storages = $application->persistentStorages()->get();
foreach ($storages as $storage) {
$storagesToDelete->push($storage);
}
}
foreach ($service->databases()->get() as $database) {
$storages = $database->persistentStorages()->get();
foreach ($storages as $storage) {
$storagesToDelete->push($storage);
}
}
foreach ($storagesToDelete as $storage) {
$commands[] = "docker volume rm -f $storage->name";
}
// Execute volume deletion first, this must be done first otherwise volumes will not be deleted.
if (! empty($commands)) {
foreach ($commands as $command) {
$result = instant_remote_process([$command], $server, false);
if ($result !== null && $result !== 0) {
Log::error('Error deleting volumes: '.$result);
}
}
}
}
if ($deleteConnectedNetworks) {
$service->deleteConnectedNetworks();
}
instant_remote_process(["docker rm -f $service->uuid"], $server, throwError: false);
} catch (\Exception $e) {
throw new \RuntimeException($e->getMessage());
} finally {
if ($deleteConfigurations) {
$service->deleteConfigurations();
}
foreach ($service->applications()->get() as $application) {
$application->forceDelete();
}
foreach ($service->databases()->get() as $database) {
$database->forceDelete();
}
foreach ($service->scheduled_tasks as $task) {
$task->delete();
}
$service->tags()->detach();
$service->forceDelete();
if ($dockerCleanup) {
CleanupDocker::dispatch($server, false, false);
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Proxy/StopProxy.php | app/Actions/Proxy/StopProxy.php | <?php
namespace App\Actions\Proxy;
use App\Events\ProxyStatusChanged;
use App\Events\ProxyStatusChangedUI;
use App\Models\Server;
use App\Services\ProxyDashboardCacheService;
use Lorisleiva\Actions\Concerns\AsAction;
class StopProxy
{
use AsAction;
public function handle(Server $server, bool $forceStop = true, int $timeout = 30, bool $restarting = false)
{
try {
$containerName = $server->isSwarm() ? 'coolify-proxy_traefik' : 'coolify-proxy';
$server->proxy->status = 'stopping';
$server->save();
if (! $restarting) {
ProxyStatusChangedUI::dispatch($server->team_id);
}
instant_remote_process(command: [
"docker stop -t=$timeout $containerName 2>/dev/null || true",
"docker rm -f $containerName 2>/dev/null || true",
'# Wait for container to be fully removed',
'for i in {1..10}; do',
" if ! docker ps -a --format \"{{.Names}}\" | grep -q \"^$containerName$\"; then",
' break',
' fi',
' sleep 1',
'done',
], server: $server, throwError: false);
$server->proxy->force_stop = $forceStop;
$server->proxy->status = 'exited';
$server->save();
} catch (\Throwable $e) {
return handleError($e);
} finally {
ProxyDashboardCacheService::clearCache($server);
if (! $restarting) {
ProxyStatusChanged::dispatch($server->id);
}
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Proxy/GetProxyConfiguration.php | app/Actions/Proxy/GetProxyConfiguration.php | <?php
namespace App\Actions\Proxy;
use App\Models\Server;
use App\Services\ProxyDashboardCacheService;
use Lorisleiva\Actions\Concerns\AsAction;
class GetProxyConfiguration
{
use AsAction;
public function handle(Server $server, bool $forceRegenerate = false): string
{
$proxyType = $server->proxyType();
if ($proxyType === 'NONE') {
return 'OK';
}
$proxy_path = $server->proxyPath();
$proxy_configuration = null;
// If not forcing regeneration, try to read existing configuration
if (! $forceRegenerate) {
$payload = [
"mkdir -p $proxy_path",
"cat $proxy_path/docker-compose.yml 2>/dev/null",
];
$proxy_configuration = instant_remote_process($payload, $server, false);
}
// Generate default configuration if:
// 1. Force regenerate is requested
// 2. Configuration file doesn't exist or is empty
if ($forceRegenerate || empty(trim($proxy_configuration ?? ''))) {
// Extract custom commands from existing config before regenerating
$custom_commands = [];
if (! empty(trim($proxy_configuration ?? ''))) {
$custom_commands = extractCustomProxyCommands($server, $proxy_configuration);
}
$proxy_configuration = str(generateDefaultProxyConfiguration($server, $custom_commands))->trim()->value();
}
if (empty($proxy_configuration)) {
throw new \Exception('Could not get or generate proxy configuration');
}
ProxyDashboardCacheService::isTraefikDashboardAvailableFromConfiguration($server, $proxy_configuration);
return $proxy_configuration;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Proxy/StartProxy.php | app/Actions/Proxy/StartProxy.php | <?php
namespace App\Actions\Proxy;
use App\Enums\ProxyTypes;
use App\Events\ProxyStatusChanged;
use App\Events\ProxyStatusChangedUI;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
use Spatie\Activitylog\Models\Activity;
class StartProxy
{
use AsAction;
public function handle(Server $server, bool $async = true, bool $force = false, bool $restarting = false): string|Activity
{
$proxyType = $server->proxyType();
if ((is_null($proxyType) || $proxyType === 'NONE' || $server->proxy->force_stop || $server->isBuildServer()) && $force === false) {
return 'OK';
}
$server->proxy->set('status', 'starting');
$server->save();
$server->refresh();
if (! $restarting) {
ProxyStatusChangedUI::dispatch($server->team_id);
}
$commands = collect([]);
$proxy_path = $server->proxyPath();
$configuration = GetProxyConfiguration::run($server);
if (! $configuration) {
throw new \Exception('Configuration is not synced');
}
SaveProxyConfiguration::run($server, $configuration);
$docker_compose_yml_base64 = base64_encode($configuration);
$server->proxy->last_applied_settings = str($docker_compose_yml_base64)->pipe('md5')->value();
$server->save();
if ($server->isSwarmManager()) {
$commands = $commands->merge([
"mkdir -p $proxy_path/dynamic",
"cd $proxy_path",
"echo 'Creating required Docker Compose file.'",
"echo 'Starting coolify-proxy.'",
'docker stack deploy --detach=true -c docker-compose.yml coolify-proxy',
"echo 'Successfully started coolify-proxy.'",
]);
} else {
if (isDev()) {
if ($proxyType === ProxyTypes::CADDY->value) {
$proxy_path = '/data/coolify/proxy/caddy';
}
}
$caddyfile = 'import /dynamic/*.caddy';
$commands = $commands->merge([
"mkdir -p $proxy_path/dynamic",
"cd $proxy_path",
"echo '$caddyfile' > $proxy_path/dynamic/Caddyfile",
"echo 'Creating required Docker Compose file.'",
"echo 'Pulling docker image.'",
'docker compose pull',
'if docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
" echo 'Stopping and removing existing coolify-proxy.'",
' docker stop coolify-proxy 2>/dev/null || true',
' docker rm -f coolify-proxy 2>/dev/null || true',
' # Wait for container to be fully removed',
' for i in {1..10}; do',
' if ! docker ps -a --format "{{.Names}}" | grep -q "^coolify-proxy$"; then',
' break',
' fi',
' echo "Waiting for coolify-proxy to be removed... ($i/10)"',
' sleep 1',
' done',
" echo 'Successfully stopped and removed existing coolify-proxy.'",
'fi',
]);
// Ensure required networks exist BEFORE docker compose up (networks are declared as external)
$commands = $commands->merge(ensureProxyNetworksExist($server));
$commands = $commands->merge([
"echo 'Starting coolify-proxy.'",
'docker compose up -d --wait --remove-orphans',
"echo 'Successfully started coolify-proxy.'",
]);
$commands = $commands->merge(connectProxyToNetworks($server));
}
if ($async) {
return remote_process($commands, $server, callEventOnFinish: 'ProxyStatusChanged', callEventData: $server->id);
} else {
instant_remote_process($commands, $server);
$server->proxy->set('type', $proxyType);
$server->save();
ProxyStatusChanged::dispatch($server->id);
return 'OK';
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Proxy/SaveProxyConfiguration.php | app/Actions/Proxy/SaveProxyConfiguration.php | <?php
namespace App\Actions\Proxy;
use App\Models\Server;
use Lorisleiva\Actions\Concerns\AsAction;
class SaveProxyConfiguration
{
use AsAction;
public function handle(Server $server, string $configuration): void
{
$proxy_path = $server->proxyPath();
$docker_compose_yml_base64 = base64_encode($configuration);
// Update the saved settings hash
$server->proxy->last_saved_settings = str($docker_compose_yml_base64)->pipe('md5')->value;
$server->save();
// Transfer the configuration file to the server
instant_remote_process([
"mkdir -p $proxy_path",
"echo '$docker_compose_yml_base64' | base64 -d | tee $proxy_path/docker-compose.yml > /dev/null",
], $server);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Actions/Proxy/CheckProxy.php | app/Actions/Proxy/CheckProxy.php | <?php
namespace App\Actions\Proxy;
use App\Enums\ProxyTypes;
use App\Models\Server;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use Lorisleiva\Actions\Concerns\AsAction;
use Symfony\Component\Yaml\Yaml;
class CheckProxy
{
use AsAction;
// It should return if the proxy should be started (true) or not (false)
public function handle(Server $server, $fromUI = false): bool
{
if (! $server->isFunctional()) {
return false;
}
if ($server->isBuildServer()) {
if ($server->proxy) {
$server->proxy = null;
$server->save();
}
return false;
}
$proxyType = $server->proxyType();
if ((is_null($proxyType) || $proxyType === 'NONE' || $server->proxy->force_stop) && ! $fromUI) {
return false;
}
if (! $server->isProxyShouldRun()) {
if ($fromUI) {
throw new \Exception('Proxy should not run. You selected the Custom Proxy.');
} else {
return false;
}
}
// Determine proxy container name based on environment
$proxyContainerName = $server->isSwarm() ? 'coolify-proxy_traefik' : 'coolify-proxy';
if ($server->isSwarm()) {
$status = getContainerStatus($server, $proxyContainerName);
$server->proxy->set('status', $status);
$server->save();
if ($status === 'running') {
return false;
}
return true;
} else {
$status = getContainerStatus($server, $proxyContainerName);
if ($status === 'running') {
$server->proxy->set('status', 'running');
$server->save();
return false;
}
if ($server->settings->is_cloudflare_tunnel) {
return false;
}
$ip = $server->ip;
if ($server->id === 0) {
$ip = 'host.docker.internal';
}
$portsToCheck = [];
try {
if ($server->proxyType() !== ProxyTypes::NONE->value) {
$proxyCompose = GetProxyConfiguration::run($server);
if (isset($proxyCompose)) {
$yaml = Yaml::parse($proxyCompose);
$configPorts = [];
if ($server->proxyType() === ProxyTypes::TRAEFIK->value) {
$ports = data_get($yaml, 'services.traefik.ports');
} elseif ($server->proxyType() === ProxyTypes::CADDY->value) {
$ports = data_get($yaml, 'services.caddy.ports');
}
if (isset($ports)) {
foreach ($ports as $port) {
$configPorts[] = str($port)->before(':')->value();
}
}
// Combine default ports with config ports
$portsToCheck = array_merge($portsToCheck, $configPorts);
}
} else {
$portsToCheck = [];
}
} catch (\Exception $e) {
Log::error('Error checking proxy: '.$e->getMessage());
}
if (count($portsToCheck) === 0) {
return false;
}
$portsToCheck = array_values(array_unique($portsToCheck));
// Check port conflicts in parallel
$conflicts = $this->checkPortConflictsInParallel($server, $portsToCheck, $proxyContainerName);
foreach ($conflicts as $port => $conflict) {
if ($conflict) {
if ($fromUI) {
throw new \Exception("Port $port is in use.<br>You must stop the process using this port.<br><br>Docs: <a target='_blank' class='dark:text-white hover:underline' href='https://coolify.io/docs'>https://coolify.io/docs</a><br>Discord: <a target='_blank' class='dark:text-white hover:underline' href='https://coolify.io/discord'>https://coolify.io/discord</a>");
} else {
return false;
}
}
}
return true;
}
}
/**
* Check multiple ports for conflicts in parallel
* Returns an array with port => conflict_status mapping
*/
private function checkPortConflictsInParallel(Server $server, array $ports, string $proxyContainerName): array
{
if (empty($ports)) {
return [];
}
try {
// Build concurrent port check commands
$results = Process::concurrently(function ($pool) use ($server, $ports, $proxyContainerName) {
foreach ($ports as $port) {
$commands = $this->buildPortCheckCommands($server, $port, $proxyContainerName);
$pool->command($commands['ssh_command'])->timeout(10);
}
});
// Process results
$conflicts = [];
foreach ($ports as $index => $port) {
$result = $results[$index] ?? null;
if ($result) {
$conflicts[$port] = $this->parsePortCheckResult($result, $port, $proxyContainerName);
} else {
// If process failed, assume no conflict to avoid false positives
$conflicts[$port] = false;
}
}
return $conflicts;
} catch (\Throwable $e) {
Log::warning('Parallel port checking failed: '.$e->getMessage().'. Falling back to sequential checking.');
// Fallback to sequential checking if parallel fails
$conflicts = [];
foreach ($ports as $port) {
$conflicts[$port] = $this->isPortConflict($server, $port, $proxyContainerName);
}
return $conflicts;
}
}
/**
* Build the SSH command for checking a specific port
*/
private function buildPortCheckCommands(Server $server, string $port, string $proxyContainerName): array
{
// First check if our own proxy is using this port (which is fine)
$getProxyContainerId = "docker ps -a --filter name=$proxyContainerName --format '{{.ID}}'";
$checkProxyPortScript = "
CONTAINER_ID=\$($getProxyContainerId);
if [ ! -z \"\$CONTAINER_ID\" ]; then
if docker inspect \$CONTAINER_ID --format '{{json .NetworkSettings.Ports}}' | grep -q '\"$port/tcp\"'; then
echo 'proxy_using_port';
exit 0;
fi;
fi;
";
// Command sets for different ways to check ports, ordered by preference
$portCheckScript = "
$checkProxyPortScript
# Try ss command first
if command -v ss >/dev/null 2>&1; then
ss_output=\$(ss -Htuln state listening sport = :$port 2>/dev/null);
if [ -z \"\$ss_output\" ]; then
echo 'port_free';
exit 0;
fi;
count=\$(echo \"\$ss_output\" | grep -c ':$port ');
if [ \$count -eq 0 ]; then
echo 'port_free';
exit 0;
fi;
# Check for dual-stack or docker processes
if [ \$count -le 2 ] && (echo \"\$ss_output\" | grep -q 'docker\\|coolify'); then
echo 'port_free';
exit 0;
fi;
echo \"port_conflict|\$ss_output\";
exit 0;
fi;
# Try netstat as fallback
if command -v netstat >/dev/null 2>&1; then
netstat_output=\$(netstat -tuln 2>/dev/null | grep ':$port ');
if [ -z \"\$netstat_output\" ]; then
echo 'port_free';
exit 0;
fi;
count=\$(echo \"\$netstat_output\" | grep -c 'LISTEN');
if [ \$count -eq 0 ]; then
echo 'port_free';
exit 0;
fi;
if [ \$count -le 2 ] && (echo \"\$netstat_output\" | grep -q 'docker\\|coolify'); then
echo 'port_free';
exit 0;
fi;
echo \"port_conflict|\$netstat_output\";
exit 0;
fi;
# Final fallback using nc
if nc -z -w1 127.0.0.1 $port >/dev/null 2>&1; then
echo 'port_conflict|nc_detected';
else
echo 'port_free';
fi;
";
$sshCommand = \App\Helpers\SshMultiplexingHelper::generateSshCommand($server, $portCheckScript);
return [
'ssh_command' => $sshCommand,
'script' => $portCheckScript,
];
}
/**
* Parse the result from port check command
*/
private function parsePortCheckResult($processResult, string $port, string $proxyContainerName): bool
{
$exitCode = $processResult->exitCode();
$output = trim($processResult->output());
$errorOutput = trim($processResult->errorOutput());
if ($exitCode !== 0) {
return false;
}
if ($output === 'proxy_using_port' || $output === 'port_free') {
return false; // No conflict
}
if (str_starts_with($output, 'port_conflict|')) {
$details = substr($output, strlen('port_conflict|'));
// Additional logic to detect dual-stack scenarios
if ($details !== 'nc_detected') {
// Check for dual-stack scenario - typically 1-2 listeners (IPv4+IPv6)
$lines = explode("\n", $details);
if (count($lines) <= 2) {
// Look for IPv4 and IPv6 in the listing
if ((strpos($details, '0.0.0.0:'.$port) !== false && strpos($details, ':::'.$port) !== false) ||
(strpos($details, '*:'.$port) !== false && preg_match('/\*:'.$port.'.*IPv[46]/', $details))) {
return false; // This is just a normal dual-stack setup
}
}
}
return true; // Real port conflict
}
return false;
}
/**
* Smart port checker that handles dual-stack configurations
* Returns true only if there's a real port conflict (not just dual-stack)
*/
private function isPortConflict(Server $server, string $port, string $proxyContainerName): bool
{
// First check if our own proxy is using this port (which is fine)
try {
$getProxyContainerId = "docker ps -a --filter name=$proxyContainerName --format '{{.ID}}'";
$containerId = trim(instant_remote_process([$getProxyContainerId], $server));
if (! empty($containerId)) {
$checkProxyPort = "docker inspect $containerId --format '{{json .NetworkSettings.Ports}}' | grep '\"$port/tcp\"'";
try {
instant_remote_process([$checkProxyPort], $server);
// Our proxy is using the port, which is fine
return false;
} catch (\Throwable $e) {
// Our container exists but not using this port
}
}
} catch (\Throwable $e) {
// Container not found or error checking, continue with regular checks
}
// Command sets for different ways to check ports, ordered by preference
$commandSets = [
// Set 1: Use ss to check listener counts by protocol stack
[
'available' => 'command -v ss >/dev/null 2>&1',
'check' => [
// Get listening process details
"ss_output=\$(ss -Htuln state listening sport = :$port 2>/dev/null) && echo \"\$ss_output\"",
// Count IPv4 listeners
"echo \"\$ss_output\" | grep -c ':$port '",
],
],
// Set 2: Use netstat as alternative to ss
[
'available' => 'command -v netstat >/dev/null 2>&1',
'check' => [
// Get listening process details
"netstat_output=\$(netstat -tuln 2>/dev/null) && echo \"\$netstat_output\" | grep ':$port '",
// Count listeners
"echo \"\$netstat_output\" | grep ':$port ' | grep -c 'LISTEN'",
],
],
// Set 3: Use lsof as last resort
[
'available' => 'command -v lsof >/dev/null 2>&1',
'check' => [
// Get process using the port
"lsof -i :$port -P -n | grep 'LISTEN'",
// Count listeners
"lsof -i :$port -P -n | grep 'LISTEN' | wc -l",
],
],
];
// Try each command set until we find one available
foreach ($commandSets as $set) {
try {
// Check if the command is available
instant_remote_process([$set['available']], $server);
// Run the actual check commands
$output = instant_remote_process($set['check'], $server, true);
// Parse the output lines
$lines = explode("\n", trim($output));
// Get the detailed output and listener count
$details = trim(implode("\n", array_slice($lines, 0, -1)));
$count = intval(trim($lines[count($lines) - 1] ?? '0'));
// If no listeners or empty result, port is free
if ($count == 0 || empty($details)) {
return false;
}
// Try to detect if this is our coolify-proxy
if (strpos($details, 'docker') !== false || strpos($details, $proxyContainerName) !== false) {
// It's likely our docker or proxy, which is fine
return false;
}
// Check for dual-stack scenario - typically 1-2 listeners (IPv4+IPv6)
// If exactly 2 listeners and both have same port, likely dual-stack
if ($count <= 2) {
// Check if it looks like a standard dual-stack setup
$isDualStack = false;
// Look for IPv4 and IPv6 in the listing (ss output format)
if (preg_match('/LISTEN.*:'.$port.'\s/', $details) &&
(preg_match('/\*:'.$port.'\s/', $details) ||
preg_match('/:::'.$port.'\s/', $details))) {
$isDualStack = true;
}
// For netstat format
if (strpos($details, '0.0.0.0:'.$port) !== false &&
strpos($details, ':::'.$port) !== false) {
$isDualStack = true;
}
// For lsof format (IPv4 and IPv6)
if (strpos($details, '*:'.$port) !== false &&
preg_match('/\*:'.$port.'.*IPv4/', $details) &&
preg_match('/\*:'.$port.'.*IPv6/', $details)) {
$isDualStack = true;
}
if ($isDualStack) {
return false; // This is just a normal dual-stack setup
}
}
// If we get here, it's likely a real port conflict
return true;
} catch (\Throwable $e) {
// This command set failed, try the next one
continue;
}
}
// Fallback to simpler check if all above methods fail
try {
// Just try to bind to the port directly to see if it's available
$checkCommand = "nc -z -w1 127.0.0.1 $port >/dev/null 2>&1 && echo 'in-use' || echo 'free'";
$result = instant_remote_process([$checkCommand], $server, true);
return trim($result) === 'in-use';
} catch (\Throwable $e) {
// If everything fails, assume the port is free to avoid false positives
return false;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Rules/ValidProxyConfigFilename.php | app/Rules/ValidProxyConfigFilename.php | <?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class ValidProxyConfigFilename implements ValidationRule
{
/**
* Reserved filenames that cannot be used.
*/
private const RESERVED_FILENAMES = [
'coolify.yaml',
'coolify.yml',
'Caddyfile',
];
/**
* Run the validation rule.
*
* Validates proxy configuration filename:
* - Must be 1-255 characters
* - No path separators (/, \) to prevent path traversal
* - Cannot start with a dot (hidden files)
* - Only alphanumeric characters, dashes, underscores, and dots allowed
* - Must have a basename before any extension
* - Cannot use reserved filenames
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (empty($value)) {
return;
}
$filename = trim($value);
// Check length (filesystem limit is typically 255 bytes)
if (strlen($filename) > 255) {
$fail('The :attribute must not exceed 255 characters.');
return;
}
// Check for path separators (prevent path traversal)
if (str_contains($filename, '/') || str_contains($filename, '\\')) {
$fail('The :attribute cannot contain path separators.');
return;
}
// Check for hidden files (starting with dot)
if (str_starts_with($filename, '.')) {
$fail('The :attribute cannot start with a dot (hidden files not allowed).');
return;
}
// Check for valid characters only: alphanumeric, dashes, underscores, dots
if (! preg_match('/^[a-zA-Z0-9._-]+$/', $filename)) {
$fail('The :attribute may only contain letters, numbers, dashes, underscores, and dots.');
return;
}
// Check for reserved filenames (case-sensitive for coolify.yaml/yml, case-insensitive check not needed as Caddyfile is exact)
if (in_array($filename, self::RESERVED_FILENAMES, true)) {
$fail('The :attribute uses a reserved filename.');
return;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Rules/ValidIpOrCidr.php | app/Rules/ValidIpOrCidr.php | <?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class ValidIpOrCidr implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (empty($value)) {
// Empty is allowed (means allow from anywhere)
return;
}
// Special case: 0.0.0.0 is allowed
if ($value === '0.0.0.0') {
return;
}
$entries = explode(',', $value);
$invalidEntries = [];
foreach ($entries as $entry) {
$entry = trim($entry);
if (empty($entry)) {
continue;
}
// Special case: 0.0.0.0 with or without subnet
if (str_starts_with($entry, '0.0.0.0')) {
continue;
}
// Check if it's CIDR notation
if (str_contains($entry, '/')) {
$parts = explode('/', $entry);
if (count($parts) !== 2) {
$invalidEntries[] = $entry;
continue;
}
[$ip, $mask] = $parts;
if (! filter_var($ip, FILTER_VALIDATE_IP) || ! is_numeric($mask) || $mask < 0 || $mask > 32) {
$invalidEntries[] = $entry;
}
} else {
// Check if it's a valid IP
if (! filter_var($entry, FILTER_VALIDATE_IP)) {
$invalidEntries[] = $entry;
}
}
}
if (! empty($invalidEntries)) {
$fail('The following entries are not valid IP addresses or CIDR notations: '.implode(', ', $invalidEntries));
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Rules/ValidGitRepositoryUrl.php | app/Rules/ValidGitRepositoryUrl.php | <?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Log;
class ValidGitRepositoryUrl implements ValidationRule
{
protected bool $allowSSH;
protected bool $allowIP;
public function __construct(bool $allowSSH = true, bool $allowIP = false)
{
$this->allowSSH = $allowSSH;
$this->allowIP = $allowIP;
}
/**
* Run the validation rule.
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (empty($value)) {
return;
}
// Check for dangerous shell metacharacters that could be used for command injection
$dangerousChars = [
';', '|', '&', '$', '`', '(', ')', '{', '}',
'[', ']', '<', '>', '\n', '\r', '\0', '"', "'",
'\\', '!', '?', '*', '^', '%', '=', '+',
'#', // Comment character that could hide commands
];
foreach ($dangerousChars as $char) {
if (str_contains($value, $char)) {
Log::warning('Git repository URL validation failed - dangerous character', [
'url' => $value,
'character' => $char,
'ip' => request()->ip(),
'user_id' => auth()->id(),
]);
$fail('The :attribute contains invalid characters.');
return;
}
}
// Check for command substitution patterns
$dangerousPatterns = [
'/\$\(.*\)/', // Command substitution $(...)
'/\${.*}/', // Variable expansion ${...}
'/;;/', // Double semicolon
'/&&/', // Command chaining
'/\|\|/', // Command chaining
'/>>/', // Redirect append
'/<</', // Here document
'/\\\n/', // Line continuation
'/\.\.[\/\\\\]/', // Directory traversal
];
foreach ($dangerousPatterns as $pattern) {
if (preg_match($pattern, $value)) {
Log::warning('Git repository URL validation failed - dangerous pattern', [
'url' => $value,
'pattern' => $pattern,
'ip' => request()->ip(),
'user_id' => auth()->id(),
]);
$fail('The :attribute contains invalid patterns.');
return;
}
}
// Validate based on URL type
if (str_starts_with($value, 'git@')) {
if (! $this->allowSSH) {
$fail('SSH URLs are not allowed.');
return;
}
// Validate SSH URL format (git@host:user/repo.git)
if (! preg_match('/^git@[a-zA-Z0-9\.\-]+:[a-zA-Z0-9\-_\/\.~]+$/', $value)) {
$fail('The :attribute is not a valid SSH repository URL.');
return;
}
} elseif (str_starts_with($value, 'http://') || str_starts_with($value, 'https://')) {
// Validate HTTP(S) URL
if (! filter_var($value, FILTER_VALIDATE_URL)) {
$fail('The :attribute is not a valid URL.');
return;
}
$parsed = parse_url($value);
// Check for IP addresses if not allowed
if (! $this->allowIP && filter_var($parsed['host'] ?? '', FILTER_VALIDATE_IP)) {
Log::warning('Git repository URL contains IP address', [
'url' => $value,
'ip' => request()->ip(),
'user_id' => auth()->id(),
]);
$fail('The :attribute cannot use IP addresses.');
return;
}
// Check for localhost/internal addresses
$host = strtolower($parsed['host'] ?? '');
$internalHosts = ['localhost', '127.0.0.1', '0.0.0.0', '::1'];
if (in_array($host, $internalHosts) || str_ends_with($host, '.local')) {
Log::warning('Git repository URL points to internal host', [
'url' => $value,
'host' => $host,
'ip' => request()->ip(),
'user_id' => auth()->id(),
]);
$fail('The :attribute cannot point to internal hosts.');
return;
}
// Ensure no query parameters or fragments
if (! empty($parsed['query']) || ! empty($parsed['fragment'])) {
$fail('The :attribute should not contain query parameters or fragments.');
return;
}
// Validate path contains only safe characters
$path = $parsed['path'] ?? '';
if (! empty($path) && ! preg_match('/^[a-zA-Z0-9\-_\/\.@~]+$/', $path)) {
$fail('The :attribute path contains invalid characters.');
return;
}
} elseif (str_starts_with($value, 'git://')) {
// Validate git:// protocol URL (supports both git://host/path and git://host:port/path with tilde)
if (! preg_match('/^git:\/\/[a-zA-Z0-9\.\-]+(:[0-9]+)?[:\/][a-zA-Z0-9\-_\/\.~]+$/', $value)) {
$fail('The :attribute is not a valid git:// URL.');
return;
}
} else {
$fail('The :attribute must start with https://, http://, git://, or git@.');
return;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Rules/ValidCloudInitYaml.php | app/Rules/ValidCloudInitYaml.php | <?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Symfony\Component\Yaml\Exception\ParseException;
use Symfony\Component\Yaml\Yaml;
class ValidCloudInitYaml implements ValidationRule
{
/**
* Run the validation rule.
*
* Validates that the cloud-init script is either:
* - Valid YAML format (for cloud-config)
* - Valid bash script (starting with #!)
* - Empty/null (optional field)
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (empty($value)) {
return;
}
$script = trim($value);
// If it's a bash script (starts with shebang), skip YAML validation
if (str_starts_with($script, '#!')) {
return;
}
// If it's a cloud-config file (starts with #cloud-config), validate YAML
if (str_starts_with($script, '#cloud-config')) {
// Remove the #cloud-config header and validate the rest as YAML
$yamlContent = preg_replace('/^#cloud-config\s*/m', '', $script, 1);
try {
Yaml::parse($yamlContent);
} catch (ParseException $e) {
$fail('The :attribute must be valid YAML format. Error: '.$e->getMessage());
}
return;
}
// If it doesn't start with #! or #cloud-config, try to parse as YAML
// (some users might omit the #cloud-config header)
try {
Yaml::parse($script);
} catch (ParseException $e) {
$fail('The :attribute must be either a valid bash script (starting with #!) or valid cloud-config YAML. YAML parse 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/Rules/DockerImageFormat.php | app/Rules/DockerImageFormat.php | <?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class DockerImageFormat implements ValidationRule
{
/**
* Run the validation rule.
*
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
// Check if the value contains ":sha256:" or ":sha" which is incorrect format
if (preg_match('/:sha256?:/i', $value)) {
$fail('The :attribute must use @ before sha256 digest (e.g., image@sha256:hash, not image:sha256:hash).');
return;
}
// Valid formats:
// 1. image:tag (e.g., nginx:latest)
// 2. registry/image:tag (e.g., ghcr.io/user/app:v1.2.3)
// 3. image@sha256:hash (e.g., nginx@sha256:abc123...)
// 4. registry/image@sha256:hash
// 5. registry:port/image:tag (e.g., localhost:5000/app:latest)
$pattern = '/^
(?:[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[0-9]+)?\/)? # Optional registry with optional port
[a-z0-9]+(?:[._\/-][a-z0-9]+)* # Image name (required)
(?::[a-z0-9][a-z0-9._-]*|@sha256:[a-f0-9]{64})? # Optional :tag or @sha256:hash
$/ix';
if (! preg_match($pattern, $value)) {
$fail('The :attribute format is invalid. Use image:tag or image@sha256:hash format.');
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Rules/ValidGitBranch.php | app/Rules/ValidGitBranch.php | <?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Log;
class ValidGitBranch implements ValidationRule
{
/**
* Run the validation rule.
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (empty($value)) {
return;
}
$branch = trim($value);
// Check for dangerous shell metacharacters
$dangerousChars = [
';', '|', '&', '$', '`', '(', ')', '{', '}',
'<', '>', '\n', '\r', '\0', '"', "'", '\\',
'!', '*', '?', '[', ']', '~', '^', ':', ' ',
'#',
];
foreach ($dangerousChars as $char) {
if (str_contains($branch, $char)) {
Log::warning('Git branch validation failed - dangerous character', [
'branch' => $branch,
'character' => $char,
'ip' => request()->ip(),
'user_id' => auth()->id(),
]);
$fail('The :attribute contains invalid characters.');
return;
}
}
// Git branch name rules:
// - Cannot contain: .., //, @{
// - Cannot start or end with: / or .
// - Cannot be empty after trimming
if (str_contains($branch, '..') ||
str_contains($branch, '//') ||
str_contains($branch, '@{')) {
$fail('The :attribute contains invalid patterns.');
return;
}
if (str_starts_with($branch, '/') ||
str_ends_with($branch, '/') ||
str_starts_with($branch, '.') ||
str_ends_with($branch, '.')) {
$fail('The :attribute cannot start or end with / or .');
return;
}
// Allow only safe characters for branch names
// Letters, numbers, hyphens, underscores, forward slashes, and dots
if (! preg_match('/^[a-zA-Z0-9\-_\/\.]+$/', $branch)) {
$fail('The :attribute contains invalid characters. Only letters, numbers, hyphens, underscores, forward slashes, and dots are allowed.');
return;
}
// Additional Git-specific validations
// Branch name cannot be 'HEAD'
if ($branch === 'HEAD') {
$fail('The :attribute cannot be HEAD.');
return;
}
// Check for consecutive dots (not allowed in Git)
if (str_contains($branch, '..')) {
$fail('The :attribute cannot contain consecutive dots.');
return;
}
// Check for .lock suffix (reserved by Git)
if (str_ends_with($branch, '.lock')) {
$fail('The :attribute cannot end with .lock.');
return;
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Rules/ValidHostname.php | app/Rules/ValidHostname.php | <?php
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Log;
class ValidHostname implements ValidationRule
{
/**
* Run the validation rule.
*
* Validates hostname according to RFC 1123:
* - Must be 1-253 characters total
* - Each label (segment between dots) must be 1-63 characters
* - Labels can contain lowercase letters (a-z), digits (0-9), and hyphens (-)
* - Labels cannot start or end with a hyphen
* - Labels cannot be all numeric
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
if (empty($value)) {
return;
}
$hostname = trim($value);
// Check total length (RFC 1123: max 253 characters)
if (strlen($hostname) > 253) {
$fail('The :attribute must not exceed 253 characters.');
return;
}
// Check for dangerous shell metacharacters
$dangerousChars = [
';', '|', '&', '$', '`', '(', ')', '{', '}',
'<', '>', '\n', '\r', '\0', '"', "'", '\\',
'!', '*', '?', '[', ']', '~', '^', ':', '#',
'@', '%', '=', '+', ',', ' ',
];
foreach ($dangerousChars as $char) {
if (str_contains($hostname, $char)) {
try {
$logData = [
'hostname' => $hostname,
'character' => $char,
];
if (function_exists('request') && app()->has('request')) {
$logData['ip'] = request()->ip();
}
if (function_exists('auth') && app()->has('auth')) {
$logData['user_id'] = auth()->id();
}
Log::warning('Hostname validation failed - dangerous character', $logData);
} catch (\Throwable $e) {
// Ignore errors when facades are not available (e.g., in unit tests)
}
$fail('The :attribute contains invalid characters. Only lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.) are allowed.');
return;
}
}
// Additional validation: hostname should not start or end with a dot
if (str_starts_with($hostname, '.') || str_ends_with($hostname, '.')) {
$fail('The :attribute cannot start or end with a dot.');
return;
}
// Check for consecutive dots
if (str_contains($hostname, '..')) {
$fail('The :attribute cannot contain consecutive dots.');
return;
}
// Split into labels (segments between dots)
$labels = explode('.', $hostname);
foreach ($labels as $label) {
// Check label length (RFC 1123: max 63 characters per label)
if (strlen($label) < 1 || strlen($label) > 63) {
$fail('The :attribute contains an invalid label. Each segment must be 1-63 characters.');
return;
}
// Check if label starts or ends with hyphen
if (str_starts_with($label, '-') || str_ends_with($label, '-')) {
$fail('The :attribute contains an invalid label. Labels cannot start or end with a hyphen.');
return;
}
// Check if label contains only valid characters (lowercase letters, digits, hyphens)
if (! preg_match('/^[a-z0-9-]+$/', $label)) {
$fail('The :attribute contains invalid characters. Only lowercase letters (a-z), numbers (0-9), hyphens (-), and dots (.) are allowed.');
return;
}
// RFC 1123 allows labels to be all numeric (unlike RFC 952)
// So we don't need to check for all-numeric labels
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Services/ProxyDashboardCacheService.php | app/Services/ProxyDashboardCacheService.php | <?php
namespace App\Services;
use App\Models\Server;
use Illuminate\Support\Facades\Cache;
class ProxyDashboardCacheService
{
/**
* Get Redis cache key for Traefik dashboard availability
*/
public static function getCacheKey(Server $server): string
{
return "server:{$server->id}:traefik:dashboard_available";
}
/**
* Check if Traefik dashboard is available from configuration
*/
public static function isTraefikDashboardAvailableFromConfiguration(Server $server, string $proxy_configuration): void
{
$cacheKey = static::getCacheKey($server);
$dashboardAvailable = str($proxy_configuration)->contains('--api.dashboard=true') &&
str($proxy_configuration)->contains('--api.insecure=true');
Cache::forever($cacheKey, $dashboardAvailable);
}
/**
* Check if Traefik dashboard is available (from cache or compute)
*/
public static function isTraefikDashboardAvailableFromCache(Server $server): bool
{
$cacheKey = static::getCacheKey($server);
return Cache::get($cacheKey) ?? false;
}
/**
* Clear Traefik dashboard cache for a server
*/
public static function clearCache(Server $server): void
{
Cache::forget(static::getCacheKey($server));
}
/**
* Clear Traefik dashboard cache for multiple servers
*/
public static function clearCacheForServers(array $serverIds): void
{
foreach ($serverIds as $serverId) {
$cacheKey = "server:{$serverId}:traefik:dashboard_available";
Cache::forget($cacheKey);
}
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Services/ChangelogService.php | app/Services/ChangelogService.php | <?php
namespace App\Services;
use App\Models\User;
use App\Models\UserChangelogRead;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Spatie\LaravelMarkdown\MarkdownRenderer;
class ChangelogService
{
public function getEntries(int $recentMonths = 3): Collection
{
// For backward compatibility, check if old changelog.json exists
if (file_exists(base_path('changelog.json'))) {
$data = $this->fetchChangelogData();
if (! $data || ! isset($data['entries'])) {
return collect();
}
return collect($data['entries'])
->filter(fn ($entry) => $this->validateEntryData($entry))
->map(function ($entry) {
$entry['published_at'] = Carbon::parse($entry['published_at']);
$entry['content_html'] = $this->parseMarkdown($entry['content']);
return (object) $entry;
})
->filter(fn ($entry) => $entry->published_at <= now())
->sortBy('published_at')
->reverse()
->values();
}
// Load entries from recent months for performance
$availableMonths = $this->getAvailableMonths();
$monthsToLoad = $availableMonths->take($recentMonths);
return $monthsToLoad
->flatMap(fn ($month) => $this->getEntriesForMonth($month))
->sortBy('published_at')
->reverse()
->values();
}
public function getAllEntries(): Collection
{
$availableMonths = $this->getAvailableMonths();
return $availableMonths
->flatMap(fn ($month) => $this->getEntriesForMonth($month))
->sortBy('published_at')
->reverse()
->values();
}
public function getEntriesForUser(User $user): Collection
{
$entries = $this->getEntries();
$readIdentifiers = UserChangelogRead::getReadIdentifiersForUser($user->id);
return $entries->map(function ($entry) use ($readIdentifiers) {
$entry->is_read = in_array($entry->tag_name, $readIdentifiers);
return $entry;
})->sortBy([
['is_read', 'asc'], // unread first
['published_at', 'desc'], // then by date
])->values();
}
public function getUnreadCountForUser(User $user): int
{
if (isDev()) {
$entries = $this->getEntries();
$readIdentifiers = UserChangelogRead::getReadIdentifiersForUser($user->id);
return $entries->reject(fn ($entry) => in_array($entry->tag_name, $readIdentifiers))->count();
} else {
return Cache::remember(
'user_unread_changelog_count_'.$user->id,
now()->addHour(),
function () use ($user) {
$entries = $this->getEntries();
$readIdentifiers = UserChangelogRead::getReadIdentifiersForUser($user->id);
return $entries->reject(fn ($entry) => in_array($entry->tag_name, $readIdentifiers))->count();
}
);
}
}
public function getAvailableMonths(): Collection
{
$pattern = base_path('changelogs/*.json');
$files = glob($pattern);
if ($files === false) {
return collect();
}
return collect($files)
->map(fn ($file) => basename($file, '.json'))
->filter(fn ($name) => preg_match('/^\d{4}-\d{2}$/', $name))
->sort()
->reverse()
->values();
}
public function getEntriesForMonth(string $month): Collection
{
$path = base_path("changelogs/{$month}.json");
if (! file_exists($path)) {
return collect();
}
$content = file_get_contents($path);
if ($content === false) {
Log::error("Failed to read changelog file: {$month}.json");
return collect();
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Log::error("Invalid JSON in {$month}.json: ".json_last_error_msg());
return collect();
}
if (! isset($data['entries']) || ! is_array($data['entries'])) {
return collect();
}
return collect($data['entries'])
->filter(fn ($entry) => $this->validateEntryData($entry))
->map(function ($entry) {
$entry['published_at'] = Carbon::parse($entry['published_at']);
$entry['content_html'] = $this->parseMarkdown($entry['content']);
return (object) $entry;
})
->filter(fn ($entry) => $entry->published_at <= now())
->sortBy('published_at')
->reverse()
->values();
}
private function fetchChangelogData(): ?array
{
// Legacy support for old changelog.json
$path = base_path('changelog.json');
if (file_exists($path)) {
$content = file_get_contents($path);
if ($content === false) {
Log::error('Failed to read changelog.json file');
return null;
}
$data = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
Log::error('Invalid JSON in changelog.json: '.json_last_error_msg());
return null;
}
return $data;
}
// New monthly structure - combine all months
$allEntries = [];
foreach ($this->getAvailableMonths() as $month) {
$monthEntries = $this->getEntriesForMonth($month);
foreach ($monthEntries as $entry) {
$allEntries[] = (array) $entry;
}
}
return ['entries' => $allEntries];
}
public function markAsReadForUser(string $version, User $user): void
{
UserChangelogRead::markAsRead($user->id, $version);
Cache::forget('user_unread_changelog_count_'.$user->id);
}
public function markAllAsReadForUser(User $user): void
{
$entries = $this->getEntries();
foreach ($entries as $entry) {
UserChangelogRead::markAsRead($user->id, $entry->tag_name);
}
Cache::forget('user_unread_changelog_count_'.$user->id);
}
private function validateEntryData(array $data): bool
{
$required = ['tag_name', 'title', 'content', 'published_at'];
foreach ($required as $field) {
if (! isset($data[$field]) || empty($data[$field])) {
return false;
}
}
return true;
}
public function clearAllReadStatus(): array
{
try {
$count = UserChangelogRead::count();
UserChangelogRead::truncate();
// Clear all user caches
$this->clearAllUserCaches();
return [
'success' => true,
'message' => "Successfully cleared {$count} read status records",
];
} catch (\Exception $e) {
Log::error('Failed to clear read status: '.$e->getMessage());
return [
'success' => false,
'message' => 'Failed to clear read status: '.$e->getMessage(),
];
}
}
private function clearAllUserCaches(): void
{
$users = User::select('id')->get();
foreach ($users as $user) {
Cache::forget('user_unread_changelog_count_'.$user->id);
}
}
private function parseMarkdown(string $content): string
{
$renderer = app(MarkdownRenderer::class);
$html = $renderer->toHtml($content);
// Apply custom Tailwind CSS classes for dark mode compatibility
$html = $this->applyCustomStyling($html);
return $html;
}
private function applyCustomStyling(string $html): string
{
// Headers
$html = preg_replace('/<h1[^>]*>/', '<h1 class="text-xl font-bold dark:text-white mb-2">', $html);
$html = preg_replace('/<h2[^>]*>/', '<h2 class="text-lg font-semibold dark:text-white mb-2">', $html);
$html = preg_replace('/<h3[^>]*>/', '<h3 class="text-md font-semibold dark:text-white mb-1">', $html);
// Paragraphs
$html = preg_replace('/<p[^>]*>/', '<p class="mb-2 dark:text-neutral-300">', $html);
// Lists
$html = preg_replace('/<ul[^>]*>/', '<ul class="mb-2 ml-4 list-disc">', $html);
$html = preg_replace('/<ol[^>]*>/', '<ol class="mb-2 ml-4 list-decimal">', $html);
$html = preg_replace('/<li[^>]*>/', '<li class="dark:text-neutral-300">', $html);
// Code blocks and inline code
$html = preg_replace('/<pre[^>]*>/', '<pre class="bg-gray-100 dark:bg-coolgray-300 p-2 rounded text-sm overflow-x-auto my-2">', $html);
$html = preg_replace('/<code[^>]*>/', '<code class="bg-gray-100 dark:bg-coolgray-300 px-1 py-0.5 rounded text-sm">', $html);
// Links - Apply styling to existing markdown links
$html = preg_replace('/<a([^>]*)>/', '<a$1 class="text-blue-500 hover:text-blue-600 underline" target="_blank" rel="noopener">', $html);
// Convert plain URLs to clickable links (that aren't already in <a> tags)
$html = preg_replace('/(?<!href="|href=\')(?<!>)(?<!\/)(https?:\/\/[^\s<>"]+)(?![^<]*<\/a>)/', '<a href="$1" class="text-blue-500 hover:text-blue-600 underline" target="_blank" rel="noopener">$1</a>', $html);
// Strong/bold text
$html = preg_replace('/<strong[^>]*>/', '<strong class="font-semibold dark:text-white">', $html);
// Emphasis/italic text
$html = preg_replace('/<em[^>]*>/', '<em class="italic dark:text-neutral-300">', $html);
return $html;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Services/ContainerStatusAggregator.php | app/Services/ContainerStatusAggregator.php | <?php
namespace App\Services;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
/**
* Container Status Aggregator Service
*
* Centralized service for aggregating container statuses into a single status string.
* Uses a priority-based state machine to determine the overall status from multiple containers.
*
* Output Format: Colon-separated (e.g., "running:healthy", "degraded:unhealthy")
* This format is used throughout the backend for consistency and machine-readability.
* UI components transform this to human-readable format (e.g., "Running (Healthy)").
*
* State Priority (highest to lowest):
* 1. Degraded (from sub-resources) β degraded:unhealthy
* 2. Restarting β degraded:unhealthy (or restarting:unknown if preserveRestarting=true)
* 3. Crash Loop (exited with restarts) β degraded:unhealthy
* 4. Mixed (running + exited) β degraded:unhealthy
* 5. Mixed (running + starting) β starting:unknown
* 6. Running β running:healthy/unhealthy/unknown
* 7. Dead/Removing β degraded:unhealthy
* 8. Paused β paused:unknown
* 9. Starting/Created β starting:unknown
* 10. Exited β exited
*
* The $preserveRestarting parameter controls whether "restarting" containers should be
* reported as "restarting:unknown" (true) or "degraded:unhealthy" (false, default).
* - Use preserveRestarting=true for individual sub-resources (ServiceApplication/ServiceDatabase)
* so they show "Restarting" in the UI.
* - Use preserveRestarting=false for overall Service status aggregation where any restarting
* container should mark the entire service as "Degraded".
*/
class ContainerStatusAggregator
{
/**
* Aggregate container statuses from status strings into a single status.
*
* @param Collection $containerStatuses Collection of status strings (e.g., "running (healthy)", "running:healthy")
* @param int $maxRestartCount Maximum restart count across containers (for crash loop detection)
* @param bool $preserveRestarting If true, "restarting" containers return "restarting:unknown" instead of "degraded:unhealthy"
* @return string Aggregated status in colon format (e.g., "running:healthy")
*/
public function aggregateFromStrings(Collection $containerStatuses, int $maxRestartCount = 0, bool $preserveRestarting = false): string
{
// Validate maxRestartCount parameter
if ($maxRestartCount < 0) {
Log::warning('Negative maxRestartCount corrected to 0', [
'original_value' => $maxRestartCount,
]);
$maxRestartCount = 0;
}
if ($maxRestartCount > 1000) {
Log::warning('High maxRestartCount detected', [
'maxRestartCount' => $maxRestartCount,
'containers' => $containerStatuses->count(),
]);
}
if ($containerStatuses->isEmpty()) {
return 'exited';
}
// Initialize state flags
$hasRunning = false;
$hasRestarting = false;
$hasUnhealthy = false;
$hasUnknown = false;
$hasExited = false;
$hasStarting = false;
$hasPaused = false;
$hasDead = false;
$hasDegraded = false;
// Parse each status string and set flags
foreach ($containerStatuses as $status) {
if (str($status)->contains('degraded')) {
$hasDegraded = true;
if (str($status)->contains('unhealthy')) {
$hasUnhealthy = true;
}
} elseif (str($status)->contains('restarting')) {
$hasRestarting = true;
} elseif (str($status)->contains('running')) {
$hasRunning = true;
if (str($status)->contains('unhealthy')) {
$hasUnhealthy = true;
}
if (str($status)->contains('unknown')) {
$hasUnknown = true;
}
} elseif (str($status)->contains('exited')) {
$hasExited = true;
} elseif (str($status)->contains('created') || str($status)->contains('starting')) {
$hasStarting = true;
} elseif (str($status)->contains('paused')) {
$hasPaused = true;
} elseif (str($status)->contains('dead') || str($status)->contains('removing')) {
$hasDead = true;
}
}
// Priority-based status resolution
return $this->resolveStatus(
$hasRunning,
$hasRestarting,
$hasUnhealthy,
$hasUnknown,
$hasExited,
$hasStarting,
$hasPaused,
$hasDead,
$hasDegraded,
$maxRestartCount,
$preserveRestarting
);
}
/**
* Aggregate container statuses from Docker container objects.
*
* @param Collection $containers Collection of Docker container objects with State property
* @param int $maxRestartCount Maximum restart count across containers (for crash loop detection)
* @param bool $preserveRestarting If true, "restarting" containers return "restarting:unknown" instead of "degraded:unhealthy"
* @return string Aggregated status in colon format (e.g., "running:healthy")
*/
public function aggregateFromContainers(Collection $containers, int $maxRestartCount = 0, bool $preserveRestarting = false): string
{
// Validate maxRestartCount parameter
if ($maxRestartCount < 0) {
Log::warning('Negative maxRestartCount corrected to 0', [
'original_value' => $maxRestartCount,
]);
$maxRestartCount = 0;
}
if ($maxRestartCount > 1000) {
Log::warning('High maxRestartCount detected', [
'maxRestartCount' => $maxRestartCount,
'containers' => $containers->count(),
]);
}
if ($containers->isEmpty()) {
return 'exited';
}
// Initialize state flags
$hasRunning = false;
$hasRestarting = false;
$hasUnhealthy = false;
$hasUnknown = false;
$hasExited = false;
$hasStarting = false;
$hasPaused = false;
$hasDead = false;
// Parse each container object and set flags
foreach ($containers as $container) {
$state = data_get($container, 'State.Status', 'exited');
$health = data_get($container, 'State.Health.Status');
if ($state === 'restarting') {
$hasRestarting = true;
} elseif ($state === 'running') {
$hasRunning = true;
if ($health === 'unhealthy') {
$hasUnhealthy = true;
} elseif (is_null($health) || $health === 'starting') {
$hasUnknown = true;
}
} elseif ($state === 'exited') {
$hasExited = true;
} elseif ($state === 'created' || $state === 'starting') {
$hasStarting = true;
} elseif ($state === 'paused') {
$hasPaused = true;
} elseif ($state === 'dead' || $state === 'removing') {
$hasDead = true;
}
}
// Priority-based status resolution
return $this->resolveStatus(
$hasRunning,
$hasRestarting,
$hasUnhealthy,
$hasUnknown,
$hasExited,
$hasStarting,
$hasPaused,
$hasDead,
false, // $hasDegraded - not applicable for container objects, only for status strings
$maxRestartCount,
$preserveRestarting
);
}
/**
* Resolve the aggregated status based on state flags (priority-based state machine).
*
* @param bool $hasRunning Has at least one running container
* @param bool $hasRestarting Has at least one restarting container
* @param bool $hasUnhealthy Has at least one unhealthy container
* @param bool $hasUnknown Has at least one container with unknown health
* @param bool $hasExited Has at least one exited container
* @param bool $hasStarting Has at least one starting/created container
* @param bool $hasPaused Has at least one paused container
* @param bool $hasDead Has at least one dead/removing container
* @param bool $hasDegraded Has at least one degraded container
* @param int $maxRestartCount Maximum restart count (for crash loop detection)
* @param bool $preserveRestarting If true, return "restarting:unknown" instead of "degraded:unhealthy" for restarting containers
* @return string Status in colon format (e.g., "running:healthy")
*/
private function resolveStatus(
bool $hasRunning,
bool $hasRestarting,
bool $hasUnhealthy,
bool $hasUnknown,
bool $hasExited,
bool $hasStarting,
bool $hasPaused,
bool $hasDead,
bool $hasDegraded,
int $maxRestartCount,
bool $preserveRestarting = false
): string {
// Priority 1: Degraded containers from sub-resources (highest priority)
// If any service/application within a service stack is degraded, the entire stack is degraded
if ($hasDegraded) {
return 'degraded:unhealthy';
}
// Priority 2: Restarting containers
// When preserveRestarting is true (for individual sub-resources), keep as "restarting"
// When false (for overall service status), mark as "degraded"
if ($hasRestarting) {
return $preserveRestarting ? 'restarting:unknown' : 'degraded:unhealthy';
}
// Priority 3: Crash loop detection (exited with restart count > 0)
if ($hasExited && $maxRestartCount > 0) {
return 'degraded:unhealthy';
}
// Priority 4: Mixed state (some running, some exited = degraded)
if ($hasRunning && $hasExited) {
return 'degraded:unhealthy';
}
// Priority 5: Mixed state (some running, some starting = still starting)
// If any component is still starting, the entire service stack is not fully ready
if ($hasRunning && $hasStarting) {
return 'starting:unknown';
}
// Priority 6: Running containers (check health status)
if ($hasRunning) {
if ($hasUnhealthy) {
return 'running:unhealthy';
} elseif ($hasUnknown) {
return 'running:unknown';
} else {
return 'running:healthy';
}
}
// Priority 7: Dead or removing containers
if ($hasDead) {
return 'degraded:unhealthy';
}
// Priority 8: Paused containers
if ($hasPaused) {
return 'paused:unknown';
}
// Priority 9: Starting/created containers
if ($hasStarting) {
return 'starting:unknown';
}
// Priority 10: All containers exited (no restart count = truly stopped)
return 'exited';
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Services/ConfigurationGenerator.php | app/Services/ConfigurationGenerator.php | <?php
namespace App\Services;
use App\Models\Application;
use Symfony\Component\Yaml\Yaml;
class ConfigurationGenerator
{
protected array $config = [];
public function __construct(protected Application $resource)
{
$this->generateConfig();
}
protected function generateConfig(): void
{
if ($this->resource instanceof Application) {
$this->config = [
'id' => $this->resource->id,
'name' => $this->resource->name,
'uuid' => $this->resource->uuid,
'description' => $this->resource->description,
'coolify_details' => [
'project_uuid' => $this->resource->project()->uuid,
'environment_uuid' => $this->resource->environment->uuid,
'destination_type' => $this->resource->destination_type,
'destination_id' => $this->resource->destination_id,
'source_type' => $this->resource->source_type,
'source_id' => $this->resource->source_id,
'private_key_id' => $this->resource->private_key_id,
],
'post_deployment_command' => $this->resource->post_deployment_command,
'post_deployment_command_container' => $this->resource->post_deployment_command_container,
'pre_deployment_command' => $this->resource->pre_deployment_command,
'pre_deployment_command_container' => $this->resource->pre_deployment_command_container,
'build' => [
'type' => $this->resource->build_pack,
'static_image' => $this->resource->static_image,
'base_directory' => $this->resource->base_directory,
'publish_directory' => $this->resource->publish_directory,
'dockerfile' => $this->resource->dockerfile,
'dockerfile_location' => $this->resource->dockerfile_location,
'dockerfile_target_build' => $this->resource->dockerfile_target_build,
'custom_docker_run_options' => $this->resource->custom_docker_options,
'compose_parsing_version' => $this->resource->compose_parsing_version,
'docker_compose' => $this->resource->docker_compose,
'docker_compose_location' => $this->resource->docker_compose_location,
'docker_compose_raw' => $this->resource->docker_compose_raw,
'docker_compose_domains' => $this->resource->docker_compose_domains,
'docker_compose_custom_start_command' => $this->resource->docker_compose_custom_start_command,
'docker_compose_custom_build_command' => $this->resource->docker_compose_custom_build_command,
'install_command' => $this->resource->install_command,
'build_command' => $this->resource->build_command,
'start_command' => $this->resource->start_command,
'watch_paths' => $this->resource->watch_paths,
],
'source' => [
'git_repository' => $this->resource->git_repository,
'git_branch' => $this->resource->git_branch,
'git_commit_sha' => $this->resource->git_commit_sha,
'repository_project_id' => $this->resource->repository_project_id,
],
'docker_registry_image' => $this->getDockerRegistryImage(),
'domains' => [
'fqdn' => $this->resource->fqdn,
'ports_exposes' => $this->resource->ports_exposes,
'ports_mappings' => $this->resource->ports_mappings,
'redirect' => $this->resource->redirect,
'custom_nginx_configuration' => $this->resource->custom_nginx_configuration,
],
'environment_variables' => [
'production' => $this->getEnvironmentVariables(),
'preview' => $this->getPreviewEnvironmentVariables(),
],
'settings' => $this->getApplicationSettings(),
'preview' => $this->getPreview(),
'limits' => $this->resource->getLimits(),
'health_check' => [
'health_check_path' => $this->resource->health_check_path,
'health_check_port' => $this->resource->health_check_port,
'health_check_host' => $this->resource->health_check_host,
'health_check_method' => $this->resource->health_check_method,
'health_check_return_code' => $this->resource->health_check_return_code,
'health_check_scheme' => $this->resource->health_check_scheme,
'health_check_response_text' => $this->resource->health_check_response_text,
'health_check_interval' => $this->resource->health_check_interval,
'health_check_timeout' => $this->resource->health_check_timeout,
'health_check_retries' => $this->resource->health_check_retries,
'health_check_start_period' => $this->resource->health_check_start_period,
'health_check_enabled' => $this->resource->health_check_enabled,
],
'webhooks_secrets' => [
'manual_webhook_secret_github' => $this->resource->manual_webhook_secret_github,
'manual_webhook_secret_gitlab' => $this->resource->manual_webhook_secret_gitlab,
'manual_webhook_secret_bitbucket' => $this->resource->manual_webhook_secret_bitbucket,
'manual_webhook_secret_gitea' => $this->resource->manual_webhook_secret_gitea,
],
'swarm' => [
'swarm_replicas' => $this->resource->swarm_replicas,
'swarm_placement_constraints' => $this->resource->swarm_placement_constraints,
],
];
}
}
protected function getPreview(): array
{
return [
'preview_url_template' => $this->resource->preview_url_template,
];
}
protected function getDockerRegistryImage(): array
{
return [
'image' => $this->resource->docker_registry_image_name,
'tag' => $this->resource->docker_registry_image_tag,
];
}
protected function getEnvironmentVariables(): array
{
$variables = collect([]);
foreach ($this->resource->environment_variables as $env) {
$variables->push([
'key' => $env->key,
'value' => $env->value,
'is_preview' => $env->is_preview,
'is_multiline' => $env->is_multiline,
]);
}
return $variables->toArray();
}
protected function getPreviewEnvironmentVariables(): array
{
$variables = collect([]);
foreach ($this->resource->environment_variables_preview as $env) {
$variables->push([
'key' => $env->key,
'value' => $env->value,
'is_preview' => $env->is_preview,
'is_multiline' => $env->is_multiline,
]);
}
return $variables->toArray();
}
protected function getApplicationSettings(): array
{
$removedKeys = ['id', 'application_id', 'created_at', 'updated_at'];
$settings = $this->resource->settings->attributesToArray();
$settings = collect($settings)->filter(function ($value, $key) use ($removedKeys) {
return ! in_array($key, $removedKeys);
})->sortBy(function ($value, $key) {
return $key;
})->toArray();
return $settings;
}
public function saveJson(string $path): void
{
file_put_contents($path, json_encode($this->config, JSON_PRETTY_PRINT));
}
public function saveYaml(string $path): void
{
file_put_contents($path, Yaml::dump($this->config, 6, 2));
}
public function toArray(): array
{
return $this->config;
}
public function toJson(): string
{
return json_encode($this->config, JSON_PRETTY_PRINT);
}
public function toYaml(): string
{
return Yaml::dump($this->config, 6, 2);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Services/HetznerService.php | app/Services/HetznerService.php | <?php
namespace App\Services;
use App\Exceptions\RateLimitException;
use Illuminate\Support\Facades\Http;
class HetznerService
{
private string $token;
private string $baseUrl = 'https://api.hetzner.cloud/v1';
public function __construct(string $token)
{
$this->token = $token;
}
private function request(string $method, string $endpoint, array $data = [])
{
$response = Http::withHeaders([
'Authorization' => 'Bearer '.$this->token,
])
->timeout(30)
->retry(3, function (int $attempt, \Exception $exception) {
// Handle rate limiting (429 Too Many Requests)
if ($exception instanceof \Illuminate\Http\Client\RequestException) {
$response = $exception->response;
if ($response && $response->status() === 429) {
// Get rate limit reset timestamp from headers
$resetTime = $response->header('RateLimit-Reset');
if ($resetTime) {
// Calculate wait time until rate limit resets
$waitSeconds = max(0, $resetTime - time());
// Cap wait time at 60 seconds for safety
return min($waitSeconds, 60) * 1000;
}
}
}
// Exponential backoff for other retriable errors: 100ms, 200ms, 400ms
return $attempt * 100;
})
->{$method}($this->baseUrl.$endpoint, $data);
if (! $response->successful()) {
if ($response->status() === 429) {
$retryAfter = $response->header('Retry-After');
if ($retryAfter === null) {
$resetTime = $response->header('RateLimit-Reset');
$retryAfter = $resetTime ? max(0, (int) $resetTime - time()) : null;
}
throw new RateLimitException(
'Rate limit exceeded. Please try again later.',
$retryAfter !== null ? (int) $retryAfter : null
);
}
throw new \Exception('Hetzner API error: '.$response->json('error.message', 'Unknown error'));
}
return $response->json();
}
private function requestPaginated(string $method, string $endpoint, string $resourceKey, array $data = []): array
{
$allResults = [];
$page = 1;
do {
$data['page'] = $page;
$data['per_page'] = 50;
$response = $this->request($method, $endpoint, $data);
if (isset($response[$resourceKey])) {
$allResults = array_merge($allResults, $response[$resourceKey]);
}
$nextPage = $response['meta']['pagination']['next_page'] ?? null;
$page = $nextPage;
} while ($nextPage !== null);
return $allResults;
}
public function getLocations(): array
{
return $this->requestPaginated('get', '/locations', 'locations');
}
public function getImages(): array
{
return $this->requestPaginated('get', '/images', 'images', [
'type' => 'system',
]);
}
public function getServerTypes(): array
{
$types = $this->requestPaginated('get', '/server_types', 'server_types');
// Filter out entries where "deprecated" is explicitly true
$filtered = array_filter($types, function ($type) {
return ! (isset($type['deprecated']) && $type['deprecated'] === true);
});
return array_values($filtered);
}
public function getSshKeys(): array
{
return $this->requestPaginated('get', '/ssh_keys', 'ssh_keys');
}
public function uploadSshKey(string $name, string $publicKey): array
{
$response = $this->request('post', '/ssh_keys', [
'name' => $name,
'public_key' => $publicKey,
]);
return $response['ssh_key'] ?? [];
}
public function createServer(array $params): array
{
ray('Hetzner createServer request', [
'endpoint' => '/servers',
'params' => $params,
]);
$response = $this->request('post', '/servers', $params);
ray('Hetzner createServer response', [
'response' => $response,
]);
return $response['server'] ?? [];
}
public function getServer(int $serverId): array
{
$response = $this->request('get', "/servers/{$serverId}");
return $response['server'] ?? [];
}
public function powerOnServer(int $serverId): array
{
$response = $this->request('post', "/servers/{$serverId}/actions/poweron");
return $response['action'] ?? [];
}
public function deleteServer(int $serverId): void
{
$this->request('delete', "/servers/{$serverId}");
}
public function getServers(): array
{
return $this->requestPaginated('get', '/servers', 'servers');
}
public function findServerByIp(string $ip): ?array
{
$servers = $this->getServers();
foreach ($servers as $server) {
// Check IPv4
$ipv4 = data_get($server, 'public_net.ipv4.ip');
if ($ipv4 === $ip) {
return $server;
}
// Check IPv6 (Hetzner returns the full /64 block)
$ipv6 = data_get($server, 'public_net.ipv6.ip');
if ($ipv6 && str_starts_with($ip, rtrim($ipv6, '/'))) {
return $server;
}
}
return null;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Services/DockerImageParser.php | app/Services/DockerImageParser.php | <?php
namespace App\Services;
class DockerImageParser
{
private string $registryUrl = '';
private string $imageName = '';
private string $tag = 'latest';
private bool $isImageHash = false;
public function parse(string $imageString): self
{
// Check for @sha256: format first (e.g., nginx@sha256:abc123...)
if (preg_match('/^(.+)@sha256:([a-f0-9]{64})$/i', $imageString, $matches)) {
$mainPart = $matches[1];
$this->tag = $matches[2];
$this->isImageHash = true;
} else {
// Split by : to handle the tag, but be careful with registry ports
$lastColon = strrpos($imageString, ':');
$hasSlash = str_contains($imageString, '/');
// If the last colon appears after the last slash, it's a tag
// Otherwise it might be a port in the registry URL
if ($lastColon !== false && (! $hasSlash || $lastColon > strrpos($imageString, '/'))) {
$mainPart = substr($imageString, 0, $lastColon);
$this->tag = substr($imageString, $lastColon + 1);
// Check if the tag is a SHA256 hash
$this->isImageHash = $this->isSha256Hash($this->tag);
} else {
$mainPart = $imageString;
$this->tag = 'latest';
$this->isImageHash = false;
}
}
// Split the main part by / to handle registry and image name
$pathParts = explode('/', $mainPart);
// If we have more than one part and the first part contains a dot or colon
// it's likely a registry URL
if (count($pathParts) > 1 && (str_contains($pathParts[0], '.') || str_contains($pathParts[0], ':'))) {
$this->registryUrl = array_shift($pathParts);
$this->imageName = implode('/', $pathParts);
} else {
$this->imageName = $mainPart;
}
return $this;
}
/**
* Check if the given string is a SHA256 hash
*/
private function isSha256Hash(string $hash): bool
{
// SHA256 hashes are 64 characters long and contain only hexadecimal characters
return preg_match('/^[a-f0-9]{64}$/i', $hash) === 1;
}
/**
* Check if the current tag is an image hash
*/
public function isImageHash(): bool
{
return $this->isImageHash;
}
/**
* Get the full image name with hash if present
*/
public function getFullImageNameWithHash(): string
{
$imageName = $this->getFullImageNameWithoutTag();
if ($this->isImageHash) {
return $imageName.'@sha256:'.$this->tag;
}
return $imageName.':'.$this->tag;
}
public function getFullImageNameWithoutTag(): string
{
if ($this->registryUrl) {
return $this->registryUrl.'/'.$this->imageName;
}
return $this->imageName;
}
public function getRegistryUrl(): string
{
return $this->registryUrl;
}
public function getImageName(): string
{
return $this->imageName;
}
public function getTag(): string
{
return $this->tag;
}
public function toString(): string
{
$parts = [];
if ($this->registryUrl) {
$parts[] = $this->registryUrl;
}
$parts[] = $this->imageName;
if ($this->isImageHash) {
return implode('/', $parts).'@sha256:'.$this->tag;
}
return implode('/', $parts).':'.$this->tag;
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Services/ConfigurationRepository.php | app/Services/ConfigurationRepository.php | <?php
namespace App\Services;
use Illuminate\Config\Repository;
class ConfigurationRepository
{
private Repository $config;
public function __construct(Repository $config)
{
$this->config = $config;
}
public function updateMailConfig($settings): void
{
if ($settings->resend_enabled) {
$this->config->set('mail.default', 'resend');
$this->config->set('mail.from.address', $settings->smtp_from_address ?? 'test@example.com');
$this->config->set('mail.from.name', $settings->smtp_from_name ?? 'Test');
$this->config->set('resend.api_key', $settings->resend_api_key);
return;
}
if ($settings->smtp_enabled) {
$encryption = match (strtolower($settings->smtp_encryption)) {
'starttls' => null,
'tls' => 'tls',
'none' => null,
default => null,
};
$this->config->set('mail.default', 'smtp');
$this->config->set('mail.from.address', $settings->smtp_from_address ?? 'test@example.com');
$this->config->set('mail.from.name', $settings->smtp_from_name ?? 'Test');
$this->config->set('mail.mailers.smtp', [
'transport' => 'smtp',
'host' => $settings->smtp_host,
'port' => $settings->smtp_port,
'encryption' => $encryption,
'username' => $settings->smtp_username,
'password' => $settings->smtp_password,
'timeout' => $settings->smtp_timeout,
'local_domain' => null,
'auto_tls' => $settings->smtp_encryption === 'none' ? '0' : '',
]);
}
}
public function disableSshMux(): void
{
$this->config->set('constants.ssh.mux_enabled', false);
}
}
| php | Apache-2.0 | f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53 | 2026-01-04T15:02:34.115123Z | false |
coollabsio/coolify | https://github.com/coollabsio/coolify/blob/f6a59fa2dce9a7cf92b59dbb9fc575c8612aaa53/app/Contracts/CustomJobRepositoryInterface.php | app/Contracts/CustomJobRepositoryInterface.php | <?php
namespace App\Contracts;
use Illuminate\Support\Collection;
use Laravel\Horizon\Contracts\JobRepository;
interface CustomJobRepositoryInterface extends JobRepository
{
/**
* Get all jobs with a specific status.
*/
public function getJobsByStatus(string $status): Collection;
/**
* Get the count of jobs with a specific status.
*/
public function countJobsByStatus(string $status): int;
}
| 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.