-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathNetworkManager.php
More file actions
98 lines (83 loc) · 2.68 KB
/
NetworkManager.php
File metadata and controls
98 lines (83 loc) · 2.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
namespace OpenRuntimes\Executor\Runner;
use Utopia\Console;
use Utopia\Orchestration\Container;
use Utopia\Orchestration\Orchestration;
use function Swoole\Coroutine\batch;
class NetworkManager
{
/** @var string[] Networks available for use */
private array $available = [];
/**
* @param string[] $networks Networks to ensure exist
*/
public function __construct(
private readonly Orchestration $orchestration,
array $networks,
) {
if (empty($networks)) {
return;
}
$jobs = array_map(
fn (string $network) => fn (): ?string => $this->ensure($network),
$networks
);
$this->available = array_values(array_filter(
batch($jobs),
fn ($v) => \is_string($v) && $v !== ''
));
}
/** @return string[] */
public function getAvailable(): array
{
return $this->available;
}
public function connectAll(Container $container): void
{
foreach ($this->available as $network) {
try {
$this->orchestration->networkConnect($container->getName(), $network);
} catch (\Throwable) {
// TODO: Orchestration library should throw a distinct exception for "already connected"
}
}
}
public function removeAll(): void
{
if (empty($this->available)) {
return;
}
batch(array_map(
fn ($network) => fn () => $this->remove($network),
$this->available
));
}
private function remove(string $network): void
{
if (!$this->orchestration->networkExists($network)) {
Console::error("[NetworkManager] Network {$network} does not exist");
return;
}
try {
$this->orchestration->removeNetwork($network);
Console::success("[NetworkManager] Removed network: {$network}");
} catch (\Throwable $e) {
Console::error("[NetworkManager] Failed to remove network {$network}: {$e->getMessage()}");
}
}
private function ensure(string $network): ?string
{
if ($this->orchestration->networkExists($network)) {
Console::info("[NetworkManager] Network {$network} already exists");
return $network;
}
try {
$this->orchestration->createNetwork($network, false);
Console::success("[NetworkManager] Created network: {$network}");
return $network;
} catch (\Throwable $e) {
Console::error("[NetworkManager] Failed to create network {$network}: {$e->getMessage()}");
return null;
}
}
}