-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathStartedGenericContainer.php
More file actions
229 lines (188 loc) · 6.84 KB
/
Copy pathStartedGenericContainer.php
File metadata and controls
229 lines (188 loc) · 6.84 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
<?php
declare(strict_types=1);
namespace Testcontainers\Container;
use Docker\API\Client;
use Docker\API\Model\ContainersIdExecPostBody;
use Docker\API\Model\ContainersIdJsonGetResponse200;
use Docker\API\Model\EndpointSettings;
use Docker\API\Model\ExecIdStartPostBody;
use Docker\API\Model\IdResponse;
use Docker\API\Model\PortBinding;
use Docker\API\Runtime\Client\Client as DockerRuntimeClient;
use Docker\Docker;
use RuntimeException;
use Testcontainers\ContainerClient\DockerContainerClient;
use Testcontainers\Utils\HostResolver;
class StartedGenericContainer implements StartedTestContainer
{
protected Docker $dockerClient;
protected ?ContainersIdJsonGetResponse200 $inspectResponse = null;
protected ?string $lastExecId = null;
public function __construct(protected readonly string $id, ?Docker $dockerClient = null)
{
$this->dockerClient = $dockerClient ?? DockerContainerClient::getDockerClient();
}
public function getId(): string
{
return $this->id;
}
public function getLastExecId(): ?string
{
return $this->lastExecId;
}
public function getClient(): Docker
{
return $this->dockerClient;
}
/**
* @param list<string> $command
*/
public function exec(array $command): string
{
$execConfig = (new ContainersIdExecPostBody())
->setCmd($command)
->setAttachStdout(true)
->setAttachStderr(true);
// Create and start the exec command
/** @var IdResponse | null $exec */
$exec = $this->dockerClient->containerExec($this->id, $execConfig);
if ($exec === null || $exec->getId() === null) {
throw new RuntimeException('Failed to create exec command');
}
$this->lastExecId = $exec->getId();
$startConfig = new ExecIdStartPostBody();
$startConfig->setDetach(false);
$contents = $this->dockerClient
->execStart($this->lastExecId, $startConfig, Client::FETCH_RESPONSE)
?->getBody()
->getContents() ?? '';
return $this->sanitizeOutput($contents);
}
public function stop(): StoppedTestContainer
{
$this->dockerClient->containerStop($this->id);
$this->dockerClient->containerDelete($this->id);
return new StoppedGenericContainer($this->id);
}
public function restart(): self
{
$this->dockerClient->containerRestart($this->id);
return $this;
}
public function logs(): string
{
$output = $this->dockerClient
->containerLogs(
$this->id,
['stdout' => true, 'stderr' => true],
DockerRuntimeClient::FETCH_RESPONSE
)
?->getBody()
->getContents() ?? '';
/**
* @var string|false $converted
*/
$converted = mb_convert_encoding($output, 'UTF-8', 'UTF-8');
return $this->sanitizeOutput($converted == false ? $output : $converted);
}
public function getHost(): string
{
return (new HostResolver($this->dockerClient))->resolveHost();
}
public function getMappedPort(int $port): int
{
$ports = (array) $this->getBoundPorts();
/** @var PortBinding | null $portBinding */
$portBinding = $ports["{$port}/tcp"][0] ?? null;
$mappedPort = $portBinding?->getHostPort();
if ($mappedPort !== null) {
return (int) $mappedPort;
}
throw new RuntimeException("Failed to get mapped port ‘{$mappedPort}’ for container");
}
public function getFirstMappedPort(): int
{
$ports = (array) $this->getBoundPorts();
$port = array_key_first($ports);
/** @var PortBinding | null $firstPortBinding */
$firstPortBinding = $ports[$port][0] ?? null;
$firstMappedPort = $firstPortBinding?->getHostPort();
if ($firstMappedPort !== null) {
return (int) $firstMappedPort;
}
throw new RuntimeException('Failed to get first mapped port for container');
}
public function getName(): string
{
return trim($this->inspect()?->getName() ?? '', '/ ');
}
/**
* @return array<string, string>
*/
public function getLabels(): array
{
return (array) $this->inspect()?->getConfig()?->getLabels();
}
/**
* @return string[]
*/
public function getNetworkNames(): array
{
$networks = (array) $this->inspect()?->getNetworkSettings()?->getNetworks();
return array_keys($networks);
}
public function getNetworkId(string $networkName): string
{
$networks = (array) $this->inspect()?->getNetworkSettings()?->getNetworks();
/** @var EndpointSettings | null $endpointSettings */
$endpointSettings = $networks[$networkName] ?? null;
$networkID = $endpointSettings?->getNetworkID();
if ($networkID !== null) {
return $networkID;
}
throw new RuntimeException("Network with name ‘{$networkName}’ does not exist");
}
public function getIpAddress(string $networkName): string
{
$networks = (array) $this->inspect()?->getNetworkSettings()?->getNetworks();
/** @var EndpointSettings | null $endpointSettings */
$endpointSettings = $networks[$networkName] ?? null;
$ipAddress = $endpointSettings?->getIPAddress();
if ($ipAddress !== null) {
return $ipAddress;
}
throw new RuntimeException("Network with name ‘{$networkName}’ does not exist");
}
protected function inspect(): ContainersIdJsonGetResponse200 | null
{
if ($this->inspectResponse === null) {
/** @var ContainersIdJsonGetResponse200 | null $inspectResponse */
$inspectResponse = $this->dockerClient->containerInspect($this->id);
$this->inspectResponse = $inspectResponse;
}
return $this->inspectResponse;
}
/**
* @return iterable<string, array<PortBinding>>
* @throws RuntimeException
*/
public function getBoundPorts(): iterable
{
/**
* For some reason, in the latest Docker releases, at this moment, the container might not be fully started.
* This can lead to issues when trying to retrieve the ports.
* TODO: find a better strategy to ensure the container is fully started or run in a loop until it is ready.
* For the loop $this->inspect() shouldn't be cached.
*/
usleep(300 * 1000);
$ports = $this->inspect()?->getNetworkSettings()?->getPorts();
if ($ports === null) {
throw new RuntimeException('Failed to get ports from container');
}
return $ports;
}
protected function sanitizeOutput(string $output): string
{
return preg_replace('/[\x00-\x1F\x7F]/u', '', $output) ?? '';
}
}