-
Notifications
You must be signed in to change notification settings - Fork 34
/
docker.php
493 lines (407 loc) · 13.7 KB
/
docker.php
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
<?php
namespace docker;
use Castor\Attribute\AsContext;
use Castor\Attribute\AsOption;
use Castor\Attribute\AsTask;
use Castor\Context;
use Symfony\Component\Process\Exception\ExceptionInterface;
use Symfony\Component\Process\ExecutableFinder;
use Symfony\Component\Process\Process;
use function Castor\cache;
use function Castor\capture;
use function Castor\context;
use function Castor\finder;
use function Castor\fs;
use function Castor\io;
use function Castor\log;
use function Castor\open;
use function Castor\run;
use function Castor\variable;
#[AsTask(description: 'Displays some help and available urls for the current project', namespace: '')]
function about(): void
{
io()->title('About this project');
io()->comment('Run <comment>castor</comment> to display all available commands.');
io()->comment('Run <comment>castor about</comment> to display this project help.');
io()->comment('Run <comment>castor help [command]</comment> to display Castor help.');
io()->section('Available URLs for this project:');
$urls = [variable('root_domain'), ...variable('extra_domains')];
$payload = @file_get_contents(sprintf('http://%s:8080/api/http/routers', variable('root_domain')));
if ($payload) {
$routers = json_decode($payload, true);
$projectName = variable('project_name');
foreach ($routers as $router) {
if (!preg_match("{^{$projectName}-(.*)@docker$}", $router['name'])) {
continue;
}
if ("frontend-{$projectName}" === $router['service']) {
continue;
}
if (!preg_match('{^Host\\(`(?P<hosts>.*)`\\)$}', $router['rule'], $matches)) {
continue;
}
$hosts = explode('`) || Host(`', $matches['hosts']);
$urls = [...$urls, ...$hosts];
}
}
io()->listing(array_map(fn ($url) => "https://{$url}", array_unique($urls)));
}
#[AsTask(description: 'Opens the project in your browser', namespace: '', aliases: ['open'])]
function open_project(): void
{
open('https://' . variable('root_domain'));
}
#[AsTask(description: 'Builds the infrastructure', aliases: ['build'])]
function build(): void
{
io()->title('Building infrastructure');
$userId = variable('user_id');
$phpVersion = variable('php_version');
$command = [
'build',
'--build-arg', "USER_ID={$userId}",
'--build-arg', "PHP_VERSION={$phpVersion}",
];
docker_compose($command, withBuilder: true);
}
#[AsTask(description: 'Builds and starts the infrastructure', aliases: ['up'])]
function up(): void
{
io()->title('Starting infrastructure');
try {
docker_compose(['up', '--detach', '--no-build']);
} catch (ExceptionInterface $e) {
io()->error('An error occured while starting the infrastructure.');
io()->note('Did you forget to run "castor docker:build"?');
io()->note('Or you forget to login to the registry?');
throw $e;
}
}
#[AsTask(description: 'Stops the infrastructure', aliases: ['stop'])]
function stop(): void
{
io()->title('Stopping infrastructure');
docker_compose(['stop']);
}
#[AsTask(description: 'Opens a shell (bash) into a builder container', aliases: ['builder'])]
function builder(): void
{
$c = context()
->withTimeout(null)
->withTty()
->withEnvironment($_ENV + $_SERVER)
->withAllowFailure()
;
docker_compose_run('bash', c: $c);
}
#[AsTask(description: 'Displays infrastructure logs', aliases: ['logs'])]
function logs(): void
{
docker_compose(['logs', '-f', '--tail', '150'], c: context()->withTty());
}
#[AsTask(description: 'Lists containers status', aliases: ['ps'])]
function ps(): void
{
docker_compose(['ps'], withBuilder: false);
}
#[AsTask(description: 'Cleans the infrastructure (remove container, volume, networks)', aliases: ['destroy'])]
function destroy(
#[AsOption(description: 'Force the destruction without confirmation', shortcut: 'f')]
bool $force = false,
): void {
io()->title('Destroying infrastructure');
if (!$force) {
io()->warning('This will permanently remove all containers, volumes, networks... created for this project.');
io()->note('You can use the --force option to avoid this confirmation.');
if (!io()->confirm('Are you sure?', false)) {
io()->comment('Aborted.');
return;
}
}
docker_compose(['down', '--remove-orphans', '--volumes', '--rmi=local'], withBuilder: true);
$files = finder()
->in(variable('root_dir') . '/infrastructure/docker/services/router/certs/')
->name('*.pem')
->files()
;
fs()->remove($files);
}
#[AsTask(description: 'Generates SSL certificates (with mkcert if available or self-signed if not)')]
function generate_certificates(
#[AsOption(description: 'Force the certificates re-generation without confirmation', shortcut: 'f')]
bool $force = false,
): void {
$sslDir = variable('root_dir') . '/infrastructure/docker/services/router/certs';
if (file_exists("{$sslDir}/cert.pem") && !$force) {
io()->comment('SSL certificates already exists.');
io()->note('Run "castor docker:generate-certificates --force" to generate new certificates.');
return;
}
io()->title('Generating SSL certificates');
if ($force) {
if (file_exists($f = "{$sslDir}/cert.pem")) {
io()->comment('Removing existing certificates in infrastructure/docker/services/router/certs/*.pem.');
unlink($f);
}
if (file_exists($f = "{$sslDir}/key.pem")) {
unlink($f);
}
}
$finder = new ExecutableFinder();
$mkcert = $finder->find('mkcert');
if ($mkcert) {
$pathCaRoot = capture(['mkcert', '-CAROOT']);
if (!is_dir($pathCaRoot)) {
io()->warning('You must have mkcert CA Root installed on your host with "mkcert -install" command.');
return;
}
$rootDomain = variable('root_domain');
run([
'mkcert',
'-cert-file', "{$sslDir}/cert.pem",
'-key-file', "{$sslDir}/key.pem",
$rootDomain,
"*.{$rootDomain}",
...variable('extra_domains'),
]);
io()->success('Successfully generated SSL certificates with mkcert.');
if ($force) {
io()->note('Please restart the infrastructure to use the new certificates with "castor up" or "castor start".');
}
return;
}
run(['infrastructure/docker/services/router/generate-ssl.sh'], quiet: true);
io()->success('Successfully generated self-signed SSL certificates in infrastructure/docker/services/router/certs/*.pem.');
io()->comment('Consider installing mkcert to generate locally trusted SSL certificates and run "castor docker:generate-certificates --force".');
if ($force) {
io()->note('Please restart the infrastructure to use the new certificates with "castor up" or "castor start".');
}
}
#[AsTask(description: 'Starts the workers', namespace: 'docker:worker', name: 'start', aliases: ['start-workers'])]
function workers_start(): void
{
io()->title('Starting workers');
$workers = get_workers();
if (!$workers) {
return;
}
run([
'docker',
'update',
'--restart=unless-stopped',
...$workers,
], quiet: true);
run([
'docker',
'start',
...$workers,
], quiet: true);
}
#[AsTask(description: 'Stops the workers', namespace: 'docker:worker', name: 'stop', aliases: ['stop-workers'])]
function workers_stop(): void
{
io()->title('Stopping workers');
$workers = get_workers();
if (!$workers) {
return;
}
run([
'docker',
'update',
'--restart=no',
...$workers,
]);
run([
'docker',
'stop',
...$workers,
]);
}
#[AsContext(default: true)]
function create_default_context(): Context
{
$data = create_default_variables() + [
'project_name' => 'app',
'root_domain' => 'app.test',
'extra_domains' => [],
'project_directory' => 'application',
'php_version' => '8.2',
'docker_compose_files' => [
'docker-compose.yml',
'docker-compose.worker.yml',
],
'macos' => false,
'power_shell' => false,
'user_id' => posix_geteuid(),
'root_dir' => \dirname(__DIR__),
];
if (file_exists($data['root_dir'] . '/infrastructure/docker/docker-compose.override.yml')) {
$data['docker_compose_files'][] = 'docker-compose.override.yml';
}
// We need an empty context to run command, since the default context has
// not been set in castor, since we ARE creating it right now
$emptyContext = new Context();
$data['composer_cache_dir'] = cache('composer_cache_dir', function () use ($emptyContext): string {
$composerCacheDir = capture(['composer', 'global', 'config', 'cache-dir', '-q'], onFailure: '', context: $emptyContext);
// If PHP is broken, the output will not be a valid path but an error message
if (!is_dir($composerCacheDir)) {
$composerCacheDir = sys_get_temp_dir() . '/castor/composer';
// If the directory does not exist, we create it. Otherwise, docker
// will do, as root, and the user will not be able to write in it.
if (!is_dir($composerCacheDir)) {
mkdir($composerCacheDir, 0777, true);
}
}
return $composerCacheDir;
});
$platform = strtolower(php_uname('s'));
if (str_contains($platform, 'darwin')) {
$data['macos'] = true;
$data['docker_compose_files'][] = 'docker-compose.docker-for-x.yml';
} elseif (\in_array($platform, ['win32', 'win64'])) {
$data['docker_compose_files'][] = 'docker-compose.docker-for-x.yml';
$data['power_shell'] = true;
}
if ($data['user_id'] > 256000) {
$data['user_id'] = 1000;
}
if (0 === $data['user_id']) {
log('Running as root? Fallback to fake user id.', 'warning');
$data['user_id'] = 1000;
}
return new Context(
$data,
pty: Process::isPtySupported(),
environment: [
'BUILDKIT_PROGRESS' => 'plain',
]
);
}
#[AsContext(name: 'ci')]
function create_ci_context(): Context
{
$c = create_default_context();
return $c
->withData([
// override the default context here
])
->withEnvironment([
'COMPOSE_ANSI' => 'never',
])
;
}
/**
* @param array<string> $subCommand
*/
function docker_compose(array $subCommand, ?Context $c = null, bool $withBuilder = false): Process
{
$c ??= context();
$domains = [variable('root_domain'), ...variable('extra_domains')];
$domains = '`' . implode('`) || Host(`', $domains) . '`';
$c = $c
->withTimeout(null)
->withEnvironment([
'PROJECT_NAME' => variable('project_name'),
'PROJECT_ROOT_DOMAIN' => variable('root_domain'),
'PROJECT_DOMAINS' => $domains,
'USER_ID' => variable('user_id'),
'COMPOSER_CACHE_DIR' => variable('composer_cache_dir'),
'PHP_VERSION' => variable('php_version'),
])
;
$command = [
'docker',
'compose',
'-p', variable('project_name'),
];
foreach (variable('docker_compose_files') as $file) {
$command[] = '-f';
$command[] = variable('root_dir') . '/infrastructure/docker/' . $file;
}
if ($withBuilder) {
$command[] = '-f';
$command[] = variable('root_dir') . '/infrastructure/docker/docker-compose.builder.yml';
}
$command = array_merge($command, $subCommand);
return run($command, context: $c);
}
function docker_compose_run(
string $runCommand,
?Context $c = null,
string $service = 'builder',
bool $noDeps = true,
?string $workDir = null,
bool $portMapping = false,
bool $withBuilder = true,
): Process {
$command = [
'run',
'--rm',
];
if ($noDeps) {
$command[] = '--no-deps';
}
if ($portMapping) {
$command[] = '--service-ports';
}
if (null !== $workDir) {
$command[] = '-w';
$command[] = $workDir;
}
$command[] = $service;
$command[] = '/bin/sh';
$command[] = '-c';
$command[] = "exec {$runCommand}";
return docker_compose($command, c: $c, withBuilder: $withBuilder);
}
function docker_exit_code(
string $runCommand,
?Context $c = null,
string $service = 'builder',
bool $noDeps = true,
?string $workDir = null,
bool $withBuilder = true,
): int {
$c = ($c ?? context())->withAllowFailure();
$process = docker_compose_run(
runCommand: $runCommand,
c: $c,
service: $service,
noDeps: $noDeps,
workDir: $workDir,
withBuilder: $withBuilder,
);
return $process->getExitCode() ?? 0;
}
// Mac users have a lot of problems running Yarn / Webpack on the Docker stack
// so this func allow them to run these tools on their host
function run_in_docker_or_locally_for_mac(string $command, ?Context $c = null): void
{
$c ??= context();
if (variable('macos')) {
run($command, context: $c->withPath(variable('root_dir')));
} else {
docker_compose_run($command, c: $c);
}
}
/**
* Find worker containers for the current project.
*
* @return array<string>
*/
function get_workers(): array
{
$command = [
'docker',
'ps',
'-a',
'--filter', 'label=docker-starter.worker.' . variable('project_name'),
'--quiet',
];
$out = capture($command);
if (!$out) {
return [];
}
$workers = explode("\n", $out);
return array_map('trim', $workers);
}