Completed
Pull Request — master (#97)
by Jindun
02:50
created

Service::removeVolumesByType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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