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 * Status 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( array() );
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'] ) ) {
138 if ( PHP_SAPI
=== 'cli' ) {
139 $this->srvCache
= wfGetMainCache(); // preferrably memcached
141 try { // look for APC, XCache, WinCache, ect...
142 $this->srvCache
= ObjectCache
::newAccelerator( array() );
143 } catch ( Exception
$e ) {
147 $this->srvCache
= $this->srvCache ?
: new EmptyBagOStuff();
150 public function getFeatures() {
151 return ( FileBackend
::ATTR_UNICODE_PATHS |
152 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
155 protected function resolveContainerPath( $container, $relStoragePath ) {
156 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
157 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
158 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
159 return null; // too long for Swift
162 return $relStoragePath;
165 public function isPathUsableInternal( $storagePath ) {
166 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
167 if ( $rel === null ) {
168 return false; // invalid
171 return is_array( $this->getContainerStat( $container ) );
175 * Sanitize and filter the custom headers from a $params array.
176 * We only allow certain Content- and X-Content- headers.
178 * @param array $params
179 * @return array Sanitized value of 'headers' field in $params
181 protected function sanitizeHdrs( array $params ) {
184 // Normalize casing, and strip out illegal headers
185 if ( isset( $params['headers'] ) ) {
186 foreach ( $params['headers'] as $name => $value ) {
187 $name = strtolower( $name );
188 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
189 continue; // blacklisted
190 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
191 $headers[$name] = $value; // allowed
192 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
193 $headers[$name] = $value; // allowed
197 // By default, Swift has annoyingly low maximum header value limits
198 if ( isset( $headers['content-disposition'] ) ) {
200 // @note: assume FileBackend::makeContentDisposition() already used
201 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
202 $part = trim( $part );
203 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
204 if ( strlen( $new ) <= 255 ) {
207 break; // too long; sigh
210 $headers['content-disposition'] = $disposition;
216 protected function doCreateInternal( array $params ) {
217 $status = Status
::newGood();
219 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
220 if ( $dstRel === null ) {
221 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
226 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
227 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
229 $reqs = array( array(
231 'url' => array( $dstCont, $dstRel ),
233 'content-length' => strlen( $params['content'] ),
234 'etag' => md5( $params['content'] ),
235 'content-type' => $contentType,
236 'x-object-meta-sha1base36' => $sha1Hash
237 ) +
$this->sanitizeHdrs( $params ),
238 'body' => $params['content']
242 $method = __METHOD__
;
243 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
244 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
245 if ( $rcode === 201 ) {
247 } elseif ( $rcode === 412 ) {
248 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
250 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
254 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
255 if ( !empty( $params['async'] ) ) { // deferred
256 $status->value
= $opHandle;
257 } else { // actually write the object in Swift
258 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
264 protected function doStoreInternal( array $params ) {
265 $status = Status
::newGood();
267 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
268 if ( $dstRel === null ) {
269 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
274 MediaWiki\
suppressWarnings();
275 $sha1Hash = sha1_file( $params['src'] );
276 MediaWiki\restoreWarnings
();
277 if ( $sha1Hash === false ) { // source doesn't exist?
278 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
282 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
283 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
285 $handle = fopen( $params['src'], 'rb' );
286 if ( $handle === false ) { // source doesn't exist?
287 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
292 $reqs = array( array(
294 'url' => array( $dstCont, $dstRel ),
296 'content-length' => filesize( $params['src'] ),
297 'etag' => md5_file( $params['src'] ),
298 'content-type' => $contentType,
299 'x-object-meta-sha1base36' => $sha1Hash
300 ) +
$this->sanitizeHdrs( $params ),
301 'body' => $handle // resource
305 $method = __METHOD__
;
306 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
307 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
308 if ( $rcode === 201 ) {
310 } elseif ( $rcode === 412 ) {
311 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
313 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
317 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
318 if ( !empty( $params['async'] ) ) { // deferred
319 $status->value
= $opHandle;
320 } else { // actually write the object in Swift
321 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
327 protected function doCopyInternal( array $params ) {
328 $status = Status
::newGood();
330 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
331 if ( $srcRel === null ) {
332 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
337 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
338 if ( $dstRel === null ) {
339 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
344 $reqs = array( array(
346 'url' => array( $dstCont, $dstRel ),
348 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
349 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
350 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
354 $method = __METHOD__
;
355 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
356 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
357 if ( $rcode === 201 ) {
359 } elseif ( $rcode === 404 ) {
360 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
362 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
366 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
367 if ( !empty( $params['async'] ) ) { // deferred
368 $status->value
= $opHandle;
369 } else { // actually write the object in Swift
370 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
376 protected function doMoveInternal( array $params ) {
377 $status = Status
::newGood();
379 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
380 if ( $srcRel === null ) {
381 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
386 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
387 if ( $dstRel === null ) {
388 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
396 'url' => array( $dstCont, $dstRel ),
398 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
399 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
400 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
403 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
405 'method' => 'DELETE',
406 'url' => array( $srcCont, $srcRel ),
412 $method = __METHOD__
;
413 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
414 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
415 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
417 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
419 } elseif ( $rcode === 404 ) {
420 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
422 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
426 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
427 if ( !empty( $params['async'] ) ) { // deferred
428 $status->value
= $opHandle;
429 } else { // actually move the object in Swift
430 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
436 protected function doDeleteInternal( array $params ) {
437 $status = Status
::newGood();
439 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
440 if ( $srcRel === null ) {
441 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
446 $reqs = array( array(
447 'method' => 'DELETE',
448 'url' => array( $srcCont, $srcRel ),
453 $method = __METHOD__
;
454 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
455 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
456 if ( $rcode === 204 ) {
458 } elseif ( $rcode === 404 ) {
459 if ( empty( $params['ignoreMissingSource'] ) ) {
460 $status->fatal( 'backend-fail-delete', $params['src'] );
463 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
467 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
468 if ( !empty( $params['async'] ) ) { // deferred
469 $status->value
= $opHandle;
470 } else { // actually delete the object in Swift
471 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
477 protected function doDescribeInternal( array $params ) {
478 $status = Status
::newGood();
480 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
481 if ( $srcRel === null ) {
482 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
487 // Fetch the old object headers/metadata...this should be in stat cache by now
488 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
489 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
490 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
493 $status->fatal( 'backend-fail-describe', $params['src'] );
498 // POST clears prior headers, so we need to merge the changes in to the old ones
500 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
501 $metaHdrs["x-object-meta-$name"] = $value;
503 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
505 $reqs = array( array(
507 'url' => array( $srcCont, $srcRel ),
508 'headers' => $metaHdrs +
$customHdrs
512 $method = __METHOD__
;
513 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
514 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
515 if ( $rcode === 202 ) {
517 } elseif ( $rcode === 404 ) {
518 $status->fatal( 'backend-fail-describe', $params['src'] );
520 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
524 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
525 if ( !empty( $params['async'] ) ) { // deferred
526 $status->value
= $opHandle;
527 } else { // actually change the object in Swift
528 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
534 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
535 $status = Status
::newGood();
537 // (a) Check if container already exists
538 $stat = $this->getContainerStat( $fullCont );
539 if ( is_array( $stat ) ) {
540 return $status; // already there
541 } elseif ( $stat === null ) {
542 $status->fatal( 'backend-fail-internal', $this->name
);
543 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
548 // (b) Create container as needed with proper ACLs
549 if ( $stat === false ) {
550 $params['op'] = 'prepare';
551 $status->merge( $this->createContainer( $fullCont, $params ) );
557 protected function doSecureInternal( $fullCont, $dir, array $params ) {
558 $status = Status
::newGood();
559 if ( empty( $params['noAccess'] ) ) {
560 return $status; // nothing to do
563 $stat = $this->getContainerStat( $fullCont );
564 if ( is_array( $stat ) ) {
565 // Make container private to end-users...
566 $status->merge( $this->setContainerAccess(
568 array( $this->swiftUser
), // read
569 array( $this->swiftUser
) // write
571 } elseif ( $stat === false ) {
572 $status->fatal( 'backend-fail-usable', $params['dir'] );
574 $status->fatal( 'backend-fail-internal', $this->name
);
575 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
581 protected function doPublishInternal( $fullCont, $dir, array $params ) {
582 $status = Status
::newGood();
584 $stat = $this->getContainerStat( $fullCont );
585 if ( is_array( $stat ) ) {
586 // Make container public to end-users...
587 $status->merge( $this->setContainerAccess(
589 array( $this->swiftUser
, '.r:*' ), // read
590 array( $this->swiftUser
) // write
592 } elseif ( $stat === false ) {
593 $status->fatal( 'backend-fail-usable', $params['dir'] );
595 $status->fatal( 'backend-fail-internal', $this->name
);
596 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
602 protected function doCleanInternal( $fullCont, $dir, array $params ) {
603 $status = Status
::newGood();
605 // Only containers themselves can be removed, all else is virtual
607 return $status; // nothing to do
610 // (a) Check the container
611 $stat = $this->getContainerStat( $fullCont, true );
612 if ( $stat === false ) {
613 return $status; // ok, nothing to do
614 } elseif ( !is_array( $stat ) ) {
615 $status->fatal( 'backend-fail-internal', $this->name
);
616 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
621 // (b) Delete the container if empty
622 if ( $stat['count'] == 0 ) {
623 $params['op'] = 'clean';
624 $status->merge( $this->deleteContainer( $fullCont, $params ) );
630 protected function doGetFileStat( array $params ) {
631 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) +
$params;
632 unset( $params['src'] );
633 $stats = $this->doGetFileStatMulti( $params );
635 return reset( $stats );
639 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
640 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
641 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
644 * @param int $format Output format (TS_* constant)
646 * @throws FileBackendError
648 protected function convertSwiftDate( $ts, $format = TS_MW
) {
650 $timestamp = new MWTimestamp( $ts );
652 return $timestamp->getTimestamp( $format );
653 } catch ( Exception
$e ) {
654 throw new FileBackendError( $e->getMessage() );
659 * Fill in any missing object metadata and save it to Swift
661 * @param array $objHdrs Object response headers
662 * @param string $path Storage path to object
663 * @return array New headers
665 protected function addMissingMetadata( array $objHdrs, $path ) {
666 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
667 return $objHdrs; // nothing to do
670 /** @noinspection PhpUnusedLocalVariableInspection */
671 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
672 wfDebugLog( 'SwiftBackend', __METHOD__
. ": $path was not stored with SHA-1 metadata." );
674 $objHdrs['x-object-meta-sha1base36'] = false;
676 $auth = $this->getAuthentication();
678 return $objHdrs; // failed
681 $status = Status
::newGood();
682 /** @noinspection PhpUnusedLocalVariableInspection */
683 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
684 if ( $status->isOK() ) {
685 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
687 $hash = $tmpFile->getSha1Base36();
688 if ( $hash !== false ) {
689 $objHdrs['x-object-meta-sha1base36'] = $hash;
690 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
691 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
693 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
694 'headers' => $this->authTokenHeaders( $auth ) +
$objHdrs
696 if ( $rcode >= 200 && $rcode <= 299 ) {
697 $this->deleteFileCache( $path );
699 return $objHdrs; // success
705 wfDebugLog( 'SwiftBackend', __METHOD__
. ": unable to set SHA-1 metadata for $path" );
707 return $objHdrs; // failed
710 protected function doGetFileContentsMulti( array $params ) {
713 $auth = $this->getAuthentication();
715 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
716 // Blindly create tmp files and stream to them, catching any exception if the file does
717 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
718 $reqs = array(); // (path => op)
720 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
721 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
722 if ( $srcRel === null ||
!$auth ) {
723 $contents[$path] = false;
726 // Create a new temporary memory file...
727 $handle = fopen( 'php://temp', 'wb' );
729 $reqs[$path] = array(
731 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
732 'headers' => $this->authTokenHeaders( $auth )
733 +
$this->headersFromParams( $params ),
737 $contents[$path] = false;
740 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
741 $reqs = $this->http
->runMulti( $reqs, $opts );
742 foreach ( $reqs as $path => $op ) {
743 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
744 if ( $rcode >= 200 && $rcode <= 299 ) {
745 rewind( $op['stream'] ); // start from the beginning
746 $contents[$path] = stream_get_contents( $op['stream'] );
747 } elseif ( $rcode === 404 ) {
748 $contents[$path] = false;
750 $this->onError( null, __METHOD__
,
751 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
753 fclose( $op['stream'] ); // close open handle
759 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
760 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
761 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
762 if ( $status->isOk() ) {
763 return ( count( $status->value
) ) > 0;
766 return null; // error
770 * @see FileBackendStore::getDirectoryListInternal()
771 * @param string $fullCont
773 * @param array $params
774 * @return SwiftFileBackendDirList
776 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
777 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
781 * @see FileBackendStore::getFileListInternal()
782 * @param string $fullCont
784 * @param array $params
785 * @return SwiftFileBackendFileList
787 public function getFileListInternal( $fullCont, $dir, array $params ) {
788 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
792 * Do not call this function outside of SwiftFileBackendFileList
794 * @param string $fullCont Resolved container name
795 * @param string $dir Resolved storage directory with no trailing slash
796 * @param string|null $after Resolved container relative path to list items after
797 * @param int $limit Max number of items to list
798 * @param array $params Parameters for getDirectoryList()
799 * @return array List of container relative resolved paths of directories directly under $dir
800 * @throws FileBackendError
802 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
804 if ( $after === INF
) {
805 return $dirs; // nothing more
808 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
810 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
811 // Non-recursive: only list dirs right under $dir
812 if ( !empty( $params['topOnly'] ) ) {
813 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
814 if ( !$status->isOk() ) {
815 return $dirs; // error
817 $objects = $status->value
;
818 foreach ( $objects as $object ) { // files and directories
819 if ( substr( $object, -1 ) === '/' ) {
820 $dirs[] = $object; // directories end in '/'
824 // Recursive: list all dirs under $dir and its subdirs
825 $getParentDir = function ( $path ) {
826 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
829 // Get directory from last item of prior page
830 $lastDir = $getParentDir( $after ); // must be first page
831 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
833 if ( !$status->isOk() ) {
834 return $dirs; // error
837 $objects = $status->value
;
839 foreach ( $objects as $object ) { // files
840 $objectDir = $getParentDir( $object ); // directory of object
842 if ( $objectDir !== false && $objectDir !== $dir ) {
843 // Swift stores paths in UTF-8, using binary sorting.
844 // See function "create_container_table" in common/db.py.
845 // If a directory is not "greater" than the last one,
846 // then it was already listed by the calling iterator.
847 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
849 do { // add dir and all its parent dirs
850 $dirs[] = "{$pDir}/";
851 $pDir = $getParentDir( $pDir );
852 } while ( $pDir !== false // sanity
853 && strcmp( $pDir, $lastDir ) > 0 // not done already
854 && strlen( $pDir ) > strlen( $dir ) // within $dir
857 $lastDir = $objectDir;
861 // Page on the unfiltered directory listing (what is returned may be filtered)
862 if ( count( $objects ) < $limit ) {
863 $after = INF
; // avoid a second RTT
865 $after = end( $objects ); // update last item
872 * Do not call this function outside of SwiftFileBackendFileList
874 * @param string $fullCont Resolved container name
875 * @param string $dir Resolved storage directory with no trailing slash
876 * @param string|null $after Resolved container relative path of file to list items after
877 * @param int $limit Max number of items to list
878 * @param array $params Parameters for getDirectoryList()
879 * @return array List of resolved container relative paths of files under $dir
880 * @throws FileBackendError
882 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
883 $files = array(); // list of (path, stat array or null) entries
884 if ( $after === INF
) {
885 return $files; // nothing more
888 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
890 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
891 // $objects will contain a list of unfiltered names or CF_Object items
892 // Non-recursive: only list files right under $dir
893 if ( !empty( $params['topOnly'] ) ) {
894 if ( !empty( $params['adviseStat'] ) ) {
895 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
897 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
900 // Recursive: list all files under $dir and its subdirs
901 if ( !empty( $params['adviseStat'] ) ) {
902 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
904 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
908 // Reformat this list into a list of (name, stat array or null) entries
909 if ( !$status->isOk() ) {
910 return $files; // error
913 $objects = $status->value
;
914 $files = $this->buildFileObjectListing( $params, $dir, $objects );
916 // Page on the unfiltered object listing (what is returned may be filtered)
917 if ( count( $objects ) < $limit ) {
918 $after = INF
; // avoid a second RTT
920 $after = end( $objects ); // update last item
921 $after = is_object( $after ) ?
$after->name
: $after;
928 * Build a list of file objects, filtering out any directories
929 * and extracting any stat info if provided in $objects (for CF_Objects)
931 * @param array $params Parameters for getDirectoryList()
932 * @param string $dir Resolved container directory path
933 * @param array $objects List of CF_Object items or object names
934 * @return array List of (names,stat array or null) entries
936 private function buildFileObjectListing( array $params, $dir, array $objects ) {
938 foreach ( $objects as $object ) {
939 if ( is_object( $object ) ) {
940 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
941 continue; // virtual directory entry; ignore
944 // Convert various random Swift dates to TS_MW
945 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
946 'size' => (int)$object->bytes
,
948 // Note: manifiest ETags are not an MD5 of the file
949 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
950 'latest' => false // eventually consistent
952 $names[] = array( $object->name
, $stat );
953 } elseif ( substr( $object, -1 ) !== '/' ) {
954 // Omit directories, which end in '/' in listings
955 $names[] = array( $object, null );
963 * Do not call this function outside of SwiftFileBackendFileList
965 * @param string $path Storage path
966 * @param array $val Stat value
968 public function loadListingStatInternal( $path, array $val ) {
969 $this->cheapCache
->set( $path, 'stat', $val );
972 protected function doGetFileXAttributes( array $params ) {
973 $stat = $this->getFileStat( $params );
975 if ( !isset( $stat['xattr'] ) ) {
976 // Stat entries filled by file listings don't include metadata/headers
977 $this->clearCache( array( $params['src'] ) );
978 $stat = $this->getFileStat( $params );
981 return $stat['xattr'];
987 protected function doGetFileSha1base36( array $params ) {
988 $stat = $this->getFileStat( $params );
990 if ( !isset( $stat['sha1'] ) ) {
991 // Stat entries filled by file listings don't include SHA1
992 $this->clearCache( array( $params['src'] ) );
993 $stat = $this->getFileStat( $params );
996 return $stat['sha1'];
1002 protected function doStreamFile( array $params ) {
1003 $status = Status
::newGood();
1005 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1006 if ( $srcRel === null ) {
1007 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1010 $auth = $this->getAuthentication();
1011 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1012 $status->fatal( 'backend-fail-stream', $params['src'] );
1017 $handle = fopen( 'php://output', 'wb' );
1019 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1021 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1022 'headers' => $this->authTokenHeaders( $auth )
1023 +
$this->headersFromParams( $params ),
1024 'stream' => $handle,
1027 if ( $rcode >= 200 && $rcode <= 299 ) {
1029 } elseif ( $rcode === 404 ) {
1030 $status->fatal( 'backend-fail-stream', $params['src'] );
1032 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1038 protected function doGetLocalCopyMulti( array $params ) {
1039 $tmpFiles = array();
1041 $auth = $this->getAuthentication();
1043 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1044 // Blindly create tmp files and stream to them, catching any exception if the file does
1045 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1046 $reqs = array(); // (path => op)
1048 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1049 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1050 if ( $srcRel === null ||
!$auth ) {
1051 $tmpFiles[$path] = null;
1054 // Get source file extension
1055 $ext = FileBackend
::extensionFromPath( $path );
1056 // Create a new temporary file...
1057 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1059 $handle = fopen( $tmpFile->getPath(), 'wb' );
1061 $reqs[$path] = array(
1063 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1064 'headers' => $this->authTokenHeaders( $auth )
1065 +
$this->headersFromParams( $params ),
1066 'stream' => $handle,
1072 $tmpFiles[$path] = $tmpFile;
1075 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1076 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1077 $reqs = $this->http
->runMulti( $reqs, $opts );
1078 foreach ( $reqs as $path => $op ) {
1079 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1080 fclose( $op['stream'] ); // close open handle
1081 if ( $rcode >= 200 && $rcode <= 299 ) {
1082 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1083 // Double check that the disk is not full/broken
1084 if ( $size != $rhdrs['content-length'] ) {
1085 $tmpFiles[$path] = null;
1086 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1087 $this->onError( null, __METHOD__
,
1088 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1090 // Set the file stat process cache in passing
1091 $stat = $this->getStatFromHeaders( $rhdrs );
1092 $stat['latest'] = $isLatest;
1093 $this->cheapCache
->set( $path, 'stat', $stat );
1094 } elseif ( $rcode === 404 ) {
1095 $tmpFiles[$path] = false;
1097 $tmpFiles[$path] = null;
1098 $this->onError( null, __METHOD__
,
1099 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1106 public function getFileHttpUrl( array $params ) {
1107 if ( $this->swiftTempUrlKey
!= '' ||
1108 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1110 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1111 if ( $srcRel === null ) {
1112 return null; // invalid path
1115 $auth = $this->getAuthentication();
1120 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1121 $expires = time() +
$ttl;
1123 if ( $this->swiftTempUrlKey
!= '' ) {
1124 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1125 // Swift wants the signature based on the unencoded object name
1126 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1127 $signature = hash_hmac( 'sha1',
1128 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1129 $this->swiftTempUrlKey
1132 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1133 } else { // give S3 API URL for rgw
1134 // Path for signature starts with the bucket
1135 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1136 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1137 // Calculate the hash
1138 $signature = base64_encode( hash_hmac(
1140 "GET\n\n\n{$expires}\n{$spath}",
1141 $this->rgwS3SecretKey
,
1144 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1145 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1146 return wfAppendQuery(
1147 str_replace( '/swift/v1', '', // S3 API is the rgw default
1148 $this->storageUrl( $auth ) . $spath ),
1150 'Signature' => $signature,
1151 'Expires' => $expires,
1152 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1160 protected function directoriesAreVirtual() {
1165 * Get headers to send to Swift when reading a file based
1166 * on a FileBackend params array, e.g. that of getLocalCopy().
1167 * $params is currently only checked for a 'latest' flag.
1169 * @param array $params
1172 protected function headersFromParams( array $params ) {
1174 if ( !empty( $params['latest'] ) ) {
1175 $hdrs['x-newest'] = 'true';
1182 * @param FileBackendStoreOpHandle[] $fileOpHandles
1186 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1187 $statuses = array();
1189 $auth = $this->getAuthentication();
1191 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1192 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1198 // Split the HTTP requests into stages that can be done concurrently
1199 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1200 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1201 $reqs = $fileOpHandle->httpOp
;
1202 // Convert the 'url' parameter to an actual URL using $auth
1203 foreach ( $reqs as $stage => &$req ) {
1204 list( $container, $relPath ) = $req['url'];
1205 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1206 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1207 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1208 $httpReqsByStage[$stage][$index] = $req;
1210 $statuses[$index] = Status
::newGood();
1213 // Run all requests for the first stage, then the next, and so on
1214 $reqCount = count( $httpReqsByStage );
1215 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1216 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1217 foreach ( $httpReqs as $index => $httpReq ) {
1218 // Run the callback for each request of this operation
1219 $callback = $fileOpHandles[$index]->callback
;
1220 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1221 // On failure, abort all remaining requests for this operation
1222 // (e.g. abort the DELETE request if the COPY request fails for a move)
1223 if ( !$statuses[$index]->isOK() ) {
1224 $stages = count( $fileOpHandles[$index]->httpOp
);
1225 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1226 unset( $httpReqsByStage[$s][$index] );
1236 * Set read/write permissions for a Swift container.
1238 * @see http://swift.openstack.org/misc.html#acls
1240 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1241 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1243 * @param string $container Resolved Swift container
1244 * @param array $readGrps List of the possible criteria for a request to have
1245 * access to read a container. Each item is one of the following formats:
1246 * - account:user : Grants access if the request is by the given user
1247 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1248 * matches the expression and the request is not for a listing.
1249 * Setting this to '*' effectively makes a container public.
1250 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1251 * matches the expression and the request is for a listing.
1252 * @param array $writeGrps A list of the possible criteria for a request to have
1253 * access to write to a container. Each item is of the following format:
1254 * - account:user : Grants access if the request is by the given user
1257 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1258 $status = Status
::newGood();
1259 $auth = $this->getAuthentication();
1262 $status->fatal( 'backend-fail-connect', $this->name
);
1267 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1269 'url' => $this->storageUrl( $auth, $container ),
1270 'headers' => $this->authTokenHeaders( $auth ) +
array(
1271 'x-container-read' => implode( ',', $readGrps ),
1272 'x-container-write' => implode( ',', $writeGrps )
1276 if ( $rcode != 204 && $rcode !== 202 ) {
1277 $status->fatal( 'backend-fail-internal', $this->name
);
1278 wfDebugLog( 'SwiftBackend', __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1285 * Get a Swift container stat array, possibly from process cache.
1286 * Use $reCache if the file count or byte count is needed.
1288 * @param string $container Container name
1289 * @param bool $bypassCache Bypass all caches and load from Swift
1290 * @return array|bool|null False on 404, null on failure
1292 protected function getContainerStat( $container, $bypassCache = false ) {
1293 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1295 if ( $bypassCache ) { // purge cache
1296 $this->containerStatCache
->clear( $container );
1297 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1298 $this->primeContainerCache( array( $container ) ); // check persistent cache
1300 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1301 $auth = $this->getAuthentication();
1306 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1308 'url' => $this->storageUrl( $auth, $container ),
1309 'headers' => $this->authTokenHeaders( $auth )
1312 if ( $rcode === 204 ) {
1314 'count' => $rhdrs['x-container-object-count'],
1315 'bytes' => $rhdrs['x-container-bytes-used']
1317 if ( $bypassCache ) {
1320 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1321 $this->setContainerCache( $container, $stat ); // update persistent cache
1323 } elseif ( $rcode === 404 ) {
1326 $this->onError( null, __METHOD__
,
1327 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1333 return $this->containerStatCache
->get( $container, 'stat' );
1337 * Create a Swift container
1339 * @param string $container Container name
1340 * @param array $params
1343 protected function createContainer( $container, array $params ) {
1344 $status = Status
::newGood();
1346 $auth = $this->getAuthentication();
1348 $status->fatal( 'backend-fail-connect', $this->name
);
1353 // @see SwiftFileBackend::setContainerAccess()
1354 if ( empty( $params['noAccess'] ) ) {
1355 $readGrps = array( '.r:*', $this->swiftUser
); // public
1357 $readGrps = array( $this->swiftUser
); // private
1359 $writeGrps = array( $this->swiftUser
); // sanity
1361 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1363 'url' => $this->storageUrl( $auth, $container ),
1364 'headers' => $this->authTokenHeaders( $auth ) +
array(
1365 'x-container-read' => implode( ',', $readGrps ),
1366 'x-container-write' => implode( ',', $writeGrps )
1370 if ( $rcode === 201 ) { // new
1372 } elseif ( $rcode === 202 ) { // already there
1373 // this shouldn't really happen, but is OK
1375 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1382 * Delete a Swift container
1384 * @param string $container Container name
1385 * @param array $params
1388 protected function deleteContainer( $container, array $params ) {
1389 $status = Status
::newGood();
1391 $auth = $this->getAuthentication();
1393 $status->fatal( 'backend-fail-connect', $this->name
);
1398 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1399 'method' => 'DELETE',
1400 'url' => $this->storageUrl( $auth, $container ),
1401 'headers' => $this->authTokenHeaders( $auth )
1404 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1405 $this->containerStatCache
->clear( $container ); // purge
1406 } elseif ( $rcode === 404 ) { // not there
1407 // this shouldn't really happen, but is OK
1408 } elseif ( $rcode === 409 ) { // not empty
1409 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1411 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1418 * Get a list of objects under a container.
1419 * Either just the names or a list of stdClass objects with details can be returned.
1421 * @param string $fullCont
1422 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1424 * @param string|null $after
1425 * @param string|null $prefix
1426 * @param string|null $delim
1427 * @return Status With the list as value
1429 private function objectListing(
1430 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1432 $status = Status
::newGood();
1434 $auth = $this->getAuthentication();
1436 $status->fatal( 'backend-fail-connect', $this->name
);
1441 $query = array( 'limit' => $limit );
1442 if ( $type === 'info' ) {
1443 $query['format'] = 'json';
1445 if ( $after !== null ) {
1446 $query['marker'] = $after;
1448 if ( $prefix !== null ) {
1449 $query['prefix'] = $prefix;
1451 if ( $delim !== null ) {
1452 $query['delimiter'] = $delim;
1455 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1457 'url' => $this->storageUrl( $auth, $fullCont ),
1459 'headers' => $this->authTokenHeaders( $auth )
1462 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1463 if ( $rcode === 200 ) { // good
1464 if ( $type === 'info' ) {
1465 $status->value
= FormatJson
::decode( trim( $rbody ) );
1467 $status->value
= explode( "\n", trim( $rbody ) );
1469 } elseif ( $rcode === 204 ) {
1470 $status->value
= array(); // empty container
1471 } elseif ( $rcode === 404 ) {
1472 $status->value
= array(); // no container
1474 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1480 protected function doPrimeContainerCache( array $containerInfo ) {
1481 foreach ( $containerInfo as $container => $info ) {
1482 $this->containerStatCache
->set( $container, 'stat', $info );
1486 protected function doGetFileStatMulti( array $params ) {
1489 $auth = $this->getAuthentication();
1492 foreach ( $params['srcs'] as $path ) {
1493 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1494 if ( $srcRel === null ) {
1495 $stats[$path] = false;
1496 continue; // invalid storage path
1497 } elseif ( !$auth ) {
1498 $stats[$path] = null;
1502 // (a) Check the container
1503 $cstat = $this->getContainerStat( $srcCont );
1504 if ( $cstat === false ) {
1505 $stats[$path] = false;
1506 continue; // ok, nothing to do
1507 } elseif ( !is_array( $cstat ) ) {
1508 $stats[$path] = null;
1512 $reqs[$path] = array(
1514 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1515 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1519 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1520 $reqs = $this->http
->runMulti( $reqs, $opts );
1522 foreach ( $params['srcs'] as $path ) {
1523 if ( array_key_exists( $path, $stats ) ) {
1524 continue; // some sort of failure above
1526 // (b) Check the file
1527 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1528 if ( $rcode === 200 ||
$rcode === 204 ) {
1529 // Update the object if it is missing some headers
1530 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1531 // Load the stat array from the headers
1532 $stat = $this->getStatFromHeaders( $rhdrs );
1533 if ( $this->isRGW
) {
1534 $stat['latest'] = true; // strong consistency
1536 } elseif ( $rcode === 404 ) {
1540 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1542 $stats[$path] = $stat;
1549 * @param array $rhdrs
1552 protected function getStatFromHeaders( array $rhdrs ) {
1553 // Fetch all of the custom metadata headers
1554 $metadata = array();
1555 foreach ( $rhdrs as $name => $value ) {
1556 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
1557 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
1560 // Fetch all of the custom raw HTTP headers
1561 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1563 // Convert various random Swift dates to TS_MW
1564 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1565 // Empty objects actually return no content-length header in Ceph
1566 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1567 'sha1' => isset( $rhdrs['x-object-meta-sha1base36'] )
1568 ?
$rhdrs['x-object-meta-sha1base36']
1570 // Note: manifiest ETags are not an MD5 of the file
1571 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1572 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1577 * @return array|null Credential map
1579 protected function getAuthentication() {
1580 if ( $this->authErrorTimestamp
!== null ) {
1581 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1582 return null; // failed last attempt; don't bother
1583 } else { // actually retry this time
1584 $this->authErrorTimestamp
= null;
1587 // Session keys expire after a while, so we renew them periodically
1588 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1589 // Authenticate with proxy and get a session key...
1590 if ( !$this->authCreds ||
$reAuth ) {
1591 $this->authSessionTimestamp
= 0;
1592 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1593 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1594 // Try to use the credential cache
1595 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1596 $this->authCreds
= $creds;
1597 // Skew the timestamp for worst case to avoid using stale credentials
1598 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1599 } else { // cache miss
1600 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1602 'url' => "{$this->swiftAuthUrl}/v1.0",
1604 'x-auth-user' => $this->swiftUser
,
1605 'x-auth-key' => $this->swiftKey
1609 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1610 $this->authCreds
= array(
1611 'auth_token' => $rhdrs['x-auth-token'],
1612 'storage_url' => $rhdrs['x-storage-url']
1614 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1615 $this->authSessionTimestamp
= time();
1616 } elseif ( $rcode === 401 ) {
1617 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1618 $this->authErrorTimestamp
= time();
1622 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1623 $this->authErrorTimestamp
= time();
1628 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1629 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1630 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1634 return $this->authCreds
;
1638 * @param array $creds From getAuthentication()
1639 * @param string $container
1640 * @param string $object
1643 protected function storageUrl( array $creds, $container = null, $object = null ) {
1644 $parts = array( $creds['storage_url'] );
1645 if ( strlen( $container ) ) {
1646 $parts[] = rawurlencode( $container );
1648 if ( strlen( $object ) ) {
1649 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1652 return implode( '/', $parts );
1656 * @param array $creds From getAuthentication()
1659 protected function authTokenHeaders( array $creds ) {
1660 return array( 'x-auth-token' => $creds['auth_token'] );
1664 * Get the cache key for a container
1666 * @param string $username
1669 private function getCredsCacheKey( $username ) {
1670 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1674 * Log an unexpected exception for this backend.
1675 * This also sets the Status object to have a fatal error.
1677 * @param Status|null $status
1678 * @param string $func
1679 * @param array $params
1680 * @param string $err Error string
1681 * @param int $code HTTP status
1682 * @param string $desc HTTP status description
1684 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1685 if ( $status instanceof Status
) {
1686 $status->fatal( 'backend-fail-internal', $this->name
);
1688 if ( $code == 401 ) { // possibly a stale token
1689 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1691 wfDebugLog( 'SwiftBackend',
1692 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1693 ( $err ?
": $err" : "" )
1699 * @see FileBackendStoreOpHandle
1701 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1702 /** @var array List of Requests for MultiHttpClient */
1708 * @param SwiftFileBackend $backend
1709 * @param Closure $callback Function that takes (HTTP request array, status)
1710 * @param array $httpOp MultiHttpClient op
1712 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1713 $this->backend
= $backend;
1714 $this->callback
= $callback;
1715 $this->httpOp
= $httpOp;
1720 * SwiftFileBackend helper class to page through listings.
1721 * Swift also has a listing limit of 10,000 objects for sanity.
1722 * Do not use this class from places outside SwiftFileBackend.
1724 * @ingroup FileBackend
1726 abstract class SwiftFileBackendList
implements Iterator
{
1727 /** @var array List of path or (path,stat array) entries */
1728 protected $bufferIter = array();
1730 /** @var string List items *after* this path */
1731 protected $bufferAfter = null;
1737 protected $params = array();
1739 /** @var SwiftFileBackend */
1742 /** @var string Container name */
1743 protected $container;
1745 /** @var string Storage directory */
1749 protected $suffixStart;
1751 const PAGE_SIZE
= 9000; // file listing buffer size
1754 * @param SwiftFileBackend $backend
1755 * @param string $fullCont Resolved container name
1756 * @param string $dir Resolved directory relative to container
1757 * @param array $params
1759 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1760 $this->backend
= $backend;
1761 $this->container
= $fullCont;
1763 if ( substr( $this->dir
, -1 ) === '/' ) {
1764 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1766 if ( $this->dir
== '' ) { // whole container
1767 $this->suffixStart
= 0;
1768 } else { // dir within container
1769 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1771 $this->params
= $params;
1775 * @see Iterator::key()
1778 public function key() {
1783 * @see Iterator::next()
1785 public function next() {
1786 // Advance to the next file in the page
1787 next( $this->bufferIter
);
1789 // Check if there are no files left in this page and
1790 // advance to the next page if this page was not empty.
1791 if ( !$this->valid() && count( $this->bufferIter
) ) {
1792 $this->bufferIter
= $this->pageFromList(
1793 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1794 ); // updates $this->bufferAfter
1799 * @see Iterator::rewind()
1801 public function rewind() {
1803 $this->bufferAfter
= null;
1804 $this->bufferIter
= $this->pageFromList(
1805 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1806 ); // updates $this->bufferAfter
1810 * @see Iterator::valid()
1813 public function valid() {
1814 if ( $this->bufferIter
=== null ) {
1815 return false; // some failure?
1817 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1822 * Get the given list portion (page)
1824 * @param string $container Resolved container name
1825 * @param string $dir Resolved path relative to container
1826 * @param string $after
1828 * @param array $params
1829 * @return Traversable|array
1831 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1835 * Iterator for listing directories
1837 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1839 * @see Iterator::current()
1840 * @return string|bool String (relative path) or false
1842 public function current() {
1843 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1846 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1847 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1852 * Iterator for listing regular files
1854 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1856 * @see Iterator::current()
1857 * @return string|bool String (relative path) or false
1859 public function current() {
1860 list( $path, $stat ) = current( $this->bufferIter
);
1861 $relPath = substr( $path, $this->suffixStart
);
1862 if ( is_array( $stat ) ) {
1863 $storageDir = rtrim( $this->params
['dir'], '/' );
1864 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1870 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1871 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );