Completed
Push — master ( 6da405...1ba64e )
by Jindun
9s
created

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