Completed
Pull Request — master (#88)
by Jindun
02:45
created

Service::getNeedVirtualHost()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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