Repository navigation
Expand file tree
/
Copy pathDocker.php
More file actions
313 lines (286 loc) · 12.1 KB
/
Copy pathDocker.php
File metadata and controls
313 lines (286 loc) · 12.1 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<?php
declare(strict_types=1);
namespace Docker;
use Docker\API\Client;
use Docker\API\Endpoint\SystemInfo;
use Docker\API\Model\AuthConfig;
use Docker\API\Model\ExecIdStartPostBody;
use Docker\Endpoint\ContainerAttach;
use Docker\Endpoint\ContainerAttachWebsocket;
use Docker\Endpoint\ContainerLogs;
use Docker\Endpoint\ContainerStats;
use Docker\Endpoint\ExecStart;
use Docker\Endpoint\ImageBuild;
use Docker\Endpoint\ImageCreate;
use Docker\Endpoint\ImagePush;
use Docker\Endpoint\InteractiveExecStart;
use Docker\Endpoint\SystemEvents;
use Docker\API\Normalizer\JaneObjectNormalizer;
use Docker\API\Runtime\Client\Endpoint;
use Docker\API\Runtime\Client\FormEncoder;
use Docker\Exception\BadRequestException;
use Docker\Exception\UnexpectedStatusCodeException;
use Docker\Http\InteractiveHttpClient;
use Docker\Serializer\LargeIntegerJsonDecode;
use Docker\Stream\AttachWebsocketStream;
use Docker\Stream\BuildStream;
use Docker\Stream\CreateImageStream;
use Docker\Stream\DockerRawStream;
use Docker\Stream\EventStream;
use Docker\Stream\InteractiveExecStream;
use Docker\Stream\PushStream;
use Docker\Stream\StatsStream;
use Docker\Stream\SocketReadStream;
use Http\Client\Socket\Stream as SocketStream;
use Nyholm\Psr7\Stream;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Serializer\Encoder\JsonEncode;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Serializer;
/**
* Docker\Docker.
*/
class Docker extends Client
{
private bool $interactiveExecEnabled = false;
private bool $throwOnUnexpectedStatus = true;
/**
* Whether an error status that the generated endpoint does not handle
* throws an UnexpectedStatusCodeException (the default).
*
* Pass false to return null for those responses, as 3.x did by default.
*/
public function throwOnUnexpectedStatus(bool $enabled = true): static
{
$this->throwOnUnexpectedStatus = $enabled;
return $this;
}
public function executeEndpoint(Endpoint $endpoint, string $fetch = self::FETCH_OBJECT)
{
if (self::FETCH_OBJECT !== $fetch) {
return parent::executeEndpoint($endpoint, $fetch);
}
$response = $this->executeRawEndpoint($endpoint);
if ($response->getStatusCode() < 400) {
return $endpoint->parseResponse($response, $this->serializer, $fetch);
}
// Error bodies are small. Buffer them so the message is still readable
// after the generated endpoint has parsed the body.
$response = $response->withBody(Stream::create((string) $response->getBody()));
$result = $endpoint->parseResponse($response, $this->serializer, $fetch);
if (null !== $result) {
return $result;
}
if ($this->throwOnUnexpectedStatus) {
throw UnexpectedStatusCodeException::fromResponse($endpoint->getMethod(), $endpoint->getUri(), $response);
}
return null;
}
/**
* {@inheritdoc}
*
* @return ($fetch is 'object' ? DockerRawStream|null : ResponseInterface)
*/
public function containerAttach(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = [])
{
return $this->executeEndpoint(new ContainerAttach(
$id,
$queryParameters,
$accept,
fn (): bool => (bool) $this->containerInspect($id)->getConfig()?->getTty()
), $fetch);
}
/**
* {@inheritdoc}
*
* @return ($fetch is 'object' ? AttachWebsocketStream|null : ResponseInterface)
*/
public function containerAttachWebsocket(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = [])
{
return $this->executeEndpoint(new ContainerAttachWebsocket($id, $queryParameters, $accept), $fetch);
}
/**
* {@inheritdoc}
*
* @return ($fetch is 'object' ? DockerRawStream|null : ResponseInterface)
*/
public function containerLogs(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = [])
{
return $this->executeEndpoint(new ContainerLogs(
$id,
$queryParameters,
$accept,
fn (): bool => (bool) $this->containerInspect($id)->getConfig()?->getTty()
), $fetch);
}
/**
* {@inheritdoc}
*
* With `stream => true` (the default) the result is a StatsStream that
* delivers one sample per frame; with `stream => false` it is one sample.
* Samples are ContainerStatsResponse models from API 1.48, and decoded
* \stdClass objects for earlier API versions.
*
* @return ($fetch is 'object' ? StatsStream|object|null : ResponseInterface)
*/
public function containerStats(string $id, array $queryParameters = [], string $fetch = self::FETCH_OBJECT)
{
return $this->executeEndpoint(new ContainerStats($id, $queryParameters), $fetch);
}
/**
* {@inheritdoc}
*
* @return ($fetch is 'object' ? DockerRawStream|null : ResponseInterface)
*/
public function execStart(string $id, ?ExecIdStartPostBody $requestBody = null, string $fetch = self::FETCH_OBJECT, array $accept = [])
{
return $this->executeEndpoint(new ExecStart($id, $requestBody, $accept), $fetch);
}
/**
* Start attached exec with nonblocking stdin/stdout/stderr. timeoutMs is a
* streaming deadline after upgrade; HTTP setup uses the factory timeout.
* Inspect the exec separately after output EOF to obtain its exit status.
*/
public function execStartInteractive(string $id, ?ExecIdStartPostBody $requestBody = null, ?int $timeoutMs = null): InteractiveExecStream
{
if (!$this->interactiveExecEnabled) {
throw new \LogicException('Interactive exec requires DockerClientFactory::createInteractive() or the default socket client.');
}
if (null !== $timeoutMs && ($timeoutMs < 1 || $timeoutMs > 86400000)) {
throw new \InvalidArgumentException('Interactive exec timeout must be between 1 and 86400000 milliseconds.');
}
if ('' === $id) {
throw new \InvalidArgumentException('An exec ID is required.');
}
$body = null === $requestBody ? new ExecIdStartPostBody() : clone $requestBody;
if ($body->getDetach()) {
throw new \InvalidArgumentException('Interactive exec cannot be detached.');
}
$body->setDetach(false);
$response = $this->executeRawEndpoint(new InteractiveExecStart($id, $body));
$stream = $response->getBody();
$mediaType = strtolower(trim(explode(';', $response->getHeaderLine('Content-Type'))[0]));
if (101 !== $response->getStatusCode()
|| 'tcp' !== strtolower(trim($response->getHeaderLine('Upgrade')))
|| !preg_match('/(?:^|,)\s*upgrade\s*(?:,|$)/i', $response->getHeaderLine('Connection'))
|| $response->hasHeader('Transfer-Encoding')
|| $response->hasHeader('Content-Encoding')
|| !\in_array($mediaType, [DockerRawStream::HEADER, DockerRawStream::MULTIPLEXED_HEADER], true)
|| (!$stream instanceof SocketReadStream && !$stream instanceof SocketStream)) {
$stream->close();
throw new \RuntimeException('Docker did not provide a supported interactive exec upgrade (HTTP '.$response->getStatusCode().').');
}
// The detached resource keeps bytes PHP read ahead with the headers.
$socket = $stream->detach();
try {
return new InteractiveExecStream($socket, !(bool) $body->getTty(), $timeoutMs);
} catch (\Throwable $error) {
if (\is_resource($socket)) {
fclose($socket);
}
throw $error;
}
}
/**
* {@inheritdoc}
*
* @param array{
* "dockerfile"?: string,
* "t"?: string|list<string>,
* "extrahosts"?: string,
* "remote"?: string,
* "q"?: bool,
* "nocache"?: bool,
* "cachefrom"?: string,
* "pull"?: string,
* "rm"?: bool,
* "forcerm"?: bool,
* "memory"?: int,
* "memswap"?: int,
* "cpushares"?: int,
* "cpusetcpus"?: string,
* "cpuperiod"?: int,
* "cpuquota"?: int,
* "buildargs"?: string,
* "shmsize"?: int,
* "squash"?: bool,
* "labels"?: string,
* "networkmode"?: string,
* "platform"?: string,
* "target"?: string,
* "outputs"?: string,
* "version"?: string,
* } $queryParameters
*
* @return ($fetch is 'object' ? BuildStream|null : ResponseInterface)
*/
public function imageBuild($requestBody = null, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT)
{
return $this->executeEndpoint(new ImageBuild($requestBody, $queryParameters, $headerParameters), $fetch);
}
/**
* {@inheritdoc}
*
* @return ($fetch is 'object' ? CreateImageStream|null : ResponseInterface)
*/
public function imageCreate(?string $requestBody = null, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT)
{
return $this->executeEndpoint(new ImageCreate($requestBody, $queryParameters, $headerParameters), $fetch);
}
/**
* {@inheritdoc}
*
* @return ($fetch is 'object' ? PushStream|null : ResponseInterface)
*/
public function imagePush(string $name, array $queryParameters = [], array $headerParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = [])
{
if (isset($headerParameters['X-Registry-Auth']) && $headerParameters['X-Registry-Auth'] instanceof AuthConfig) {
$headerParameters['X-Registry-Auth'] = base64_encode($this->serializer->serialize($headerParameters['X-Registry-Auth'], 'json'));
}
return $this->executeEndpoint(new ImagePush($name, $queryParameters, $headerParameters, $accept), $fetch);
}
/**
* {@inheritdoc}
*
* @return ($fetch is 'object' ? EventStream|null : ResponseInterface)
*/
public function systemEvents(array $queryParameters = [], string $fetch = self::FETCH_OBJECT, array $accept = [])
{
// API 1.52 and later accept an Accept header; earlier endpoints ignore it.
return $this->executeEndpoint(new SystemEvents($queryParameters, $accept), $fetch);
}
public static function create(
$httpClient = null,
array $additionalPlugins = [],
array $additionalNormalizers = [],
bool $applyServerPlugins = true
): self {
if (null === $httpClient) {
$httpClient = DockerClientFactory::createInteractiveFromEnv();
$applyServerPlugins = false;
}
$client = parent::create($httpClient, $additionalPlugins, $additionalNormalizers, $applyServerPlugins);
$client->serializer = new Serializer(
[new ArrayDenormalizer(), new JaneObjectNormalizer(), ...$additionalNormalizers],
[new JsonEncoder(new JsonEncode(), new LargeIntegerJsonDecode(['json_decode_associative' => true])), new FormEncoder()]
);
$client->interactiveExecEnabled = $httpClient instanceof InteractiveHttpClient;
$response = $client->executeRawEndpoint(new SystemInfo());
$testClient = $response->getBody()->getContents();
$jsonObj = json_decode($testClient);
if ($jsonObj !== null) {
if (isset($jsonObj->message)) {
// Check if the client is too new
if (strpos($jsonObj->message, 'client version') !== false && strpos($jsonObj->message, 'is too new') !== false) {
throw new BadRequestException("The client version is not supported by your version of Docker. Message: {$jsonObj->message}", $response);
} else {
throw new BadRequestException($jsonObj->message, $response);
}
}
} else {
throw new BadRequestException("Failed to decode JSON.", $response);
}
return $client;
}
}