-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathDockerController.php
More file actions
496 lines (390 loc) · 20.1 KB
/
DockerController.php
File metadata and controls
496 lines (390 loc) · 20.1 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
<?php
declare(strict_types=1);
namespace AIO\Controller;
use AIO\Container\Container;
use AIO\Container\ContainerState;
use AIO\ContainerDefinitionFetcher;
use AIO\Docker\DockerActionManager;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use AIO\Data\ConfigurationManager;
use Slim\Psr7\NonBufferedBody;
readonly class DockerController {
private const string TOP_CONTAINER = 'nextcloud-aio-apache';
private function getLatestMajorVersion(): string {
return '33';
}
public function __construct(
private DockerActionManager $dockerActionManager,
private ContainerDefinitionFetcher $containerDefinitionFetcher,
private ConfigurationManager $configurationManager
) {
}
private function PerformRecursiveContainerStart(string $id, bool $pullImage = true, ?\Closure $addToStreamingResponseBody = null) : void {
$container = $this->containerDefinitionFetcher->GetContainerById($id);
// Start all dependencies first and then itself
foreach($container->dependsOn as $dependency) {
$this->PerformRecursiveContainerStart($dependency, $pullImage, $addToStreamingResponseBody);
}
// Don't start if container is already running
// This is expected to happen if a container is defined in depends_on of multiple containers
if ($container->GetRunningState() === ContainerState::Running) {
error_log('Not starting ' . $id . ' because it was already started.');
return;
}
$this->dockerActionManager->DeleteContainer($container);
$this->dockerActionManager->CreateVolumes($container);
$this->dockerActionManager->PullImage($container, $pullImage, $addToStreamingResponseBody);
$this->dockerActionManager->CreateContainer($container);
$this->dockerActionManager->StartContainer($container, $addToStreamingResponseBody);
$this->dockerActionManager->ConnectContainerToNetwork($container);
}
private function PerformRecursiveImagePull(string $id) : void {
$container = $this->containerDefinitionFetcher->GetContainerById($id);
// Pull all dependencies first and then itself
foreach($container->dependsOn as $dependency) {
$this->PerformRecursiveImagePull($dependency);
}
$this->dockerActionManager->PullImage($container, true);
}
public function PullAllContainerImages(): void {
$id = self::TOP_CONTAINER;
$this->PerformRecursiveImagePull($id);
}
public function GetLogs(Request $request, Response $response, array $args) : Response
{
$requestParams = $request->getQueryParams();
$id = '';
if (isset($requestParams['id']) && is_string($requestParams['id'])) {
$id = $requestParams['id'];
}
if (str_starts_with($id, 'nextcloud-aio-')) {
$since = $this->getTimestampForDockerLogsApiSince($requestParams['since'] ?? '');
$logs = $this->dockerActionManager->GetLogs($id, $since);
} else {
$logs = 'Container not found.';
}
$body = $response->getBody();
$body->write($logs);
return $response
->withStatus(200)
->withHeader('Content-Type', 'text/plain; charset=utf-8')
->withHeader('Content-Disposition', 'inline');
}
public function StartBackupContainerBackup(Request $request, Response $response, array $args) : Response {
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$forceStopNextcloud = true;
$this->startBackup($forceStopNextcloud, $addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function startBackup(bool $forceStopNextcloud = false, ?\Closure $addToStreamingResponseBody = null) : void {
$this->configurationManager->backupMode = 'backup';
$id = self::TOP_CONTAINER;
$this->PerformRecursiveContainerStop($id, $forceStopNextcloud, $addToStreamingResponseBody);
$id = 'nextcloud-aio-borgbackup';
$this->PerformRecursiveContainerStart($id, true, $addToStreamingResponseBody);
}
public function StartBackupContainerCheck(Request $request, Response $response, array $args) : Response {
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$this->checkBackup($addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function StartBackupContainerList(Request $request, Response $response, array $args) : Response {
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$this->listBackup($addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function checkBackup(?\Closure $addToStreamingResponseBody = null) : void {
$this->configurationManager->backupMode = 'check';
$id = 'nextcloud-aio-borgbackup';
$this->PerformRecursiveContainerStart($id, true, $addToStreamingResponseBody);
}
private function listBackup(?\Closure $addToStreamingResponseBody = null) : void {
$this->configurationManager->backupMode = 'list';
$id = 'nextcloud-aio-borgbackup';
$this->PerformRecursiveContainerStart($id, true, $addToStreamingResponseBody);
}
public function StartBackupContainerRestore(Request $request, Response $response, array $args) : Response {
$this->configurationManager->startTransaction();
$this->configurationManager->backupMode = 'restore';
$this->configurationManager->selectedRestoreTime = $request->getParsedBody()['selected_restore_time'] ?? '';
$this->configurationManager->restoreExcludePreviews = isset($request->getParsedBody()['restore-exclude-previews']);
$this->configurationManager->commitTransaction();
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$id = self::TOP_CONTAINER;
$forceStopNextcloud = true;
$this->PerformRecursiveContainerStop($id, $forceStopNextcloud, $addToStreamingResponseBody);
$id = 'nextcloud-aio-borgbackup';
$this->PerformRecursiveContainerStart($id, true, $addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function StartBackupContainerCheckRepair(Request $request, Response $response, array $args) : Response {
$this->configurationManager->backupMode = 'check-repair';
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$id = 'nextcloud-aio-borgbackup';
$this->PerformRecursiveContainerStart($id, true, $addToStreamingResponseBody);
// Restore to backup check which is needed to make the UI logic work correctly
$this->configurationManager->backupMode = 'check';
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function StartBackupContainerTest(Request $request, Response $response, array $args) : Response {
$this->configurationManager->startTransaction();
$this->configurationManager->backupMode = 'test';
$this->configurationManager->instanceRestoreAttempt = false;
$this->configurationManager->commitTransaction();
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$id = self::TOP_CONTAINER;
$this->PerformRecursiveContainerStop($id, true, $addToStreamingResponseBody);
$id = 'nextcloud-aio-borgbackup';
$this->PerformRecursiveContainerStart($id, true, $addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function StartContainer(Request $request, Response $response, array $args) : Response
{
$uri = $request->getUri();
$host = $uri->getHost();
$port = $uri->getPort();
$path = $request->getParsedBody()['base_path'] ?? '';
if ($port === 8000) {
error_log('The AIO_URL-port was discovered to be 8000 which is not expected. It is now set to 443.');
$port = 443;
}
if (isset($request->getParsedBody()['install_latest_major'])) {
$installLatestMajor = $this->getLatestMajorVersion();
} else {
$installLatestMajor = '';
}
$this->configurationManager->startTransaction();
$this->configurationManager->installLatestMajor = $installLatestMajor;
// set AIO_URL
$this->configurationManager->aioUrl = $host . ':' . (string)$port . $path;
// set wasStartButtonClicked
$this->configurationManager->wasStartButtonClicked = true;
$this->configurationManager->commitTransaction();
// Do not pull container images in case 'bypass_container_update' is set via url params
// Needed for local testing
$pullImage = !isset($request->getParsedBody()['bypass_container_update']);
if ($pullImage === false) {
error_log('WARNING: Not pulling container images. Instead, using local ones.');
}
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
// Start container
$this->startTopContainer($pullImage, $addToStreamingResponseBody);
// Clear apcu cache in order to check if container updates are available
// Temporarily disabled as it leads much faster to docker rate limits
// apcu_clear_cache();
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function startTopContainer(bool $pullImage, ?\Closure $addToStreamingResponseBody = null) : void {
$this->configurationManager->aioToken = bin2hex(random_bytes(24));
// Stop domaincheck since apache would not be able to start otherwise
$this->StopDomaincheckContainer();
$id = self::TOP_CONTAINER;
$this->PerformRecursiveContainerStart($id, $pullImage, $addToStreamingResponseBody);
}
public function StartWatchtowerContainer(Request $request, Response $response, array $args) : Response {
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$this->startWatchtower($addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function startWatchtower(?\Closure $addToStreamingResponseBody = null) : void {
$id = 'nextcloud-aio-watchtower';
$this->PerformRecursiveContainerStart($id, true, $addToStreamingResponseBody);
}
private function PerformRecursiveContainerStop(string $id, bool $forceStopNextcloud = false, ?\Closure $addToStreamingResponseBody = null) : void
{
$container = $this->containerDefinitionFetcher->GetContainerById($id);
// This is a hack but no better solution was found for the meantime
// Stop Collabora first to make sure it force-saves
// See https://github.com/nextcloud/richdocuments/issues/3799
if ($id === self::TOP_CONTAINER && $this->configurationManager->isCollaboraEnabled) {
$this->PerformRecursiveContainerStop('nextcloud-aio-collabora', false, $addToStreamingResponseBody);
}
if ($addToStreamingResponseBody !== null) {
$addToStreamingResponseBody($container, "Stopping container");
}
// Stop itself first and then all the dependencies
if ($id !== 'nextcloud-aio-nextcloud') {
$this->dockerActionManager->StopContainer($container);
} else {
// We want to stop the Nextcloud container after 10s and not wait for the configured stop_grace_period
$this->dockerActionManager->StopContainer($container, $forceStopNextcloud);
}
foreach($container->dependsOn as $dependency) {
$this->PerformRecursiveContainerStop($dependency, $forceStopNextcloud, $addToStreamingResponseBody);
}
}
public function StopContainer(Request $request, Response $response, array $args) : Response
{
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$addToStreamingResponseBody = $this->getAddToStreamingResponseBody($nonbufResp);
$id = self::TOP_CONTAINER;
$forceStopNextcloud = true;
$this->PerformRecursiveContainerStop($id, $forceStopNextcloud, $addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function RunNextcloudUpgradeToLatestMajor(Request $request, Response $response, array $args) : Response {
$this->configurationManager->installLatestMajor = $this->getLatestMajorVersion();
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$body = $nonbufResp->getBody();
$addToStreamingResponseBody = function (string $message) use ($body) : void {
$body->write("<div>" . htmlspecialchars($message, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "</div>");
};
$this->dockerActionManager->RunNextcloudUpgradeToLatestMajor($addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function SystemPrune(Request $request, Response $response, array $args) : Response {
// Get streaming response start and closure
$nonbufResp = $this->startStreamingResponse($response);
$body = $nonbufResp->getBody();
$addToStreamingResponseBody = function (string $message) use ($body) : void {
$body->write("<div>$message</div>");
};
$this->dockerActionManager->SystemPrune($addToStreamingResponseBody);
// End streaming response
$this->finalizeStreamingResponse($nonbufResp);
return $nonbufResp;
}
public function stopTopContainer() : void {
$id = self::TOP_CONTAINER;
$this->PerformRecursiveContainerStop($id);
}
public function StartDomaincheckContainer() : void
{
# Don't start if domain is already set
if ($this->configurationManager->domain !== '' || $this->configurationManager->wasStartButtonClicked) {
return;
}
$id = 'nextcloud-aio-domaincheck';
$cacheKey = 'domaincheckWasStarted';
$domaincheckContainer = $this->containerDefinitionFetcher->GetContainerById($id);
$apacheContainer = $this->containerDefinitionFetcher->GetContainerById(self::TOP_CONTAINER);
// Don't start if apache is already running
if ($apacheContainer->GetRunningState() === ContainerState::Running) {
return;
// Don't start if domaincheck is already running
} elseif ($domaincheckContainer->GetRunningState() === ContainerState::Running) {
$domaincheckWasStarted = apcu_fetch($cacheKey);
// Start domaincheck again when 10 minutes are over by not returning here
if($domaincheckWasStarted !== false && is_string($domaincheckWasStarted)) {
return;
}
}
$this->StopDomaincheckContainer();
try {
$this->PerformRecursiveContainerStart($id);
} catch (\Exception $e) {
error_log('Could not start domaincheck container: ' . $e->getMessage());
}
// Cache the start for 10 minutes
apcu_add($cacheKey, '1', 600);
}
private function StopDomaincheckContainer() : void
{
$id = 'nextcloud-aio-domaincheck';
$this->PerformRecursiveContainerStop($id);
}
private function getStreamingResponseHtmlStart() : string {
return <<<END
<!DOCTYPE html>
<html lang="en" class="overlay-iframe">
<head>
<link rel="stylesheet" href="../../style.css?v8" media="all" />
<script type="text/javascript" src="../../scroll-into-view.js"></script>
</head>
<body>
END;
}
private function startStreamingResponse(Response $response) : Response {
$nonbufResp = $response
->withBody(new NonBufferedBody())
->withHeader('Content-Type', 'text/html; charset=utf-8')
->withHeader('X-Accel-Buffering', 'no')
->withHeader('Content-Length', '-1')
->withHeader('Cache-Control', 'no-cache');
// Text written into this body is immediately sent to the client, without waiting for later content.
$streamingResponseBody = $nonbufResp->getBody();
$streamingResponseBody->write($this->getStreamingResponseHtmlStart());
return $nonbufResp;
}
private function getAddToStreamingResponseBody(Response $nonbufResp) : ?\Closure {
// Create a closure to pass around to the code, which should to the logging (because it e.g. decides
// if it'll actually pull an image), but which should not need to know anything about the
// wanted markup or formatting.
$addToStreamingResponseBody = function (Container $container, string $message) use ($nonbufResp) : void {
$nonbufResp->getBody()->write("<div>{$container->displayName}: {$message}</div>");
};
return $addToStreamingResponseBody;
}
private function finalizeStreamingResponse(Response $nonbufResp) : void {
$nonbufResp->getBody()->write($this->getStreamingResponseHtmlEnd());
}
private function getStreamingResponseHtmlEnd() : string {
return "\n </body>\n</html>";
}
private function getTimestampForDockerLogsApiSince(string $input) : string
{
if ($input === '') {
return '';
}
// We expect an RFC3339Nano string with Timezone UTC here, as docker will put out.
// Unfortunately PHP doesn't support this format with nanoseconds, so we have to help
// ourselves a little bit.
// First we split off the nanoseconds.
preg_match('/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})\.(\d{9}).*/', $input, $match);
if (count($match) !== 3) {
// The input doesn't match our expectations, it might be manipulated, we ignore it.
return '';
}
$datetime = \DateTimeImmutable::createFromFormat("Y-m-d\\TH:i:s", $match[1]);
$nanoseconds = $match[2];
if ($datetime === false) {
// Input was not parseable, it might be manipulated, we ignore it.
return '';
}
// Format the datetime as unix timestamp.
$timestamp = $datetime->format('U');
// Increase the nanoseconds by 1, so we don't get the line with exactly the original datetime again.
$nanoseconds = strval(intval($nanoseconds) + 1);
// Now append the nanoseconds to the timestamp-string.
return "{$timestamp}.{$nanoseconds}";
}
}