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 * Only allows certain "standard" 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 ) {
182 return isset( $params['headers'] )
183 ?
$this->getCustomHeaders( $params['headers'] )
189 * @param array $rawHeaders
190 * @return array Custom non-metadata HTTP headers
192 protected function getCustomHeaders( array $rawHeaders ) {
195 // Normalize casing, and strip out illegal headers
196 foreach ( $rawHeaders as $name => $value ) {
197 $name = strtolower( $name );
198 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
199 continue; // blacklisted
200 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
201 $headers[$name] = $value; // allowed
202 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
203 $headers[$name] = $value; // allowed
206 // By default, Swift has annoyingly low maximum header value limits
207 if ( isset( $headers['content-disposition'] ) ) {
209 // @note: assume FileBackend::makeContentDisposition() already used
210 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
211 $part = trim( $part );
212 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
213 if ( strlen( $new ) <= 255 ) {
216 break; // too long; sigh
219 $headers['content-disposition'] = $disposition;
226 * @param array $rawHeaders
227 * @return array Custom metadata headers
229 protected function getMetadataHeaders( array $rawHeaders ) {
231 foreach ( $rawHeaders as $name => $value ) {
232 $name = strtolower( $name );
233 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
234 $headers[$name] = $value;
242 * @param array $rawHeaders
243 * @return array Custom metadata headers with prefix removed
245 protected function getMetadata( array $rawHeaders ) {
247 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
248 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
254 protected function doCreateInternal( array $params ) {
255 $status = Status
::newGood();
257 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
258 if ( $dstRel === null ) {
259 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
264 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
265 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
267 $reqs = array( array(
269 'url' => array( $dstCont, $dstRel ),
271 'content-length' => strlen( $params['content'] ),
272 'etag' => md5( $params['content'] ),
273 'content-type' => $contentType,
274 'x-object-meta-sha1base36' => $sha1Hash
275 ) +
$this->sanitizeHdrs( $params ),
276 'body' => $params['content']
280 $method = __METHOD__
;
281 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
282 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
283 if ( $rcode === 201 ) {
285 } elseif ( $rcode === 412 ) {
286 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
288 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
292 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
293 if ( !empty( $params['async'] ) ) { // deferred
294 $status->value
= $opHandle;
295 } else { // actually write the object in Swift
296 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
302 protected function doStoreInternal( array $params ) {
303 $status = Status
::newGood();
305 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
306 if ( $dstRel === null ) {
307 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
312 MediaWiki\
suppressWarnings();
313 $sha1Hash = sha1_file( $params['src'] );
314 MediaWiki\restoreWarnings
();
315 if ( $sha1Hash === false ) { // source doesn't exist?
316 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
320 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
321 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
323 $handle = fopen( $params['src'], 'rb' );
324 if ( $handle === false ) { // source doesn't exist?
325 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
330 $reqs = array( array(
332 'url' => array( $dstCont, $dstRel ),
334 'content-length' => filesize( $params['src'] ),
335 'etag' => md5_file( $params['src'] ),
336 'content-type' => $contentType,
337 'x-object-meta-sha1base36' => $sha1Hash
338 ) +
$this->sanitizeHdrs( $params ),
339 'body' => $handle // resource
343 $method = __METHOD__
;
344 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
345 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
346 if ( $rcode === 201 ) {
348 } elseif ( $rcode === 412 ) {
349 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
351 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
355 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
356 if ( !empty( $params['async'] ) ) { // deferred
357 $status->value
= $opHandle;
358 } else { // actually write the object in Swift
359 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
365 protected function doCopyInternal( array $params ) {
366 $status = Status
::newGood();
368 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
369 if ( $srcRel === null ) {
370 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
375 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
376 if ( $dstRel === null ) {
377 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
382 $reqs = array( array(
384 'url' => array( $dstCont, $dstRel ),
386 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
387 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
388 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
392 $method = __METHOD__
;
393 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
394 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
395 if ( $rcode === 201 ) {
397 } elseif ( $rcode === 404 ) {
398 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
400 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
404 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
405 if ( !empty( $params['async'] ) ) { // deferred
406 $status->value
= $opHandle;
407 } else { // actually write the object in Swift
408 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
414 protected function doMoveInternal( array $params ) {
415 $status = Status
::newGood();
417 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
418 if ( $srcRel === null ) {
419 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
424 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
425 if ( $dstRel === null ) {
426 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
434 'url' => array( $dstCont, $dstRel ),
436 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
437 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
438 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
441 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
443 'method' => 'DELETE',
444 'url' => array( $srcCont, $srcRel ),
450 $method = __METHOD__
;
451 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
452 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
453 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
455 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
457 } elseif ( $rcode === 404 ) {
458 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
460 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
464 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
465 if ( !empty( $params['async'] ) ) { // deferred
466 $status->value
= $opHandle;
467 } else { // actually move the object in Swift
468 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
474 protected function doDeleteInternal( array $params ) {
475 $status = Status
::newGood();
477 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
478 if ( $srcRel === null ) {
479 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
484 $reqs = array( array(
485 'method' => 'DELETE',
486 'url' => array( $srcCont, $srcRel ),
491 $method = __METHOD__
;
492 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
493 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
494 if ( $rcode === 204 ) {
496 } elseif ( $rcode === 404 ) {
497 if ( empty( $params['ignoreMissingSource'] ) ) {
498 $status->fatal( 'backend-fail-delete', $params['src'] );
501 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
505 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
506 if ( !empty( $params['async'] ) ) { // deferred
507 $status->value
= $opHandle;
508 } else { // actually delete the object in Swift
509 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
515 protected function doDescribeInternal( array $params ) {
516 $status = Status
::newGood();
518 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
519 if ( $srcRel === null ) {
520 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
525 // Fetch the old object headers/metadata...this should be in stat cache by now
526 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
527 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
528 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
531 $status->fatal( 'backend-fail-describe', $params['src'] );
536 // POST clears prior headers, so we need to merge the changes in to the old ones
538 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
539 $metaHdrs["x-object-meta-$name"] = $value;
541 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
543 $reqs = array( array(
545 'url' => array( $srcCont, $srcRel ),
546 'headers' => $metaHdrs +
$customHdrs
550 $method = __METHOD__
;
551 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
552 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
553 if ( $rcode === 202 ) {
555 } elseif ( $rcode === 404 ) {
556 $status->fatal( 'backend-fail-describe', $params['src'] );
558 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
562 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
563 if ( !empty( $params['async'] ) ) { // deferred
564 $status->value
= $opHandle;
565 } else { // actually change the object in Swift
566 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
572 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
573 $status = Status
::newGood();
575 // (a) Check if container already exists
576 $stat = $this->getContainerStat( $fullCont );
577 if ( is_array( $stat ) ) {
578 return $status; // already there
579 } elseif ( $stat === null ) {
580 $status->fatal( 'backend-fail-internal', $this->name
);
581 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
586 // (b) Create container as needed with proper ACLs
587 if ( $stat === false ) {
588 $params['op'] = 'prepare';
589 $status->merge( $this->createContainer( $fullCont, $params ) );
595 protected function doSecureInternal( $fullCont, $dir, array $params ) {
596 $status = Status
::newGood();
597 if ( empty( $params['noAccess'] ) ) {
598 return $status; // nothing to do
601 $stat = $this->getContainerStat( $fullCont );
602 if ( is_array( $stat ) ) {
603 // Make container private to end-users...
604 $status->merge( $this->setContainerAccess(
606 array( $this->swiftUser
), // read
607 array( $this->swiftUser
) // write
609 } elseif ( $stat === false ) {
610 $status->fatal( 'backend-fail-usable', $params['dir'] );
612 $status->fatal( 'backend-fail-internal', $this->name
);
613 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
619 protected function doPublishInternal( $fullCont, $dir, array $params ) {
620 $status = Status
::newGood();
622 $stat = $this->getContainerStat( $fullCont );
623 if ( is_array( $stat ) ) {
624 // Make container public to end-users...
625 $status->merge( $this->setContainerAccess(
627 array( $this->swiftUser
, '.r:*' ), // read
628 array( $this->swiftUser
) // write
630 } elseif ( $stat === false ) {
631 $status->fatal( 'backend-fail-usable', $params['dir'] );
633 $status->fatal( 'backend-fail-internal', $this->name
);
634 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
640 protected function doCleanInternal( $fullCont, $dir, array $params ) {
641 $status = Status
::newGood();
643 // Only containers themselves can be removed, all else is virtual
645 return $status; // nothing to do
648 // (a) Check the container
649 $stat = $this->getContainerStat( $fullCont, true );
650 if ( $stat === false ) {
651 return $status; // ok, nothing to do
652 } elseif ( !is_array( $stat ) ) {
653 $status->fatal( 'backend-fail-internal', $this->name
);
654 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
659 // (b) Delete the container if empty
660 if ( $stat['count'] == 0 ) {
661 $params['op'] = 'clean';
662 $status->merge( $this->deleteContainer( $fullCont, $params ) );
668 protected function doGetFileStat( array $params ) {
669 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) +
$params;
670 unset( $params['src'] );
671 $stats = $this->doGetFileStatMulti( $params );
673 return reset( $stats );
677 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
678 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
679 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
682 * @param int $format Output format (TS_* constant)
684 * @throws FileBackendError
686 protected function convertSwiftDate( $ts, $format = TS_MW
) {
688 $timestamp = new MWTimestamp( $ts );
690 return $timestamp->getTimestamp( $format );
691 } catch ( Exception
$e ) {
692 throw new FileBackendError( $e->getMessage() );
697 * Fill in any missing object metadata and save it to Swift
699 * @param array $objHdrs Object response headers
700 * @param string $path Storage path to object
701 * @return array New headers
703 protected function addMissingMetadata( array $objHdrs, $path ) {
704 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
705 return $objHdrs; // nothing to do
708 /** @noinspection PhpUnusedLocalVariableInspection */
709 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
710 wfDebugLog( 'SwiftBackend', __METHOD__
. ": $path was not stored with SHA-1 metadata." );
712 $objHdrs['x-object-meta-sha1base36'] = false;
714 $auth = $this->getAuthentication();
716 return $objHdrs; // failed
719 $status = Status
::newGood();
720 /** @noinspection PhpUnusedLocalVariableInspection */
721 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
722 if ( $status->isOK() ) {
723 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
725 $hash = $tmpFile->getSha1Base36();
726 if ( $hash !== false ) {
727 $objHdrs['x-object-meta-sha1base36'] = $hash;
728 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
729 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
731 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
732 'headers' => $this->authTokenHeaders( $auth ) +
$objHdrs
734 if ( $rcode >= 200 && $rcode <= 299 ) {
735 $this->deleteFileCache( $path );
737 return $objHdrs; // success
743 wfDebugLog( 'SwiftBackend', __METHOD__
. ": unable to set SHA-1 metadata for $path" );
745 return $objHdrs; // failed
748 protected function doGetFileContentsMulti( array $params ) {
751 $auth = $this->getAuthentication();
753 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
754 // Blindly create tmp files and stream to them, catching any exception if the file does
755 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
756 $reqs = array(); // (path => op)
758 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
759 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
760 if ( $srcRel === null ||
!$auth ) {
761 $contents[$path] = false;
764 // Create a new temporary memory file...
765 $handle = fopen( 'php://temp', 'wb' );
767 $reqs[$path] = array(
769 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
770 'headers' => $this->authTokenHeaders( $auth )
771 +
$this->headersFromParams( $params ),
775 $contents[$path] = false;
778 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
779 $reqs = $this->http
->runMulti( $reqs, $opts );
780 foreach ( $reqs as $path => $op ) {
781 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
782 if ( $rcode >= 200 && $rcode <= 299 ) {
783 rewind( $op['stream'] ); // start from the beginning
784 $contents[$path] = stream_get_contents( $op['stream'] );
785 } elseif ( $rcode === 404 ) {
786 $contents[$path] = false;
788 $this->onError( null, __METHOD__
,
789 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
791 fclose( $op['stream'] ); // close open handle
797 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
798 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
799 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
800 if ( $status->isOk() ) {
801 return ( count( $status->value
) ) > 0;
804 return null; // error
808 * @see FileBackendStore::getDirectoryListInternal()
809 * @param string $fullCont
811 * @param array $params
812 * @return SwiftFileBackendDirList
814 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
815 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
819 * @see FileBackendStore::getFileListInternal()
820 * @param string $fullCont
822 * @param array $params
823 * @return SwiftFileBackendFileList
825 public function getFileListInternal( $fullCont, $dir, array $params ) {
826 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
830 * Do not call this function outside of SwiftFileBackendFileList
832 * @param string $fullCont Resolved container name
833 * @param string $dir Resolved storage directory with no trailing slash
834 * @param string|null $after Resolved container relative path to list items after
835 * @param int $limit Max number of items to list
836 * @param array $params Parameters for getDirectoryList()
837 * @return array List of container relative resolved paths of directories directly under $dir
838 * @throws FileBackendError
840 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
842 if ( $after === INF
) {
843 return $dirs; // nothing more
846 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
848 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
849 // Non-recursive: only list dirs right under $dir
850 if ( !empty( $params['topOnly'] ) ) {
851 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
852 if ( !$status->isOk() ) {
853 return $dirs; // error
855 $objects = $status->value
;
856 foreach ( $objects as $object ) { // files and directories
857 if ( substr( $object, -1 ) === '/' ) {
858 $dirs[] = $object; // directories end in '/'
862 // Recursive: list all dirs under $dir and its subdirs
863 $getParentDir = function ( $path ) {
864 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
867 // Get directory from last item of prior page
868 $lastDir = $getParentDir( $after ); // must be first page
869 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
871 if ( !$status->isOk() ) {
872 return $dirs; // error
875 $objects = $status->value
;
877 foreach ( $objects as $object ) { // files
878 $objectDir = $getParentDir( $object ); // directory of object
880 if ( $objectDir !== false && $objectDir !== $dir ) {
881 // Swift stores paths in UTF-8, using binary sorting.
882 // See function "create_container_table" in common/db.py.
883 // If a directory is not "greater" than the last one,
884 // then it was already listed by the calling iterator.
885 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
887 do { // add dir and all its parent dirs
888 $dirs[] = "{$pDir}/";
889 $pDir = $getParentDir( $pDir );
890 } while ( $pDir !== false // sanity
891 && strcmp( $pDir, $lastDir ) > 0 // not done already
892 && strlen( $pDir ) > strlen( $dir ) // within $dir
895 $lastDir = $objectDir;
899 // Page on the unfiltered directory listing (what is returned may be filtered)
900 if ( count( $objects ) < $limit ) {
901 $after = INF
; // avoid a second RTT
903 $after = end( $objects ); // update last item
910 * Do not call this function outside of SwiftFileBackendFileList
912 * @param string $fullCont Resolved container name
913 * @param string $dir Resolved storage directory with no trailing slash
914 * @param string|null $after Resolved container relative path of file to list items after
915 * @param int $limit Max number of items to list
916 * @param array $params Parameters for getDirectoryList()
917 * @return array List of resolved container relative paths of files under $dir
918 * @throws FileBackendError
920 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
921 $files = array(); // list of (path, stat array or null) entries
922 if ( $after === INF
) {
923 return $files; // nothing more
926 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
928 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
929 // $objects will contain a list of unfiltered names or CF_Object items
930 // Non-recursive: only list files right under $dir
931 if ( !empty( $params['topOnly'] ) ) {
932 if ( !empty( $params['adviseStat'] ) ) {
933 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
935 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
938 // Recursive: list all files under $dir and its subdirs
939 if ( !empty( $params['adviseStat'] ) ) {
940 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
942 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
946 // Reformat this list into a list of (name, stat array or null) entries
947 if ( !$status->isOk() ) {
948 return $files; // error
951 $objects = $status->value
;
952 $files = $this->buildFileObjectListing( $params, $dir, $objects );
954 // Page on the unfiltered object listing (what is returned may be filtered)
955 if ( count( $objects ) < $limit ) {
956 $after = INF
; // avoid a second RTT
958 $after = end( $objects ); // update last item
959 $after = is_object( $after ) ?
$after->name
: $after;
966 * Build a list of file objects, filtering out any directories
967 * and extracting any stat info if provided in $objects (for CF_Objects)
969 * @param array $params Parameters for getDirectoryList()
970 * @param string $dir Resolved container directory path
971 * @param array $objects List of CF_Object items or object names
972 * @return array List of (names,stat array or null) entries
974 private function buildFileObjectListing( array $params, $dir, array $objects ) {
976 foreach ( $objects as $object ) {
977 if ( is_object( $object ) ) {
978 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
979 continue; // virtual directory entry; ignore
982 // Convert various random Swift dates to TS_MW
983 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
984 'size' => (int)$object->bytes
,
986 // Note: manifiest ETags are not an MD5 of the file
987 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
988 'latest' => false // eventually consistent
990 $names[] = array( $object->name
, $stat );
991 } elseif ( substr( $object, -1 ) !== '/' ) {
992 // Omit directories, which end in '/' in listings
993 $names[] = array( $object, null );
1001 * Do not call this function outside of SwiftFileBackendFileList
1003 * @param string $path Storage path
1004 * @param array $val Stat value
1006 public function loadListingStatInternal( $path, array $val ) {
1007 $this->cheapCache
->set( $path, 'stat', $val );
1010 protected function doGetFileXAttributes( array $params ) {
1011 $stat = $this->getFileStat( $params );
1013 if ( !isset( $stat['xattr'] ) ) {
1014 // Stat entries filled by file listings don't include metadata/headers
1015 $this->clearCache( array( $params['src'] ) );
1016 $stat = $this->getFileStat( $params );
1019 return $stat['xattr'];
1025 protected function doGetFileSha1base36( array $params ) {
1026 $stat = $this->getFileStat( $params );
1028 if ( !isset( $stat['sha1'] ) ) {
1029 // Stat entries filled by file listings don't include SHA1
1030 $this->clearCache( array( $params['src'] ) );
1031 $stat = $this->getFileStat( $params );
1034 return $stat['sha1'];
1040 protected function doStreamFile( array $params ) {
1041 $status = Status
::newGood();
1043 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1044 if ( $srcRel === null ) {
1045 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1048 $auth = $this->getAuthentication();
1049 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1050 $status->fatal( 'backend-fail-stream', $params['src'] );
1055 $handle = fopen( 'php://output', 'wb' );
1057 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1059 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1060 'headers' => $this->authTokenHeaders( $auth )
1061 +
$this->headersFromParams( $params ),
1062 'stream' => $handle,
1065 if ( $rcode >= 200 && $rcode <= 299 ) {
1067 } elseif ( $rcode === 404 ) {
1068 $status->fatal( 'backend-fail-stream', $params['src'] );
1070 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1076 protected function doGetLocalCopyMulti( array $params ) {
1077 $tmpFiles = array();
1079 $auth = $this->getAuthentication();
1081 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1082 // Blindly create tmp files and stream to them, catching any exception if the file does
1083 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1084 $reqs = array(); // (path => op)
1086 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1087 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1088 if ( $srcRel === null ||
!$auth ) {
1089 $tmpFiles[$path] = null;
1092 // Get source file extension
1093 $ext = FileBackend
::extensionFromPath( $path );
1094 // Create a new temporary file...
1095 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1097 $handle = fopen( $tmpFile->getPath(), 'wb' );
1099 $reqs[$path] = array(
1101 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1102 'headers' => $this->authTokenHeaders( $auth )
1103 +
$this->headersFromParams( $params ),
1104 'stream' => $handle,
1110 $tmpFiles[$path] = $tmpFile;
1113 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1114 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1115 $reqs = $this->http
->runMulti( $reqs, $opts );
1116 foreach ( $reqs as $path => $op ) {
1117 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1118 fclose( $op['stream'] ); // close open handle
1119 if ( $rcode >= 200 && $rcode <= 299 ) {
1120 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1121 // Double check that the disk is not full/broken
1122 if ( $size != $rhdrs['content-length'] ) {
1123 $tmpFiles[$path] = null;
1124 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1125 $this->onError( null, __METHOD__
,
1126 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1128 // Set the file stat process cache in passing
1129 $stat = $this->getStatFromHeaders( $rhdrs );
1130 $stat['latest'] = $isLatest;
1131 $this->cheapCache
->set( $path, 'stat', $stat );
1132 } elseif ( $rcode === 404 ) {
1133 $tmpFiles[$path] = false;
1135 $tmpFiles[$path] = null;
1136 $this->onError( null, __METHOD__
,
1137 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1144 public function getFileHttpUrl( array $params ) {
1145 if ( $this->swiftTempUrlKey
!= '' ||
1146 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1148 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1149 if ( $srcRel === null ) {
1150 return null; // invalid path
1153 $auth = $this->getAuthentication();
1158 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1159 $expires = time() +
$ttl;
1161 if ( $this->swiftTempUrlKey
!= '' ) {
1162 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1163 // Swift wants the signature based on the unencoded object name
1164 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1165 $signature = hash_hmac( 'sha1',
1166 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1167 $this->swiftTempUrlKey
1170 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1171 } else { // give S3 API URL for rgw
1172 // Path for signature starts with the bucket
1173 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1174 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1175 // Calculate the hash
1176 $signature = base64_encode( hash_hmac(
1178 "GET\n\n\n{$expires}\n{$spath}",
1179 $this->rgwS3SecretKey
,
1182 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1183 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1184 return wfAppendQuery(
1185 str_replace( '/swift/v1', '', // S3 API is the rgw default
1186 $this->storageUrl( $auth ) . $spath ),
1188 'Signature' => $signature,
1189 'Expires' => $expires,
1190 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1198 protected function directoriesAreVirtual() {
1203 * Get headers to send to Swift when reading a file based
1204 * on a FileBackend params array, e.g. that of getLocalCopy().
1205 * $params is currently only checked for a 'latest' flag.
1207 * @param array $params
1210 protected function headersFromParams( array $params ) {
1212 if ( !empty( $params['latest'] ) ) {
1213 $hdrs['x-newest'] = 'true';
1220 * @param FileBackendStoreOpHandle[] $fileOpHandles
1224 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1225 $statuses = array();
1227 $auth = $this->getAuthentication();
1229 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1230 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1236 // Split the HTTP requests into stages that can be done concurrently
1237 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1238 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1239 $reqs = $fileOpHandle->httpOp
;
1240 // Convert the 'url' parameter to an actual URL using $auth
1241 foreach ( $reqs as $stage => &$req ) {
1242 list( $container, $relPath ) = $req['url'];
1243 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1244 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1245 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1246 $httpReqsByStage[$stage][$index] = $req;
1248 $statuses[$index] = Status
::newGood();
1251 // Run all requests for the first stage, then the next, and so on
1252 $reqCount = count( $httpReqsByStage );
1253 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1254 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1255 foreach ( $httpReqs as $index => $httpReq ) {
1256 // Run the callback for each request of this operation
1257 $callback = $fileOpHandles[$index]->callback
;
1258 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1259 // On failure, abort all remaining requests for this operation
1260 // (e.g. abort the DELETE request if the COPY request fails for a move)
1261 if ( !$statuses[$index]->isOK() ) {
1262 $stages = count( $fileOpHandles[$index]->httpOp
);
1263 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1264 unset( $httpReqsByStage[$s][$index] );
1274 * Set read/write permissions for a Swift container.
1276 * @see http://swift.openstack.org/misc.html#acls
1278 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1279 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1281 * @param string $container Resolved Swift container
1282 * @param array $readGrps List of the possible criteria for a request to have
1283 * access to read a container. Each item is one of the following formats:
1284 * - account:user : Grants access if the request is by the given user
1285 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1286 * matches the expression and the request is not for a listing.
1287 * Setting this to '*' effectively makes a container public.
1288 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1289 * matches the expression and the request is for a listing.
1290 * @param array $writeGrps A list of the possible criteria for a request to have
1291 * access to write to a container. Each item is of the following format:
1292 * - account:user : Grants access if the request is by the given user
1295 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1296 $status = Status
::newGood();
1297 $auth = $this->getAuthentication();
1300 $status->fatal( 'backend-fail-connect', $this->name
);
1305 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1307 'url' => $this->storageUrl( $auth, $container ),
1308 'headers' => $this->authTokenHeaders( $auth ) +
array(
1309 'x-container-read' => implode( ',', $readGrps ),
1310 'x-container-write' => implode( ',', $writeGrps )
1314 if ( $rcode != 204 && $rcode !== 202 ) {
1315 $status->fatal( 'backend-fail-internal', $this->name
);
1316 wfDebugLog( 'SwiftBackend', __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1323 * Get a Swift container stat array, possibly from process cache.
1324 * Use $reCache if the file count or byte count is needed.
1326 * @param string $container Container name
1327 * @param bool $bypassCache Bypass all caches and load from Swift
1328 * @return array|bool|null False on 404, null on failure
1330 protected function getContainerStat( $container, $bypassCache = false ) {
1331 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1333 if ( $bypassCache ) { // purge cache
1334 $this->containerStatCache
->clear( $container );
1335 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1336 $this->primeContainerCache( array( $container ) ); // check persistent cache
1338 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1339 $auth = $this->getAuthentication();
1344 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1346 'url' => $this->storageUrl( $auth, $container ),
1347 'headers' => $this->authTokenHeaders( $auth )
1350 if ( $rcode === 204 ) {
1352 'count' => $rhdrs['x-container-object-count'],
1353 'bytes' => $rhdrs['x-container-bytes-used']
1355 if ( $bypassCache ) {
1358 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1359 $this->setContainerCache( $container, $stat ); // update persistent cache
1361 } elseif ( $rcode === 404 ) {
1364 $this->onError( null, __METHOD__
,
1365 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1371 return $this->containerStatCache
->get( $container, 'stat' );
1375 * Create a Swift container
1377 * @param string $container Container name
1378 * @param array $params
1381 protected function createContainer( $container, array $params ) {
1382 $status = Status
::newGood();
1384 $auth = $this->getAuthentication();
1386 $status->fatal( 'backend-fail-connect', $this->name
);
1391 // @see SwiftFileBackend::setContainerAccess()
1392 if ( empty( $params['noAccess'] ) ) {
1393 $readGrps = array( '.r:*', $this->swiftUser
); // public
1395 $readGrps = array( $this->swiftUser
); // private
1397 $writeGrps = array( $this->swiftUser
); // sanity
1399 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1401 'url' => $this->storageUrl( $auth, $container ),
1402 'headers' => $this->authTokenHeaders( $auth ) +
array(
1403 'x-container-read' => implode( ',', $readGrps ),
1404 'x-container-write' => implode( ',', $writeGrps )
1408 if ( $rcode === 201 ) { // new
1410 } elseif ( $rcode === 202 ) { // already there
1411 // this shouldn't really happen, but is OK
1413 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1420 * Delete a Swift container
1422 * @param string $container Container name
1423 * @param array $params
1426 protected function deleteContainer( $container, array $params ) {
1427 $status = Status
::newGood();
1429 $auth = $this->getAuthentication();
1431 $status->fatal( 'backend-fail-connect', $this->name
);
1436 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1437 'method' => 'DELETE',
1438 'url' => $this->storageUrl( $auth, $container ),
1439 'headers' => $this->authTokenHeaders( $auth )
1442 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1443 $this->containerStatCache
->clear( $container ); // purge
1444 } elseif ( $rcode === 404 ) { // not there
1445 // this shouldn't really happen, but is OK
1446 } elseif ( $rcode === 409 ) { // not empty
1447 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1449 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1456 * Get a list of objects under a container.
1457 * Either just the names or a list of stdClass objects with details can be returned.
1459 * @param string $fullCont
1460 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1462 * @param string|null $after
1463 * @param string|null $prefix
1464 * @param string|null $delim
1465 * @return Status With the list as value
1467 private function objectListing(
1468 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1470 $status = Status
::newGood();
1472 $auth = $this->getAuthentication();
1474 $status->fatal( 'backend-fail-connect', $this->name
);
1479 $query = array( 'limit' => $limit );
1480 if ( $type === 'info' ) {
1481 $query['format'] = 'json';
1483 if ( $after !== null ) {
1484 $query['marker'] = $after;
1486 if ( $prefix !== null ) {
1487 $query['prefix'] = $prefix;
1489 if ( $delim !== null ) {
1490 $query['delimiter'] = $delim;
1493 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1495 'url' => $this->storageUrl( $auth, $fullCont ),
1497 'headers' => $this->authTokenHeaders( $auth )
1500 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1501 if ( $rcode === 200 ) { // good
1502 if ( $type === 'info' ) {
1503 $status->value
= FormatJson
::decode( trim( $rbody ) );
1505 $status->value
= explode( "\n", trim( $rbody ) );
1507 } elseif ( $rcode === 204 ) {
1508 $status->value
= array(); // empty container
1509 } elseif ( $rcode === 404 ) {
1510 $status->value
= array(); // no container
1512 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1518 protected function doPrimeContainerCache( array $containerInfo ) {
1519 foreach ( $containerInfo as $container => $info ) {
1520 $this->containerStatCache
->set( $container, 'stat', $info );
1524 protected function doGetFileStatMulti( array $params ) {
1527 $auth = $this->getAuthentication();
1530 foreach ( $params['srcs'] as $path ) {
1531 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1532 if ( $srcRel === null ) {
1533 $stats[$path] = false;
1534 continue; // invalid storage path
1535 } elseif ( !$auth ) {
1536 $stats[$path] = null;
1540 // (a) Check the container
1541 $cstat = $this->getContainerStat( $srcCont );
1542 if ( $cstat === false ) {
1543 $stats[$path] = false;
1544 continue; // ok, nothing to do
1545 } elseif ( !is_array( $cstat ) ) {
1546 $stats[$path] = null;
1550 $reqs[$path] = array(
1552 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1553 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1557 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1558 $reqs = $this->http
->runMulti( $reqs, $opts );
1560 foreach ( $params['srcs'] as $path ) {
1561 if ( array_key_exists( $path, $stats ) ) {
1562 continue; // some sort of failure above
1564 // (b) Check the file
1565 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1566 if ( $rcode === 200 ||
$rcode === 204 ) {
1567 // Update the object if it is missing some headers
1568 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1569 // Load the stat array from the headers
1570 $stat = $this->getStatFromHeaders( $rhdrs );
1571 if ( $this->isRGW
) {
1572 $stat['latest'] = true; // strong consistency
1574 } elseif ( $rcode === 404 ) {
1578 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1580 $stats[$path] = $stat;
1587 * @param array $rhdrs
1590 protected function getStatFromHeaders( array $rhdrs ) {
1591 // Fetch all of the custom metadata headers
1592 $metadata = $this->getMetadata( $rhdrs );
1593 // Fetch all of the custom raw HTTP headers
1594 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1597 // Convert various random Swift dates to TS_MW
1598 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1599 // Empty objects actually return no content-length header in Ceph
1600 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1601 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1602 // Note: manifiest ETags are not an MD5 of the file
1603 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1604 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1609 * @return array|null Credential map
1611 protected function getAuthentication() {
1612 if ( $this->authErrorTimestamp
!== null ) {
1613 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1614 return null; // failed last attempt; don't bother
1615 } else { // actually retry this time
1616 $this->authErrorTimestamp
= null;
1619 // Session keys expire after a while, so we renew them periodically
1620 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1621 // Authenticate with proxy and get a session key...
1622 if ( !$this->authCreds ||
$reAuth ) {
1623 $this->authSessionTimestamp
= 0;
1624 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1625 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1626 // Try to use the credential cache
1627 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1628 $this->authCreds
= $creds;
1629 // Skew the timestamp for worst case to avoid using stale credentials
1630 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1631 } else { // cache miss
1632 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1634 'url' => "{$this->swiftAuthUrl}/v1.0",
1636 'x-auth-user' => $this->swiftUser
,
1637 'x-auth-key' => $this->swiftKey
1641 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1642 $this->authCreds
= array(
1643 'auth_token' => $rhdrs['x-auth-token'],
1644 'storage_url' => $rhdrs['x-storage-url']
1646 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1647 $this->authSessionTimestamp
= time();
1648 } elseif ( $rcode === 401 ) {
1649 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1650 $this->authErrorTimestamp
= time();
1654 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1655 $this->authErrorTimestamp
= time();
1660 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1661 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1662 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1666 return $this->authCreds
;
1670 * @param array $creds From getAuthentication()
1671 * @param string $container
1672 * @param string $object
1675 protected function storageUrl( array $creds, $container = null, $object = null ) {
1676 $parts = array( $creds['storage_url'] );
1677 if ( strlen( $container ) ) {
1678 $parts[] = rawurlencode( $container );
1680 if ( strlen( $object ) ) {
1681 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1684 return implode( '/', $parts );
1688 * @param array $creds From getAuthentication()
1691 protected function authTokenHeaders( array $creds ) {
1692 return array( 'x-auth-token' => $creds['auth_token'] );
1696 * Get the cache key for a container
1698 * @param string $username
1701 private function getCredsCacheKey( $username ) {
1702 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1706 * Log an unexpected exception for this backend.
1707 * This also sets the Status object to have a fatal error.
1709 * @param Status|null $status
1710 * @param string $func
1711 * @param array $params
1712 * @param string $err Error string
1713 * @param int $code HTTP status
1714 * @param string $desc HTTP status description
1716 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1717 if ( $status instanceof Status
) {
1718 $status->fatal( 'backend-fail-internal', $this->name
);
1720 if ( $code == 401 ) { // possibly a stale token
1721 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1723 wfDebugLog( 'SwiftBackend',
1724 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1725 ( $err ?
": $err" : "" )
1731 * @see FileBackendStoreOpHandle
1733 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1734 /** @var array List of Requests for MultiHttpClient */
1740 * @param SwiftFileBackend $backend
1741 * @param Closure $callback Function that takes (HTTP request array, status)
1742 * @param array $httpOp MultiHttpClient op
1744 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1745 $this->backend
= $backend;
1746 $this->callback
= $callback;
1747 $this->httpOp
= $httpOp;
1752 * SwiftFileBackend helper class to page through listings.
1753 * Swift also has a listing limit of 10,000 objects for sanity.
1754 * Do not use this class from places outside SwiftFileBackend.
1756 * @ingroup FileBackend
1758 abstract class SwiftFileBackendList
implements Iterator
{
1759 /** @var array List of path or (path,stat array) entries */
1760 protected $bufferIter = array();
1762 /** @var string List items *after* this path */
1763 protected $bufferAfter = null;
1769 protected $params = array();
1771 /** @var SwiftFileBackend */
1774 /** @var string Container name */
1775 protected $container;
1777 /** @var string Storage directory */
1781 protected $suffixStart;
1783 const PAGE_SIZE
= 9000; // file listing buffer size
1786 * @param SwiftFileBackend $backend
1787 * @param string $fullCont Resolved container name
1788 * @param string $dir Resolved directory relative to container
1789 * @param array $params
1791 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1792 $this->backend
= $backend;
1793 $this->container
= $fullCont;
1795 if ( substr( $this->dir
, -1 ) === '/' ) {
1796 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1798 if ( $this->dir
== '' ) { // whole container
1799 $this->suffixStart
= 0;
1800 } else { // dir within container
1801 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1803 $this->params
= $params;
1807 * @see Iterator::key()
1810 public function key() {
1815 * @see Iterator::next()
1817 public function next() {
1818 // Advance to the next file in the page
1819 next( $this->bufferIter
);
1821 // Check if there are no files left in this page and
1822 // advance to the next page if this page was not empty.
1823 if ( !$this->valid() && count( $this->bufferIter
) ) {
1824 $this->bufferIter
= $this->pageFromList(
1825 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1826 ); // updates $this->bufferAfter
1831 * @see Iterator::rewind()
1833 public function rewind() {
1835 $this->bufferAfter
= null;
1836 $this->bufferIter
= $this->pageFromList(
1837 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1838 ); // updates $this->bufferAfter
1842 * @see Iterator::valid()
1845 public function valid() {
1846 if ( $this->bufferIter
=== null ) {
1847 return false; // some failure?
1849 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1854 * Get the given list portion (page)
1856 * @param string $container Resolved container name
1857 * @param string $dir Resolved path relative to container
1858 * @param string $after
1860 * @param array $params
1861 * @return Traversable|array
1863 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1867 * Iterator for listing directories
1869 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1871 * @see Iterator::current()
1872 * @return string|bool String (relative path) or false
1874 public function current() {
1875 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1878 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1879 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1884 * Iterator for listing regular files
1886 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1888 * @see Iterator::current()
1889 * @return string|bool String (relative path) or false
1891 public function current() {
1892 list( $path, $stat ) = current( $this->bufferIter
);
1893 $relPath = substr( $path, $this->suffixStart
);
1894 if ( is_array( $stat ) ) {
1895 $storageDir = rtrim( $this->params
['dir'], '/' );
1896 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1902 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1903 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );