| 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 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 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 |
|
| 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 |
public function __construct( |
| 79 |
S3ClientInterface $client, |
| 80 |
$source, |
| 81 |
$dest, |
| 82 |
array $options = [] |
| 83 |
) { |
| 84 |
$this->client = $client; |
| 85 |
|
| 86 |
|
| 87 |
$this->destination = $this->prepareTarget($dest); |
| 88 |
if ($this->destination['scheme'] === 's3') { |
| 89 |
$this->s3Args = $this->getS3Args($this->destination['path']); |
| 90 |
} |
| 91 |
|
| 92 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
public function promise(): PromiseInterface |
| 169 |
{ |
| 170 |
|
| 171 |
if (!$this->promise) { |
| 172 |
|
| 173 |
$this->promise = $this->sourceMetadata['scheme'] === 'file' |
| 174 |
? $this->createUploadPromise() |
| 175 |
: $this->createDownloadPromise(); |
| 176 |
} |
| 177 |
|
| 178 |
return $this->promise; |
| 179 |
} |
| 180 |
|
| 181 |
|
| 182 |
|
| 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 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 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 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
private function determineScheme($path) |
| 229 |
{ |
| 230 |
return !strpos($path, '://') ? 'file' : explode('://', $path)[0]; |
| 231 |
} |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 300 |
$commands []= $command; |
| 301 |
} |
| 302 |
|
| 303 |
|
| 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 |
|
| 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 |
|
| 324 |
|
| 325 |
return Promise\Each::ofLimitAll($files, $this->concurrency, $this->after); |
| 326 |
} |
| 327 |
|
| 328 |
|
| 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 |
|
| 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 |
|
| 419 |
$before and $before($command); |
| 420 |
|
| 421 |
|
| 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 |
|
| 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 |
} |