-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Expand file tree
/
Copy pathservices.php
More file actions
505 lines (457 loc) · 20.3 KB
/
Copy pathservices.php
File metadata and controls
505 lines (457 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<?php
use App\Models\Application;
use App\Models\Service;
use App\Models\ServiceApplication;
use App\Models\ServiceDatabase;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Stringable;
use Spatie\Url\Url;
use Symfony\Component\Yaml\Yaml;
function replaceRegex(?string $name = null)
{
return "/\\\${?{$name}[^}]*}?|\\\${$name}\w+/";
}
function collectRegex(string $name)
{
return "/{$name}\w+/";
}
/**
* Extract content between balanced braces, handling nested braces properly.
*
* @param string $str The string to search
* @param int $startPos Position to start searching from
* @return array|null Array with 'content', 'start', and 'end' keys, or null if no balanced braces found
*/
function extractBalancedBraceContent(string $str, int $startPos = 0): ?array
{
// Find opening brace
if ($startPos >= strlen($str)) {
return null;
}
$openPos = strpos($str, '{', $startPos);
if ($openPos === false) {
return null;
}
// Track depth to find matching closing brace
$depth = 1;
$pos = $openPos + 1;
$len = strlen($str);
while ($pos < $len && $depth > 0) {
if ($str[$pos] === '{') {
$depth++;
} elseif ($str[$pos] === '}') {
$depth--;
}
$pos++;
}
if ($depth !== 0) {
// Unbalanced braces
return null;
}
return [
'content' => substr($str, $openPos + 1, $pos - $openPos - 2),
'start' => $openPos,
'end' => $pos - 1,
];
}
/**
* Split variable expression on operators (:-, -, :?, ?) while respecting nested braces.
*
* @param string $content The content to split (without outer ${...})
* @return array|null Array with 'variable', 'operator', and 'default' keys, or null if no operator found
*/
function splitOnOperatorOutsideNested(string $content): ?array
{
$operators = [':-', '-', ':?', '?'];
$depth = 0;
$len = strlen($content);
for ($i = 0; $i < $len; $i++) {
if ($content[$i] === '{') {
$depth++;
} elseif ($content[$i] === '}') {
$depth--;
} elseif ($depth === 0) {
// Check for operators only at depth 0 (outside nested braces)
foreach ($operators as $op) {
if (substr($content, $i, strlen($op)) === $op) {
return [
'variable' => substr($content, 0, $i),
'operator' => $op,
'default' => substr($content, $i + strlen($op)),
];
}
}
}
}
return null;
}
function replaceVariables(string $variable): Stringable
{
// Handle ${VAR} syntax with proper brace matching
$str = str($variable);
// Handle ${VAR} format
if ($str->startsWith('${')) {
$result = extractBalancedBraceContent($variable, 0);
if ($result !== null) {
return str($result['content']);
}
// Fallback to old behavior for malformed input
return $str->before('}')->replaceFirst('$', '')->replaceFirst('{', '');
}
// Handle {VAR} format (from regex capture group without $)
if ($str->startsWith('{') && $str->endsWith('}')) {
return str(substr($variable, 1, -1));
}
// Handle {VAR format (from regex capture group, may be truncated)
if ($str->startsWith('{')) {
$result = extractBalancedBraceContent('$'.$variable, 0);
if ($result !== null) {
return str($result['content']);
}
// Fallback: remove { and get content before }
return $str->replaceFirst('{', '')->before('}');
}
// Handle bare $VAR format (no braces)
if ($str->startsWith('$')) {
return $str->replaceFirst('$', '');
}
return $str;
}
function getFilesystemVolumesFromServer(ServiceApplication|ServiceDatabase|Application $oneService, bool $isInit = false)
{
try {
if ($oneService->getMorphClass() === Application::class) {
$workdir = $oneService->workdir();
$server = $oneService->destination->server;
} else {
$workdir = $oneService->service->workdir();
$server = $oneService->service->server;
}
$fileVolumes = $oneService->fileStorages()->get();
$commands = collect([
"mkdir -p $workdir > /dev/null 2>&1 || true",
"cd $workdir",
]);
instant_remote_process($commands, $server);
foreach ($fileVolumes as $fileVolume) {
$path = str(data_get($fileVolume, 'fs_path'));
$content = data_get($fileVolume, 'content');
if ($path->startsWith('.')) {
$path = $path->after('.');
$fileLocation = $workdir.$path;
} else {
$fileLocation = $path;
}
// Exists and is a file
$isFile = instant_remote_process(["test -f $fileLocation && echo OK || echo NOK"], $server);
// Exists and is a directory
$isDir = instant_remote_process(["test -d $fileLocation && echo OK || echo NOK"], $server);
if ($isFile === 'OK') {
$fileVolume->is_directory = false;
$fileVolume->save();
if ($fileVolume->is_based_on_git) {
$fileVolume->loadStorageOnServer();
}
} elseif ($isDir === 'OK') {
// If its a directory & exists
$fileVolume->content = null;
$fileVolume->is_directory = true;
$fileVolume->save();
} elseif ($isFile === 'NOK' && $isDir === 'NOK' && ! $fileVolume->is_directory && $isInit && $content) {
// Does not exists (no dir or file), not flagged as directory, is init, has content
$fileVolume->content = $content;
$fileVolume->is_directory = false;
$fileVolume->save();
$content = base64_encode($content);
$dir = str($fileLocation)->dirname();
instant_remote_process([
"mkdir -p $dir",
"echo '$content' | base64 -d | tee $fileLocation",
], $server);
} elseif ($isFile === 'NOK' && $isDir === 'NOK' && $fileVolume->is_directory && $isInit) {
// Does not exists (no dir or file), flagged as directory, is init
$fileVolume->content = null;
$fileVolume->is_directory = true;
$fileVolume->save();
instant_remote_process(["mkdir -p $fileLocation"], $server);
} elseif ($isFile === 'NOK' && $isDir === 'NOK' && ! $fileVolume->is_directory && $isInit && is_null($content)) {
// Does not exists (no dir or file), not flagged as directory, is init, has no content => create directory
$fileVolume->content = null;
$fileVolume->is_directory = true;
$fileVolume->save();
instant_remote_process(["mkdir -p $fileLocation"], $server);
}
}
} catch (Throwable $e) {
return handleError($e);
}
}
function updateCompose(ServiceApplication|ServiceDatabase $resource)
{
try {
$name = data_get($resource, 'name');
$dockerComposeRaw = data_get($resource, 'service.docker_compose_raw');
if (! $dockerComposeRaw) {
throw new Exception('No compose file found or not a valid YAML file.');
}
$dockerCompose = Yaml::parse($dockerComposeRaw);
// Switch Image
$updatedImage = data_get_str($resource, 'image');
$currentImage = data_get_str($dockerCompose, "services.{$name}.image");
if ($currentImage !== $updatedImage) {
data_set($dockerCompose, "services.{$name}.image", $updatedImage->value());
$dockerComposeRaw = Yaml::dump($dockerCompose, 10, 2);
$resource->service->docker_compose_raw = $dockerComposeRaw;
$resource->service->save();
$resource->image = $updatedImage;
$resource->save();
}
// Extract SERVICE_URL and SERVICE_FQDN variable names from the compose template
// to ensure we use the exact names defined in the template (which may be abbreviated)
// IMPORTANT: Only extract variables that are DIRECTLY DECLARED for this service,
// not variables that are merely referenced from other services
$serviceConfig = data_get($dockerCompose, "services.{$name}");
$environment = data_get($serviceConfig, 'environment', []);
$templateVariableNames = [];
foreach ($environment as $key => $value) {
if (is_int($key) && is_string($value)) {
// List-style: "- SERVICE_URL_APP_3000" or "- SERVICE_URL_APP_3000=value"
// Extract variable name (before '=' if present)
$envVarName = str($value)->before('=')->trim();
// Only include if it's a direct declaration (not a reference like ${VAR})
// Direct declarations look like: SERVICE_URL_APP or SERVICE_URL_APP_3000
// References look like: NEXT_PUBLIC_URL=${SERVICE_URL_APP}
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
} elseif (is_string($key)) {
// Map-style: "SERVICE_URL_APP_3000: value" or "SERVICE_FQDN_DB: localhost"
$envVarName = str($key);
if ($envVarName->startsWith('SERVICE_FQDN_') || $envVarName->startsWith('SERVICE_URL_')) {
$templateVariableNames[] = $envVarName->value();
}
}
// DO NOT extract variables that are only referenced with ${VAR_NAME} syntax
// Those belong to other services and will be updated when THOSE services are updated
}
// Remove duplicates
$templateVariableNames = array_unique($templateVariableNames);
// Extract unique service names to process (preserving the original case from template)
// This allows us to create both URL and FQDN pairs regardless of which one is in the template
$serviceNamesToProcess = [];
foreach ($templateVariableNames as $templateVarName) {
$parsed = parseServiceEnvironmentVariable($templateVarName);
// Extract the original service name with case preserved from the template
$strKey = str($templateVarName);
if ($parsed['has_port']) {
// For port-specific variables, get the name between SERVICE_URL_/SERVICE_FQDN_ and the last underscore
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->beforeLast('_')->value();
} else {
continue;
}
} else {
// For base variables, get everything after SERVICE_URL_/SERVICE_FQDN_
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->value();
} else {
continue;
}
}
// Use lowercase key for array indexing (to group case variations together)
$serviceKey = str($serviceName)->lower()->value();
// Track both base service name and port-specific variant
if (! isset($serviceNamesToProcess[$serviceKey])) {
$serviceNamesToProcess[$serviceKey] = [
'base' => $serviceName, // Preserve original case
'ports' => [],
];
}
// If this variable has a port, track it
if ($parsed['has_port'] && $parsed['port']) {
$serviceNamesToProcess[$serviceKey]['ports'][] = $parsed['port'];
}
}
// Delete all existing SERVICE_URL and SERVICE_FQDN variables for these service names
// We need to delete both URL and FQDN variants, with and without ports
foreach ($serviceNamesToProcess as $serviceInfo) {
$serviceName = $serviceInfo['base'];
// Delete base variables
$resource->service->environment_variables()->where('key', "SERVICE_URL_{$serviceName}")->delete();
$resource->service->environment_variables()->where('key', "SERVICE_FQDN_{$serviceName}")->delete();
// Delete port-specific variables
foreach ($serviceInfo['ports'] as $port) {
$resource->service->environment_variables()->where('key', "SERVICE_URL_{$serviceName}_{$port}")->delete();
$resource->service->environment_variables()->where('key', "SERVICE_FQDN_{$serviceName}_{$port}")->delete();
}
}
if ($resource->fqdn) {
$resourceFqdns = str($resource->fqdn)->explode(',');
$resourceFqdns = $resourceFqdns->first();
$url = Url::fromString($resourceFqdns);
$port = $url->getPort();
$path = $url->getPath();
// Prepare URL value (with scheme and host)
$urlValue = $url->getScheme().'://'.$url->getHost();
$urlValue = ($path === '/') ? $urlValue : $urlValue.$path;
// Prepare FQDN value (host only, no scheme)
$fqdnHost = $url->getHost();
$fqdnValue = str($fqdnHost)->after('://');
if ($path !== '/') {
$fqdnValue = $fqdnValue.$path;
}
// For each service name found in template, create BOTH SERVICE_URL and SERVICE_FQDN pairs
foreach ($serviceNamesToProcess as $serviceInfo) {
$serviceName = $serviceInfo['base'];
$ports = array_unique($serviceInfo['ports']);
// ALWAYS create base pair (without port)
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_URL_{$serviceName}",
], [
'value' => $urlValue,
'is_preview' => false,
]);
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_FQDN_{$serviceName}",
], [
'value' => $fqdnValue,
'is_preview' => false,
]);
// Create port-specific pairs for each port found in template or FQDN
$allPorts = $ports;
if ($port && ! in_array($port, $allPorts)) {
$allPorts[] = $port;
}
foreach ($allPorts as $portNum) {
$urlWithPort = $urlValue.':'.$portNum;
$fqdnWithPort = $fqdnValue.':'.$portNum;
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_URL_{$serviceName}_{$portNum}",
], [
'value' => $urlWithPort,
'is_preview' => false,
]);
$resource->service->environment_variables()->updateOrCreate([
'resourceable_type' => Service::class,
'resourceable_id' => $resource->service_id,
'key' => "SERVICE_FQDN_{$serviceName}_{$portNum}",
], [
'value' => $fqdnWithPort,
'is_preview' => false,
]);
}
}
}
} catch (Throwable $e) {
return handleError($e);
}
}
function serviceKeys()
{
return get_service_templates()->keys();
}
/**
* Parse a SERVICE_URL_* or SERVICE_FQDN_* variable to extract the service name and port.
*
* This function detects if a service environment variable has a port suffix by checking
* if the last segment after the underscore is numeric.
*
* Examples:
* - SERVICE_URL_APP_3000 → ['service_name' => 'app', 'port' => '3000', 'has_port' => true]
* - SERVICE_URL_MY_API_8080 → ['service_name' => 'my_api', 'port' => '8080', 'has_port' => true]
* - SERVICE_URL_MY_APP → ['service_name' => 'my_app', 'port' => null, 'has_port' => false]
* - SERVICE_FQDN_REDIS_CACHE_6379 → ['service_name' => 'redis_cache', 'port' => '6379', 'has_port' => true]
*
* @param string $key The environment variable key (e.g., SERVICE_URL_APP_3000)
* @return array{service_name: string, port: string|null, has_port: bool} Parsed service information
*/
function parseServiceEnvironmentVariable(string $key): array
{
$strKey = str($key);
$lastSegment = $strKey->afterLast('_')->value();
$hasPort = is_numeric($lastSegment) && ctype_digit($lastSegment);
if ($hasPort) {
// Port-specific variable (e.g., SERVICE_URL_APP_3000)
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->beforeLast('_')->lower()->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->beforeLast('_')->lower()->value();
} else {
$serviceName = '';
}
$port = $lastSegment;
} else {
// Base variable without port (e.g., SERVICE_URL_APP)
if ($strKey->startsWith('SERVICE_URL_')) {
$serviceName = $strKey->after('SERVICE_URL_')->lower()->value();
} elseif ($strKey->startsWith('SERVICE_FQDN_')) {
$serviceName = $strKey->after('SERVICE_FQDN_')->lower()->value();
} else {
$serviceName = '';
}
$port = null;
}
return [
'service_name' => $serviceName,
'port' => $port,
'has_port' => $hasPort,
];
}
/**
* Apply service-specific application prerequisites after service parse.
*
* This function configures application-level settings that are required for
* specific one-click services to work correctly (e.g., disabling gzip for Beszel,
* disabling strip prefix for Appwrite services).
*
* Must be called AFTER $service->parse() since it requires applications to exist.
*
* @param Service $service The service to apply prerequisites to
*/
function applyServiceApplicationPrerequisites(Service $service): void
{
try {
// Extract service name from service name (format: "servicename-uuid")
$serviceName = str($service->name)->beforeLast('-')->value();
// Apply gzip disabling if needed
if (array_key_exists($serviceName, NEEDS_TO_DISABLE_GZIP)) {
$applicationNames = NEEDS_TO_DISABLE_GZIP[$serviceName];
foreach ($applicationNames as $applicationName) {
$application = $service->applications()->whereName($applicationName)->first();
if ($application) {
$application->is_gzip_enabled = false;
$application->save();
}
}
}
// Apply stripprefix disabling if needed
if (array_key_exists($serviceName, NEEDS_TO_DISABLE_STRIPPREFIX)) {
$applicationNames = NEEDS_TO_DISABLE_STRIPPREFIX[$serviceName];
foreach ($applicationNames as $applicationName) {
$application = $service->applications()->whereName($applicationName)->first();
if ($application) {
$application->is_stripprefix_enabled = false;
$application->save();
}
}
}
} catch (Throwable $e) {
// Log error but don't throw - prerequisites are nice-to-have, not critical
Log::error('Failed to apply service application prerequisites', [
'service_id' => $service->id,
'service_name' => $service->name,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
}
}