Debian Codegraph @

lib/3rdParty/composer/aws/aws-sdk-php/src/S3/Transfer.php

raw symbols SCIP
1 <?php
2 namespace Aws\S3;
3
4 use Aws;
5 use Aws\CommandInterface;
6 use Aws\Exception\AwsException;
7 use Aws\MetricsBuilder;
8 use GuzzleHttp\Promise;
9 use GuzzleHttp\Promise\PromiseInterface;
10 use GuzzleHttp\Promise\PromisorInterface;
11 use Iterator;
12
13 /**
14 * Transfers files from the local filesystem to S3 or from S3 to the local
15 * filesystem.
16 *
17 * This class does not support copying from the local filesystem to somewhere
18 * else on the local filesystem or from one S3 bucket to another.
19 */
20 class Transfer implements PromisorInterface
21 {
22 private $client;
23 private $promise;
24 private $source;
25 private $sourceMetadata;
26 private $destination;
27 private $concurrency;
28 private $mupThreshold;
29 private $before;
30 private $after;
31 private $s3Args = [];
32 private $addContentMD5;
33
34 /**
35 * When providing the $source argument, you may provide a string referencing
36 * the path to a directory on disk to upload, an s3 scheme URI that contains
37 * the bucket and key (e.g., "s3://bucket/key"), or an \Iterator object
38 * that yields strings containing filenames that are the path to a file on
39 * disk or an s3 scheme URI. The bucket portion of the s3 URI may be an S3
40 * access point ARN. The "/key" portion of an s3 URI is optional.
41 *
42 * When providing an iterator for the $source argument, you must also
43 * provide a 'base_dir' key value pair in the $options argument.
44 *
45 * The $dest argument can be the path to a directory on disk or an s3
46 * scheme URI (e.g., "s3://bucket/key").
47 *
48 * The options array can contain the following key value pairs:
49 *
50 * - base_dir: (string) Base directory of the source, if $source is an
51 * iterator. If the $source option is not an array, then this option is
52 * ignored.
53 * - before: (callable) A callback to invoke before each transfer. The
54 * callback accepts a single argument: Aws\CommandInterface $command.
55 * The provided command will be either a GetObject, PutObject,
56 * InitiateMultipartUpload, or UploadPart command.
57 * - after: (callable) A callback to invoke after each transfer promise is fulfilled.
58 * The function is invoked with three arguments: the fulfillment value, the index
59 * position from the iterable list of the promise, and the aggregate
60 * promise that manages all the promises. The aggregate promise may
61 * be resolved from within the callback to short-circuit the promise.
62 * - mup_threshold: (int) Size in bytes in which a multipart upload should
63 * be used instead of PutObject. Defaults to 20971520 (20 MB).
64 * - concurrency: (int, default=5) Number of files to upload concurrently.
65 * The ideal concurrency value will vary based on the number of files
66 * being uploaded and the average size of each file. Generally speaking,
67 * smaller files benefit from a higher concurrency while larger files
68 * will not.
69 * - debug: (bool) Set to true to print out debug information for
70 * transfers. Set to an fopen() resource to write to a specific stream
71 * rather than writing to STDOUT.
72 *
73 * @param S3ClientInterface $client Client used for transfers.
74 * @param string|Iterator $source Where the files are transferred from.
75 * @param string $dest Where the files are transferred to.
76 * @param array $options Hash of options.
77 */
78 public function __construct(
79 S3ClientInterface $client,
80 $source,
81 $dest,
82 array $options = []
83 ) {
84 $this->client = $client;
85
86 // Prepare the destination.
87 $this->destination = $this->prepareTarget($dest);
88 if ($this->destination['scheme'] === 's3') {
89 $this->s3Args = $this->getS3Args($this->destination['path']);
90 }
91
92 // Prepare the source.
93 if (is_string($source)) {
94 $this->sourceMetadata = $this->prepareTarget($source);
95 $this->source = $source;
96 } elseif ($source instanceof Iterator) {
97 if (empty($options['base_dir'])) {
98 throw new \InvalidArgumentException('You must provide the source'
99 . ' argument as a string or provide the "base_dir" option.');
100 }
101
102 $this->sourceMetadata = $this->prepareTarget($options['base_dir']);
103 $this->source = $source;
104 } else {
105 throw new \InvalidArgumentException('source must be the path to a '
106 . 'directory or an iterator that yields file names.');
107 }
108
109 // Validate schemes.
110 if ($this->sourceMetadata['scheme'] === $this->destination['scheme']) {
111 throw new \InvalidArgumentException("You cannot copy from"
112 . " {$this->sourceMetadata['scheme']} to"
113 . " {$this->destination['scheme']}."
114 );
115 }
116
117 // Handle multipart-related options.
118 $this->concurrency = isset($options['concurrency'])
119 ? $options['concurrency']
120 : MultipartUploader::DEFAULT_CONCURRENCY;
121 $this->mupThreshold = isset($options['mup_threshold'])
122 ? $options['mup_threshold']
123 : 16777216;
124 if ($this->mupThreshold < MultipartUploader::PART_MIN_SIZE) {
125 throw new \InvalidArgumentException('mup_threshold must be >= 5MB');
126 }
127
128 // Handle "before" callback option.
129 if (isset($options['before'])) {
130 $this->before = $options['before'];
131 if (!is_callable($this->before)) {
132 throw new \InvalidArgumentException('before must be a callable.');
133 }
134 }
135
136 // Handle "after" callback option.
137 if (isset($options['after'])) {
138 $this->after = $options['after'];
139 if (!is_callable($this->after)) {
140 throw new \InvalidArgumentException('after must be a callable.');
141 }
142 }
143
144 // Handle "debug" option.
145 if (isset($options['debug'])) {
146 if ($options['debug'] === true) {
147 $options['debug'] = fopen('php://output', 'w');
148 }
149 if (is_resource($options['debug'])) {
150 $this->addDebugToBefore($options['debug']);
151 }
152 }
153
154 // Handle "add_content_md5" option.
155 $this->addContentMD5 = isset($options['add_content_md5'])
156 && $options['add_content_md5'] === true;
157 MetricsBuilder::appendMetricsCaptureMiddleware(
158 $this->client->getHandlerList(),
159 MetricsBuilder::S3_TRANSFER
160 );
161 }
162
163 /**
164 * Transfers the files.
165 *
166 * @return PromiseInterface
167 */
168 public function promise(): PromiseInterface
169 {
170 // If the promise has been created, just return it.
171 if (!$this->promise) {
172 // Create an upload/download promise for the transfer.
173 $this->promise = $this->sourceMetadata['scheme'] === 'file'
174 ? $this->createUploadPromise()
175 : $this->createDownloadPromise();
176 }
177
178 return $this->promise;
179 }
180
181 /**
182 * Transfers the files synchronously.
183 */
184 public function transfer()
185 {
186 $this->promise()->wait();
187 }
188
189 private function prepareTarget($targetPath)
190 {
191 $target = [
192 'path' => $this->normalizePath($targetPath),
193 'scheme' => $this->determineScheme($targetPath),
194 ];
195
196 if ($target['scheme'] !== 's3' && $target['scheme'] !== 'file') {
197 throw new \InvalidArgumentException('Scheme must be "s3" or "file".');
198 }
199
200 return $target;
201 }
202
203 /**
204 * Creates an array that contains Bucket and Key by parsing the filename.
205 *
206 * @param string $path Path to parse.
207 *
208 * @return array
209 */
210 private function getS3Args($path)
211 {
212 $parts = explode('/', str_replace('s3://', '', $path), 2);
213 $args = ['Bucket' => $parts[0]];
214 if (isset($parts[1])) {
215 $args['Key'] = $parts[1];
216 }
217
218 return $args;
219 }
220
221 /**
222 * Parses the scheme from a filename.
223 *
224 * @param string $path Path to parse.
225 *
226 * @return string
227 */
228 private function determineScheme($path)
229 {
230 return !strpos($path, '://') ? 'file' : explode('://', $path)[0];
231 }
232
233 /**
234 * Normalize a path so that it has UNIX-style directory separators and no trailing /
235 *
236 * @param string $path
237 *
238 * @return string
239 */
240 private function normalizePath($path)
241 {
242 return rtrim(str_replace('\\', '/', $path), '/');
243 }
244
245 private function resolvesOutsideTargetDirectory($sink, $objectKey)
246 {
247 $resolved = [];
248 $sections = explode('/', $sink);
249 $targetSectionsLength = count(explode('/', $objectKey));
250 $targetSections = array_slice($sections, -($targetSectionsLength + 1));
251 $targetDirectory = $targetSections[0];
252
253 foreach ($targetSections as $section) {
254 if ($section === '.' || $section === '') {
255 continue;
256 }
257 if ($section === '..') {
258 array_pop($resolved);
259 if (empty($resolved) || $resolved[0] !== $targetDirectory) {
260 return true;
261 }
262 } else {
263 $resolved []= $section;
264 }
265 }
266 return false;
267 }
268
269 private function createDownloadPromise()
270 {
271 $parts = $this->getS3Args($this->sourceMetadata['path']);
272 $prefix = "s3://{$parts['Bucket']}/"
273 . (isset($parts['Key']) ? $parts['Key'] . '/' : '');
274
275 $commands = [];
276 foreach ($this->getDownloadsIterator() as $object) {
277 // Prepare the sink.
278 $objectKey = preg_replace('/^' . preg_quote($prefix, '/') . '/', '', $object);
279 $sink = $this->destination['path'] . '/' . $objectKey;
280
281 $command = $this->client->getCommand(
282 'GetObject',
283 $this->getS3Args($object) + ['@http' => ['sink' => $sink]]
284 );
285
286 if ($this->resolvesOutsideTargetDirectory($sink, $objectKey)) {
287 throw new AwsException(
288 'Cannot download key ' . $objectKey
289 . ', its relative path resolves outside the'
290 . ' parent directory', $command);
291 }
292
293 // Create the directory if needed.
294 $dir = dirname($sink);
295 if (!is_dir($dir) && !mkdir($dir, 0777, true)) {
296 throw new \RuntimeException("Could not create dir: {$dir}");
297 }
298
299 // Create the command.
300 $commands []= $command;
301 }
302
303 // Create a GetObject command pool and return the promise.
304 return (new Aws\CommandPool($this->client, $commands, [
305 'concurrency' => $this->concurrency,
306 'before' => $this->before,
307 'fulfill' => $this->after,
308 'rejected' => function ($reason, $idx, Promise\PromiseInterface $p) {
309 $p->reject($reason);
310 }
311 ]))->promise();
312 }
313
314 private function createUploadPromise()
315 {
316 // Map each file into a promise that performs the actual transfer.
317 $files = \Aws\map($this->getUploadsIterator(), function ($file) {
318 return (filesize($file) >= $this->mupThreshold)
319 ? $this->uploadMultipart($file)
320 : $this->upload($file);
321 });
322
323 // Create an EachPromise, that will concurrently handle the upload
324 // operations' yielded promises from the iterator.
325 return Promise\Each::ofLimitAll($files, $this->concurrency, $this->after);
326 }
327
328 /** @return Iterator */
329 private function getUploadsIterator()
330 {
331 if (is_string($this->source)) {
332 return Aws\filter(
333 Aws\recursive_dir_iterator($this->sourceMetadata['path']),
334 function ($file) { return !is_dir($file); }
335 );
336 }
337
338 return $this->source;
339 }
340
341 /** @return Iterator */
342 private function getDownloadsIterator()
343 {
344 if (is_string($this->source)) {
345 $listArgs = $this->getS3Args($this->sourceMetadata['path']);
346 if (isset($listArgs['Key'])) {
347 $listArgs['Prefix'] = $listArgs['Key'] . '/';
348 unset($listArgs['Key']);
349 }
350
351 $files = $this->client
352 ->getPaginator('ListObjects', $listArgs)
353 ->search('Contents[].Key');
354 $files = Aws\map($files, function ($key) use ($listArgs) {
355 return "s3://{$listArgs['Bucket']}/$key";
356 });
357 return Aws\filter($files, function ($key) {
358 return substr($key, -1, 1) !== '/';
359 });
360 }
361
362 return $this->source;
363 }
364
365 private function upload($filename)
366 {
367 $args = $this->s3Args;
368 $args['SourceFile'] = $filename;
369 $args['Key'] = $this->createS3Key($filename);
370 $args['AddContentMD5'] = $this->addContentMD5;
371 $command = $this->client->getCommand('PutObject', $args);
372 $this->before and call_user_func($this->before, $command);
373
374 return $this->client->executeAsync($command);
375 }
376
377 private function uploadMultipart($filename)
378 {
379 $args = $this->s3Args;
380 $args['Key'] = $this->createS3Key($filename);
381 $filename = $filename instanceof \SplFileInfo ? $filename->getPathname() : $filename;
382
383 return (new MultipartUploader($this->client, $filename, [
384 'bucket' => $args['Bucket'],
385 'key' => $args['Key'],
386 'before_initiate' => $this->before,
387 'before_upload' => $this->before,
388 'before_complete' => $this->before,
389 'concurrency' => $this->concurrency,
390 'add_content_md5' => $this->addContentMD5
391 ]))->promise();
392 }
393
394 private function createS3Key($filename)
395 {
396 $filename = $this->normalizePath($filename);
397 $relative_file_path = ltrim(
398 preg_replace('#^' . preg_quote($this->sourceMetadata['path']) . '#', '', $filename),
399 '/\\'
400 );
401
402 if (isset($this->s3Args['Key'])) {
403 return rtrim($this->s3Args['Key'], '/').'/'.$relative_file_path;
404 }
405
406 return $relative_file_path;
407 }
408
409 private function addDebugToBefore($debug)
410 {
411 $before = $this->before;
412 $sourcePath = $this->sourceMetadata['path'];
413 $s3Args = $this->s3Args;
414
415 $this->before = static function (
416 CommandInterface $command
417 ) use ($before, $debug, $sourcePath, $s3Args) {
418 // Call the composed before function.
419 $before and $before($command);
420
421 // Determine the source and dest values based on operation.
422 switch ($operation = $command->getName()) {
423 case 'GetObject':
424 $source = "s3://{$command['Bucket']}/{$command['Key']}";
425 $dest = $command['@http']['sink'];
426 break;
427 case 'PutObject':
428 $source = $command['SourceFile'];
429 $dest = "s3://{$command['Bucket']}/{$command['Key']}";
430 break;
431 case 'UploadPart':
432 $part = $command['PartNumber'];
433 case 'CreateMultipartUpload':
434 case 'CompleteMultipartUpload':
435 $sourceKey = $command['Key'];
436 if (isset($s3Args['Key']) && strpos($sourceKey, $s3Args['Key']) === 0) {
437 $sourceKey = substr($sourceKey, strlen($s3Args['Key']) + 1);
438 }
439 $source = "{$sourcePath}/{$sourceKey}";
440 $dest = "s3://{$command['Bucket']}/{$command['Key']}";
441 break;
442 default:
443 throw new \UnexpectedValueException(
444 "Transfer encountered an unexpected operation: {$operation}."
445 );
446 }
447
448 // Print the debugging message.
449 $context = sprintf('%s -> %s (%s)', $source, $dest, $operation);
450 if (isset($part)) {
451 $context .= " : Part={$part}";
452 }
453 fwrite($debug, "Transferring {$context}\n");
454 };
455 }
456 }