Debian Codegraph @

vendor/wikimedia/shellbox/src/Command/LocalBoxedExecutor.php

raw
1 <?php
2
3 namespace Shellbox\Command;
4
5 use GuzzleHttp\ClientInterface as GuzzleClientInterface;
6 use GuzzleHttp\Exception\RequestException;
7 use GuzzleHttp\HandlerStack;
8 use GuzzleHttp\MessageFormatter;
9 use GuzzleHttp\Middleware;
10 use GuzzleHttp\Promise\EachPromise;
11 use GuzzleHttp\Psr7\Request;
12 use GuzzleHttp\Psr7\Response;
13 use Psr\Http\Client\ClientInterface;
14 use Psr\Http\Message\ResponseInterface;
15 use Psr\Log\LoggerInterface;
16 use Psr\Log\NullLogger;
17 use Shellbox\FileUtils;
18 use Shellbox\ShellboxError;
19 use Shellbox\TempDirManager;
20
21 /**
22 * An executor which runs a BoxedCommand locally.
23 *
24 * This is overridden by ServerBoxedExecutor, which runs a BoxedCommand in the
25 * context of a Server.
26 */
27 class LocalBoxedExecutor extends BoxedExecutor {
28 /** @var UnboxedExecutor */
29 protected $unboxedExecutor;
30 /** @var TempDirManager */
31 protected $tempDirManager;
32 /** @var LoggerInterface */
33 protected $logger;
34 /** @var ClientInterface|null */
35 private $urlFileClient;
36 /** @var int */
37 private $urlFileConcurrency = 1;
38 /** @var int */
39 private $uploadAttempts = 3;
40 /** @var int|float */
41 private $retryDelay = 1.0;
42
43 private const PUT_SUCCESS = [ 200, 201, 202, 204 ];
44
45 /**
46 * @param UnboxedExecutor $unboxedExecutor
47 * @param TempDirManager $tempDirManager
48 */
49 public function __construct(
50 UnboxedExecutor $unboxedExecutor,
51 TempDirManager $tempDirManager
52 ) {
53 $this->unboxedExecutor = $unboxedExecutor;
54 $this->tempDirManager = $tempDirManager;
55 $this->logger = new NullLogger;
56 }
57
58 public function executeValid( BoxedCommand $command ) {
59 $command = $this->applyBoxConfig( $command );
60 $this->createInputFiles( $command );
61 $this->prepareOutputDirectories( $command );
62 $result = $this->createResult();
63 $result->merge( $this->unboxedExecutor->execute( $command ) );
64 $this->collectOutputFiles( $command, $result );
65 $this->cleanup();
66 return $result;
67 }
68
69 /**
70 * Set the logger
71 *
72 * @param LoggerInterface $logger
73 */
74 public function setLogger( LoggerInterface $logger ) {
75 $this->logger = $logger;
76 }
77
78 /**
79 * Set the client to use for fetching and putting files specified by URL.
80 *
81 * @since 4.1.0
82 * @param ClientInterface $urlFileClient
83 * @param array $options Associative array of upload/download options:
84 * - concurrency: The maximum number of concurrent connections to use.
85 * This will be ignored if the client does not implement Guzzle's
86 * interface, with its async methods.
87 * - uploadAttempts: The maximum number of times to try to upload a given
88 * file; the number of retries plus one.
89 * before throwing a fatal error, discarding the command's results.
90 * - retryDelay: The number of seconds to delay between retries.
91 */
92 public function setUrlFileClient( ClientInterface $urlFileClient, array $options = [] ) {
93 $this->urlFileClient = $urlFileClient;
94 if ( isset( $options['concurrency'] ) ) {
95 $this->urlFileConcurrency = $options['concurrency'];
96 }
97 if ( isset( $options['uploadAttempts'] ) ) {
98 $this->uploadAttempts = $options['uploadAttempts'];
99 }
100 if ( isset( $options['retryDelay'] ) ) {
101 $this->retryDelay = $options['retryDelay'];
102 }
103 }
104
105 public function areUrlFilesAllowed() {
106 return $this->urlFileClient !== null;
107 }
108
109 /**
110 * @return BoxedResult
111 */
112 protected function createResult() {
113 return new BoxedResult;
114 }
115
116 /**
117 * Copy input files from the BoxedCommand to the working directory, ready
118 * for command execution.
119 *
120 * @param BoxedCommand $command
121 */
122 protected function createInputFiles( BoxedCommand $command ) {
123 $filesToDownload = [];
124 foreach ( $command->getInputFiles() as $boxedName => $file ) {
125 if ( $file instanceof InputFileWithContents ) {
126 $path = $this->tempDirManager->preparePath( $boxedName );
127 $file->copyTo( $path );
128 } elseif ( $file instanceof InputFileFromUrl ) {
129 $filesToDownload[$boxedName] = $file;
130 } else {
131 throw new ShellboxError( "Unknown input file type for file \"$boxedName\"" );
132 }
133 }
134 if ( $filesToDownload ) {
135 $this->downloadFiles( $filesToDownload );
136 }
137 }
138
139 /**
140 * Download the InputFileFromUrl files to the working directory
141 *
142 * @param InputFileFromUrl[] $files The files to download, keyed by name
143 */
144 protected function downloadFiles( array $files ) {
145 $requests = [];
146 foreach ( $files as $boxedName => $file ) {
147 $requests[$boxedName] = new Request(
148 'GET',
149 $file->getUrl(),
150 $file->getHeaders()
151 );
152 }
153 if ( $this->urlFileClient instanceof GuzzleClientInterface ) {
154 $this->downloadFilesWithGuzzle( $this->urlFileClient, $requests );
155 } elseif ( !$this->urlFileClient ) {
156 throw new ShellboxError( "Can't download files with no HTTP client configured" );
157 } else {
158 $this->downloadFilesWithPsrClient( $this->urlFileClient, $requests );
159 }
160 }
161
162 private function downloadFilesWithPsrClient( ClientInterface $client, array $requests ) {
163 foreach ( $requests as $boxedName => $request ) {
164 $response = $client->sendRequest( $request );
165 $code = $response->getStatusCode();
166 $this->logger->info( 'URL PSR file request: {method} {uri} -> {code}',
167 [
168 'method' => $request->getMethod(),
169 'uri' => (string)$request->getUri(),
170 'code' => $code,
171 ]
172 );
173 if ( $code !== 200 ) {
174 $this->throwUrlFileError( $boxedName, $response,
175 'Failed to download input file' );
176 }
177 $path = $this->tempDirManager->preparePath( $boxedName );
178 FileUtils::copyStreamToFile( $response->getBody(), $path );
179 }
180 }
181
182 /**
183 * Download the files with streaming and concurrency. It doesn't really
184 * have to use Guzzle, it could be a user-supplied client that implements
185 * Guzzle's interface. But the 'sink' option must be supported.
186 *
187 * @param GuzzleClientInterface $client
188 * @param Request[] $requests
189 */
190 private function downloadFilesWithGuzzle( GuzzleClientInterface $client, array $requests ) {
191 $handler = HandlerStack::create();
192 $handler->unshift( Middleware::log( $this->logger, $this->getUrlMessageFormatter() ) );
193 $options = [
194 'handler' => $handler,
195 'allow_redirects' => false
196 ];
197
198 $promises = function () use ( $requests, $client, $options ) {
199 foreach ( $requests as $boxedName => $request ) {
200 $path = $this->tempDirManager->preparePath( $boxedName );
201 yield $boxedName
202 => $client->sendAsync( $request, $options + [ 'sink' => $path ] );
203 }
204 };
205 $each = new EachPromise(
206 $promises(),
207 [
208 'concurrency' => $this->urlFileConcurrency,
209 'fulfilled' => function ( Response $response, $boxedName ) {
210 $code = $response->getStatusCode();
211 if ( $code !== 200 ) {
212 $this->throwUrlFileError( $boxedName, $response,
213 'Failed to download input file' );
214 }
215 },
216 'rejected' => static function ( RequestException $reason, $boxedName ) {
217 // @phan-suppress-previous-line PhanPluginNeverReturnFunction
218 throw new ShellboxError(
219 "Failed to download input file \"$boxedName\": " .
220 $reason->getMessage() );
221 },
222 ]
223 );
224 $each->promise()->wait();
225 }
226
227 /**
228 * Throw an error due to an invalid response
229 *
230 * @param string $boxedName
231 * @param ResponseInterface $response
232 * @param string $prefix
233 * @return never
234 * @throws ShellboxError
235 */
236 private function throwUrlFileError( string $boxedName, ResponseInterface $response, $prefix ) {
237 $code = $response->getStatusCode();
238 $message = $response->getBody()->getContents();
239 $message = strip_tags( $message );
240 if ( strlen( $message ) > 1000 ) {
241 $message = substr( $message, 0, 1000 );
242 }
243 throw new ShellboxError(
244 "$prefix \"$boxedName\" with code $code: $message" );
245 }
246
247 /**
248 * Ensure that any subdirectories named in registered output files are
249 * created, so that the command can write the files there.
250 *
251 * @param BoxedCommand $command
252 */
253 protected function prepareOutputDirectories( BoxedCommand $command ) {
254 foreach ( $command->getOutputFiles() as $boxedName => $file ) {
255 $this->tempDirManager->preparePath( $boxedName );
256 }
257
258 foreach ( $command->getOutputGlobs() as $boxedName => $file ) {
259 $this->tempDirManager->preparePath( $boxedName );
260 }
261 }
262
263 /**
264 * Modify the configuration of the command as required by the BoxedCommand
265 * abstraction, returning a cloned BoxedCommand.
266 *
267 * @param BoxedCommand $command
268 * @return BoxedCommand
269 */
270 protected function applyBoxConfig( BoxedCommand $command ) {
271 $command = clone $command;
272 return $command
273 ->workingDirectory( $this->tempDirManager->prepareBasePath() )
274 ->passStdin( false )
275 ->forwardStderr( false );
276 }
277
278 /**
279 * This is called after the command has run. Find any output files which
280 * match output files and globs that were registered in the BoxedCommand.
281 *
282 * @param BoxedCommand $command
283 * @param BoxedResult $result
284 * @return OutputFile[] OutputFile objects indexed by the found filename
285 * relative to the working directory.
286 */
287 protected function findOutputFiles( BoxedCommand $command, BoxedResult $result ) {
288 $files = [];
289 foreach ( $command->getOutputFiles() as $boxedName => $file ) {
290 $sourcePath = $this->tempDirManager->getPath( $boxedName );
291 if ( file_exists( $sourcePath ) ) {
292 $requiredCode = $file->getRequiredExitCode();
293 if ( $requiredCode !== null && $result->getExitCode() !== $requiredCode ) {
294 $this->logger->debug(
295 "Ignoring output file $boxedName: required exit code not returned" );
296 } else {
297 $files[$boxedName] = $file;
298 }
299 } else {
300 $this->logger->debug( 'After executing route ' . $command->getRouteName() .
301 ": did not find expected output file $boxedName" );
302 }
303 }
304
305 foreach ( $command->getOutputGlobs() as $glob ) {
306 $prefixPath = $this->tempDirManager->getPath( $glob->getPrefix() );
307 foreach ( glob( "$prefixPath*.{$glob->getExtension()}" ) as $path ) {
308 $base = basename( $path );
309 if ( strpos( $glob->getPrefix(), '/' ) === false ) {
310 $boxedName = $base;
311 } else {
312 $boxedName = dirname( $glob->getPrefix() ) . '/' . $base;
313 }
314 $files[$boxedName] = $glob->getOutputFile( $boxedName );
315 }
316 }
317
318 return $files;
319 }
320
321 /**
322 * This is called after the command has run. Find output files and copy
323 * them to the registered destination location, which may be either a path
324 * outside the working directory, or a string. Register the details in the
325 * supplied BoxedResult.
326 *
327 * @param BoxedCommand $command
328 * @param BoxedResult $result
329 */
330 protected function collectOutputFiles( BoxedCommand $command, BoxedResult $result ) {
331 $filesToUpload = [];
332 foreach ( $this->findOutputFiles( $command, $result ) as $boxedName => $outputFile ) {
333 if ( $outputFile instanceof OutputFileWithContents ) {
334 $outputFile->copyFromFile( $this->tempDirManager->getPath( $boxedName ) );
335 } elseif ( $outputFile instanceof OutputFileToUrl ) {
336 $filesToUpload[$boxedName] = $outputFile;
337 }
338 $result->addOutputFile( $boxedName, $outputFile );
339 }
340
341 if ( $filesToUpload ) {
342 $this->uploadFiles( $filesToUpload );
343 }
344 }
345
346 /**
347 * @param OutputFileToUrl[] $files
348 */
349 protected function uploadFiles( array $files ) {
350 $requests = [];
351 foreach ( $files as $boxedName => $file ) {
352 $stream = FileUtils::openInputFileStream( $this->tempDirManager->getPath( $boxedName ) );
353 $headers = $file->getHeaders();
354 if ( $file->isMwContentHashEnabled() ) {
355 $headers += FileUtils::getMwHashes( $stream );
356 $stream->rewind();
357 }
358 $headers['content-length'] = $stream->getSize();
359 $requests[$boxedName] = new Request(
360 'PUT',
361 $file->getUrl(),
362 $headers,
363 $stream
364 );
365 }
366 if ( $this->urlFileClient instanceof GuzzleClientInterface ) {
367 $this->uploadFilesWithGuzzle( $this->urlFileClient, $requests );
368 } elseif ( !$this->urlFileClient ) {
369 throw new ShellboxError( "Can't upload files with no HTTP client configured" );
370 } else {
371 $this->uploadFilesWithPsrClient( $this->urlFileClient, $requests );
372 }
373 }
374
375 /**
376 * @param GuzzleClientInterface $client
377 * @param Request[] $requests
378 */
379 private function uploadFilesWithGuzzle( GuzzleClientInterface $client, array $requests ) {
380 $likelyPermanent = [ 404 ];
381 $handler = HandlerStack::create();
382 $handler->unshift( Middleware::log( $this->logger, $this->getUrlMessageFormatter() ) );
383 $options = [
384 'handler' => $handler,
385 'allow_redirects' => false,
386 ];
387
388 $shouldRetry = function ( $retries, Request $request, ?Response $response,
389 ?RequestException $exception ) use ( $likelyPermanent )
390 {
391 if ( $retries + 1 >= $this->uploadAttempts ) {
392 return false;
393 }
394 if ( !$response || $exception ) {
395 return true;
396 }
397 $code = $response->getStatusCode();
398 if ( in_array( $code, $likelyPermanent ) ) {
399 return false;
400 }
401 return !in_array( $code, self::PUT_SUCCESS );
402 };
403
404 $delay = $this->retryDelay;
405 $delayFunc = static function () use ( $delay ) {
406 return $delay;
407 };
408
409 $handler->unshift( Middleware::retry( $shouldRetry, $delayFunc ) );
410
411 $promises = static function () use ( $requests, $client, $options ) {
412 foreach ( $requests as $boxedName => $request ) {
413 yield $boxedName => $client->sendAsync( $request, $options );
414 }
415 };
416
417 $each = new EachPromise(
418 $promises(),
419 [
420 'concurrency' => $this->urlFileConcurrency,
421 'fulfilled' => function ( Response $response, $boxedName ) {
422 if ( !in_array( $response->getStatusCode(), self::PUT_SUCCESS ) ) {
423 $this->throwUrlFileError( $boxedName, $response,
424 'Failed to upload output file' );
425 }
426 },
427 'rejected' => static function ( RequestException $ex, $boxedName ) {
428 // @phan-suppress-previous-line PhanPluginNeverReturnFunction
429 throw new ShellboxError(
430 "Failed to upload output file \"$boxedName\": " .
431 $ex->getMessage() );
432 },
433 ]
434 );
435 $each->promise()->wait();
436 }
437
438 /**
439 * @param ClientInterface $client
440 * @param Request[] $requests
441 */
442 private function uploadFilesWithPsrClient( ClientInterface $client, array $requests ) {
443 foreach ( $requests as $boxedName => $request ) {
444 $response = $client->sendRequest( $request );
445 $code = $response->getStatusCode();
446 $this->logger->info( 'URL PSR file request: {method} {uri} -> {code}',
447 [
448 'method' => $request->getMethod(),
449 'uri' => (string)$request->getUri(),
450 'code' => $code,
451 ]
452 );
453 if ( !in_array( $code, self::PUT_SUCCESS ) ) {
454 $this->throwUrlFileError( $boxedName, $response,
455 'Failed to upload output file' );
456 }
457 $path = $this->tempDirManager->preparePath( $boxedName );
458 FileUtils::copyStreamToFile( $response->getBody(), $path );
459 }
460 }
461
462 /**
463 * Get the MessageFormatter to use for logging URL file requests
464 * @return MessageFormatter
465 */
466 private function getUrlMessageFormatter() {
467 return new MessageFormatter( 'URL file request: {method} {uri} -> {code} {error}' );
468 }
469
470 /**
471 * Clean up files after execute
472 */
473 protected function cleanup() {
474 $this->tempDirManager->teardown();
475 }
476 }