3 * OpenStack Swift based file backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 * @author Aaron Schulz
27 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
29 * StatusValue messages should avoid mentioning the Swift account name.
30 * Likewise, error suppression should be used to avoid path disclosure.
32 * @ingroup FileBackend
35 class SwiftFileBackend
extends FileBackendStore
{
36 /** @var MultiHttpClient */
39 /** @var int TTL in seconds */
42 /** @var string Authentication base URL (without version) */
43 protected $swiftAuthUrl;
45 /** @var string Swift user (account:user) to authenticate as */
48 /** @var string Secret key for user */
51 /** @var string Shared secret value for making temp URLs */
52 protected $swiftTempUrlKey;
54 /** @var string S3 access key (RADOS Gateway) */
55 protected $rgwS3AccessKey;
57 /** @var string S3 authentication key (RADOS Gateway) */
58 protected $rgwS3SecretKey;
63 /** @var ProcessCacheLRU Container stat cache */
64 protected $containerStatCache;
69 /** @var int UNIX timestamp */
70 protected $authSessionTimestamp = 0;
72 /** @var int UNIX timestamp */
73 protected $authErrorTimestamp = null;
75 /** @var bool Whether the server is an Ceph RGW */
76 protected $isRGW = false;
79 * @see FileBackendStore::__construct()
80 * Additional $config params include:
81 * - swiftAuthUrl : Swift authentication server URL
82 * - swiftUser : Swift user used by MediaWiki (account:username)
83 * - swiftKey : Swift authentication key for the above user
84 * - swiftAuthTTL : Swift authentication TTL (seconds)
85 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
86 * Do not set this until it has been set in the backend.
87 * - shardViaHashLevels : Map of container names to sharding config with:
88 * - base : base of hash characters, 16 or 36
89 * - levels : the number of hash levels (and digits)
90 * - repeat : hash subdirectories are prefixed with all the
91 * parent hash directory names (e.g. "a/ab/abc")
92 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
93 * If those are not available, then the main cache will be used.
94 * This is probably insecure in shared hosting environments.
95 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
96 * Do not set this until it has been set in the backend.
97 * This is used for generating expiring pre-authenticated URLs.
98 * Only use this when using rgw and to work around
99 * http://tracker.newdream.net/issues/3454.
100 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
101 * Do not set this until it has been set in the backend.
102 * This is used for generating expiring pre-authenticated URLs.
103 * Only use this when using rgw and to work around
104 * http://tracker.newdream.net/issues/3454.
106 public function __construct( array $config ) {
107 parent
::__construct( $config );
109 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
110 $this->swiftUser
= $config['swiftUser'];
111 $this->swiftKey
= $config['swiftKey'];
113 $this->authTTL
= isset( $config['swiftAuthTTL'] )
114 ?
$config['swiftAuthTTL']
115 : 15 * 60; // some sane number
116 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
117 ?
$config['swiftTempUrlKey']
119 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
120 ?
$config['shardViaHashLevels']
122 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
123 ?
$config['rgwS3AccessKey']
125 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
126 ?
$config['rgwS3SecretKey']
128 // HTTP helper client
129 $this->http
= new MultiHttpClient( [] );
130 // Cache container information to mask latency
131 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
132 $this->memCache
= $config['wanCache'];
134 // Process cache for container info
135 $this->containerStatCache
= new ProcessCacheLRU( 300 );
136 // Cache auth token information to avoid RTTs
137 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
138 $this->srvCache
= $config['srvCache'];
140 $this->srvCache
= new EmptyBagOStuff();
144 public function getFeatures() {
145 return ( FileBackend
::ATTR_UNICODE_PATHS |
146 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
149 protected function resolveContainerPath( $container, $relStoragePath ) {
150 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
151 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
152 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
153 return null; // too long for Swift
156 return $relStoragePath;
159 public function isPathUsableInternal( $storagePath ) {
160 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
161 if ( $rel === null ) {
162 return false; // invalid
165 return is_array( $this->getContainerStat( $container ) );
169 * Sanitize and filter the custom headers from a $params array.
170 * Only allows certain "standard" Content- and X-Content- headers.
172 * @param array $params
173 * @return array Sanitized value of 'headers' field in $params
175 protected function sanitizeHdrs( array $params ) {
176 return isset( $params['headers'] )
177 ?
$this->getCustomHeaders( $params['headers'] )
182 * @param array $rawHeaders
183 * @return array Custom non-metadata HTTP headers
185 protected function getCustomHeaders( array $rawHeaders ) {
188 // Normalize casing, and strip out illegal headers
189 foreach ( $rawHeaders as $name => $value ) {
190 $name = strtolower( $name );
191 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
192 continue; // blacklisted
193 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
194 $headers[$name] = $value; // allowed
195 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
196 $headers[$name] = $value; // allowed
199 // By default, Swift has annoyingly low maximum header value limits
200 if ( isset( $headers['content-disposition'] ) ) {
202 // @note: assume FileBackend::makeContentDisposition() already used
203 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
204 $part = trim( $part );
205 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
206 if ( strlen( $new ) <= 255 ) {
209 break; // too long; sigh
212 $headers['content-disposition'] = $disposition;
219 * @param array $rawHeaders
220 * @return array Custom metadata headers
222 protected function getMetadataHeaders( array $rawHeaders ) {
224 foreach ( $rawHeaders as $name => $value ) {
225 $name = strtolower( $name );
226 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
227 $headers[$name] = $value;
235 * @param array $rawHeaders
236 * @return array Custom metadata headers with prefix removed
238 protected function getMetadata( array $rawHeaders ) {
240 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
241 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
247 protected function doCreateInternal( array $params ) {
248 $status = $this->newStatus();
250 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
251 if ( $dstRel === null ) {
252 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
257 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
258 $contentType = isset( $params['headers']['content-type'] )
259 ?
$params['headers']['content-type']
260 : $this->getContentType( $params['dst'], $params['content'], null );
264 'url' => [ $dstCont, $dstRel ],
266 'content-length' => strlen( $params['content'] ),
267 'etag' => md5( $params['content'] ),
268 'content-type' => $contentType,
269 'x-object-meta-sha1base36' => $sha1Hash
270 ] +
$this->sanitizeHdrs( $params ),
271 'body' => $params['content']
274 $method = __METHOD__
;
275 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
276 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
277 if ( $rcode === 201 ) {
279 } elseif ( $rcode === 412 ) {
280 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
282 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
286 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
287 if ( !empty( $params['async'] ) ) { // deferred
288 $status->value
= $opHandle;
289 } else { // actually write the object in Swift
290 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
296 protected function doStoreInternal( array $params ) {
297 $status = $this->newStatus();
299 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
300 if ( $dstRel === null ) {
301 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
306 MediaWiki\
suppressWarnings();
307 $sha1Hash = sha1_file( $params['src'] );
308 MediaWiki\restoreWarnings
();
309 if ( $sha1Hash === false ) { // source doesn't exist?
310 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
314 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
315 $contentType = isset( $params['headers']['content-type'] )
316 ?
$params['headers']['content-type']
317 : $this->getContentType( $params['dst'], null, $params['src'] );
319 $handle = fopen( $params['src'], 'rb' );
320 if ( $handle === false ) { // source doesn't exist?
321 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
328 'url' => [ $dstCont, $dstRel ],
330 'content-length' => filesize( $params['src'] ),
331 'etag' => md5_file( $params['src'] ),
332 'content-type' => $contentType,
333 'x-object-meta-sha1base36' => $sha1Hash
334 ] +
$this->sanitizeHdrs( $params ),
335 'body' => $handle // resource
338 $method = __METHOD__
;
339 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
340 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
341 if ( $rcode === 201 ) {
343 } elseif ( $rcode === 412 ) {
344 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
346 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
350 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
351 $opHandle->resourcesToClose
[] = $handle;
353 if ( !empty( $params['async'] ) ) { // deferred
354 $status->value
= $opHandle;
355 } else { // actually write the object in Swift
356 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
362 protected function doCopyInternal( array $params ) {
363 $status = $this->newStatus();
365 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
366 if ( $srcRel === null ) {
367 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
372 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
373 if ( $dstRel === null ) {
374 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
381 'url' => [ $dstCont, $dstRel ],
383 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
384 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
385 ] +
$this->sanitizeHdrs( $params ), // extra headers merged into object
388 $method = __METHOD__
;
389 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
390 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
391 if ( $rcode === 201 ) {
393 } elseif ( $rcode === 404 ) {
394 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
396 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
400 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
401 if ( !empty( $params['async'] ) ) { // deferred
402 $status->value
= $opHandle;
403 } else { // actually write the object in Swift
404 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
410 protected function doMoveInternal( array $params ) {
411 $status = $this->newStatus();
413 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
414 if ( $srcRel === null ) {
415 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
420 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
421 if ( $dstRel === null ) {
422 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
430 'url' => [ $dstCont, $dstRel ],
432 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
433 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
434 ] +
$this->sanitizeHdrs( $params ) // extra headers merged into object
437 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
439 'method' => 'DELETE',
440 'url' => [ $srcCont, $srcRel ],
445 $method = __METHOD__
;
446 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
447 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
448 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
450 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
452 } elseif ( $rcode === 404 ) {
453 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
455 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
459 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
460 if ( !empty( $params['async'] ) ) { // deferred
461 $status->value
= $opHandle;
462 } else { // actually move the object in Swift
463 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
469 protected function doDeleteInternal( array $params ) {
470 $status = $this->newStatus();
472 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
473 if ( $srcRel === null ) {
474 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
480 'method' => 'DELETE',
481 'url' => [ $srcCont, $srcRel ],
485 $method = __METHOD__
;
486 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
487 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
488 if ( $rcode === 204 ) {
490 } elseif ( $rcode === 404 ) {
491 if ( empty( $params['ignoreMissingSource'] ) ) {
492 $status->fatal( 'backend-fail-delete', $params['src'] );
495 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
499 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
500 if ( !empty( $params['async'] ) ) { // deferred
501 $status->value
= $opHandle;
502 } else { // actually delete the object in Swift
503 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
509 protected function doDescribeInternal( array $params ) {
510 $status = $this->newStatus();
512 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
513 if ( $srcRel === null ) {
514 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
519 // Fetch the old object headers/metadata...this should be in stat cache by now
520 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
521 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
522 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
525 $status->fatal( 'backend-fail-describe', $params['src'] );
530 // POST clears prior headers, so we need to merge the changes in to the old ones
532 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
533 $metaHdrs["x-object-meta-$name"] = $value;
535 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
539 'url' => [ $srcCont, $srcRel ],
540 'headers' => $metaHdrs +
$customHdrs
543 $method = __METHOD__
;
544 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
545 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
546 if ( $rcode === 202 ) {
548 } elseif ( $rcode === 404 ) {
549 $status->fatal( 'backend-fail-describe', $params['src'] );
551 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
555 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
556 if ( !empty( $params['async'] ) ) { // deferred
557 $status->value
= $opHandle;
558 } else { // actually change the object in Swift
559 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
565 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
566 $status = $this->newStatus();
568 // (a) Check if container already exists
569 $stat = $this->getContainerStat( $fullCont );
570 if ( is_array( $stat ) ) {
571 return $status; // already there
572 } elseif ( $stat === null ) {
573 $status->fatal( 'backend-fail-internal', $this->name
);
574 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
579 // (b) Create container as needed with proper ACLs
580 if ( $stat === false ) {
581 $params['op'] = 'prepare';
582 $status->merge( $this->createContainer( $fullCont, $params ) );
588 protected function doSecureInternal( $fullCont, $dir, array $params ) {
589 $status = $this->newStatus();
590 if ( empty( $params['noAccess'] ) ) {
591 return $status; // nothing to do
594 $stat = $this->getContainerStat( $fullCont );
595 if ( is_array( $stat ) ) {
596 // Make container private to end-users...
597 $status->merge( $this->setContainerAccess(
599 [ $this->swiftUser
], // read
600 [ $this->swiftUser
] // write
602 } elseif ( $stat === false ) {
603 $status->fatal( 'backend-fail-usable', $params['dir'] );
605 $status->fatal( 'backend-fail-internal', $this->name
);
606 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
612 protected function doPublishInternal( $fullCont, $dir, array $params ) {
613 $status = $this->newStatus();
615 $stat = $this->getContainerStat( $fullCont );
616 if ( is_array( $stat ) ) {
617 // Make container public to end-users...
618 $status->merge( $this->setContainerAccess(
620 [ $this->swiftUser
, '.r:*' ], // read
621 [ $this->swiftUser
] // write
623 } elseif ( $stat === false ) {
624 $status->fatal( 'backend-fail-usable', $params['dir'] );
626 $status->fatal( 'backend-fail-internal', $this->name
);
627 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
633 protected function doCleanInternal( $fullCont, $dir, array $params ) {
634 $status = $this->newStatus();
636 // Only containers themselves can be removed, all else is virtual
638 return $status; // nothing to do
641 // (a) Check the container
642 $stat = $this->getContainerStat( $fullCont, true );
643 if ( $stat === false ) {
644 return $status; // ok, nothing to do
645 } elseif ( !is_array( $stat ) ) {
646 $status->fatal( 'backend-fail-internal', $this->name
);
647 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
652 // (b) Delete the container if empty
653 if ( $stat['count'] == 0 ) {
654 $params['op'] = 'clean';
655 $status->merge( $this->deleteContainer( $fullCont, $params ) );
661 protected function doGetFileStat( array $params ) {
662 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
663 unset( $params['src'] );
664 $stats = $this->doGetFileStatMulti( $params );
666 return reset( $stats );
670 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
671 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
672 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
675 * @param int $format Output format (TS_* constant)
677 * @throws FileBackendError
679 protected function convertSwiftDate( $ts, $format = TS_MW
) {
681 $timestamp = new MWTimestamp( $ts );
683 return $timestamp->getTimestamp( $format );
684 } catch ( Exception
$e ) {
685 throw new FileBackendError( $e->getMessage() );
690 * Fill in any missing object metadata and save it to Swift
692 * @param array $objHdrs Object response headers
693 * @param string $path Storage path to object
694 * @return array New headers
696 protected function addMissingMetadata( array $objHdrs, $path ) {
697 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
698 return $objHdrs; // nothing to do
701 /** @noinspection PhpUnusedLocalVariableInspection */
702 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
703 $this->logger
->error( __METHOD__
. ": $path was not stored with SHA-1 metadata." );
705 $objHdrs['x-object-meta-sha1base36'] = false;
707 $auth = $this->getAuthentication();
709 return $objHdrs; // failed
712 // Find prior custom HTTP headers
713 $postHeaders = $this->getCustomHeaders( $objHdrs );
714 // Find prior metadata headers
715 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
717 $status = $this->newStatus();
718 /** @noinspection PhpUnusedLocalVariableInspection */
719 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
720 if ( $status->isOK() ) {
721 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
723 $hash = $tmpFile->getSha1Base36();
724 if ( $hash !== false ) {
725 $objHdrs['x-object-meta-sha1base36'] = $hash;
726 // Merge new SHA1 header into the old ones
727 $postHeaders['x-object-meta-sha1base36'] = $hash;
728 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
729 list( $rcode ) = $this->http
->run( [
731 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
732 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
734 if ( $rcode >= 200 && $rcode <= 299 ) {
735 $this->deleteFileCache( $path );
737 return $objHdrs; // success
743 $this->logger
->error( __METHOD__
. ": unable to set SHA-1 metadata for $path" );
745 return $objHdrs; // failed
748 protected function doGetFileContentsMulti( array $params ) {
751 $auth = $this->getAuthentication();
753 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
754 // Blindly create tmp files and stream to them, catching any exception if the file does
755 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
756 $reqs = []; // (path => op)
758 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
759 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
760 if ( $srcRel === null ||
!$auth ) {
761 $contents[$path] = false;
764 // Create a new temporary memory file...
765 $handle = fopen( 'php://temp', 'wb' );
769 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
770 'headers' => $this->authTokenHeaders( $auth )
771 +
$this->headersFromParams( $params ),
775 $contents[$path] = false;
778 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
779 $reqs = $this->http
->runMulti( $reqs, $opts );
780 foreach ( $reqs as $path => $op ) {
781 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
782 if ( $rcode >= 200 && $rcode <= 299 ) {
783 rewind( $op['stream'] ); // start from the beginning
784 $contents[$path] = stream_get_contents( $op['stream'] );
785 } elseif ( $rcode === 404 ) {
786 $contents[$path] = false;
788 $this->onError( null, __METHOD__
,
789 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
791 fclose( $op['stream'] ); // close open handle
797 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
798 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
799 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
800 if ( $status->isOK() ) {
801 return ( count( $status->value
) ) > 0;
804 return null; // error
808 * @see FileBackendStore::getDirectoryListInternal()
809 * @param string $fullCont
811 * @param array $params
812 * @return SwiftFileBackendDirList
814 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
815 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
819 * @see FileBackendStore::getFileListInternal()
820 * @param string $fullCont
822 * @param array $params
823 * @return SwiftFileBackendFileList
825 public function getFileListInternal( $fullCont, $dir, array $params ) {
826 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
830 * Do not call this function outside of SwiftFileBackendFileList
832 * @param string $fullCont Resolved container name
833 * @param string $dir Resolved storage directory with no trailing slash
834 * @param string|null $after Resolved container relative path to list items after
835 * @param int $limit Max number of items to list
836 * @param array $params Parameters for getDirectoryList()
837 * @return array List of container relative resolved paths of directories directly under $dir
838 * @throws FileBackendError
840 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
842 if ( $after === INF
) {
843 return $dirs; // nothing more
846 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
848 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
849 // Non-recursive: only list dirs right under $dir
850 if ( !empty( $params['topOnly'] ) ) {
851 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
852 if ( !$status->isOK() ) {
853 throw new FileBackendError( "Iterator page I/O error." );
855 $objects = $status->value
;
856 foreach ( $objects as $object ) { // files and directories
857 if ( substr( $object, -1 ) === '/' ) {
858 $dirs[] = $object; // directories end in '/'
862 // Recursive: list all dirs under $dir and its subdirs
863 $getParentDir = function ( $path ) {
864 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
867 // Get directory from last item of prior page
868 $lastDir = $getParentDir( $after ); // must be first page
869 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
871 if ( !$status->isOK() ) {
872 throw new FileBackendError( "Iterator page I/O error." );
875 $objects = $status->value
;
877 foreach ( $objects as $object ) { // files
878 $objectDir = $getParentDir( $object ); // directory of object
880 if ( $objectDir !== false && $objectDir !== $dir ) {
881 // Swift stores paths in UTF-8, using binary sorting.
882 // See function "create_container_table" in common/db.py.
883 // If a directory is not "greater" than the last one,
884 // then it was already listed by the calling iterator.
885 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
887 do { // add dir and all its parent dirs
888 $dirs[] = "{$pDir}/";
889 $pDir = $getParentDir( $pDir );
890 } while ( $pDir !== false // sanity
891 && strcmp( $pDir, $lastDir ) > 0 // not done already
892 && strlen( $pDir ) > strlen( $dir ) // within $dir
895 $lastDir = $objectDir;
899 // Page on the unfiltered directory listing (what is returned may be filtered)
900 if ( count( $objects ) < $limit ) {
901 $after = INF
; // avoid a second RTT
903 $after = end( $objects ); // update last item
910 * Do not call this function outside of SwiftFileBackendFileList
912 * @param string $fullCont Resolved container name
913 * @param string $dir Resolved storage directory with no trailing slash
914 * @param string|null $after Resolved container relative path of file to list items after
915 * @param int $limit Max number of items to list
916 * @param array $params Parameters for getDirectoryList()
917 * @return array List of resolved container relative paths of files under $dir
918 * @throws FileBackendError
920 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
921 $files = []; // list of (path, stat array or null) entries
922 if ( $after === INF
) {
923 return $files; // nothing more
926 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
928 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
929 // $objects will contain a list of unfiltered names or CF_Object items
930 // Non-recursive: only list files right under $dir
931 if ( !empty( $params['topOnly'] ) ) {
932 if ( !empty( $params['adviseStat'] ) ) {
933 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
935 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
938 // Recursive: list all files under $dir and its subdirs
939 if ( !empty( $params['adviseStat'] ) ) {
940 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
942 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
946 // Reformat this list into a list of (name, stat array or null) entries
947 if ( !$status->isOK() ) {
948 throw new FileBackendError( "Iterator page I/O error." );
951 $objects = $status->value
;
952 $files = $this->buildFileObjectListing( $params, $dir, $objects );
954 // Page on the unfiltered object listing (what is returned may be filtered)
955 if ( count( $objects ) < $limit ) {
956 $after = INF
; // avoid a second RTT
958 $after = end( $objects ); // update last item
959 $after = is_object( $after ) ?
$after->name
: $after;
966 * Build a list of file objects, filtering out any directories
967 * and extracting any stat info if provided in $objects (for CF_Objects)
969 * @param array $params Parameters for getDirectoryList()
970 * @param string $dir Resolved container directory path
971 * @param array $objects List of CF_Object items or object names
972 * @return array List of (names,stat array or null) entries
974 private function buildFileObjectListing( array $params, $dir, array $objects ) {
976 foreach ( $objects as $object ) {
977 if ( is_object( $object ) ) {
978 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
979 continue; // virtual directory entry; ignore
982 // Convert various random Swift dates to TS_MW
983 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
984 'size' => (int)$object->bytes
,
986 // Note: manifiest ETags are not an MD5 of the file
987 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
988 'latest' => false // eventually consistent
990 $names[] = [ $object->name
, $stat ];
991 } elseif ( substr( $object, -1 ) !== '/' ) {
992 // Omit directories, which end in '/' in listings
993 $names[] = [ $object, null ];
1001 * Do not call this function outside of SwiftFileBackendFileList
1003 * @param string $path Storage path
1004 * @param array $val Stat value
1006 public function loadListingStatInternal( $path, array $val ) {
1007 $this->cheapCache
->set( $path, 'stat', $val );
1010 protected function doGetFileXAttributes( array $params ) {
1011 $stat = $this->getFileStat( $params );
1013 if ( !isset( $stat['xattr'] ) ) {
1014 // Stat entries filled by file listings don't include metadata/headers
1015 $this->clearCache( [ $params['src'] ] );
1016 $stat = $this->getFileStat( $params );
1019 return $stat['xattr'];
1025 protected function doGetFileSha1base36( array $params ) {
1026 $stat = $this->getFileStat( $params );
1028 if ( !isset( $stat['sha1'] ) ) {
1029 // Stat entries filled by file listings don't include SHA1
1030 $this->clearCache( [ $params['src'] ] );
1031 $stat = $this->getFileStat( $params );
1034 return $stat['sha1'];
1040 protected function doStreamFile( array $params ) {
1041 $status = $this->newStatus();
1043 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1045 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1046 if ( $srcRel === null ) {
1047 StreamFile
::send404Message( $params['src'], $flags );
1048 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1053 $auth = $this->getAuthentication();
1054 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1055 StreamFile
::send404Message( $params['src'], $flags );
1056 $status->fatal( 'backend-fail-stream', $params['src'] );
1061 // If "headers" is set, we only want to send them if the file is there.
1062 // Do not bother checking if the file exists if headers are not set though.
1063 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1064 StreamFile
::send404Message( $params['src'], $flags );
1065 $status->fatal( 'backend-fail-stream', $params['src'] );
1070 // Send the requested additional headers
1071 foreach ( $params['headers'] as $header ) {
1072 header( $header ); // aways send
1075 if ( empty( $params['allowOB'] ) ) {
1076 // Cancel output buffering and gzipping if set
1077 call_user_func( $this->obResetFunc
);
1080 $handle = fopen( 'php://output', 'wb' );
1081 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1083 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1084 'headers' => $this->authTokenHeaders( $auth )
1085 +
$this->headersFromParams( $params ) +
$params['options'],
1086 'stream' => $handle,
1087 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1090 if ( $rcode >= 200 && $rcode <= 299 ) {
1092 } elseif ( $rcode === 404 ) {
1093 $status->fatal( 'backend-fail-stream', $params['src'] );
1094 // Per T43113, nasty things can happen if bad cache entries get
1095 // stuck in cache. It's also possible that this error can come up
1096 // with simple race conditions. Clear out the stat cache to be safe.
1097 $this->clearCache( [ $params['src'] ] );
1098 $this->deleteFileCache( $params['src'] );
1100 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1106 protected function doGetLocalCopyMulti( array $params ) {
1107 /** @var TempFSFile[] $tmpFiles */
1110 $auth = $this->getAuthentication();
1112 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1113 // Blindly create tmp files and stream to them, catching any exception if the file does
1114 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1115 $reqs = []; // (path => op)
1117 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1118 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1119 if ( $srcRel === null ||
!$auth ) {
1120 $tmpFiles[$path] = null;
1123 // Get source file extension
1124 $ext = FileBackend
::extensionFromPath( $path );
1125 // Create a new temporary file...
1126 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext, $this->tmpDirectory
);
1128 $handle = fopen( $tmpFile->getPath(), 'wb' );
1132 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1133 'headers' => $this->authTokenHeaders( $auth )
1134 +
$this->headersFromParams( $params ),
1135 'stream' => $handle,
1141 $tmpFiles[$path] = $tmpFile;
1144 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1145 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1146 $reqs = $this->http
->runMulti( $reqs, $opts );
1147 foreach ( $reqs as $path => $op ) {
1148 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1149 fclose( $op['stream'] ); // close open handle
1150 if ( $rcode >= 200 && $rcode <= 299 ) {
1151 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1152 // Double check that the disk is not full/broken
1153 if ( $size != $rhdrs['content-length'] ) {
1154 $tmpFiles[$path] = null;
1155 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1156 $this->onError( null, __METHOD__
,
1157 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1159 // Set the file stat process cache in passing
1160 $stat = $this->getStatFromHeaders( $rhdrs );
1161 $stat['latest'] = $isLatest;
1162 $this->cheapCache
->set( $path, 'stat', $stat );
1163 } elseif ( $rcode === 404 ) {
1164 $tmpFiles[$path] = false;
1166 $tmpFiles[$path] = null;
1167 $this->onError( null, __METHOD__
,
1168 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1175 public function getFileHttpUrl( array $params ) {
1176 if ( $this->swiftTempUrlKey
!= '' ||
1177 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1179 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1180 if ( $srcRel === null ) {
1181 return null; // invalid path
1184 $auth = $this->getAuthentication();
1189 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1190 $expires = time() +
$ttl;
1192 if ( $this->swiftTempUrlKey
!= '' ) {
1193 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1194 // Swift wants the signature based on the unencoded object name
1195 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1196 $signature = hash_hmac( 'sha1',
1197 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1198 $this->swiftTempUrlKey
1201 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1202 } else { // give S3 API URL for rgw
1203 // Path for signature starts with the bucket
1204 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1205 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1206 // Calculate the hash
1207 $signature = base64_encode( hash_hmac(
1209 "GET\n\n\n{$expires}\n{$spath}",
1210 $this->rgwS3SecretKey
,
1213 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1214 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1215 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1216 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1219 'Signature' => $signature,
1220 'Expires' => $expires,
1221 'AWSAccessKeyId' => $this->rgwS3AccessKey
1229 protected function directoriesAreVirtual() {
1234 * Get headers to send to Swift when reading a file based
1235 * on a FileBackend params array, e.g. that of getLocalCopy().
1236 * $params is currently only checked for a 'latest' flag.
1238 * @param array $params
1241 protected function headersFromParams( array $params ) {
1243 if ( !empty( $params['latest'] ) ) {
1244 $hdrs['x-newest'] = 'true';
1251 * @param FileBackendStoreOpHandle[] $fileOpHandles
1253 * @return StatusValue[]
1255 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1256 /** @var $statuses StatusValue[] */
1259 $auth = $this->getAuthentication();
1261 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1262 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1268 // Split the HTTP requests into stages that can be done concurrently
1269 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1270 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1271 /** @var SwiftFileOpHandle $fileOpHandle */
1272 $reqs = $fileOpHandle->httpOp
;
1273 // Convert the 'url' parameter to an actual URL using $auth
1274 foreach ( $reqs as $stage => &$req ) {
1275 list( $container, $relPath ) = $req['url'];
1276 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1277 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : [];
1278 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1279 $httpReqsByStage[$stage][$index] = $req;
1281 $statuses[$index] = $this->newStatus();
1284 // Run all requests for the first stage, then the next, and so on
1285 $reqCount = count( $httpReqsByStage );
1286 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1287 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1288 foreach ( $httpReqs as $index => $httpReq ) {
1289 // Run the callback for each request of this operation
1290 $callback = $fileOpHandles[$index]->callback
;
1291 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1292 // On failure, abort all remaining requests for this operation
1293 // (e.g. abort the DELETE request if the COPY request fails for a move)
1294 if ( !$statuses[$index]->isOK() ) {
1295 $stages = count( $fileOpHandles[$index]->httpOp
);
1296 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1297 unset( $httpReqsByStage[$s][$index] );
1307 * Set read/write permissions for a Swift container.
1309 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1311 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1312 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1314 * @param string $container Resolved Swift container
1315 * @param array $readGrps List of the possible criteria for a request to have
1316 * access to read a container. Each item is one of the following formats:
1317 * - account:user : Grants access if the request is by the given user
1318 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1319 * matches the expression and the request is not for a listing.
1320 * Setting this to '*' effectively makes a container public.
1321 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1322 * matches the expression and the request is for a listing.
1323 * @param array $writeGrps A list of the possible criteria for a request to have
1324 * access to write to a container. Each item is of the following format:
1325 * - account:user : Grants access if the request is by the given user
1326 * @return StatusValue
1328 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1329 $status = $this->newStatus();
1330 $auth = $this->getAuthentication();
1333 $status->fatal( 'backend-fail-connect', $this->name
);
1338 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1340 'url' => $this->storageUrl( $auth, $container ),
1341 'headers' => $this->authTokenHeaders( $auth ) +
[
1342 'x-container-read' => implode( ',', $readGrps ),
1343 'x-container-write' => implode( ',', $writeGrps )
1347 if ( $rcode != 204 && $rcode !== 202 ) {
1348 $status->fatal( 'backend-fail-internal', $this->name
);
1349 $this->logger
->error( __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1356 * Get a Swift container stat array, possibly from process cache.
1357 * Use $reCache if the file count or byte count is needed.
1359 * @param string $container Container name
1360 * @param bool $bypassCache Bypass all caches and load from Swift
1361 * @return array|bool|null False on 404, null on failure
1363 protected function getContainerStat( $container, $bypassCache = false ) {
1364 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1366 if ( $bypassCache ) { // purge cache
1367 $this->containerStatCache
->clear( $container );
1368 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1369 $this->primeContainerCache( [ $container ] ); // check persistent cache
1371 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1372 $auth = $this->getAuthentication();
1377 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1379 'url' => $this->storageUrl( $auth, $container ),
1380 'headers' => $this->authTokenHeaders( $auth )
1383 if ( $rcode === 204 ) {
1385 'count' => $rhdrs['x-container-object-count'],
1386 'bytes' => $rhdrs['x-container-bytes-used']
1388 if ( $bypassCache ) {
1391 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1392 $this->setContainerCache( $container, $stat ); // update persistent cache
1394 } elseif ( $rcode === 404 ) {
1397 $this->onError( null, __METHOD__
,
1398 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1404 return $this->containerStatCache
->get( $container, 'stat' );
1408 * Create a Swift container
1410 * @param string $container Container name
1411 * @param array $params
1412 * @return StatusValue
1414 protected function createContainer( $container, array $params ) {
1415 $status = $this->newStatus();
1417 $auth = $this->getAuthentication();
1419 $status->fatal( 'backend-fail-connect', $this->name
);
1424 // @see SwiftFileBackend::setContainerAccess()
1425 if ( empty( $params['noAccess'] ) ) {
1426 $readGrps = [ '.r:*', $this->swiftUser
]; // public
1428 $readGrps = [ $this->swiftUser
]; // private
1430 $writeGrps = [ $this->swiftUser
]; // sanity
1432 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1434 'url' => $this->storageUrl( $auth, $container ),
1435 'headers' => $this->authTokenHeaders( $auth ) +
[
1436 'x-container-read' => implode( ',', $readGrps ),
1437 'x-container-write' => implode( ',', $writeGrps )
1441 if ( $rcode === 201 ) { // new
1443 } elseif ( $rcode === 202 ) { // already there
1444 // this shouldn't really happen, but is OK
1446 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1453 * Delete a Swift container
1455 * @param string $container Container name
1456 * @param array $params
1457 * @return StatusValue
1459 protected function deleteContainer( $container, array $params ) {
1460 $status = $this->newStatus();
1462 $auth = $this->getAuthentication();
1464 $status->fatal( 'backend-fail-connect', $this->name
);
1469 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1470 'method' => 'DELETE',
1471 'url' => $this->storageUrl( $auth, $container ),
1472 'headers' => $this->authTokenHeaders( $auth )
1475 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1476 $this->containerStatCache
->clear( $container ); // purge
1477 } elseif ( $rcode === 404 ) { // not there
1478 // this shouldn't really happen, but is OK
1479 } elseif ( $rcode === 409 ) { // not empty
1480 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1482 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1489 * Get a list of objects under a container.
1490 * Either just the names or a list of stdClass objects with details can be returned.
1492 * @param string $fullCont
1493 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1495 * @param string|null $after
1496 * @param string|null $prefix
1497 * @param string|null $delim
1498 * @return StatusValue With the list as value
1500 private function objectListing(
1501 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1503 $status = $this->newStatus();
1505 $auth = $this->getAuthentication();
1507 $status->fatal( 'backend-fail-connect', $this->name
);
1512 $query = [ 'limit' => $limit ];
1513 if ( $type === 'info' ) {
1514 $query['format'] = 'json';
1516 if ( $after !== null ) {
1517 $query['marker'] = $after;
1519 if ( $prefix !== null ) {
1520 $query['prefix'] = $prefix;
1522 if ( $delim !== null ) {
1523 $query['delimiter'] = $delim;
1526 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1528 'url' => $this->storageUrl( $auth, $fullCont ),
1530 'headers' => $this->authTokenHeaders( $auth )
1533 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1534 if ( $rcode === 200 ) { // good
1535 if ( $type === 'info' ) {
1536 $status->value
= FormatJson
::decode( trim( $rbody ) );
1538 $status->value
= explode( "\n", trim( $rbody ) );
1540 } elseif ( $rcode === 204 ) {
1541 $status->value
= []; // empty container
1542 } elseif ( $rcode === 404 ) {
1543 $status->value
= []; // no container
1545 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1551 protected function doPrimeContainerCache( array $containerInfo ) {
1552 foreach ( $containerInfo as $container => $info ) {
1553 $this->containerStatCache
->set( $container, 'stat', $info );
1557 protected function doGetFileStatMulti( array $params ) {
1560 $auth = $this->getAuthentication();
1563 foreach ( $params['srcs'] as $path ) {
1564 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1565 if ( $srcRel === null ) {
1566 $stats[$path] = false;
1567 continue; // invalid storage path
1568 } elseif ( !$auth ) {
1569 $stats[$path] = null;
1573 // (a) Check the container
1574 $cstat = $this->getContainerStat( $srcCont );
1575 if ( $cstat === false ) {
1576 $stats[$path] = false;
1577 continue; // ok, nothing to do
1578 } elseif ( !is_array( $cstat ) ) {
1579 $stats[$path] = null;
1585 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1586 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1590 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1591 $reqs = $this->http
->runMulti( $reqs, $opts );
1593 foreach ( $params['srcs'] as $path ) {
1594 if ( array_key_exists( $path, $stats ) ) {
1595 continue; // some sort of failure above
1597 // (b) Check the file
1598 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1599 if ( $rcode === 200 ||
$rcode === 204 ) {
1600 // Update the object if it is missing some headers
1601 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1602 // Load the stat array from the headers
1603 $stat = $this->getStatFromHeaders( $rhdrs );
1604 if ( $this->isRGW
) {
1605 $stat['latest'] = true; // strong consistency
1607 } elseif ( $rcode === 404 ) {
1611 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1613 $stats[$path] = $stat;
1620 * @param array $rhdrs
1623 protected function getStatFromHeaders( array $rhdrs ) {
1624 // Fetch all of the custom metadata headers
1625 $metadata = $this->getMetadata( $rhdrs );
1626 // Fetch all of the custom raw HTTP headers
1627 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1630 // Convert various random Swift dates to TS_MW
1631 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1632 // Empty objects actually return no content-length header in Ceph
1633 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1634 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1635 // Note: manifiest ETags are not an MD5 of the file
1636 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1637 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1642 * @return array|null Credential map
1644 protected function getAuthentication() {
1645 if ( $this->authErrorTimestamp
!== null ) {
1646 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1647 return null; // failed last attempt; don't bother
1648 } else { // actually retry this time
1649 $this->authErrorTimestamp
= null;
1652 // Session keys expire after a while, so we renew them periodically
1653 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1654 // Authenticate with proxy and get a session key...
1655 if ( !$this->authCreds ||
$reAuth ) {
1656 $this->authSessionTimestamp
= 0;
1657 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1658 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1659 // Try to use the credential cache
1660 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1661 $this->authCreds
= $creds;
1662 // Skew the timestamp for worst case to avoid using stale credentials
1663 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1664 } else { // cache miss
1665 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1667 'url' => "{$this->swiftAuthUrl}/v1.0",
1669 'x-auth-user' => $this->swiftUser
,
1670 'x-auth-key' => $this->swiftKey
1674 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1675 $this->authCreds
= [
1676 'auth_token' => $rhdrs['x-auth-token'],
1677 'storage_url' => $rhdrs['x-storage-url']
1679 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1680 $this->authSessionTimestamp
= time();
1681 } elseif ( $rcode === 401 ) {
1682 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1683 $this->authErrorTimestamp
= time();
1687 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1688 $this->authErrorTimestamp
= time();
1693 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1694 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1695 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1699 return $this->authCreds
;
1703 * @param array $creds From getAuthentication()
1704 * @param string $container
1705 * @param string $object
1708 protected function storageUrl( array $creds, $container = null, $object = null ) {
1709 $parts = [ $creds['storage_url'] ];
1710 if ( strlen( $container ) ) {
1711 $parts[] = rawurlencode( $container );
1713 if ( strlen( $object ) ) {
1714 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1717 return implode( '/', $parts );
1721 * @param array $creds From getAuthentication()
1724 protected function authTokenHeaders( array $creds ) {
1725 return [ 'x-auth-token' => $creds['auth_token'] ];
1729 * Get the cache key for a container
1731 * @param string $username
1734 private function getCredsCacheKey( $username ) {
1735 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1739 * Log an unexpected exception for this backend.
1740 * This also sets the StatusValue object to have a fatal error.
1742 * @param StatusValue|null $status
1743 * @param string $func
1744 * @param array $params
1745 * @param string $err Error string
1746 * @param int $code HTTP status
1747 * @param string $desc HTTP StatusValue description
1749 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1750 if ( $status instanceof StatusValue
) {
1751 $status->fatal( 'backend-fail-internal', $this->name
);
1753 if ( $code == 401 ) { // possibly a stale token
1754 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1756 $this->logger
->error(
1757 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1758 ( $err ?
": $err" : "" )
1764 * @see FileBackendStoreOpHandle
1766 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1767 /** @var array List of Requests for MultiHttpClient */
1773 * @param SwiftFileBackend $backend
1774 * @param Closure $callback Function that takes (HTTP request array, status)
1775 * @param array $httpOp MultiHttpClient op
1777 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1778 $this->backend
= $backend;
1779 $this->callback
= $callback;
1780 $this->httpOp
= $httpOp;
1785 * SwiftFileBackend helper class to page through listings.
1786 * Swift also has a listing limit of 10,000 objects for sanity.
1787 * Do not use this class from places outside SwiftFileBackend.
1789 * @ingroup FileBackend
1791 abstract class SwiftFileBackendList
implements Iterator
{
1792 /** @var array List of path or (path,stat array) entries */
1793 protected $bufferIter = [];
1795 /** @var string List items *after* this path */
1796 protected $bufferAfter = null;
1802 protected $params = [];
1804 /** @var SwiftFileBackend */
1807 /** @var string Container name */
1808 protected $container;
1810 /** @var string Storage directory */
1814 protected $suffixStart;
1816 const PAGE_SIZE
= 9000; // file listing buffer size
1819 * @param SwiftFileBackend $backend
1820 * @param string $fullCont Resolved container name
1821 * @param string $dir Resolved directory relative to container
1822 * @param array $params
1824 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1825 $this->backend
= $backend;
1826 $this->container
= $fullCont;
1828 if ( substr( $this->dir
, -1 ) === '/' ) {
1829 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1831 if ( $this->dir
== '' ) { // whole container
1832 $this->suffixStart
= 0;
1833 } else { // dir within container
1834 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1836 $this->params
= $params;
1840 * @see Iterator::key()
1843 public function key() {
1848 * @see Iterator::next()
1850 public function next() {
1851 // Advance to the next file in the page
1852 next( $this->bufferIter
);
1854 // Check if there are no files left in this page and
1855 // advance to the next page if this page was not empty.
1856 if ( !$this->valid() && count( $this->bufferIter
) ) {
1857 $this->bufferIter
= $this->pageFromList(
1858 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1859 ); // updates $this->bufferAfter
1864 * @see Iterator::rewind()
1866 public function rewind() {
1868 $this->bufferAfter
= null;
1869 $this->bufferIter
= $this->pageFromList(
1870 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1871 ); // updates $this->bufferAfter
1875 * @see Iterator::valid()
1878 public function valid() {
1879 if ( $this->bufferIter
=== null ) {
1880 return false; // some failure?
1882 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1887 * Get the given list portion (page)
1889 * @param string $container Resolved container name
1890 * @param string $dir Resolved path relative to container
1891 * @param string $after
1893 * @param array $params
1894 * @return Traversable|array
1896 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1900 * Iterator for listing directories
1902 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1904 * @see Iterator::current()
1905 * @return string|bool String (relative path) or false
1907 public function current() {
1908 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1911 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1912 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1917 * Iterator for listing regular files
1919 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1921 * @see Iterator::current()
1922 * @return string|bool String (relative path) or false
1924 public function current() {
1925 list( $path, $stat ) = current( $this->bufferIter
);
1926 $relPath = substr( $path, $this->suffixStart
);
1927 if ( is_array( $stat ) ) {
1928 $storageDir = rtrim( $this->params
['dir'], '/' );
1929 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1935 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1936 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );