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 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
201 $part = trim( $part );
202 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
203 if ( strlen( $new ) <= 255 ) {
206 break; // too long; sigh
209 $headers['content-disposition'] = $disposition;
215 protected function doCreateInternal( array $params ) {
216 $status = Status
::newGood();
218 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
219 if ( $dstRel === null ) {
220 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
225 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
226 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
228 $reqs = array( array(
230 'url' => array( $dstCont, $dstRel ),
232 'content-length' => strlen( $params['content'] ),
233 'etag' => md5( $params['content'] ),
234 'content-type' => $contentType,
235 'x-object-meta-sha1base36' => $sha1Hash
236 ) +
$this->sanitizeHdrs( $params ),
237 'body' => $params['content']
241 $method = __METHOD__
;
242 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
243 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
244 if ( $rcode === 201 ) {
246 } elseif ( $rcode === 412 ) {
247 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
249 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
253 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
254 if ( !empty( $params['async'] ) ) { // deferred
255 $status->value
= $opHandle;
256 } else { // actually write the object in Swift
257 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
263 protected function doStoreInternal( array $params ) {
264 $status = Status
::newGood();
266 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
267 if ( $dstRel === null ) {
268 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
273 MediaWiki\
suppressWarnings();
274 $sha1Hash = sha1_file( $params['src'] );
275 MediaWiki\restoreWarnings
();
276 if ( $sha1Hash === false ) { // source doesn't exist?
277 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
281 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
282 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
284 $handle = fopen( $params['src'], 'rb' );
285 if ( $handle === false ) { // source doesn't exist?
286 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
291 $reqs = array( array(
293 'url' => array( $dstCont, $dstRel ),
295 'content-length' => filesize( $params['src'] ),
296 'etag' => md5_file( $params['src'] ),
297 'content-type' => $contentType,
298 'x-object-meta-sha1base36' => $sha1Hash
299 ) +
$this->sanitizeHdrs( $params ),
300 'body' => $handle // resource
304 $method = __METHOD__
;
305 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
306 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
307 if ( $rcode === 201 ) {
309 } elseif ( $rcode === 412 ) {
310 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
312 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
316 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
317 if ( !empty( $params['async'] ) ) { // deferred
318 $status->value
= $opHandle;
319 } else { // actually write the object in Swift
320 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
326 protected function doCopyInternal( array $params ) {
327 $status = Status
::newGood();
329 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
330 if ( $srcRel === null ) {
331 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
336 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
337 if ( $dstRel === null ) {
338 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
343 $reqs = array( array(
345 'url' => array( $dstCont, $dstRel ),
347 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
348 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
349 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
353 $method = __METHOD__
;
354 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
355 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
356 if ( $rcode === 201 ) {
358 } elseif ( $rcode === 404 ) {
359 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
361 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
365 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
366 if ( !empty( $params['async'] ) ) { // deferred
367 $status->value
= $opHandle;
368 } else { // actually write the object in Swift
369 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
375 protected function doMoveInternal( array $params ) {
376 $status = Status
::newGood();
378 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
379 if ( $srcRel === null ) {
380 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
385 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
386 if ( $dstRel === null ) {
387 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
395 'url' => array( $dstCont, $dstRel ),
397 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
398 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
399 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
402 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
404 'method' => 'DELETE',
405 'url' => array( $srcCont, $srcRel ),
411 $method = __METHOD__
;
412 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
413 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
414 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
416 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
418 } elseif ( $rcode === 404 ) {
419 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
421 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
425 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
426 if ( !empty( $params['async'] ) ) { // deferred
427 $status->value
= $opHandle;
428 } else { // actually move the object in Swift
429 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
435 protected function doDeleteInternal( array $params ) {
436 $status = Status
::newGood();
438 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
439 if ( $srcRel === null ) {
440 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
445 $reqs = array( array(
446 'method' => 'DELETE',
447 'url' => array( $srcCont, $srcRel ),
452 $method = __METHOD__
;
453 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
454 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
455 if ( $rcode === 204 ) {
457 } elseif ( $rcode === 404 ) {
458 if ( empty( $params['ignoreMissingSource'] ) ) {
459 $status->fatal( 'backend-fail-delete', $params['src'] );
462 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
466 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
467 if ( !empty( $params['async'] ) ) { // deferred
468 $status->value
= $opHandle;
469 } else { // actually delete the object in Swift
470 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
476 protected function doDescribeInternal( array $params ) {
477 $status = Status
::newGood();
479 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
480 if ( $srcRel === null ) {
481 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
486 // Fetch the old object headers/metadata...this should be in stat cache by now
487 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
488 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
489 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
492 $status->fatal( 'backend-fail-describe', $params['src'] );
497 // POST clears prior headers, so we need to merge the changes in to the old ones
499 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
500 $metaHdrs["x-object-meta-$name"] = $value;
502 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
504 $reqs = array( array(
506 'url' => array( $srcCont, $srcRel ),
507 'headers' => $metaHdrs +
$customHdrs
511 $method = __METHOD__
;
512 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
513 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
514 if ( $rcode === 202 ) {
516 } elseif ( $rcode === 404 ) {
517 $status->fatal( 'backend-fail-describe', $params['src'] );
519 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
523 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
524 if ( !empty( $params['async'] ) ) { // deferred
525 $status->value
= $opHandle;
526 } else { // actually change the object in Swift
527 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
533 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
534 $status = Status
::newGood();
536 // (a) Check if container already exists
537 $stat = $this->getContainerStat( $fullCont );
538 if ( is_array( $stat ) ) {
539 return $status; // already there
540 } elseif ( $stat === null ) {
541 $status->fatal( 'backend-fail-internal', $this->name
);
542 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
547 // (b) Create container as needed with proper ACLs
548 if ( $stat === false ) {
549 $params['op'] = 'prepare';
550 $status->merge( $this->createContainer( $fullCont, $params ) );
556 protected function doSecureInternal( $fullCont, $dir, array $params ) {
557 $status = Status
::newGood();
558 if ( empty( $params['noAccess'] ) ) {
559 return $status; // nothing to do
562 $stat = $this->getContainerStat( $fullCont );
563 if ( is_array( $stat ) ) {
564 // Make container private to end-users...
565 $status->merge( $this->setContainerAccess(
567 array( $this->swiftUser
), // read
568 array( $this->swiftUser
) // write
570 } elseif ( $stat === false ) {
571 $status->fatal( 'backend-fail-usable', $params['dir'] );
573 $status->fatal( 'backend-fail-internal', $this->name
);
574 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
580 protected function doPublishInternal( $fullCont, $dir, array $params ) {
581 $status = Status
::newGood();
583 $stat = $this->getContainerStat( $fullCont );
584 if ( is_array( $stat ) ) {
585 // Make container public to end-users...
586 $status->merge( $this->setContainerAccess(
588 array( $this->swiftUser
, '.r:*' ), // read
589 array( $this->swiftUser
) // write
591 } elseif ( $stat === false ) {
592 $status->fatal( 'backend-fail-usable', $params['dir'] );
594 $status->fatal( 'backend-fail-internal', $this->name
);
595 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
601 protected function doCleanInternal( $fullCont, $dir, array $params ) {
602 $status = Status
::newGood();
604 // Only containers themselves can be removed, all else is virtual
606 return $status; // nothing to do
609 // (a) Check the container
610 $stat = $this->getContainerStat( $fullCont, true );
611 if ( $stat === false ) {
612 return $status; // ok, nothing to do
613 } elseif ( !is_array( $stat ) ) {
614 $status->fatal( 'backend-fail-internal', $this->name
);
615 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
620 // (b) Delete the container if empty
621 if ( $stat['count'] == 0 ) {
622 $params['op'] = 'clean';
623 $status->merge( $this->deleteContainer( $fullCont, $params ) );
629 protected function doGetFileStat( array $params ) {
630 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) +
$params;
631 unset( $params['src'] );
632 $stats = $this->doGetFileStatMulti( $params );
634 return reset( $stats );
638 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
639 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
640 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
643 * @param int $format Output format (TS_* constant)
645 * @throws FileBackendError
647 protected function convertSwiftDate( $ts, $format = TS_MW
) {
649 $timestamp = new MWTimestamp( $ts );
651 return $timestamp->getTimestamp( $format );
652 } catch ( Exception
$e ) {
653 throw new FileBackendError( $e->getMessage() );
658 * Fill in any missing object metadata and save it to Swift
660 * @param array $objHdrs Object response headers
661 * @param string $path Storage path to object
662 * @return array New headers
664 protected function addMissingMetadata( array $objHdrs, $path ) {
665 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
666 return $objHdrs; // nothing to do
669 /** @noinspection PhpUnusedLocalVariableInspection */
670 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
671 wfDebugLog( 'SwiftBackend', __METHOD__
. ": $path was not stored with SHA-1 metadata." );
673 $auth = $this->getAuthentication();
675 $objHdrs['x-object-meta-sha1base36'] = false;
677 return $objHdrs; // failed
680 $status = Status
::newGood();
681 /** @noinspection PhpUnusedLocalVariableInspection */
682 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
683 if ( $status->isOK() ) {
684 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
686 $hash = $tmpFile->getSha1Base36();
687 if ( $hash !== false ) {
688 $objHdrs['x-object-meta-sha1base36'] = $hash;
689 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
690 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
692 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
693 'headers' => $this->authTokenHeaders( $auth ) +
$objHdrs
695 if ( $rcode >= 200 && $rcode <= 299 ) {
696 return $objHdrs; // success
702 wfDebugLog( 'SwiftBackend', __METHOD__
. ": unable to set SHA-1 metadata for $path" );
703 $objHdrs['x-object-meta-sha1base36'] = false;
705 return $objHdrs; // failed
708 protected function doGetFileContentsMulti( array $params ) {
711 $auth = $this->getAuthentication();
713 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
714 // Blindly create tmp files and stream to them, catching any exception if the file does
715 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
716 $reqs = array(); // (path => op)
718 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
719 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
720 if ( $srcRel === null ||
!$auth ) {
721 $contents[$path] = false;
724 // Create a new temporary memory file...
725 $handle = fopen( 'php://temp', 'wb' );
727 $reqs[$path] = array(
729 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
730 'headers' => $this->authTokenHeaders( $auth )
731 +
$this->headersFromParams( $params ),
735 $contents[$path] = false;
738 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
739 $reqs = $this->http
->runMulti( $reqs, $opts );
740 foreach ( $reqs as $path => $op ) {
741 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
742 if ( $rcode >= 200 && $rcode <= 299 ) {
743 rewind( $op['stream'] ); // start from the beginning
744 $contents[$path] = stream_get_contents( $op['stream'] );
745 } elseif ( $rcode === 404 ) {
746 $contents[$path] = false;
748 $this->onError( null, __METHOD__
,
749 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
751 fclose( $op['stream'] ); // close open handle
757 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
758 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
759 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
760 if ( $status->isOk() ) {
761 return ( count( $status->value
) ) > 0;
764 return null; // error
768 * @see FileBackendStore::getDirectoryListInternal()
769 * @param string $fullCont
771 * @param array $params
772 * @return SwiftFileBackendDirList
774 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
775 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
779 * @see FileBackendStore::getFileListInternal()
780 * @param string $fullCont
782 * @param array $params
783 * @return SwiftFileBackendFileList
785 public function getFileListInternal( $fullCont, $dir, array $params ) {
786 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
790 * Do not call this function outside of SwiftFileBackendFileList
792 * @param string $fullCont Resolved container name
793 * @param string $dir Resolved storage directory with no trailing slash
794 * @param string|null $after Resolved container relative path to list items after
795 * @param int $limit Max number of items to list
796 * @param array $params Parameters for getDirectoryList()
797 * @return array List of container relative resolved paths of directories directly under $dir
798 * @throws FileBackendError
800 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
802 if ( $after === INF
) {
803 return $dirs; // nothing more
806 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
808 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
809 // Non-recursive: only list dirs right under $dir
810 if ( !empty( $params['topOnly'] ) ) {
811 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
812 if ( !$status->isOk() ) {
813 return $dirs; // error
815 $objects = $status->value
;
816 foreach ( $objects as $object ) { // files and directories
817 if ( substr( $object, -1 ) === '/' ) {
818 $dirs[] = $object; // directories end in '/'
822 // Recursive: list all dirs under $dir and its subdirs
823 $getParentDir = function ( $path ) {
824 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
827 // Get directory from last item of prior page
828 $lastDir = $getParentDir( $after ); // must be first page
829 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
831 if ( !$status->isOk() ) {
832 return $dirs; // error
835 $objects = $status->value
;
837 foreach ( $objects as $object ) { // files
838 $objectDir = $getParentDir( $object ); // directory of object
840 if ( $objectDir !== false && $objectDir !== $dir ) {
841 // Swift stores paths in UTF-8, using binary sorting.
842 // See function "create_container_table" in common/db.py.
843 // If a directory is not "greater" than the last one,
844 // then it was already listed by the calling iterator.
845 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
847 do { // add dir and all its parent dirs
848 $dirs[] = "{$pDir}/";
849 $pDir = $getParentDir( $pDir );
850 } while ( $pDir !== false // sanity
851 && strcmp( $pDir, $lastDir ) > 0 // not done already
852 && strlen( $pDir ) > strlen( $dir ) // within $dir
855 $lastDir = $objectDir;
859 // Page on the unfiltered directory listing (what is returned may be filtered)
860 if ( count( $objects ) < $limit ) {
861 $after = INF
; // avoid a second RTT
863 $after = end( $objects ); // update last item
870 * Do not call this function outside of SwiftFileBackendFileList
872 * @param string $fullCont Resolved container name
873 * @param string $dir Resolved storage directory with no trailing slash
874 * @param string|null $after Resolved container relative path of file to list items after
875 * @param int $limit Max number of items to list
876 * @param array $params Parameters for getDirectoryList()
877 * @return array List of resolved container relative paths of files under $dir
878 * @throws FileBackendError
880 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
881 $files = array(); // list of (path, stat array or null) entries
882 if ( $after === INF
) {
883 return $files; // nothing more
886 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
888 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
889 // $objects will contain a list of unfiltered names or CF_Object items
890 // Non-recursive: only list files right under $dir
891 if ( !empty( $params['topOnly'] ) ) {
892 if ( !empty( $params['adviseStat'] ) ) {
893 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
895 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
898 // Recursive: list all files under $dir and its subdirs
899 if ( !empty( $params['adviseStat'] ) ) {
900 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
902 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
906 // Reformat this list into a list of (name, stat array or null) entries
907 if ( !$status->isOk() ) {
908 return $files; // error
911 $objects = $status->value
;
912 $files = $this->buildFileObjectListing( $params, $dir, $objects );
914 // Page on the unfiltered object listing (what is returned may be filtered)
915 if ( count( $objects ) < $limit ) {
916 $after = INF
; // avoid a second RTT
918 $after = end( $objects ); // update last item
919 $after = is_object( $after ) ?
$after->name
: $after;
926 * Build a list of file objects, filtering out any directories
927 * and extracting any stat info if provided in $objects (for CF_Objects)
929 * @param array $params Parameters for getDirectoryList()
930 * @param string $dir Resolved container directory path
931 * @param array $objects List of CF_Object items or object names
932 * @return array List of (names,stat array or null) entries
934 private function buildFileObjectListing( array $params, $dir, array $objects ) {
936 foreach ( $objects as $object ) {
937 if ( is_object( $object ) ) {
938 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
939 continue; // virtual directory entry; ignore
942 // Convert various random Swift dates to TS_MW
943 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
944 'size' => (int)$object->bytes
,
946 // Note: manifiest ETags are not an MD5 of the file
947 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
948 'latest' => false // eventually consistent
950 $names[] = array( $object->name
, $stat );
951 } elseif ( substr( $object, -1 ) !== '/' ) {
952 // Omit directories, which end in '/' in listings
953 $names[] = array( $object, null );
961 * Do not call this function outside of SwiftFileBackendFileList
963 * @param string $path Storage path
964 * @param array $val Stat value
966 public function loadListingStatInternal( $path, array $val ) {
967 $this->cheapCache
->set( $path, 'stat', $val );
970 protected function doGetFileXAttributes( array $params ) {
971 $stat = $this->getFileStat( $params );
973 if ( !isset( $stat['xattr'] ) ) {
974 // Stat entries filled by file listings don't include metadata/headers
975 $this->clearCache( array( $params['src'] ) );
976 $stat = $this->getFileStat( $params );
979 return $stat['xattr'];
985 protected function doGetFileSha1base36( array $params ) {
986 $stat = $this->getFileStat( $params );
988 if ( !isset( $stat['sha1'] ) ) {
989 // Stat entries filled by file listings don't include SHA1
990 $this->clearCache( array( $params['src'] ) );
991 $stat = $this->getFileStat( $params );
994 return $stat['sha1'];
1000 protected function doStreamFile( array $params ) {
1001 $status = Status
::newGood();
1003 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1004 if ( $srcRel === null ) {
1005 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1008 $auth = $this->getAuthentication();
1009 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1010 $status->fatal( 'backend-fail-stream', $params['src'] );
1015 $handle = fopen( 'php://output', 'wb' );
1017 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1019 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1020 'headers' => $this->authTokenHeaders( $auth )
1021 +
$this->headersFromParams( $params ),
1022 'stream' => $handle,
1025 if ( $rcode >= 200 && $rcode <= 299 ) {
1027 } elseif ( $rcode === 404 ) {
1028 $status->fatal( 'backend-fail-stream', $params['src'] );
1030 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1036 protected function doGetLocalCopyMulti( array $params ) {
1037 $tmpFiles = array();
1039 $auth = $this->getAuthentication();
1041 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1042 // Blindly create tmp files and stream to them, catching any exception if the file does
1043 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1044 $reqs = array(); // (path => op)
1046 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1047 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1048 if ( $srcRel === null ||
!$auth ) {
1049 $tmpFiles[$path] = null;
1052 // Get source file extension
1053 $ext = FileBackend
::extensionFromPath( $path );
1054 // Create a new temporary file...
1055 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1057 $handle = fopen( $tmpFile->getPath(), 'wb' );
1059 $reqs[$path] = array(
1061 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1062 'headers' => $this->authTokenHeaders( $auth )
1063 +
$this->headersFromParams( $params ),
1064 'stream' => $handle,
1070 $tmpFiles[$path] = $tmpFile;
1073 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1074 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1075 $reqs = $this->http
->runMulti( $reqs, $opts );
1076 foreach ( $reqs as $path => $op ) {
1077 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1078 fclose( $op['stream'] ); // close open handle
1079 if ( $rcode >= 200 && $rcode <= 299 ) {
1080 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1081 // Double check that the disk is not full/broken
1082 if ( $size != $rhdrs['content-length'] ) {
1083 $tmpFiles[$path] = null;
1084 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1085 $this->onError( null, __METHOD__
,
1086 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1088 // Set the file stat process cache in passing
1089 $stat = $this->getStatFromHeaders( $rhdrs );
1090 $stat['latest'] = $isLatest;
1091 $this->cheapCache
->set( $path, 'stat', $stat );
1092 } elseif ( $rcode === 404 ) {
1093 $tmpFiles[$path] = false;
1095 $tmpFiles[$path] = null;
1096 $this->onError( null, __METHOD__
,
1097 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1104 public function getFileHttpUrl( array $params ) {
1105 if ( $this->swiftTempUrlKey
!= '' ||
1106 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1108 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1109 if ( $srcRel === null ) {
1110 return null; // invalid path
1113 $auth = $this->getAuthentication();
1118 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1119 $expires = time() +
$ttl;
1121 if ( $this->swiftTempUrlKey
!= '' ) {
1122 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1123 // Swift wants the signature based on the unencoded object name
1124 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1125 $signature = hash_hmac( 'sha1',
1126 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1127 $this->swiftTempUrlKey
1130 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1131 } else { // give S3 API URL for rgw
1132 // Path for signature starts with the bucket
1133 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1134 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1135 // Calculate the hash
1136 $signature = base64_encode( hash_hmac(
1138 "GET\n\n\n{$expires}\n{$spath}",
1139 $this->rgwS3SecretKey
,
1142 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1143 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1144 return wfAppendQuery(
1145 str_replace( '/swift/v1', '', // S3 API is the rgw default
1146 $this->storageUrl( $auth ) . $spath ),
1148 'Signature' => $signature,
1149 'Expires' => $expires,
1150 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1158 protected function directoriesAreVirtual() {
1163 * Get headers to send to Swift when reading a file based
1164 * on a FileBackend params array, e.g. that of getLocalCopy().
1165 * $params is currently only checked for a 'latest' flag.
1167 * @param array $params
1170 protected function headersFromParams( array $params ) {
1172 if ( !empty( $params['latest'] ) ) {
1173 $hdrs['x-newest'] = 'true';
1180 * @param FileBackendStoreOpHandle[] $fileOpHandles
1184 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1185 $statuses = array();
1187 $auth = $this->getAuthentication();
1189 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1190 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1196 // Split the HTTP requests into stages that can be done concurrently
1197 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1198 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1199 $reqs = $fileOpHandle->httpOp
;
1200 // Convert the 'url' parameter to an actual URL using $auth
1201 foreach ( $reqs as $stage => &$req ) {
1202 list( $container, $relPath ) = $req['url'];
1203 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1204 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1205 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1206 $httpReqsByStage[$stage][$index] = $req;
1208 $statuses[$index] = Status
::newGood();
1211 // Run all requests for the first stage, then the next, and so on
1212 $reqCount = count( $httpReqsByStage );
1213 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1214 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1215 foreach ( $httpReqs as $index => $httpReq ) {
1216 // Run the callback for each request of this operation
1217 $callback = $fileOpHandles[$index]->callback
;
1218 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1219 // On failure, abort all remaining requests for this operation
1220 // (e.g. abort the DELETE request if the COPY request fails for a move)
1221 if ( !$statuses[$index]->isOK() ) {
1222 $stages = count( $fileOpHandles[$index]->httpOp
);
1223 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1224 unset( $httpReqsByStage[$s][$index] );
1234 * Set read/write permissions for a Swift container.
1236 * @see http://swift.openstack.org/misc.html#acls
1238 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1239 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1241 * @param string $container Resolved Swift container
1242 * @param array $readGrps List of the possible criteria for a request to have
1243 * access to read a container. Each item is one of the following formats:
1244 * - account:user : Grants access if the request is by the given user
1245 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1246 * matches the expression and the request is not for a listing.
1247 * Setting this to '*' effectively makes a container public.
1248 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1249 * matches the expression and the request is for a listing.
1250 * @param array $writeGrps A list of the possible criteria for a request to have
1251 * access to write to a container. Each item is of the following format:
1252 * - account:user : Grants access if the request is by the given user
1255 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1256 $status = Status
::newGood();
1257 $auth = $this->getAuthentication();
1260 $status->fatal( 'backend-fail-connect', $this->name
);
1265 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1267 'url' => $this->storageUrl( $auth, $container ),
1268 'headers' => $this->authTokenHeaders( $auth ) +
array(
1269 'x-container-read' => implode( ',', $readGrps ),
1270 'x-container-write' => implode( ',', $writeGrps )
1274 if ( $rcode != 204 && $rcode !== 202 ) {
1275 $status->fatal( 'backend-fail-internal', $this->name
);
1276 wfDebugLog( 'SwiftBackend', __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1283 * Get a Swift container stat array, possibly from process cache.
1284 * Use $reCache if the file count or byte count is needed.
1286 * @param string $container Container name
1287 * @param bool $bypassCache Bypass all caches and load from Swift
1288 * @return array|bool|null False on 404, null on failure
1290 protected function getContainerStat( $container, $bypassCache = false ) {
1291 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1293 if ( $bypassCache ) { // purge cache
1294 $this->containerStatCache
->clear( $container );
1295 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1296 $this->primeContainerCache( array( $container ) ); // check persistent cache
1298 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1299 $auth = $this->getAuthentication();
1304 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1306 'url' => $this->storageUrl( $auth, $container ),
1307 'headers' => $this->authTokenHeaders( $auth )
1310 if ( $rcode === 204 ) {
1312 'count' => $rhdrs['x-container-object-count'],
1313 'bytes' => $rhdrs['x-container-bytes-used']
1315 if ( $bypassCache ) {
1318 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1319 $this->setContainerCache( $container, $stat ); // update persistent cache
1321 } elseif ( $rcode === 404 ) {
1324 $this->onError( null, __METHOD__
,
1325 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1331 return $this->containerStatCache
->get( $container, 'stat' );
1335 * Create a Swift container
1337 * @param string $container Container name
1338 * @param array $params
1341 protected function createContainer( $container, array $params ) {
1342 $status = Status
::newGood();
1344 $auth = $this->getAuthentication();
1346 $status->fatal( 'backend-fail-connect', $this->name
);
1351 // @see SwiftFileBackend::setContainerAccess()
1352 if ( empty( $params['noAccess'] ) ) {
1353 $readGrps = array( '.r:*', $this->swiftUser
); // public
1355 $readGrps = array( $this->swiftUser
); // private
1357 $writeGrps = array( $this->swiftUser
); // sanity
1359 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1361 'url' => $this->storageUrl( $auth, $container ),
1362 'headers' => $this->authTokenHeaders( $auth ) +
array(
1363 'x-container-read' => implode( ',', $readGrps ),
1364 'x-container-write' => implode( ',', $writeGrps )
1368 if ( $rcode === 201 ) { // new
1370 } elseif ( $rcode === 202 ) { // already there
1371 // this shouldn't really happen, but is OK
1373 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1380 * Delete a Swift container
1382 * @param string $container Container name
1383 * @param array $params
1386 protected function deleteContainer( $container, array $params ) {
1387 $status = Status
::newGood();
1389 $auth = $this->getAuthentication();
1391 $status->fatal( 'backend-fail-connect', $this->name
);
1396 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1397 'method' => 'DELETE',
1398 'url' => $this->storageUrl( $auth, $container ),
1399 'headers' => $this->authTokenHeaders( $auth )
1402 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1403 $this->containerStatCache
->clear( $container ); // purge
1404 } elseif ( $rcode === 404 ) { // not there
1405 // this shouldn't really happen, but is OK
1406 } elseif ( $rcode === 409 ) { // not empty
1407 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1409 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1416 * Get a list of objects under a container.
1417 * Either just the names or a list of stdClass objects with details can be returned.
1419 * @param string $fullCont
1420 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1422 * @param string|null $after
1423 * @param string|null $prefix
1424 * @param string|null $delim
1425 * @return Status With the list as value
1427 private function objectListing(
1428 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1430 $status = Status
::newGood();
1432 $auth = $this->getAuthentication();
1434 $status->fatal( 'backend-fail-connect', $this->name
);
1439 $query = array( 'limit' => $limit );
1440 if ( $type === 'info' ) {
1441 $query['format'] = 'json';
1443 if ( $after !== null ) {
1444 $query['marker'] = $after;
1446 if ( $prefix !== null ) {
1447 $query['prefix'] = $prefix;
1449 if ( $delim !== null ) {
1450 $query['delimiter'] = $delim;
1453 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1455 'url' => $this->storageUrl( $auth, $fullCont ),
1457 'headers' => $this->authTokenHeaders( $auth )
1460 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1461 if ( $rcode === 200 ) { // good
1462 if ( $type === 'info' ) {
1463 $status->value
= FormatJson
::decode( trim( $rbody ) );
1465 $status->value
= explode( "\n", trim( $rbody ) );
1467 } elseif ( $rcode === 204 ) {
1468 $status->value
= array(); // empty container
1469 } elseif ( $rcode === 404 ) {
1470 $status->value
= array(); // no container
1472 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1478 protected function doPrimeContainerCache( array $containerInfo ) {
1479 foreach ( $containerInfo as $container => $info ) {
1480 $this->containerStatCache
->set( $container, 'stat', $info );
1484 protected function doGetFileStatMulti( array $params ) {
1487 $auth = $this->getAuthentication();
1490 foreach ( $params['srcs'] as $path ) {
1491 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1492 if ( $srcRel === null ) {
1493 $stats[$path] = false;
1494 continue; // invalid storage path
1495 } elseif ( !$auth ) {
1496 $stats[$path] = null;
1500 // (a) Check the container
1501 $cstat = $this->getContainerStat( $srcCont );
1502 if ( $cstat === false ) {
1503 $stats[$path] = false;
1504 continue; // ok, nothing to do
1505 } elseif ( !is_array( $cstat ) ) {
1506 $stats[$path] = null;
1510 $reqs[$path] = array(
1512 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1513 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1517 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1518 $reqs = $this->http
->runMulti( $reqs, $opts );
1520 foreach ( $params['srcs'] as $path ) {
1521 if ( array_key_exists( $path, $stats ) ) {
1522 continue; // some sort of failure above
1524 // (b) Check the file
1525 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1526 if ( $rcode === 200 ||
$rcode === 204 ) {
1527 // Update the object if it is missing some headers
1528 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1529 // Load the stat array from the headers
1530 $stat = $this->getStatFromHeaders( $rhdrs );
1531 if ( $this->isRGW
) {
1532 $stat['latest'] = true; // strong consistency
1534 } elseif ( $rcode === 404 ) {
1538 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1540 $stats[$path] = $stat;
1547 * @param array $rhdrs
1550 protected function getStatFromHeaders( array $rhdrs ) {
1551 // Fetch all of the custom metadata headers
1552 $metadata = array();
1553 foreach ( $rhdrs as $name => $value ) {
1554 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
1555 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
1558 // Fetch all of the custom raw HTTP headers
1559 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1561 // Convert various random Swift dates to TS_MW
1562 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1563 // Empty objects actually return no content-length header in Ceph
1564 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1565 'sha1' => isset( $rhdrs['x-object-meta-sha1base36'] )
1566 ?
$rhdrs['x-object-meta-sha1base36']
1568 // Note: manifiest ETags are not an MD5 of the file
1569 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1570 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1575 * @return array|null Credential map
1577 protected function getAuthentication() {
1578 if ( $this->authErrorTimestamp
!== null ) {
1579 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1580 return null; // failed last attempt; don't bother
1581 } else { // actually retry this time
1582 $this->authErrorTimestamp
= null;
1585 // Session keys expire after a while, so we renew them periodically
1586 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1587 // Authenticate with proxy and get a session key...
1588 if ( !$this->authCreds ||
$reAuth ) {
1589 $this->authSessionTimestamp
= 0;
1590 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1591 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1592 // Try to use the credential cache
1593 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1594 $this->authCreds
= $creds;
1595 // Skew the timestamp for worst case to avoid using stale credentials
1596 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1597 } else { // cache miss
1598 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1600 'url' => "{$this->swiftAuthUrl}/v1.0",
1602 'x-auth-user' => $this->swiftUser
,
1603 'x-auth-key' => $this->swiftKey
1607 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1608 $this->authCreds
= array(
1609 'auth_token' => $rhdrs['x-auth-token'],
1610 'storage_url' => $rhdrs['x-storage-url']
1612 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1613 $this->authSessionTimestamp
= time();
1614 } elseif ( $rcode === 401 ) {
1615 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1616 $this->authErrorTimestamp
= time();
1620 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1621 $this->authErrorTimestamp
= time();
1626 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1627 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1628 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1632 return $this->authCreds
;
1636 * @param array $creds From getAuthentication()
1637 * @param string $container
1638 * @param string $object
1641 protected function storageUrl( array $creds, $container = null, $object = null ) {
1642 $parts = array( $creds['storage_url'] );
1643 if ( strlen( $container ) ) {
1644 $parts[] = rawurlencode( $container );
1646 if ( strlen( $object ) ) {
1647 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1650 return implode( '/', $parts );
1654 * @param array $creds From getAuthentication()
1657 protected function authTokenHeaders( array $creds ) {
1658 return array( 'x-auth-token' => $creds['auth_token'] );
1662 * Get the cache key for a container
1664 * @param string $username
1667 private function getCredsCacheKey( $username ) {
1668 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1672 * Log an unexpected exception for this backend.
1673 * This also sets the Status object to have a fatal error.
1675 * @param Status|null $status
1676 * @param string $func
1677 * @param array $params
1678 * @param string $err Error string
1679 * @param int $code HTTP status
1680 * @param string $desc HTTP status description
1682 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1683 if ( $status instanceof Status
) {
1684 $status->fatal( 'backend-fail-internal', $this->name
);
1686 if ( $code == 401 ) { // possibly a stale token
1687 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1689 wfDebugLog( 'SwiftBackend',
1690 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1691 ( $err ?
": $err" : "" )
1697 * @see FileBackendStoreOpHandle
1699 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1700 /** @var array List of Requests for MultiHttpClient */
1706 * @param SwiftFileBackend $backend
1707 * @param Closure $callback Function that takes (HTTP request array, status)
1708 * @param array $httpOp MultiHttpClient op
1710 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1711 $this->backend
= $backend;
1712 $this->callback
= $callback;
1713 $this->httpOp
= $httpOp;
1718 * SwiftFileBackend helper class to page through listings.
1719 * Swift also has a listing limit of 10,000 objects for sanity.
1720 * Do not use this class from places outside SwiftFileBackend.
1722 * @ingroup FileBackend
1724 abstract class SwiftFileBackendList
implements Iterator
{
1725 /** @var array List of path or (path,stat array) entries */
1726 protected $bufferIter = array();
1728 /** @var string List items *after* this path */
1729 protected $bufferAfter = null;
1735 protected $params = array();
1737 /** @var SwiftFileBackend */
1740 /** @var string Container name */
1741 protected $container;
1743 /** @var string Storage directory */
1747 protected $suffixStart;
1749 const PAGE_SIZE
= 9000; // file listing buffer size
1752 * @param SwiftFileBackend $backend
1753 * @param string $fullCont Resolved container name
1754 * @param string $dir Resolved directory relative to container
1755 * @param array $params
1757 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1758 $this->backend
= $backend;
1759 $this->container
= $fullCont;
1761 if ( substr( $this->dir
, -1 ) === '/' ) {
1762 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1764 if ( $this->dir
== '' ) { // whole container
1765 $this->suffixStart
= 0;
1766 } else { // dir within container
1767 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1769 $this->params
= $params;
1773 * @see Iterator::key()
1776 public function key() {
1781 * @see Iterator::next()
1783 public function next() {
1784 // Advance to the next file in the page
1785 next( $this->bufferIter
);
1787 // Check if there are no files left in this page and
1788 // advance to the next page if this page was not empty.
1789 if ( !$this->valid() && count( $this->bufferIter
) ) {
1790 $this->bufferIter
= $this->pageFromList(
1791 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1792 ); // updates $this->bufferAfter
1797 * @see Iterator::rewind()
1799 public function rewind() {
1801 $this->bufferAfter
= null;
1802 $this->bufferIter
= $this->pageFromList(
1803 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1804 ); // updates $this->bufferAfter
1808 * @see Iterator::valid()
1811 public function valid() {
1812 if ( $this->bufferIter
=== null ) {
1813 return false; // some failure?
1815 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1820 * Get the given list portion (page)
1822 * @param string $container Resolved container name
1823 * @param string $dir Resolved path relative to container
1824 * @param string $after
1826 * @param array $params
1827 * @return Traversable|array
1829 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1833 * Iterator for listing directories
1835 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1837 * @see Iterator::current()
1838 * @return string|bool String (relative path) or false
1840 public function current() {
1841 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1844 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1845 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1850 * Iterator for listing regular files
1852 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1854 * @see Iterator::current()
1855 * @return string|bool String (relative path) or false
1857 public function current() {
1858 list( $path, $stat ) = current( $this->bufferIter
);
1859 $relPath = substr( $path, $this->suffixStart
);
1860 if ( is_array( $stat ) ) {
1861 $storageDir = rtrim( $this->params
['dir'], '/' );
1862 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1868 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1869 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );