Completed
Push — master ( 4c931f...d5bb13 )
by David
17s
created

Service::addVirtualHostPrefix()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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