Completed
Push — master ( f6a8c2...6b83e1 )
by David
25s
created

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