Completed
Push — master ( 833968...e0f813 )
by David
12s
created

Service::getVirtualHosts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace TheAentMachine\Service;
4
5
use Opis\JsonSchema\ValidationError;
6
use Opis\JsonSchema\Validator;
7
use TheAentMachine\Aenthill\CommonMetadata;
8
use TheAentMachine\Aenthill\Manifest;
9
use TheAentMachine\Service\Enum\EnvVariableTypeEnum;
10
use TheAentMachine\Service\Enum\VolumeTypeEnum;
11
use TheAentMachine\Service\Environment\EnvVariable;
12
use TheAentMachine\Service\Exception\ServiceException;
13
use TheAentMachine\Service\Volume\BindVolume;
14
use TheAentMachine\Service\Volume\NamedVolume;
15
use TheAentMachine\Service\Volume\TmpfsVolume;
16
use TheAentMachine\Service\Volume\Volume;
17
use TheAentMachine\Yaml\CommentedItem;
18
19
class Service implements \JsonSerializable
20
{
21
    /** @var string */
22
    private $serviceName = '';
23
    /** @var string|null */
24
    private $image;
25
    /** @var string[] */
26
    private $command = [];
27
    /** @var int[] */
28
    private $internalPorts = [];
29
    /** @var string[] */
30
    private $dependsOn = [];
31
    /** @var array<int, array<string, string|int>> */
32
    private $ports = [];
33
    /** @var array<string, CommentedItem> */
34
    private $labels = [];
35
    /** @var array<string, EnvVariable> */
36
    private $environment = [];
37
    /** @var mixed[] */
38
    private $volumes = [];
39
    /** @var null|bool */
40
    private $needVirtualHost;
41
    /** @var array<int, array<string, string|int>> */
42
    private $virtualHosts = [];
43
    /** @var null|bool */
44
    private $needBuild;
45
    /** @var \stdClass */
46
    private $validatorSchema;
47
    /** @var string[] */
48
    private $dockerfileCommands = [];
49
    /** @var null|string */
50
    private $requestMemory;
51
    /** @var null|string */
52
    private $requestCpu;
53
    /** @var null|string */
54
    private $requestStorage;
55
    /** @var null|string */
56
    private $limitMemory;
57
    /** @var null|string */
58
    private $limitCpu;
59
    /** @var string[] */
60
    private $destEnvTypes = []; // empty === all env types
61
62
    /**
63
     * Service constructor.
64
     */
65
    public function __construct()
66
    {
67
        $this->validatorSchema = \GuzzleHttp\json_decode((string)file_get_contents(__DIR__ . '/ServiceJsonSchema.json'), false);
68
    }
69
70
    /**
71
     * @param mixed[] $payload
72
     * @return Service
73
     * @throws ServiceException
74
     */
75
    public static function parsePayload(array $payload): Service
76
    {
77
        $service = new self();
78
        $service->checkValidity($payload);
79
        $service->serviceName = $payload['serviceName'] ?? '';
80
        if (!empty($s = $payload['service'] ?? [])) {
81
            $service->image = $s['image'] ?? null;
82
            $service->command = $s['command'] ?? [];
83
            $service->internalPorts = $s['internalPorts'] ?? [];
84
            $service->dependsOn = $s['dependsOn'] ?? [];
85
            $service->ports = $s['ports'] ?? [];
86
            if (!empty($labels = $s['labels'])) {
87
                foreach ($labels as $key => $label) {
88
                    $service->addLabel($key, $label['value'], $label['comment'] ?? null);
89
                }
90
            }
91
            if (!empty($environment = $s['environment'])) {
92
                foreach ($environment as $key => $env) {
93
                    $service->addEnvVar($key, $env['value'], $env['type'], $env['comment'] ?? null);
94
                }
95
            }
96
            if (!empty($volumes = $s['volumes'])) {
97
                foreach ($volumes as $vol) {
98
                    $service->addVolume($vol['type'], $vol['source'], $vol['comment'] ?? null, $vol['target'] ?? '', $vol['readOnly'] ?? false);
99
                }
100
            }
101
            $service->needVirtualHost = $s['needVirtualHost'] ?? null;
102
            $service->virtualHosts = $s['virtualHosts'] ?? [];
103
            $service->needBuild = $s['needBuild'] ?? null;
104
        }
105
        $service->dockerfileCommands = $payload['dockerfileCommands'] ?? [];
106
        $service->destEnvTypes = $payload['destEnvTypes'] ?? [];
107
108
        if (!empty($resources = $payload['resources'])) {
109
            if (!empty($r = $resources['requests'])) {
110
                $service->requestMemory = $r['memory'] ?? null;
111
                $service->requestCpu = $r['cpu'] ?? null;
112
                $service->requestStorage= $r['storage'] ?? null;
113
            }
114
            if (!empty($l = $resources['limits'])) {
115
                $service->limitMemory = $l['memory'] ?? null;
116
                $service->limitCpu = $l['cpu'] ?? null;
117
            }
118
        }
119
120
        return $service;
121
    }
122
123
    /**
124
     * Specify data which should be serialized to JSON
125
     * @link http://php.net/manual/en/jsonserializable.jsonserialize.php
126
     * @return array data which can be serialized by <b>json_encode</b>,
127
     * which is a value of any type other than a resource.
128
     * @since 5.4.0
129
     * @throws ServiceException
130
     */
131
    public function jsonSerialize(): array
132
    {
133
        $labelMap = function (CommentedItem $commentedItem): array {
134
            return null === $commentedItem->getComment() ?
135
                ['value' => $commentedItem->getItem()] :
136
                ['value' => $commentedItem->getItem(), 'comment' => $commentedItem->getComment()];
137
        };
138
139
        $jsonSerializeMap = function (\JsonSerializable $obj): array {
140
            return $obj->jsonSerialize();
141
        };
142
143
        $json = array(
144
            'serviceName' => $this->serviceName,
145
        );
146
147
        $service = array_filter([
148
            'image' => $this->image,
149
            'command' => $this->command,
150
            'internalPorts' => $this->internalPorts,
151
            'dependsOn' => $this->dependsOn,
152
            'ports' => $this->ports,
153
            'labels' => array_map($labelMap, $this->labels),
154
            'environment' => array_map($jsonSerializeMap, $this->environment),
155
            'volumes' => array_map($jsonSerializeMap, $this->volumes),
156
            'needVirtualHost' => $this->needVirtualHost,
157
            'virtualHosts' => $this->virtualHosts,
158
            'needBuild' => $this->needBuild,
159
        ]);
160
161
        if (!empty($service)) {
162
            $json['service'] = $service;
163
        }
164
165
        if (!empty($this->dockerfileCommands)) {
166
            $json['dockerfileCommands'] = $this->dockerfileCommands;
167
        }
168
169
        $json['destEnvTypes'] = $this->destEnvTypes;
170
171
        $resources = array_filter([
172
            'requests' => array_filter([
173
                'memory' => $this->requestMemory,
174
                'cpu' => $this->requestCpu,
175
                'storage' => $this->requestStorage,
176
            ]),
177
            'limits' => array_filter([
178
                'memory' => $this->limitMemory,
179
                'cpu' => $this->limitCpu,
180
            ]),
181
        ]);
182
183
        if (!empty($resources)) {
184
            $json['resources'] = $resources;
185
        }
186
187
        $this->checkValidity($json);
188
        return $json;
189
    }
190
191
    /** @return mixed[] */
192
    public function imageJsonSerialize(): array
193
    {
194
        $dockerfileCommands = [];
195
        $dockerfileCommands[] = 'FROM ' . $this->image;
196
        foreach ($this->environment as $key => $env) {
197
            if ($env->getType() === EnvVariableTypeEnum::IMAGE_ENV_VARIABLE) {
198
                $dockerfileCommands[] = "ENV $key" . '=' . $env->getValue();
199
            }
200
        }
201
        foreach ($this->volumes as $volume) {
202
            if ($volume->getType() === VolumeTypeEnum::BIND_VOLUME) {
203
                $dockerfileCommands[] = 'COPY ' . $volume->getSource() . ' ' . $volume->getTarget();
204
            }
205
        }
206
207
        if (!empty($this->command)) {
208
            $dockerfileCommands[] = 'CMD ' . implode(' ', $this->command);
209
        }
210
211
        $dockerfileCommands = array_merge($dockerfileCommands, $this->dockerfileCommands);
212
213
        return [
214
            'serviceName' => $this->serviceName,
215
            'dockerfileCommands' => $dockerfileCommands,
216
            'destEnvTypes' => $this->destEnvTypes,
217
        ];
218
    }
219
220
    /**
221
     * @param \stdClass|array|string $data
222
     * @return bool
223
     * @throws ServiceException
224
     */
225
    private function checkValidity($data): bool
226
    {
227
        if (\is_array($data)) {
228
            $data = \GuzzleHttp\json_decode(\GuzzleHttp\json_encode($data), false);
229
        }
230
        $validator = new Validator();
231
        $result = $validator->dataValidation($data, $this->validatorSchema);
232
        if (!$result->isValid()) {
233
            /** @var ValidationError $vError */
234
            $vError = $result->getFirstError();
235
            throw ServiceException::invalidServiceData($vError);
236
        }
237
        return $result->isValid();
238
    }
239
240
241
    /************************ getters **********************/
242
243
    public function getServiceName(): string
244
    {
245
        return $this->serviceName;
246
    }
247
248
    public function getImage(): ?string
249
    {
250
        return $this->image;
251
    }
252
253
    /** @return string[] */
254
    public function getCommand(): array
255
    {
256
        return $this->command;
257
    }
258
259
    /** @return int[] */
260
    public function getInternalPorts(): array
261
    {
262
        return $this->internalPorts;
263
    }
264
265
    /** @return string[] */
266
    public function getDependsOn(): array
267
    {
268
        return $this->dependsOn;
269
    }
270
271
    /** @return array<int, array<string, string|int>> */
272
    public function getPorts(): array
273
    {
274
        return $this->ports;
275
    }
276
277
    /** @return array<string, CommentedItem> */
278
    public function getLabels(): array
279
    {
280
        return $this->labels;
281
    }
282
283
    /** @return array<string, EnvVariable> */
284
    public function getEnvironment(): array
285
    {
286
        return $this->environment;
287
    }
288
289
    /** @return mixed[] */
290
    public function getVolumes(): array
291
    {
292
        return $this->volumes;
293
    }
294
295
    public function getNeedVirtualHost(): ?bool
296
    {
297
        return $this->needVirtualHost;
298
    }
299
300
    /** @return array<int, array<string, string|int>> */
301
    public function getVirtualHosts(): array
302
    {
303
        return $this->virtualHosts;
304
    }
305
306
    public function getNeedBuild(): ?bool
307
    {
308
        return $this->needBuild;
309
    }
310
311
    /** @return string[] */
312
    public function getDockerfileCommands(): array
313
    {
314
        return $this->dockerfileCommands;
315
    }
316
317
    public function getRequestMemory(): ?string
318
    {
319
        return $this->requestMemory;
320
    }
321
322
    public function getRequestCpu(): ?string
323
    {
324
        return $this->requestCpu;
325
    }
326
327
    public function getRequestStorage(): ?string
328
    {
329
        return $this->requestStorage;
330
    }
331
332
    public function getLimitMemory(): ?string
333
    {
334
        return $this->limitMemory;
335
    }
336
337
    public function getLimitCpu(): ?string
338
    {
339
        return $this->limitCpu;
340
    }
341
342
    /**  @return string[] */
343
    public function getDestEnvTypes(): array
344
    {
345
        return $this->destEnvTypes;
346
    }
347
348
349
    /************************ setters **********************/
350
351
    public function setServiceName(string $serviceName): void
352
    {
353
        $this->serviceName = $serviceName;
354
    }
355
356
    public function setImage(?string $image): void
357
    {
358
        $this->image = $image;
359
    }
360
361
    /** @param string[] $command */
362
    public function setCommand(array $command): void
363
    {
364
        $this->command = $command;
365
    }
366
367
    /** @param int[] $internalPorts */
368
    public function setInternalPorts(array $internalPorts): void
369
    {
370
        $this->internalPorts = $internalPorts;
371
    }
372
373
    /** @param string[] $dependsOn */
374
    public function setDependsOn(array $dependsOn): void
375
    {
376
        $this->dependsOn = $dependsOn;
377
    }
378
379
    public function setRequestMemory(string $requestMemory): void
380
    {
381
        $this->requestMemory = $requestMemory;
382
    }
383
384
    public function setRequestCpu(string $requestCpu): void
385
    {
386
        $this->requestCpu = $requestCpu;
387
    }
388
389
    public function setRequestStorage(string $requestStorage): void
390
    {
391
        $this->requestStorage = $requestStorage;
392
    }
393
394
    public function setLimitMemory(string $limitMemory): void
395
    {
396
        $this->limitMemory = $limitMemory;
397
    }
398
399
    public function setLimitCpu(string $limitCpu): void
400
    {
401
        $this->limitCpu = $limitCpu;
402
    }
403
404
    public function setNeedVirtualHost(?bool $needVirtualHost): void
405
    {
406
        $this->needVirtualHost = $needVirtualHost;
407
    }
408
409
    public function setNeedBuild(?bool $needBuild): void
410
    {
411
        $this->needBuild = $needBuild;
412
    }
413
414
415
    /************************ adders **********************/
416
417
    public function addCommand(string $command): void
418
    {
419
        $this->command[] = $command;
420
    }
421
422
    public function addInternalPort(int $internalPort): void
423
    {
424
        $this->internalPorts[] = $internalPort;
425
    }
426
427
    public function addDependsOn(string $dependsOn): void
428
    {
429
        $this->dependsOn[] = $dependsOn;
430
    }
431
432
    public function addPort(int $source, int $target, ?string $comment = null): void
433
    {
434
        $this->ports[] = array_filter([
435
            'source' => $source,
436
            'target' => $target,
437
            'comment' => $comment,
438
        ], function ($v) {
439
            return null !== $v;
440
        });
441
    }
442
443
    public function addLabel(string $key, string $value, ?string $comment = null): void
444
    {
445
        $this->labels[$key] = new CommentedItem($value, $comment);
446
    }
447
448
    public function addVirtualHost(?string $host, int $port, ?string $comment): void
449
    {
450
        $this->needVirtualHost = true;
451
        $array = [];
452
        if (null !== $host && '' !== $host) {
453
            $array['host'] = $host;
454
        }
455
        $array['port'] = $port;
456
        if (null !== $comment && '' !== $comment) {
457
            $array['comment'] = $comment;
458
        }
459
        $this->virtualHosts[] = $array;
460
    }
461
462
463
    /************************ environment adders & contains **********************/
464
465
    /** @throws ServiceException */
466
    private function addEnvVar(string $key, string $value, string $type, ?string $comment = null): void
467
    {
468
        switch ($type) {
469
            case EnvVariableTypeEnum::SHARED_ENV_VARIABLE:
470
                $this->addSharedEnvVariable($key, $value, $comment);
471
                break;
472
            case EnvVariableTypeEnum::SHARED_SECRET:
473
                $this->addSharedSecret($key, $value, $comment);
474
                break;
475
            case EnvVariableTypeEnum::IMAGE_ENV_VARIABLE:
476
                $this->addImageEnvVariable($key, $value, $comment);
477
                break;
478
            case EnvVariableTypeEnum::CONTAINER_ENV_VARIABLE:
479
                $this->addContainerEnvVariable($key, $value, $comment);
480
                break;
481
            default:
482
                throw ServiceException::unknownEnvVariableType($type);
483
        }
484
    }
485
486
    public function addSharedEnvVariable(string $key, string $value, ?string $comment = null): void
487
    {
488
        $this->environment[$key] = new EnvVariable($value, EnvVariableTypeEnum::SHARED_ENV_VARIABLE, $comment);
489
    }
490
491
    public function addSharedSecret(string $key, string $value, ?string $comment = null): void
492
    {
493
        $this->environment[$key] = new EnvVariable($value, EnvVariableTypeEnum::SHARED_SECRET, $comment);
494
    }
495
496
    public function addImageEnvVariable(string $key, string $value, ?string $comment = null): void
497
    {
498
        $this->environment[$key] = new EnvVariable($value, EnvVariableTypeEnum::IMAGE_ENV_VARIABLE, $comment);
499
    }
500
501
    public function addContainerEnvVariable(string $key, string $value, ?string $comment = null): void
502
    {
503
        $this->environment[$key] = new EnvVariable($value, EnvVariableTypeEnum::CONTAINER_ENV_VARIABLE, $comment);
504
    }
505
506
    /** @return array<string, EnvVariable> */
507
    private function getAllEnvVariablesByType(string $type): array
508
    {
509
        $res = [];
510
        /**
511
         * @var string $key
512
         * @var EnvVariable $envVar
513
         */
514
        foreach ($this->environment as $key => $envVar) {
515
            if ($envVar->getType() === $type) {
516
                $res[$key] = $envVar;
517
            }
518
        }
519
        return $res;
520
    }
521
522
    /** @return array<string, EnvVariable> */
523
    public function getAllSharedEnvVariable(): array
524
    {
525
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::SHARED_ENV_VARIABLE);
526
    }
527
528
    /** @return array<string, EnvVariable> */
529
    public function getAllSharedSecret(): array
530
    {
531
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::SHARED_SECRET);
532
    }
533
534
    /** @return array<string, EnvVariable> */
535
    public function getAllImageEnvVariable(): array
536
    {
537
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::IMAGE_ENV_VARIABLE);
538
    }
539
540
    /** @return array<string, EnvVariable> */
541
    public function getAllContainerEnvVariable(): array
542
    {
543
        return $this->getAllEnvVariablesByType(EnvVariableTypeEnum::CONTAINER_ENV_VARIABLE);
544
    }
545
546
547
    /************************ volumes adders & removers **********************/
548
549
    /** @throws ServiceException */
550
    private function addVolume(string $type, string $source, ?string $comment = null, string $target = '', bool $readOnly = false): void
551
    {
552
        switch ($type) {
553
            case VolumeTypeEnum::NAMED_VOLUME:
554
                $this->addNamedVolume($source, $target, $readOnly, $comment);
555
                break;
556
            case VolumeTypeEnum::BIND_VOLUME:
557
                $this->addBindVolume($source, $target, $readOnly, $comment);
558
                break;
559
            case VolumeTypeEnum::TMPFS_VOLUME:
560
                $this->addTmpfsVolume($source, $comment);
561
                break;
562
            default:
563
                throw ServiceException::unknownVolumeType($type);
564
        }
565
    }
566
567
    public function addNamedVolume(string $source, string $target, bool $readOnly = false, ?string $comment = null): void
568
    {
569
        $this->volumes[] = new NamedVolume($source, $target, $readOnly, $comment);
570
    }
571
572
    public function addBindVolume(string $source, string $target, bool $readOnly = false, ?string $comment = null): void
573
    {
574
        $this->volumes[] = new BindVolume($source, $target, $readOnly, $comment);
575
    }
576
577
    public function addTmpfsVolume(string $source, ?string $comment = null): void
578
    {
579
        $this->volumes[] = new TmpfsVolume($source, $comment);
580
    }
581
582
    public function addDockerfileCommand(string $dockerfileCommand): void
583
    {
584
        $this->dockerfileCommands[] = $dockerfileCommand;
585
    }
586
587
    private function removeVolumesByType(string $type): void
588
    {
589
        $filterFunction = function (Volume $vol) use ($type) {
590
            return $vol->getType() !== $type;
591
        };
592
        $this->volumes = array_values(array_filter($this->volumes, $filterFunction));
593
    }
594
595
    public function removeAllBindVolumes(): void
596
    {
597
        $this->removeVolumesByType(VolumeTypeEnum::BIND_VOLUME);
598
    }
599
600
    public function removeAllNamedVolumes(): void
601
    {
602
        $this->removeVolumesByType(VolumeTypeEnum::NAMED_VOLUME);
603
    }
604
605
    public function removeAllTmpfsVolumes(): void
606
    {
607
        $this->removeVolumesByType(VolumeTypeEnum::TMPFS_VOLUME);
608
    }
609
610
    public function removeVolumesBySource(string $source): void
611
    {
612
        $filterFunction = function (Volume $vol) use ($source) {
613
            return $vol->getSource() !== $source;
614
        };
615
        $this->volumes = array_values(array_filter($this->volumes, $filterFunction));
616
    }
617
618
619
    /************************ destEnvTypes stuffs **********************/
620
621
    public function addDestEnvType(string $envType, bool $keepTheOtherEnvTypes = true): void
622
    {
623
        if (!$keepTheOtherEnvTypes) {
624
            $this->destEnvTypes = [];
625
        }
626
        $this->destEnvTypes[] = $envType;
627
    }
628
629
    public function isForDevEnvType(): bool
630
    {
631
        return empty($this->destEnvTypes) || \in_array(CommonMetadata::ENV_TYPE_DEV, $this->destEnvTypes);
632
    }
633
634
    public function isForTestEnvType(): bool
635
    {
636
        return empty($this->destEnvTypes) || \in_array(CommonMetadata::ENV_TYPE_TEST, $this->destEnvTypes);
637
    }
638
639
    public function isForProdEnvType(): bool
640
    {
641
        return empty($this->destEnvTypes) || \in_array(CommonMetadata::ENV_TYPE_PROD, $this->destEnvTypes);
642
    }
643
644
    public function isForMyEnvType(): bool
645
    {
646
        $myEnvType = Manifest::getMetadata(CommonMetadata::ENV_TYPE_KEY);
647
        return empty($this->destEnvTypes) || \in_array($myEnvType, $this->destEnvTypes, true);
648
    }
649
}
650