MediaWiki master
SwiftFileBackend.php
Go to the documentation of this file.
1<?php
25namespace Wikimedia\FileBackend;
26
27use Exception;
28use LockManager;
29use MapCacheLRU;
30use Psr\Log\LoggerInterface;
31use Shellbox\Command\BoxedCommand;
32use StatusValue;
33use stdClass;
34use Wikimedia\AtEase\AtEase;
42use Wikimedia\RequestTimeout\TimeoutException;
43use Wikimedia\Timestamp\ConvertibleTimestamp;
44
55 private const DEFAULT_HTTP_OPTIONS = [ 'httpVersion' => 'v1.1' ];
56 private const AUTH_FAILURE_ERROR = 'Could not connect due to prior authentication failure';
57
59 protected $http;
61 protected $authTTL;
63 protected $swiftAuthUrl;
67 protected $swiftUser;
69 protected $swiftKey;
77 protected $rgwS3AccessKey;
79 protected $rgwS3SecretKey;
81 protected $readUsers;
83 protected $writeUsers;
88
90 protected $srvCache;
91
94
96 protected $authCreds;
98 protected $authErrorTimestamp = null;
99
101 protected $isRGW = false;
102
146 public function __construct( array $config ) {
147 parent::__construct( $config );
148 // Required settings
149 $this->swiftAuthUrl = $config['swiftAuthUrl'];
150 $this->swiftUser = $config['swiftUser'];
151 $this->swiftKey = $config['swiftKey'];
152 // Optional settings
153 $this->authTTL = $config['swiftAuthTTL'] ?? 15 * 60; // some sensible number
154 $this->swiftTempUrlKey = $config['swiftTempUrlKey'] ?? '';
155 $this->canShellboxGetTempUrl = $config['canShellboxGetTempUrl'] ?? false;
156 $this->shellboxIpRange = $config['shellboxIpRange'] ?? null;
157 $this->swiftStorageUrl = $config['swiftStorageUrl'] ?? null;
158 $this->shardViaHashLevels = $config['shardViaHashLevels'] ?? '';
159 $this->rgwS3AccessKey = $config['rgwS3AccessKey'] ?? '';
160 $this->rgwS3SecretKey = $config['rgwS3SecretKey'] ?? '';
161
162 // HTTP helper client
163 $httpOptions = [];
164 foreach ( [ 'connTimeout', 'reqTimeout' ] as $optionName ) {
165 if ( isset( $config[$optionName] ) ) {
166 $httpOptions[$optionName] = $config[$optionName];
167 }
168 }
169 $this->http = new MultiHttpClient( $httpOptions );
170 $this->http->setLogger( $this->logger );
171
172 // Cache container information to mask latency
173 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache ) {
174 $this->memCache = $config['wanCache'];
175 }
176 // Process cache for container info
177 $this->containerStatCache = new MapCacheLRU( 300 );
178 // Cache auth token information to avoid RTTs
179 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
180 $this->srvCache = $config['srvCache'];
181 } else {
182 $this->srvCache = new EmptyBagOStuff();
183 }
184 $this->readUsers = $config['readUsers'] ?? [];
185 $this->writeUsers = $config['writeUsers'] ?? [];
186 $this->secureReadUsers = $config['secureReadUsers'] ?? [];
187 $this->secureWriteUsers = $config['secureWriteUsers'] ?? [];
188 // Per https://docs.openstack.org/swift/latest/overview_large_objects.html
189 // we need to split objects if they are larger than 5 GB. Support for
190 // splitting objects has not yet been implemented by this class
191 // so limit max file size to 5GiB.
192 $this->maxFileSize = 5 * 1024 * 1024 * 1024;
193 }
194
195 public function setLogger( LoggerInterface $logger ) {
196 parent::setLogger( $logger );
197 $this->http->setLogger( $logger );
198 }
199
200 public function getFeatures() {
201 return (
202 self::ATTR_UNICODE_PATHS |
203 self::ATTR_HEADERS |
204 self::ATTR_METADATA
205 );
206 }
207
208 protected function resolveContainerPath( $container, $relStoragePath ) {
209 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
210 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
211 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
212 return null; // too long for Swift
213 }
214
215 return $relStoragePath;
216 }
217
218 public function isPathUsableInternal( $storagePath ) {
219 [ $container, $rel ] = $this->resolveStoragePathReal( $storagePath );
220 if ( $rel === null ) {
221 return false; // invalid
222 }
223
224 return is_array( $this->getContainerStat( $container ) );
225 }
226
236 protected function extractMutableContentHeaders( array $headers ) {
237 $contentHeaders = [];
238 // Normalize casing, and strip out illegal headers
239 foreach ( $headers as $name => $value ) {
240 $name = strtolower( $name );
241 if ( $name === 'x-delete-at' && is_numeric( $value ) ) {
242 // Expects a Unix Epoch date
243 $contentHeaders[$name] = $value;
244 } elseif ( $name === 'x-delete-after' && is_numeric( $value ) ) {
245 // Expects number of minutes time to live.
246 $contentHeaders[$name] = $value;
247 } elseif ( preg_match( '/^(x-)?content-(?!length$)/', $name ) ) {
248 // Only allow content-* and x-content-* headers (but not content-length)
249 $contentHeaders[$name] = $value;
250 } elseif ( $name === 'content-type' && $value !== '' ) {
251 // This header can be set to a value but not unset
252 $contentHeaders[$name] = $value;
253 }
254 }
255 // By default, Swift has annoyingly low maximum header value limits
256 if ( isset( $contentHeaders['content-disposition'] ) ) {
257 $maxLength = 255;
258 // @note: assume FileBackend::makeContentDisposition() already used
259 $offset = $maxLength - strlen( $contentHeaders['content-disposition'] );
260 if ( $offset < 0 ) {
261 $pos = strrpos( $contentHeaders['content-disposition'], ';', $offset );
262 $contentHeaders['content-disposition'] = $pos === false
263 ? ''
264 : trim( substr( $contentHeaders['content-disposition'], 0, $pos ) );
265 }
266 }
267
268 return $contentHeaders;
269 }
270
276 protected function extractMetadataHeaders( array $headers ) {
277 $metadataHeaders = [];
278 foreach ( $headers as $name => $value ) {
279 $name = strtolower( $name );
280 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
281 $metadataHeaders[$name] = $value;
282 }
283 }
284
285 return $metadataHeaders;
286 }
287
293 protected function getMetadataFromHeaders( array $headers ) {
294 $prefixLen = strlen( 'x-object-meta-' );
295
296 $metadata = [];
297 foreach ( $this->extractMetadataHeaders( $headers ) as $name => $value ) {
298 $metadata[substr( $name, $prefixLen )] = $value;
299 }
300
301 return $metadata;
302 }
303
304 protected function doCreateInternal( array $params ) {
305 $status = $this->newStatus();
306
307 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
308 if ( $dstRel === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
310
311 return $status;
312 }
313
314 // Headers that are not strictly a function of the file content
315 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] );
316 // Make sure that the "content-type" header is set to something sensible
317 $mutableHeaders['content-type']
318 ??= $this->getContentType( $params['dst'], $params['content'], null );
319
320 $reqs = [ [
321 'method' => 'PUT',
322 'container' => $dstCont,
323 'relPath' => $dstRel,
324 'headers' => array_merge(
325 $mutableHeaders,
326 [
327 'etag' => md5( $params['content'] ),
328 'content-length' => strlen( $params['content'] ),
329 'x-object-meta-sha1base36' =>
330 \Wikimedia\base_convert( sha1( $params['content'] ), 16, 36, 31 )
331 ]
332 ),
333 'body' => $params['content']
334 ] ];
335
336 $method = __METHOD__;
337 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
338 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
339 if ( $rcode === 201 || $rcode === 202 ) {
340 // good
341 } elseif ( $rcode === 412 ) {
342 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
343 } else {
344 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
345 }
346
347 return SwiftFileOpHandle::CONTINUE_IF_OK;
348 };
349
350 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
351 if ( !empty( $params['async'] ) ) { // deferred
352 $status->value = $opHandle;
353 } else { // actually write the object in Swift
354 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
355 }
356
357 return $status;
358 }
359
360 protected function doStoreInternal( array $params ) {
361 $status = $this->newStatus();
362
363 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
364 if ( $dstRel === null ) {
365 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
366
367 return $status;
368 }
369
370 // Open a handle to the source file so that it can be streamed. The size and hash
371 // will be computed using the handle. In the off chance that the source file changes
372 // during this operation, the PUT will fail due to an ETag mismatch and be aborted.
373 AtEase::suppressWarnings();
374 $srcHandle = fopen( $params['src'], 'rb' );
375 AtEase::restoreWarnings();
376 if ( $srcHandle === false ) { // source doesn't exist?
377 $status->fatal( 'backend-fail-notexists', $params['src'] );
378
379 return $status;
380 }
381
382 // Compute the MD5 and SHA-1 hashes in one pass
383 $srcSize = fstat( $srcHandle )['size'];
384 $md5Context = hash_init( 'md5' );
385 $sha1Context = hash_init( 'sha1' );
386 $hashDigestSize = 0;
387 while ( !feof( $srcHandle ) ) {
388 $buffer = (string)fread( $srcHandle, 131_072 ); // 128 KiB
389 hash_update( $md5Context, $buffer );
390 hash_update( $sha1Context, $buffer );
391 $hashDigestSize += strlen( $buffer );
392 }
393 // Reset the handle back to the beginning so that it can be streamed
394 rewind( $srcHandle );
395
396 if ( $hashDigestSize !== $srcSize ) {
397 $status->fatal( 'backend-fail-hash', $params['src'] );
398
399 return $status;
400 }
401
402 // Headers that are not strictly a function of the file content
403 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] );
404 // Make sure that the "content-type" header is set to something sensible
405 $mutableHeaders['content-type']
406 ??= $this->getContentType( $params['dst'], null, $params['src'] );
407
408 $reqs = [ [
409 'method' => 'PUT',
410 'container' => $dstCont,
411 'relPath' => $dstRel,
412 'headers' => array_merge(
413 $mutableHeaders,
414 [
415 'content-length' => $srcSize,
416 'etag' => hash_final( $md5Context ),
417 'x-object-meta-sha1base36' =>
418 \Wikimedia\base_convert( hash_final( $sha1Context ), 16, 36, 31 )
419 ]
420 ),
421 'body' => $srcHandle // resource
422 ] ];
423
424 $method = __METHOD__;
425 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
426 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
427 if ( $rcode === 201 || $rcode === 202 ) {
428 // good
429 } elseif ( $rcode === 412 ) {
430 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
431 } else {
432 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
433 }
434
435 return SwiftFileOpHandle::CONTINUE_IF_OK;
436 };
437
438 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
439 $opHandle->resourcesToClose[] = $srcHandle;
440
441 if ( !empty( $params['async'] ) ) { // deferred
442 $status->value = $opHandle;
443 } else { // actually write the object in Swift
444 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
445 }
446
447 return $status;
448 }
449
450 protected function doCopyInternal( array $params ) {
451 $status = $this->newStatus();
452
453 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
454 if ( $srcRel === null ) {
455 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
456
457 return $status;
458 }
459
460 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
461 if ( $dstRel === null ) {
462 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
463
464 return $status;
465 }
466
467 $reqs = [ [
468 'method' => 'PUT',
469 'container' => $dstCont,
470 'relPath' => $dstRel,
471 'headers' => array_merge(
472 $this->extractMutableContentHeaders( $params['headers'] ?? [] ),
473 [
474 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
475 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
476 ]
477 )
478 ] ];
479
480 $method = __METHOD__;
481 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
482 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
483 if ( $rcode === 201 ) {
484 // good
485 } elseif ( $rcode === 404 ) {
486 if ( empty( $params['ignoreMissingSource'] ) ) {
487 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
488 }
489 } else {
490 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
491 }
492
493 return SwiftFileOpHandle::CONTINUE_IF_OK;
494 };
495
496 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
497 if ( !empty( $params['async'] ) ) { // deferred
498 $status->value = $opHandle;
499 } else { // actually write the object in Swift
500 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
501 }
502
503 return $status;
504 }
505
506 protected function doMoveInternal( array $params ) {
507 $status = $this->newStatus();
508
509 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
510 if ( $srcRel === null ) {
511 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
512
513 return $status;
514 }
515
516 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
517 if ( $dstRel === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
519
520 return $status;
521 }
522
523 $reqs = [ [
524 'method' => 'PUT',
525 'container' => $dstCont,
526 'relPath' => $dstRel,
527 'headers' => array_merge(
528 $this->extractMutableContentHeaders( $params['headers'] ?? [] ),
529 [
530 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
531 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
532 ]
533 )
534 ] ];
535 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
536 $reqs[] = [
537 'method' => 'DELETE',
538 'container' => $srcCont,
539 'relPath' => $srcRel,
540 'headers' => []
541 ];
542 }
543
544 $method = __METHOD__;
545 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
546 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
547 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
548 // good
549 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
550 // good
551 } elseif ( $rcode === 404 ) {
552 if ( empty( $params['ignoreMissingSource'] ) ) {
553 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
554 } else {
555 // Leave Status as OK but skip the DELETE request
556 return SwiftFileOpHandle::CONTINUE_NO;
557 }
558 } else {
559 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
560 }
561
562 return SwiftFileOpHandle::CONTINUE_IF_OK;
563 };
564
565 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
566 if ( !empty( $params['async'] ) ) { // deferred
567 $status->value = $opHandle;
568 } else { // actually move the object in Swift
569 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
570 }
571
572 return $status;
573 }
574
575 protected function doDeleteInternal( array $params ) {
576 $status = $this->newStatus();
577
578 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
579 if ( $srcRel === null ) {
580 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
581
582 return $status;
583 }
584
585 $reqs = [ [
586 'method' => 'DELETE',
587 'container' => $srcCont,
588 'relPath' => $srcRel,
589 'headers' => []
590 ] ];
591
592 $method = __METHOD__;
593 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
594 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
595 if ( $rcode === 204 ) {
596 // good
597 } elseif ( $rcode === 404 ) {
598 if ( empty( $params['ignoreMissingSource'] ) ) {
599 $status->fatal( 'backend-fail-delete', $params['src'] );
600 }
601 } else {
602 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
603 }
604
605 return SwiftFileOpHandle::CONTINUE_IF_OK;
606 };
607
608 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
609 if ( !empty( $params['async'] ) ) { // deferred
610 $status->value = $opHandle;
611 } else { // actually delete the object in Swift
612 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
613 }
614
615 return $status;
616 }
617
618 protected function doDescribeInternal( array $params ) {
619 $status = $this->newStatus();
620
621 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
622 if ( $srcRel === null ) {
623 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
624
625 return $status;
626 }
627
628 // Fetch the old object headers/metadata...this should be in stat cache by now
629 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
630 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
631 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
632 }
633 if ( !$stat ) {
634 $status->fatal( 'backend-fail-describe', $params['src'] );
635
636 return $status;
637 }
638
639 // Swift object POST clears any prior headers, so merge the new and old headers here.
640 // Also, during, POST, libcurl adds "Content-Type: application/x-www-form-urlencoded"
641 // if "Content-Type" is not set, which would clobber the header value for the object.
642 $oldMetadataHeaders = [];
643 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
644 $oldMetadataHeaders["x-object-meta-$name"] = $value;
645 }
646 $newContentHeaders = $this->extractMutableContentHeaders( $params['headers'] ?? [] );
647 $oldContentHeaders = $stat['xattr']['headers'];
648
649 $reqs = [ [
650 'method' => 'POST',
651 'container' => $srcCont,
652 'relPath' => $srcRel,
653 'headers' => $oldMetadataHeaders + $newContentHeaders + $oldContentHeaders
654 ] ];
655
656 $method = __METHOD__;
657 $handler = function ( array $request, StatusValue $status ) use ( $method, $params ) {
658 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
659 if ( $rcode === 202 ) {
660 // good
661 } elseif ( $rcode === 404 ) {
662 $status->fatal( 'backend-fail-describe', $params['src'] );
663 } else {
664 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
665 }
666 };
667
668 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
669 if ( !empty( $params['async'] ) ) { // deferred
670 $status->value = $opHandle;
671 } else { // actually change the object in Swift
672 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
673 }
674
675 return $status;
676 }
677
681 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
682 $status = $this->newStatus();
683
684 // (a) Check if container already exists
685 $stat = $this->getContainerStat( $fullCont );
686 if ( is_array( $stat ) ) {
687 return $status; // already there
688 } elseif ( $stat === self::RES_ERROR ) {
689 $status->fatal( 'backend-fail-internal', $this->name );
690 $this->logger->error( __METHOD__ . ': cannot get container stat' );
691 } else {
692 // (b) Create container as needed with proper ACLs
693 $params['op'] = 'prepare';
694 $status->merge( $this->createContainer( $fullCont, $params ) );
695 }
696
697 return $status;
698 }
699
700 protected function doSecureInternal( $fullCont, $dir, array $params ) {
701 $status = $this->newStatus();
702 if ( empty( $params['noAccess'] ) ) {
703 return $status; // nothing to do
704 }
705
706 $stat = $this->getContainerStat( $fullCont );
707 if ( is_array( $stat ) ) {
708 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
709 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
710 // Make container private to end-users...
711 $status->merge( $this->setContainerAccess(
712 $fullCont,
715 ) );
716 } elseif ( $stat === self::RES_ABSENT ) {
717 $status->fatal( 'backend-fail-usable', $params['dir'] );
718 } else {
719 $status->fatal( 'backend-fail-internal', $this->name );
720 $this->logger->error( __METHOD__ . ': cannot get container stat' );
721 }
722
723 return $status;
724 }
725
726 protected function doPublishInternal( $fullCont, $dir, array $params ) {
727 $status = $this->newStatus();
728 if ( empty( $params['access'] ) ) {
729 return $status; // nothing to do
730 }
731
732 $stat = $this->getContainerStat( $fullCont );
733 if ( is_array( $stat ) ) {
734 $readUsers = array_merge( $this->readUsers, [ $this->swiftUser, '.r:*' ] );
735 if ( !empty( $params['listing'] ) ) {
736 array_push( $readUsers, '.rlistings' );
737 }
738 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
739
740 // Make container public to end-users...
741 $status->merge( $this->setContainerAccess(
742 $fullCont,
745 ) );
746 } elseif ( $stat === self::RES_ABSENT ) {
747 $status->fatal( 'backend-fail-usable', $params['dir'] );
748 } else {
749 $status->fatal( 'backend-fail-internal', $this->name );
750 $this->logger->error( __METHOD__ . ': cannot get container stat' );
751 }
752
753 return $status;
754 }
755
756 protected function doCleanInternal( $fullCont, $dir, array $params ) {
757 $status = $this->newStatus();
758
759 // Only containers themselves can be removed, all else is virtual
760 if ( $dir != '' ) {
761 return $status; // nothing to do
762 }
763
764 // (a) Check the container
765 $stat = $this->getContainerStat( $fullCont, true );
766 if ( $stat === self::RES_ABSENT ) {
767 return $status; // ok, nothing to do
768 } elseif ( $stat === self::RES_ERROR ) {
769 $status->fatal( 'backend-fail-internal', $this->name );
770 $this->logger->error( __METHOD__ . ': cannot get container stat' );
771 } elseif ( is_array( $stat ) && $stat['count'] == 0 ) {
772 // (b) Delete the container if empty
773 $params['op'] = 'clean';
774 $status->merge( $this->deleteContainer( $fullCont, $params ) );
775 }
776
777 return $status;
778 }
779
780 protected function doGetFileStat( array $params ) {
781 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] + $params;
782 unset( $params['src'] );
783 $stats = $this->doGetFileStatMulti( $params );
784
785 return reset( $stats );
786 }
787
798 protected function convertSwiftDate( $ts, $format = TS_MW ) {
799 try {
800 $timestamp = new ConvertibleTimestamp( $ts );
801
802 return $timestamp->getTimestamp( $format );
803 } catch ( TimeoutException $e ) {
804 throw $e;
805 } catch ( Exception $e ) {
806 throw new FileBackendError( $e->getMessage() );
807 }
808 }
809
817 protected function addMissingHashMetadata( array $objHdrs, $path ) {
818 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
819 return $objHdrs; // nothing to do
820 }
821
823 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
824 $this->logger->error( __METHOD__ . ": {path} was not stored with SHA-1 metadata.",
825 [ 'path' => $path ] );
826
827 $objHdrs['x-object-meta-sha1base36'] = false;
828
829 // Find prior custom HTTP headers
830 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
831 // Find prior metadata headers
832 $postHeaders += $this->extractMetadataHeaders( $objHdrs );
833
834 $status = $this->newStatus();
836 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager::LOCK_UW, $status );
837 if ( $status->isOK() ) {
838 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
839 if ( $tmpFile ) {
840 $hash = $tmpFile->getSha1Base36();
841 if ( $hash !== false ) {
842 $objHdrs['x-object-meta-sha1base36'] = $hash;
843 // Merge new SHA1 header into the old ones
844 $postHeaders['x-object-meta-sha1base36'] = $hash;
845 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
846 [ $rcode ] = $this->requestWithAuth( [
847 'method' => 'POST',
848 'container' => $srcCont,
849 'relPath' => $srcRel,
850 'headers' => $postHeaders
851 ] );
852 if ( $rcode >= 200 && $rcode <= 299 ) {
853 $this->deleteFileCache( $path );
854
855 return $objHdrs; // success
856 }
857 }
858 }
859 }
860
861 $this->logger->error( __METHOD__ . ': unable to set SHA-1 metadata for {path}',
862 [ 'path' => $path ] );
863
864 return $objHdrs; // failed
865 }
866
867 protected function doGetFileContentsMulti( array $params ) {
868 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
869 // Blindly create tmp files and stream to them, catching any exception
870 // if the file does not exist. Do not waste time doing file stats here.
871 $reqs = []; // (path => op)
872
873 // Initial dummy values to preserve path order
874 $contents = array_fill_keys( $params['srcs'], self::RES_ERROR );
875 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
876 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
877 if ( $srcRel === null ) {
878 continue; // invalid storage path
879 }
880 // Create a new temporary memory file...
881 $handle = fopen( 'php://temp', 'wb' );
882 if ( $handle ) {
883 $reqs[$path] = [
884 'method' => 'GET',
885 'container' => $srcCont,
886 'relPath' => $srcRel,
887 'headers' => $this->headersFromParams( $params ),
888 'stream' => $handle,
889 ];
890 }
891 }
892
893 $reqs = $this->requestMultiWithAuth(
894 $reqs,
895 [ 'maxConnsPerHost' => $params['concurrency'] ]
896 );
897 foreach ( $reqs as $path => $op ) {
898 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
899 if ( $rcode >= 200 && $rcode <= 299 ) {
900 rewind( $op['stream'] ); // start from the beginning
901 $content = (string)stream_get_contents( $op['stream'] );
902 $size = strlen( $content );
903 // Make sure that stream finished
904 if ( $size === (int)$rhdrs['content-length'] ) {
905 $contents[$path] = $content;
906 } else {
907 $contents[$path] = self::RES_ERROR;
908 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
909 $this->onError( null, __METHOD__,
910 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
911 }
912 } elseif ( $rcode === 404 ) {
913 $contents[$path] = self::RES_ABSENT;
914 } else {
915 $contents[$path] = self::RES_ERROR;
916 $this->onError( null, __METHOD__,
917 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
918 }
919 fclose( $op['stream'] ); // close open handle
920 }
921
922 return $contents;
923 }
924
925 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
926 $prefix = ( $dir == '' ) ? null : "{$dir}/";
927 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
928 if ( $status->isOK() ) {
929 return ( count( $status->value ) ) > 0;
930 }
931
932 return self::RES_ERROR;
933 }
934
942 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
943 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
944 }
945
953 public function getFileListInternal( $fullCont, $dir, array $params ) {
954 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
955 }
956
968 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
969 $dirs = [];
970 if ( $after === INF ) {
971 return $dirs; // nothing more
972 }
973
975 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
976
977 $prefix = ( $dir == '' ) ? null : "{$dir}/";
978 // Non-recursive: only list dirs right under $dir
979 if ( !empty( $params['topOnly'] ) ) {
980 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
981 if ( !$status->isOK() ) {
982 throw new FileBackendError( "Iterator page I/O error." );
983 }
984 $objects = $status->value;
985 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
986 foreach ( $objects as $object ) { // files and directories
987 if ( substr( $object, -1 ) === '/' ) {
988 $dirs[] = $object; // directories end in '/'
989 }
990 }
991 } else {
992 // Recursive: list all dirs under $dir and its subdirs
993 $getParentDir = static function ( $path ) {
994 return ( $path !== null && strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
995 };
996
997 // Get directory from last item of prior page
998 $lastDir = $getParentDir( $after ); // must be first page
999 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
1000
1001 if ( !$status->isOK() ) {
1002 throw new FileBackendError( "Iterator page I/O error." );
1003 }
1004
1005 $objects = $status->value;
1006
1007 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
1008 foreach ( $objects as $object ) { // files
1009 $objectDir = $getParentDir( $object ); // directory of object
1010
1011 if ( $objectDir !== false && $objectDir !== $dir ) {
1012 // Swift stores paths in UTF-8, using binary sorting.
1013 // See function "create_container_table" in common/db.py.
1014 // If a directory is not "greater" than the last one,
1015 // then it was already listed by the calling iterator.
1016 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1017 $pDir = $objectDir;
1018 do { // add dir and all its parent dirs
1019 $dirs[] = "{$pDir}/";
1020 $pDir = $getParentDir( $pDir );
1021 } while ( $pDir !== false
1022 && strcmp( $pDir, $lastDir ) > 0 // not done already
1023 && strlen( $pDir ) > strlen( $dir ) // within $dir
1024 );
1025 }
1026 $lastDir = $objectDir;
1027 }
1028 }
1029 }
1030 // Page on the unfiltered directory listing (what is returned may be filtered)
1031 if ( count( $objects ) < $limit ) {
1032 $after = INF; // avoid a second RTT
1033 } else {
1034 $after = end( $objects ); // update last item
1035 }
1036
1037 return $dirs;
1038 }
1039
1051 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1052 $files = []; // list of (path, stat map or null) entries
1053 if ( $after === INF ) {
1054 return $files; // nothing more
1055 }
1056
1058 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1059
1060 $prefix = ( $dir == '' ) ? null : "{$dir}/";
1061 // $objects will contain a list of unfiltered names or stdClass items
1062 // Non-recursive: only list files right under $dir
1063 if ( !empty( $params['topOnly'] ) ) {
1064 if ( !empty( $params['adviseStat'] ) ) {
1065 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
1066 } else {
1067 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
1068 }
1069 } else {
1070 // Recursive: list all files under $dir and its subdirs
1071 if ( !empty( $params['adviseStat'] ) ) {
1072 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
1073 } else {
1074 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
1075 }
1076 }
1077
1078 // Reformat this list into a list of (name, stat map or null) entries
1079 if ( !$status->isOK() ) {
1080 throw new FileBackendError( "Iterator page I/O error." );
1081 }
1082
1083 $objects = $status->value;
1084 $files = $this->buildFileObjectListing( $objects );
1085
1086 // Page on the unfiltered object listing (what is returned may be filtered)
1087 if ( count( $objects ) < $limit ) {
1088 $after = INF; // avoid a second RTT
1089 } else {
1090 $after = end( $objects ); // update last item
1091 $after = is_object( $after ) ? $after->name : $after;
1092 }
1093
1094 return $files;
1095 }
1096
1104 private function buildFileObjectListing( array $objects ) {
1105 $names = [];
1106 foreach ( $objects as $object ) {
1107 if ( is_object( $object ) ) {
1108 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
1109 continue; // virtual directory entry; ignore
1110 }
1111 $stat = [
1112 // Convert various random Swift dates to TS_MW
1113 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
1114 'size' => (int)$object->bytes,
1115 'sha1' => null,
1116 // Note: manifest ETags are not an MD5 of the file
1117 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
1118 'latest' => false // eventually consistent
1119 ];
1120 $names[] = [ $object->name, $stat ];
1121 } elseif ( substr( $object, -1 ) !== '/' ) {
1122 // Omit directories, which end in '/' in listings
1123 $names[] = [ $object, null ];
1124 }
1125 }
1126
1127 return $names;
1128 }
1129
1136 public function loadListingStatInternal( $path, array $val ) {
1137 $this->cheapCache->setField( $path, 'stat', $val );
1138 }
1139
1140 protected function doGetFileXAttributes( array $params ) {
1141 $stat = $this->getFileStat( $params );
1142 // Stat entries filled by file listings don't include metadata/headers
1143 if ( is_array( $stat ) && !isset( $stat['xattr'] ) ) {
1144 $this->clearCache( [ $params['src'] ] );
1145 $stat = $this->getFileStat( $params );
1146 }
1147
1148 if ( is_array( $stat ) ) {
1149 return $stat['xattr'];
1150 }
1151
1152 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1153 }
1154
1155 protected function doGetFileSha1base36( array $params ) {
1156 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1157 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1158 $params['requireSHA1'] = true;
1159
1160 $stat = $this->getFileStat( $params );
1161 if ( is_array( $stat ) ) {
1162 return $stat['sha1'];
1163 }
1164
1165 return $stat === self::RES_ERROR ? self::RES_ERROR : self::RES_ABSENT;
1166 }
1167
1168 protected function doStreamFile( array $params ) {
1169 $status = $this->newStatus();
1170
1171 $flags = !empty( $params['headless'] ) ? HTTPFileStreamer::STREAM_HEADLESS : 0;
1172
1173 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
1174 if ( $srcRel === null ) {
1175 HTTPFileStreamer::send404Message( $params['src'], $flags );
1176 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1177
1178 return $status;
1179 }
1180
1181 if ( !is_array( $this->getContainerStat( $srcCont ) ) ) {
1182 HTTPFileStreamer::send404Message( $params['src'], $flags );
1183 $status->fatal( 'backend-fail-stream', $params['src'] );
1184
1185 return $status;
1186 }
1187
1188 // If "headers" is set, we only want to send them if the file is there.
1189 // Do not bother checking if the file exists if headers are not set though.
1190 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1191 HTTPFileStreamer::send404Message( $params['src'], $flags );
1192 $status->fatal( 'backend-fail-stream', $params['src'] );
1193
1194 return $status;
1195 }
1196
1197 // Send the requested additional headers
1198 if ( empty( $params['headless'] ) ) {
1199 foreach ( $params['headers'] as $header ) {
1200 $this->header( $header );
1201 }
1202 }
1203
1204 if ( empty( $params['allowOB'] ) ) {
1205 // Cancel output buffering and gzipping if set
1206 $this->resetOutputBuffer();
1207 }
1208
1209 $handle = fopen( 'php://output', 'wb' );
1210 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1211 'method' => 'GET',
1212 'container' => $srcCont,
1213 'relPath' => $srcRel,
1214 'headers' => $this->headersFromParams( $params ) + $params['options'],
1215 'stream' => $handle,
1216 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1217 ] );
1218
1219 if ( $rcode >= 200 && $rcode <= 299 ) {
1220 // good
1221 } elseif ( $rcode === 404 ) {
1222 $status->fatal( 'backend-fail-stream', $params['src'] );
1223 // Per T43113, nasty things can happen if bad cache entries get
1224 // stuck in cache. It's also possible that this error can come up
1225 // with simple race conditions. Clear out the stat cache to be safe.
1226 $this->clearCache( [ $params['src'] ] );
1227 $this->deleteFileCache( $params['src'] );
1228 } else {
1229 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1230 }
1231
1232 return $status;
1233 }
1234
1235 protected function doGetLocalCopyMulti( array $params ) {
1236 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1237 // Blindly create tmp files and stream to them, catching any exception
1238 // if the file does not exist. Do not waste time doing file stats here.
1239 $reqs = []; // (path => op)
1240
1241 // Initial dummy values to preserve path order
1242 $tmpFiles = array_fill_keys( $params['srcs'], self::RES_ERROR );
1243 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1244 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
1245 if ( $srcRel === null ) {
1246 continue; // invalid storage path
1247 }
1248 // Get source file extension
1250 // Create a new temporary file...
1251 $tmpFile = $this->tmpFileFactory->newTempFSFile( 'localcopy_', $ext );
1252 $handle = $tmpFile ? fopen( $tmpFile->getPath(), 'wb' ) : false;
1253 if ( $handle ) {
1254 $reqs[$path] = [
1255 'method' => 'GET',
1256 'container' => $srcCont,
1257 'relPath' => $srcRel,
1258 'headers' => $this->headersFromParams( $params ),
1259 'stream' => $handle,
1260 ];
1261 $tmpFiles[$path] = $tmpFile;
1262 }
1263 }
1264
1265 // Ceph RADOS Gateway is in use (strong consistency) or X-Newest will be used
1266 $latest = ( $this->isRGW || !empty( $params['latest'] ) );
1267
1268 $reqs = $this->requestMultiWithAuth(
1269 $reqs,
1270 [ 'maxConnsPerHost' => $params['concurrency'] ]
1271 );
1272 foreach ( $reqs as $path => $op ) {
1273 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
1274 fclose( $op['stream'] ); // close open handle
1275 if ( $rcode >= 200 && $rcode <= 299 ) {
1277 $tmpFile = $tmpFiles[$path];
1278 // Make sure that the stream finished and fully wrote to disk
1279 $size = $tmpFile->getSize();
1280 if ( $size !== (int)$rhdrs['content-length'] ) {
1281 $tmpFiles[$path] = self::RES_ERROR;
1282 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1283 $this->onError( null, __METHOD__,
1284 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc );
1285 }
1286 // Set the file stat process cache in passing
1287 $stat = $this->getStatFromHeaders( $rhdrs );
1288 $stat['latest'] = $latest;
1289 $this->cheapCache->setField( $path, 'stat', $stat );
1290 } elseif ( $rcode === 404 ) {
1291 $tmpFiles[$path] = self::RES_ABSENT;
1292 $this->cheapCache->setField(
1293 $path,
1294 'stat',
1295 $latest ? self::ABSENT_LATEST : self::ABSENT_NORMAL
1296 );
1297 } else {
1298 $tmpFiles[$path] = self::RES_ERROR;
1299 $this->onError( null, __METHOD__,
1300 [ 'src' => $path ] + $ep, $rerr, $rcode, $rdesc, $rbody );
1301 }
1302 }
1303
1304 return $tmpFiles;
1305 }
1306
1307 public function addShellboxInputFile( BoxedCommand $command, string $boxedName,
1308 array $params
1309 ) {
1310 if ( $this->canShellboxGetTempUrl ) {
1311 $urlParams = [ 'src' => $params['src'] ];
1312 if ( $this->shellboxIpRange !== null ) {
1313 $urlParams['ipRange'] = $this->shellboxIpRange;
1314 }
1315 $url = $this->getFileHttpUrl( $urlParams );
1316 if ( $url ) {
1317 $command->inputFileFromUrl( $boxedName, $url );
1318 return $this->newStatus();
1319 }
1320 }
1321 return parent::addShellboxInputFile( $command, $boxedName, $params );
1322 }
1323
1324 public function getFileHttpUrl( array $params ) {
1325 if ( $this->swiftTempUrlKey == '' &&
1326 ( $this->rgwS3AccessKey == '' || $this->rgwS3SecretKey != '' )
1327 ) {
1328 $this->logger->debug( "Can't get Swift file URL: no key available" );
1329 return self::TEMPURL_ERROR;
1330 }
1331
1332 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
1333 if ( $srcRel === null ) {
1334 $this->logger->debug( "Can't get Swift file URL: can't resolve path" );
1335 return self::TEMPURL_ERROR; // invalid path
1336 }
1337
1338 $auth = $this->getAuthentication();
1339 if ( !$auth ) {
1340 $this->logger->debug( "Can't get Swift file URL: authentication failed" );
1341 return self::TEMPURL_ERROR;
1342 }
1343
1344 $method = $params['method'] ?? 'GET';
1345 $ttl = $params['ttl'] ?? 86400;
1346 $expires = time() + $ttl;
1347
1348 if ( $this->swiftTempUrlKey != '' ) {
1349 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1350 // Swift wants the signature based on the unencoded object name
1351 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1352 $messageParts = [
1353 $method,
1354 $expires,
1355 "{$contPath}/{$srcRel}"
1356 ];
1357 $query = [
1358 'temp_url_expires' => $expires,
1359 ];
1360 if ( isset( $params['ipRange'] ) ) {
1361 array_unshift( $messageParts, "ip={$params['ipRange']}" );
1362 $query['temp_url_ip_range'] = $params['ipRange'];
1363 }
1364
1365 $signature = hash_hmac( 'sha1',
1366 implode( "\n", $messageParts ),
1367 $this->swiftTempUrlKey
1368 );
1369 $query = [ 'temp_url_sig' => $signature ] + $query;
1370
1371 return $url . '?' . http_build_query( $query );
1372 } else { // give S3 API URL for rgw
1373 // Path for signature starts with the bucket
1374 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1375 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1376 // Calculate the hash
1377 $signature = base64_encode( hash_hmac(
1378 'sha1',
1379 "{$method}\n\n\n{$expires}\n{$spath}",
1380 $this->rgwS3SecretKey,
1381 true // raw
1382 ) );
1383 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1384 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1385 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1386 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1387 '?' .
1388 http_build_query( [
1389 'Signature' => $signature,
1390 'Expires' => $expires,
1391 'AWSAccessKeyId' => $this->rgwS3AccessKey
1392 ] );
1393 }
1394 }
1395
1396 protected function directoriesAreVirtual() {
1397 return true;
1398 }
1399
1408 protected function headersFromParams( array $params ) {
1409 $hdrs = [];
1410 if ( !empty( $params['latest'] ) ) {
1411 $hdrs['x-newest'] = 'true';
1412 }
1413
1414 return $hdrs;
1415 }
1416
1417 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1419 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1420
1422 $statuses = [];
1423
1424 // Split the HTTP requests into stages that can be done concurrently
1425 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1426 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1427 $reqs = $fileOpHandle->httpOp;
1428 foreach ( $reqs as $stage => $req ) {
1429 $httpReqsByStage[$stage][$index] = $req;
1430 }
1431 $statuses[$index] = $this->newStatus();
1432 }
1433
1434 // Run all requests for the first stage, then the next, and so on
1435 $reqCount = count( $httpReqsByStage );
1436 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1437 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1438 foreach ( $httpReqs as $index => $httpReq ) {
1440 $fileOpHandle = $fileOpHandles[$index];
1441 // Run the callback for each request of this operation
1442 $status = $statuses[$index];
1443 ( $fileOpHandle->callback )( $httpReq, $status );
1444 // On failure, abort all remaining requests for this operation. This is used
1445 // in "move" operations to abort the DELETE request if the PUT request fails.
1446 if (
1447 !$status->isOK() ||
1448 $fileOpHandle->state === $fileOpHandle::CONTINUE_NO
1449 ) {
1450 $stages = count( $fileOpHandle->httpOp );
1451 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1452 unset( $httpReqsByStage[$s][$index] );
1453 }
1454 }
1455 }
1456 }
1457
1458 return $statuses;
1459 }
1460
1483 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1484 $status = $this->newStatus();
1485
1486 [ $rcode, , , , ] = $this->requestWithAuth( [
1487 'method' => 'POST',
1488 'container' => $container,
1489 'headers' => [
1490 'x-container-read' => implode( ',', $readUsers ),
1491 'x-container-write' => implode( ',', $writeUsers )
1492 ]
1493 ] );
1494
1495 if ( $rcode != 204 && $rcode !== 202 ) {
1496 $status->fatal( 'backend-fail-internal', $this->name );
1497 $this->logger->error( __METHOD__ . ': unexpected rcode value ({rcode})',
1498 [ 'rcode' => $rcode ] );
1499 }
1500
1501 return $status;
1502 }
1503
1512 protected function getContainerStat( $container, $bypassCache = false ) {
1514 $ps = $this->scopedProfileSection( __METHOD__ . "-{$this->name}" );
1515
1516 if ( $bypassCache ) { // purge cache
1517 $this->containerStatCache->clear( $container );
1518 } elseif ( !$this->containerStatCache->hasField( $container, 'stat' ) ) {
1519 $this->primeContainerCache( [ $container ] ); // check persistent cache
1520 }
1521 if ( !$this->containerStatCache->hasField( $container, 'stat' ) ) {
1522 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1523 'method' => 'HEAD',
1524 'container' => $container
1525 ] );
1526
1527 if ( $rcode === 204 ) {
1528 $stat = [
1529 'count' => $rhdrs['x-container-object-count'],
1530 'bytes' => $rhdrs['x-container-bytes-used']
1531 ];
1532 if ( $bypassCache ) {
1533 return $stat;
1534 } else {
1535 $this->containerStatCache->setField( $container, 'stat', $stat ); // cache it
1536 $this->setContainerCache( $container, $stat ); // update persistent cache
1537 }
1538 } elseif ( $rcode === 404 ) {
1539 return self::RES_ABSENT;
1540 } else {
1541 $this->onError( null, __METHOD__,
1542 [ 'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1543
1544 return self::RES_ERROR;
1545 }
1546 }
1547
1548 return $this->containerStatCache->getField( $container, 'stat' );
1549 }
1550
1558 protected function createContainer( $container, array $params ) {
1559 $status = $this->newStatus();
1560
1561 // @see SwiftFileBackend::setContainerAccess()
1562 if ( empty( $params['noAccess'] ) ) {
1563 // public
1564 $readUsers = array_merge( $this->readUsers, [ '.r:*', $this->swiftUser ] );
1565 if ( empty( $params['noListing'] ) ) {
1566 array_push( $readUsers, '.rlistings' );
1567 }
1568 $writeUsers = array_merge( $this->writeUsers, [ $this->swiftUser ] );
1569 } else {
1570 // private
1571 $readUsers = array_merge( $this->secureReadUsers, [ $this->swiftUser ] );
1572 $writeUsers = array_merge( $this->secureWriteUsers, [ $this->swiftUser ] );
1573 }
1574
1575 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1576 'method' => 'PUT',
1577 'container' => $container,
1578 'headers' => [
1579 'x-container-read' => implode( ',', $readUsers ),
1580 'x-container-write' => implode( ',', $writeUsers )
1581 ]
1582 ] );
1583
1584 if ( $rcode === 201 ) { // new
1585 // good
1586 } elseif ( $rcode === 202 ) { // already there
1587 // this shouldn't really happen, but is OK
1588 } else {
1589 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1590 }
1591
1592 return $status;
1593 }
1594
1602 protected function deleteContainer( $container, array $params ) {
1603 $status = $this->newStatus();
1604
1605 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1606 'method' => 'DELETE',
1607 'container' => $container
1608 ] );
1609
1610 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1611 $this->containerStatCache->clear( $container ); // purge
1612 } elseif ( $rcode === 404 ) { // not there
1613 // this shouldn't really happen, but is OK
1614 } elseif ( $rcode === 409 ) { // not empty
1615 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1616 } else {
1617 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1618 }
1619
1620 return $status;
1621 }
1622
1635 private function objectListing(
1636 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1637 ) {
1638 $status = $this->newStatus();
1639
1640 $query = [ 'limit' => $limit ];
1641 if ( $type === 'info' ) {
1642 $query['format'] = 'json';
1643 }
1644 if ( $after !== null ) {
1645 $query['marker'] = $after;
1646 }
1647 if ( $prefix !== null ) {
1648 $query['prefix'] = $prefix;
1649 }
1650 if ( $delim !== null ) {
1651 $query['delimiter'] = $delim;
1652 }
1653
1654 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1655 'method' => 'GET',
1656 'container' => $fullCont,
1657 'query' => $query,
1658 ] );
1659
1660 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1661 if ( $rcode === 200 ) { // good
1662 if ( $type === 'info' ) {
1663 $status->value = json_decode( trim( $rbody ) );
1664 } else {
1665 $status->value = explode( "\n", trim( $rbody ) );
1666 }
1667 } elseif ( $rcode === 204 ) {
1668 $status->value = []; // empty container
1669 } elseif ( $rcode === 404 ) {
1670 $status->value = []; // no container
1671 } else {
1672 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1673 }
1674
1675 return $status;
1676 }
1677
1678 protected function doPrimeContainerCache( array $containerInfo ) {
1679 foreach ( $containerInfo as $container => $info ) {
1680 $this->containerStatCache->setField( $container, 'stat', $info );
1681 }
1682 }
1683
1684 protected function doGetFileStatMulti( array $params ) {
1685 $stats = [];
1686
1687 $reqs = []; // (path => op)
1688 // (a) Check the containers of the paths...
1689 foreach ( $params['srcs'] as $path ) {
1690 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
1691 if ( $srcRel === null ) {
1692 // invalid storage path
1693 $stats[$path] = self::RES_ERROR;
1694 continue;
1695 }
1696
1697 $cstat = $this->getContainerStat( $srcCont );
1698 if ( $cstat === self::RES_ABSENT ) {
1699 $stats[$path] = self::RES_ABSENT;
1700 continue; // ok, nothing to do
1701 } elseif ( $cstat === self::RES_ERROR ) {
1702 $stats[$path] = self::RES_ERROR;
1703 continue;
1704 }
1705
1706 $reqs[$path] = [
1707 'method' => 'HEAD',
1708 'container' => $srcCont,
1709 'relPath' => $srcRel,
1710 'headers' => $this->headersFromParams( $params )
1711 ];
1712 }
1713
1714 // (b) Check the files themselves...
1715 $reqs = $this->requestMultiWithAuth(
1716 $reqs,
1717 [ 'maxConnsPerHost' => $params['concurrency'] ]
1718 );
1719 foreach ( $reqs as $path => $op ) {
1720 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
1721 if ( $rcode === 200 || $rcode === 204 ) {
1722 // Update the object if it is missing some headers
1723 if ( !empty( $params['requireSHA1'] ) ) {
1724 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1725 }
1726 // Load the stat map from the headers
1727 $stat = $this->getStatFromHeaders( $rhdrs );
1728 if ( $this->isRGW ) {
1729 $stat['latest'] = true; // strong consistency
1730 }
1731 } elseif ( $rcode === 404 ) {
1732 $stat = self::RES_ABSENT;
1733 } else {
1734 $stat = self::RES_ERROR;
1735 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc, $rbody );
1736 }
1737 $stats[$path] = $stat;
1738 }
1739
1740 return $stats;
1741 }
1742
1747 protected function getStatFromHeaders( array $rhdrs ) {
1748 // Fetch all of the custom metadata headers
1749 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1750 // Fetch all of the custom raw HTTP headers
1751 $headers = $this->extractMutableContentHeaders( $rhdrs );
1752
1753 return [
1754 // Convert various random Swift dates to TS_MW
1755 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1756 // Empty objects actually return no content-length header in Ceph
1757 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1758 'sha1' => $metadata['sha1base36'] ?? null,
1759 // Note: manifest ETags are not an MD5 of the file
1760 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1761 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1762 ];
1763 }
1764
1770 protected function getAuthentication() {
1771 if ( $this->authErrorTimestamp !== null ) {
1772 $interval = time() - $this->authErrorTimestamp;
1773 if ( $interval < 60 ) {
1774 $this->logger->debug(
1775 'rejecting request since auth failure occurred {interval} seconds ago',
1776 [ 'interval' => $interval ]
1777 );
1778 return null;
1779 } else { // actually retry this time
1780 $this->authErrorTimestamp = null;
1781 }
1782 }
1783 // Authenticate with proxy and get a session key...
1784 if ( !$this->authCreds ) {
1785 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1786 $creds = $this->srvCache->get( $cacheKey ); // credentials
1787 // Try to use the credential cache
1788 if ( isset( $creds['auth_token'] )
1789 && isset( $creds['storage_url'] )
1790 && isset( $creds['expiry_time'] )
1791 && $creds['expiry_time'] > time()
1792 ) {
1793 $this->setAuthCreds( $creds );
1794 } else { // cache miss
1795 $this->refreshAuthentication();
1796 }
1797 }
1798
1799 return $this->authCreds;
1800 }
1801
1807 private function setAuthCreds( ?array $creds ) {
1808 $this->logger->debug( 'Using auth token with expiry_time={expiry_time}',
1809 [
1810 'expiry_time' => isset( $creds['expiry_time'] )
1811 ? gmdate( 'c', $creds['expiry_time'] ) : 'null'
1812 ]
1813 );
1814 $this->authCreds = $creds;
1815 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1816 if ( $creds && str_ends_with( $creds['storage_url'], '/v1' ) ) {
1817 $this->isRGW = true; // take advantage of strong consistency in Ceph
1818 }
1819 }
1820
1826 private function refreshAuthentication() {
1827 [ $rcode, , $rhdrs, $rbody, ] = $this->http->run( [
1828 'method' => 'GET',
1829 'url' => "{$this->swiftAuthUrl}/v1.0",
1830 'headers' => [
1831 'x-auth-user' => $this->swiftUser,
1832 'x-auth-key' => $this->swiftKey
1833 ]
1834 ], self::DEFAULT_HTTP_OPTIONS );
1835
1836 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1837 if ( isset( $rhdrs['x-auth-token-expires'] ) ) {
1838 $ttl = intval( $rhdrs['x-auth-token-expires'] );
1839 } else {
1840 $ttl = $this->authTTL;
1841 }
1842 $expiryTime = time() + $ttl;
1843 $creds = [
1844 'auth_token' => $rhdrs['x-auth-token'],
1845 'storage_url' => $this->swiftStorageUrl ?? $rhdrs['x-storage-url'],
1846 'expiry_time' => $expiryTime,
1847 ];
1848 $this->srvCache->set( $this->getCredsCacheKey( $this->swiftUser ), $creds, $expiryTime );
1849 } elseif ( $rcode === 401 ) {
1850 $this->onError( null, __METHOD__, [], "Authentication failed.", $rcode );
1851 $this->authErrorTimestamp = time();
1852 $creds = null;
1853 } else {
1854 $this->onError( null, __METHOD__, [], "HTTP return code: $rcode", $rcode, $rbody );
1855 $this->authErrorTimestamp = time();
1856 $creds = null;
1857 }
1858 $this->setAuthCreds( $creds );
1859 return $creds;
1860 }
1861
1868 protected function storageUrl( array $creds, $container = null, $object = null ) {
1869 $parts = [ $creds['storage_url'] ];
1870 if ( ( $container ?? '' ) !== '' ) {
1871 $parts[] = rawurlencode( $container );
1872 }
1873 if ( ( $object ?? '' ) !== '' ) {
1874 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1875 }
1876
1877 return implode( '/', $parts );
1878 }
1879
1884 protected function authTokenHeaders( array $creds ) {
1885 return [ 'x-auth-token' => $creds['auth_token'] ];
1886 }
1887
1894 private function getCredsCacheKey( $username ) {
1895 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1896 }
1897
1912 private function requestWithAuth( array $req, array $options = [] ) {
1913 return $this->requestMultiWithAuth( [ $req ], $options )[0]['response'];
1914 }
1915
1925 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1926 $remainingTries = 2;
1927 $auth = $this->getAuthentication();
1928 while ( true ) {
1929 if ( !$auth ) {
1930 foreach ( $reqs as &$req ) {
1931 if ( !isset( $req['response'] ) ) {
1932 $req['response'] = $this->getAuthFailureResponse();
1933 }
1934 }
1935 break;
1936 }
1937 foreach ( $reqs as &$req ) {
1938 '@phan-var array $req'; // Not array[]
1939 if ( isset( $req['response'] ) ) {
1940 // Request was attempted before
1941 // Retry only if it gave a 401 response code
1942 if ( $req['response']['code'] !== 401 ) {
1943 continue;
1944 }
1945 }
1946 $req['headers'] = $this->authTokenHeaders( $auth ) + ( $req['headers'] ?? [] );
1947 $req['url'] = $this->storageUrl( $auth, $req['container'], $req['relPath'] ?? null );
1948 }
1949 unset( $req );
1950 $reqs = $this->http->runMulti( $reqs, $options + self::DEFAULT_HTTP_OPTIONS );
1951 if ( --$remainingTries > 0 ) {
1952 // Retry if any request failed with 401 "not authorized"
1953 foreach ( $reqs as $req ) {
1954 if ( $req['response']['code'] === 401 ) {
1955 $auth = $this->refreshAuthentication();
1956 continue 2;
1957 }
1958 }
1959 }
1960 break;
1961 }
1962 return $reqs;
1963 }
1964
1973 private function getAuthFailureResponse() {
1974 return [
1975 'code' => 0,
1976 0 => 0,
1977 'reason' => '',
1978 1 => '',
1979 'headers' => [],
1980 2 => [],
1981 'body' => '',
1982 3 => '',
1983 'error' => self::AUTH_FAILURE_ERROR,
1984 4 => self::AUTH_FAILURE_ERROR
1985 ];
1986 }
1987
1995 private function isAuthFailureResponse( $code, $error ) {
1996 return $code === 0 && $error === self::AUTH_FAILURE_ERROR;
1997 }
1998
2011 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '', $body = '' ) {
2012 if ( $this->isAuthFailureResponse( $code, $err ) ) {
2013 if ( $status instanceof StatusValue ) {
2014 $status->fatal( 'backend-fail-connect', $this->name );
2015 }
2016 // Already logged
2017 return;
2018 }
2019 if ( $status instanceof StatusValue ) {
2020 $status->fatal( 'backend-fail-internal', $this->name );
2021 }
2022 $msg = "HTTP {code} ({desc}) in '{func}'";
2023 $msgParams = [
2024 'code' => $code,
2025 'desc' => $desc,
2026 'func' => $func,
2027 'req_params' => $params,
2028 ];
2029 if ( $err ) {
2030 $msg .= ': {err}';
2031 $msgParams['err'] = $err;
2032 }
2033 if ( $code == 502 ) {
2034 $msg .= ' ({truncatedBody})';
2035 $msgParams['truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
2036 }
2037 $this->logger->error( $msg, $msgParams );
2038 }
2039}
2040
2042class_alias( SwiftFileBackend::class, 'SwiftFileBackend' );
Resource locking handling.
Store key-value entries in a size-limited in-memory LRU cache.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
File backend exception for checked exceptions (e.g.
Base class for all backends using particular storage medium.
getContentType( $storagePath, $content, $fsPath)
Get the content type to use in HEAD/GET requests for a file.
resolveStoragePathReal( $storagePath)
Like resolveStoragePath() except null values are returned if the container is sharded and the shard c...
executeOpHandlesInternal(array $fileOpHandles)
Execute a list of FileBackendStoreOpHandle handles in parallel.
setContainerCache( $container, array $val)
Set the cached info for a container.
getFileStat(array $params)
Get quick information about a file at a storage path in the backend.
fileExists(array $params)
Check if a file exists at a storage path in the backend.
clearCache(?array $paths=null)
Invalidate any in-process file stat and property cache.
deleteFileCache( $path)
Delete the cached stat info for a file path.
primeContainerCache(array $items)
Do a batch lookup from cache for container stats for all containers used in a list of container names...
string $name
Unique backend name.
getLocalCopy(array $params)
Get a local copy on disk of the file at a storage path in the backend.
static extensionFromPath( $path, $case='lowercase')
Get the final extension from a storage or FS path.
getScopedFileLocks(array $paths, $type, StatusValue $status, $timeout=0)
Lock the files at the given storage paths in the backend.
newStatus( $message=null,... $params)
Yields the result of the status wrapper callback on either:
static send404Message( $fname, $flags=0)
Send out a standard 404 message for a file.
Class for an OpenStack Swift (or Ceph RGW) based file backend.
getAuthentication()
Get the cached auth token.
MapCacheLRU $containerStatCache
Container stat cache.
headersFromParams(array $params)
Get headers to send to Swift when reading a file based on a FileBackend params array,...
getFileListInternal( $fullCont, $dir, array $params)
resolveContainerPath( $container, $relStoragePath)
Resolve a relative storage path, checking if it's allowed by the backend.
doCleanInternal( $fullCont, $dir, array $params)
string $swiftTempUrlKey
Shared secret value for making temp URLs.
addMissingHashMetadata(array $objHdrs, $path)
Fill in any missing object metadata and save it to Swift.
array $writeUsers
Additional users (account:user) with write permissions on public containers.
string $swiftAuthUrl
Authentication base URL (without version)
doDirectoryExists( $fullCont, $dir, array $params)
storageUrl(array $creds, $container=null, $object=null)
onError( $status, $func, array $params, $err='', $code=0, $desc='', $body='')
Log an unexpected exception for this backend.
createContainer( $container, array $params)
Create a Swift container.
array $secureWriteUsers
Additional users (account:user) with write permissions on private containers.
doPrimeContainerCache(array $containerInfo)
Fill the backend-specific process cache given an array of resolved container names and their correspo...
array $readUsers
Additional users (account:user) with read permissions on public containers.
convertSwiftDate( $ts, $format=TS_MW)
Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
getDirectoryListInternal( $fullCont, $dir, array $params)
getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params)
Do not call this function outside of SwiftFileBackendFileList.
deleteContainer( $container, array $params)
Delete a Swift container.
directoriesAreVirtual()
Is this a key/value store where directories are just virtual? Virtual directories exists in so much a...
string $rgwS3AccessKey
S3 access key (RADOS Gateway)
addShellboxInputFile(BoxedCommand $command, string $boxedName, array $params)
Add a file to a Shellbox command as an input file.
doPrepareInternal( $fullCont, $dir, array $params)
FileBackendStore::doPrepare() to override StatusValue Good status without value for success,...
extractMutableContentHeaders(array $headers)
Filter/normalize a header map to only include mutable "content-"/"x-content-" headers.
string $swiftUser
Swift user (account:user) to authenticate as.
getFeatures()
Get the a bitfield of extra features supported by the backend medium.
string $swiftStorageUrl
Override of storage base URL.
doGetFileStatMulti(array $params)
Get file stat information (concurrently if possible) for several files.
loadListingStatInternal( $path, array $val)
Do not call this function outside of SwiftFileBackendFileList.
isPathUsableInternal( $storagePath)
Check if a file can be created or changed at a given storage path in the backend.
setContainerAccess( $container, array $readUsers, array $writeUsers)
Set read/write permissions for a Swift container.
string $rgwS3SecretKey
S3 authentication key (RADOS Gateway)
getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params)
Do not call this function outside of SwiftFileBackendFileList.
array $secureReadUsers
Additional users (account:user) with read permissions on private containers.
bool $isRGW
Whether the server is an Ceph RGW.
int null $authErrorTimestamp
UNIX timestamp.
doSecureInternal( $fullCont, $dir, array $params)
doPublishInternal( $fullCont, $dir, array $params)
getContainerStat( $container, $bypassCache=false)
Get a Swift container stat map, possibly from process cache.
Class to handle multiple HTTP requests.
Abstract class for any ephemeral data store.
Definition BagOStuff.php:88
No-op implementation that stores nothing.
Multi-datacenter aware caching interface.
array $params
The job parameters.
This program is free software; you can redistribute it and/or modify it under the terms of the GNU Ge...
$header