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 // Preferrably memcached
140 $this->srvCache
= ObjectCache
::getLocalClusterInstance();
142 // Look for APC, XCache, WinCache, ect...
143 $this->srvCache
= ObjectCache
::newAccelerator( CACHE_NONE
);
146 $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 // Find prior custom HTTP headers
720 $postHeaders = $this->getCustomHeaders( $objHdrs );
721 // Find prior metadata headers
722 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
724 $status = Status
::newGood();
725 /** @noinspection PhpUnusedLocalVariableInspection */
726 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
727 if ( $status->isOK() ) {
728 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
730 $hash = $tmpFile->getSha1Base36();
731 if ( $hash !== false ) {
732 $objHdrs['x-object-meta-sha1base36'] = $hash;
733 // Merge new SHA1 header into the old ones
734 $postHeaders['x-object-meta-sha1base36'] = $hash;
735 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
736 list( $rcode ) = $this->http
->run( array(
738 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
739 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
741 if ( $rcode >= 200 && $rcode <= 299 ) {
742 $this->deleteFileCache( $path );
744 return $objHdrs; // success
750 wfDebugLog( 'SwiftBackend', __METHOD__
. ": unable to set SHA-1 metadata for $path" );
752 return $objHdrs; // failed
755 protected function doGetFileContentsMulti( array $params ) {
758 $auth = $this->getAuthentication();
760 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
761 // Blindly create tmp files and stream to them, catching any exception if the file does
762 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
763 $reqs = array(); // (path => op)
765 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
766 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
767 if ( $srcRel === null ||
!$auth ) {
768 $contents[$path] = false;
771 // Create a new temporary memory file...
772 $handle = fopen( 'php://temp', 'wb' );
774 $reqs[$path] = array(
776 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
777 'headers' => $this->authTokenHeaders( $auth )
778 +
$this->headersFromParams( $params ),
782 $contents[$path] = false;
785 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
786 $reqs = $this->http
->runMulti( $reqs, $opts );
787 foreach ( $reqs as $path => $op ) {
788 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
789 if ( $rcode >= 200 && $rcode <= 299 ) {
790 rewind( $op['stream'] ); // start from the beginning
791 $contents[$path] = stream_get_contents( $op['stream'] );
792 } elseif ( $rcode === 404 ) {
793 $contents[$path] = false;
795 $this->onError( null, __METHOD__
,
796 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
798 fclose( $op['stream'] ); // close open handle
804 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
805 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
806 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
807 if ( $status->isOk() ) {
808 return ( count( $status->value
) ) > 0;
811 return null; // error
815 * @see FileBackendStore::getDirectoryListInternal()
816 * @param string $fullCont
818 * @param array $params
819 * @return SwiftFileBackendDirList
821 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
822 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
826 * @see FileBackendStore::getFileListInternal()
827 * @param string $fullCont
829 * @param array $params
830 * @return SwiftFileBackendFileList
832 public function getFileListInternal( $fullCont, $dir, array $params ) {
833 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
837 * Do not call this function outside of SwiftFileBackendFileList
839 * @param string $fullCont Resolved container name
840 * @param string $dir Resolved storage directory with no trailing slash
841 * @param string|null $after Resolved container relative path to list items after
842 * @param int $limit Max number of items to list
843 * @param array $params Parameters for getDirectoryList()
844 * @return array List of container relative resolved paths of directories directly under $dir
845 * @throws FileBackendError
847 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
849 if ( $after === INF
) {
850 return $dirs; // nothing more
853 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
855 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
856 // Non-recursive: only list dirs right under $dir
857 if ( !empty( $params['topOnly'] ) ) {
858 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
859 if ( !$status->isOk() ) {
860 return $dirs; // error
862 $objects = $status->value
;
863 foreach ( $objects as $object ) { // files and directories
864 if ( substr( $object, -1 ) === '/' ) {
865 $dirs[] = $object; // directories end in '/'
869 // Recursive: list all dirs under $dir and its subdirs
870 $getParentDir = function ( $path ) {
871 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
874 // Get directory from last item of prior page
875 $lastDir = $getParentDir( $after ); // must be first page
876 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
878 if ( !$status->isOk() ) {
879 return $dirs; // error
882 $objects = $status->value
;
884 foreach ( $objects as $object ) { // files
885 $objectDir = $getParentDir( $object ); // directory of object
887 if ( $objectDir !== false && $objectDir !== $dir ) {
888 // Swift stores paths in UTF-8, using binary sorting.
889 // See function "create_container_table" in common/db.py.
890 // If a directory is not "greater" than the last one,
891 // then it was already listed by the calling iterator.
892 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
894 do { // add dir and all its parent dirs
895 $dirs[] = "{$pDir}/";
896 $pDir = $getParentDir( $pDir );
897 } while ( $pDir !== false // sanity
898 && strcmp( $pDir, $lastDir ) > 0 // not done already
899 && strlen( $pDir ) > strlen( $dir ) // within $dir
902 $lastDir = $objectDir;
906 // Page on the unfiltered directory listing (what is returned may be filtered)
907 if ( count( $objects ) < $limit ) {
908 $after = INF
; // avoid a second RTT
910 $after = end( $objects ); // update last item
917 * Do not call this function outside of SwiftFileBackendFileList
919 * @param string $fullCont Resolved container name
920 * @param string $dir Resolved storage directory with no trailing slash
921 * @param string|null $after Resolved container relative path of file to list items after
922 * @param int $limit Max number of items to list
923 * @param array $params Parameters for getDirectoryList()
924 * @return array List of resolved container relative paths of files under $dir
925 * @throws FileBackendError
927 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
928 $files = array(); // list of (path, stat array or null) entries
929 if ( $after === INF
) {
930 return $files; // nothing more
933 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
935 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
936 // $objects will contain a list of unfiltered names or CF_Object items
937 // Non-recursive: only list files right under $dir
938 if ( !empty( $params['topOnly'] ) ) {
939 if ( !empty( $params['adviseStat'] ) ) {
940 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
942 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
945 // Recursive: list all files under $dir and its subdirs
946 if ( !empty( $params['adviseStat'] ) ) {
947 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
949 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
953 // Reformat this list into a list of (name, stat array or null) entries
954 if ( !$status->isOk() ) {
955 return $files; // error
958 $objects = $status->value
;
959 $files = $this->buildFileObjectListing( $params, $dir, $objects );
961 // Page on the unfiltered object listing (what is returned may be filtered)
962 if ( count( $objects ) < $limit ) {
963 $after = INF
; // avoid a second RTT
965 $after = end( $objects ); // update last item
966 $after = is_object( $after ) ?
$after->name
: $after;
973 * Build a list of file objects, filtering out any directories
974 * and extracting any stat info if provided in $objects (for CF_Objects)
976 * @param array $params Parameters for getDirectoryList()
977 * @param string $dir Resolved container directory path
978 * @param array $objects List of CF_Object items or object names
979 * @return array List of (names,stat array or null) entries
981 private function buildFileObjectListing( array $params, $dir, array $objects ) {
983 foreach ( $objects as $object ) {
984 if ( is_object( $object ) ) {
985 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
986 continue; // virtual directory entry; ignore
989 // Convert various random Swift dates to TS_MW
990 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
991 'size' => (int)$object->bytes
,
993 // Note: manifiest ETags are not an MD5 of the file
994 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
995 'latest' => false // eventually consistent
997 $names[] = array( $object->name
, $stat );
998 } elseif ( substr( $object, -1 ) !== '/' ) {
999 // Omit directories, which end in '/' in listings
1000 $names[] = array( $object, null );
1008 * Do not call this function outside of SwiftFileBackendFileList
1010 * @param string $path Storage path
1011 * @param array $val Stat value
1013 public function loadListingStatInternal( $path, array $val ) {
1014 $this->cheapCache
->set( $path, 'stat', $val );
1017 protected function doGetFileXAttributes( array $params ) {
1018 $stat = $this->getFileStat( $params );
1020 if ( !isset( $stat['xattr'] ) ) {
1021 // Stat entries filled by file listings don't include metadata/headers
1022 $this->clearCache( array( $params['src'] ) );
1023 $stat = $this->getFileStat( $params );
1026 return $stat['xattr'];
1032 protected function doGetFileSha1base36( array $params ) {
1033 $stat = $this->getFileStat( $params );
1035 if ( !isset( $stat['sha1'] ) ) {
1036 // Stat entries filled by file listings don't include SHA1
1037 $this->clearCache( array( $params['src'] ) );
1038 $stat = $this->getFileStat( $params );
1041 return $stat['sha1'];
1047 protected function doStreamFile( array $params ) {
1048 $status = Status
::newGood();
1050 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1051 if ( $srcRel === null ) {
1052 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1055 $auth = $this->getAuthentication();
1056 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1057 $status->fatal( 'backend-fail-stream', $params['src'] );
1062 $handle = fopen( 'php://output', 'wb' );
1064 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1066 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1067 'headers' => $this->authTokenHeaders( $auth )
1068 +
$this->headersFromParams( $params ),
1069 'stream' => $handle,
1072 if ( $rcode >= 200 && $rcode <= 299 ) {
1074 } elseif ( $rcode === 404 ) {
1075 $status->fatal( 'backend-fail-stream', $params['src'] );
1077 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1083 protected function doGetLocalCopyMulti( array $params ) {
1084 $tmpFiles = array();
1086 $auth = $this->getAuthentication();
1088 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1089 // Blindly create tmp files and stream to them, catching any exception if the file does
1090 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1091 $reqs = array(); // (path => op)
1093 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1094 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1095 if ( $srcRel === null ||
!$auth ) {
1096 $tmpFiles[$path] = null;
1099 // Get source file extension
1100 $ext = FileBackend
::extensionFromPath( $path );
1101 // Create a new temporary file...
1102 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1104 $handle = fopen( $tmpFile->getPath(), 'wb' );
1106 $reqs[$path] = array(
1108 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1109 'headers' => $this->authTokenHeaders( $auth )
1110 +
$this->headersFromParams( $params ),
1111 'stream' => $handle,
1117 $tmpFiles[$path] = $tmpFile;
1120 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1121 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1122 $reqs = $this->http
->runMulti( $reqs, $opts );
1123 foreach ( $reqs as $path => $op ) {
1124 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1125 fclose( $op['stream'] ); // close open handle
1126 if ( $rcode >= 200 && $rcode <= 299 ) {
1127 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1128 // Double check that the disk is not full/broken
1129 if ( $size != $rhdrs['content-length'] ) {
1130 $tmpFiles[$path] = null;
1131 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1132 $this->onError( null, __METHOD__
,
1133 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1135 // Set the file stat process cache in passing
1136 $stat = $this->getStatFromHeaders( $rhdrs );
1137 $stat['latest'] = $isLatest;
1138 $this->cheapCache
->set( $path, 'stat', $stat );
1139 } elseif ( $rcode === 404 ) {
1140 $tmpFiles[$path] = false;
1142 $tmpFiles[$path] = null;
1143 $this->onError( null, __METHOD__
,
1144 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1151 public function getFileHttpUrl( array $params ) {
1152 if ( $this->swiftTempUrlKey
!= '' ||
1153 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1155 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1156 if ( $srcRel === null ) {
1157 return null; // invalid path
1160 $auth = $this->getAuthentication();
1165 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1166 $expires = time() +
$ttl;
1168 if ( $this->swiftTempUrlKey
!= '' ) {
1169 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1170 // Swift wants the signature based on the unencoded object name
1171 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1172 $signature = hash_hmac( 'sha1',
1173 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1174 $this->swiftTempUrlKey
1177 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1178 } else { // give S3 API URL for rgw
1179 // Path for signature starts with the bucket
1180 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1181 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1182 // Calculate the hash
1183 $signature = base64_encode( hash_hmac(
1185 "GET\n\n\n{$expires}\n{$spath}",
1186 $this->rgwS3SecretKey
,
1189 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1190 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1191 return wfAppendQuery(
1192 str_replace( '/swift/v1', '', // S3 API is the rgw default
1193 $this->storageUrl( $auth ) . $spath ),
1195 'Signature' => $signature,
1196 'Expires' => $expires,
1197 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1205 protected function directoriesAreVirtual() {
1210 * Get headers to send to Swift when reading a file based
1211 * on a FileBackend params array, e.g. that of getLocalCopy().
1212 * $params is currently only checked for a 'latest' flag.
1214 * @param array $params
1217 protected function headersFromParams( array $params ) {
1219 if ( !empty( $params['latest'] ) ) {
1220 $hdrs['x-newest'] = 'true';
1227 * @param FileBackendStoreOpHandle[] $fileOpHandles
1231 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1232 $statuses = array();
1234 $auth = $this->getAuthentication();
1236 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1237 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1243 // Split the HTTP requests into stages that can be done concurrently
1244 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1245 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1246 $reqs = $fileOpHandle->httpOp
;
1247 // Convert the 'url' parameter to an actual URL using $auth
1248 foreach ( $reqs as $stage => &$req ) {
1249 list( $container, $relPath ) = $req['url'];
1250 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1251 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1252 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1253 $httpReqsByStage[$stage][$index] = $req;
1255 $statuses[$index] = Status
::newGood();
1258 // Run all requests for the first stage, then the next, and so on
1259 $reqCount = count( $httpReqsByStage );
1260 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1261 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1262 foreach ( $httpReqs as $index => $httpReq ) {
1263 // Run the callback for each request of this operation
1264 $callback = $fileOpHandles[$index]->callback
;
1265 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1266 // On failure, abort all remaining requests for this operation
1267 // (e.g. abort the DELETE request if the COPY request fails for a move)
1268 if ( !$statuses[$index]->isOK() ) {
1269 $stages = count( $fileOpHandles[$index]->httpOp
);
1270 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1271 unset( $httpReqsByStage[$s][$index] );
1281 * Set read/write permissions for a Swift container.
1283 * @see http://swift.openstack.org/misc.html#acls
1285 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1286 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1288 * @param string $container Resolved Swift container
1289 * @param array $readGrps List of the possible criteria for a request to have
1290 * access to read a container. Each item is one of the following formats:
1291 * - account:user : Grants access if the request is by the given user
1292 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1293 * matches the expression and the request is not for a listing.
1294 * Setting this to '*' effectively makes a container public.
1295 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1296 * matches the expression and the request is for a listing.
1297 * @param array $writeGrps A list of the possible criteria for a request to have
1298 * access to write to a container. Each item is of the following format:
1299 * - account:user : Grants access if the request is by the given user
1302 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1303 $status = Status
::newGood();
1304 $auth = $this->getAuthentication();
1307 $status->fatal( 'backend-fail-connect', $this->name
);
1312 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1314 'url' => $this->storageUrl( $auth, $container ),
1315 'headers' => $this->authTokenHeaders( $auth ) +
array(
1316 'x-container-read' => implode( ',', $readGrps ),
1317 'x-container-write' => implode( ',', $writeGrps )
1321 if ( $rcode != 204 && $rcode !== 202 ) {
1322 $status->fatal( 'backend-fail-internal', $this->name
);
1323 wfDebugLog( 'SwiftBackend', __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1330 * Get a Swift container stat array, possibly from process cache.
1331 * Use $reCache if the file count or byte count is needed.
1333 * @param string $container Container name
1334 * @param bool $bypassCache Bypass all caches and load from Swift
1335 * @return array|bool|null False on 404, null on failure
1337 protected function getContainerStat( $container, $bypassCache = false ) {
1338 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1340 if ( $bypassCache ) { // purge cache
1341 $this->containerStatCache
->clear( $container );
1342 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1343 $this->primeContainerCache( array( $container ) ); // check persistent cache
1345 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1346 $auth = $this->getAuthentication();
1351 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1353 'url' => $this->storageUrl( $auth, $container ),
1354 'headers' => $this->authTokenHeaders( $auth )
1357 if ( $rcode === 204 ) {
1359 'count' => $rhdrs['x-container-object-count'],
1360 'bytes' => $rhdrs['x-container-bytes-used']
1362 if ( $bypassCache ) {
1365 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1366 $this->setContainerCache( $container, $stat ); // update persistent cache
1368 } elseif ( $rcode === 404 ) {
1371 $this->onError( null, __METHOD__
,
1372 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1378 return $this->containerStatCache
->get( $container, 'stat' );
1382 * Create a Swift container
1384 * @param string $container Container name
1385 * @param array $params
1388 protected function createContainer( $container, array $params ) {
1389 $status = Status
::newGood();
1391 $auth = $this->getAuthentication();
1393 $status->fatal( 'backend-fail-connect', $this->name
);
1398 // @see SwiftFileBackend::setContainerAccess()
1399 if ( empty( $params['noAccess'] ) ) {
1400 $readGrps = array( '.r:*', $this->swiftUser
); // public
1402 $readGrps = array( $this->swiftUser
); // private
1404 $writeGrps = array( $this->swiftUser
); // sanity
1406 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1408 'url' => $this->storageUrl( $auth, $container ),
1409 'headers' => $this->authTokenHeaders( $auth ) +
array(
1410 'x-container-read' => implode( ',', $readGrps ),
1411 'x-container-write' => implode( ',', $writeGrps )
1415 if ( $rcode === 201 ) { // new
1417 } elseif ( $rcode === 202 ) { // already there
1418 // this shouldn't really happen, but is OK
1420 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1427 * Delete a Swift container
1429 * @param string $container Container name
1430 * @param array $params
1433 protected function deleteContainer( $container, array $params ) {
1434 $status = Status
::newGood();
1436 $auth = $this->getAuthentication();
1438 $status->fatal( 'backend-fail-connect', $this->name
);
1443 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1444 'method' => 'DELETE',
1445 'url' => $this->storageUrl( $auth, $container ),
1446 'headers' => $this->authTokenHeaders( $auth )
1449 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1450 $this->containerStatCache
->clear( $container ); // purge
1451 } elseif ( $rcode === 404 ) { // not there
1452 // this shouldn't really happen, but is OK
1453 } elseif ( $rcode === 409 ) { // not empty
1454 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1456 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1463 * Get a list of objects under a container.
1464 * Either just the names or a list of stdClass objects with details can be returned.
1466 * @param string $fullCont
1467 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1469 * @param string|null $after
1470 * @param string|null $prefix
1471 * @param string|null $delim
1472 * @return Status With the list as value
1474 private function objectListing(
1475 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1477 $status = Status
::newGood();
1479 $auth = $this->getAuthentication();
1481 $status->fatal( 'backend-fail-connect', $this->name
);
1486 $query = array( 'limit' => $limit );
1487 if ( $type === 'info' ) {
1488 $query['format'] = 'json';
1490 if ( $after !== null ) {
1491 $query['marker'] = $after;
1493 if ( $prefix !== null ) {
1494 $query['prefix'] = $prefix;
1496 if ( $delim !== null ) {
1497 $query['delimiter'] = $delim;
1500 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1502 'url' => $this->storageUrl( $auth, $fullCont ),
1504 'headers' => $this->authTokenHeaders( $auth )
1507 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1508 if ( $rcode === 200 ) { // good
1509 if ( $type === 'info' ) {
1510 $status->value
= FormatJson
::decode( trim( $rbody ) );
1512 $status->value
= explode( "\n", trim( $rbody ) );
1514 } elseif ( $rcode === 204 ) {
1515 $status->value
= array(); // empty container
1516 } elseif ( $rcode === 404 ) {
1517 $status->value
= array(); // no container
1519 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1525 protected function doPrimeContainerCache( array $containerInfo ) {
1526 foreach ( $containerInfo as $container => $info ) {
1527 $this->containerStatCache
->set( $container, 'stat', $info );
1531 protected function doGetFileStatMulti( array $params ) {
1534 $auth = $this->getAuthentication();
1537 foreach ( $params['srcs'] as $path ) {
1538 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1539 if ( $srcRel === null ) {
1540 $stats[$path] = false;
1541 continue; // invalid storage path
1542 } elseif ( !$auth ) {
1543 $stats[$path] = null;
1547 // (a) Check the container
1548 $cstat = $this->getContainerStat( $srcCont );
1549 if ( $cstat === false ) {
1550 $stats[$path] = false;
1551 continue; // ok, nothing to do
1552 } elseif ( !is_array( $cstat ) ) {
1553 $stats[$path] = null;
1557 $reqs[$path] = array(
1559 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1560 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1564 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1565 $reqs = $this->http
->runMulti( $reqs, $opts );
1567 foreach ( $params['srcs'] as $path ) {
1568 if ( array_key_exists( $path, $stats ) ) {
1569 continue; // some sort of failure above
1571 // (b) Check the file
1572 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1573 if ( $rcode === 200 ||
$rcode === 204 ) {
1574 // Update the object if it is missing some headers
1575 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1576 // Load the stat array from the headers
1577 $stat = $this->getStatFromHeaders( $rhdrs );
1578 if ( $this->isRGW
) {
1579 $stat['latest'] = true; // strong consistency
1581 } elseif ( $rcode === 404 ) {
1585 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1587 $stats[$path] = $stat;
1594 * @param array $rhdrs
1597 protected function getStatFromHeaders( array $rhdrs ) {
1598 // Fetch all of the custom metadata headers
1599 $metadata = $this->getMetadata( $rhdrs );
1600 // Fetch all of the custom raw HTTP headers
1601 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1604 // Convert various random Swift dates to TS_MW
1605 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1606 // Empty objects actually return no content-length header in Ceph
1607 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1608 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1609 // Note: manifiest ETags are not an MD5 of the file
1610 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1611 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1616 * @return array|null Credential map
1618 protected function getAuthentication() {
1619 if ( $this->authErrorTimestamp
!== null ) {
1620 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1621 return null; // failed last attempt; don't bother
1622 } else { // actually retry this time
1623 $this->authErrorTimestamp
= null;
1626 // Session keys expire after a while, so we renew them periodically
1627 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1628 // Authenticate with proxy and get a session key...
1629 if ( !$this->authCreds ||
$reAuth ) {
1630 $this->authSessionTimestamp
= 0;
1631 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1632 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1633 // Try to use the credential cache
1634 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1635 $this->authCreds
= $creds;
1636 // Skew the timestamp for worst case to avoid using stale credentials
1637 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1638 } else { // cache miss
1639 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1641 'url' => "{$this->swiftAuthUrl}/v1.0",
1643 'x-auth-user' => $this->swiftUser
,
1644 'x-auth-key' => $this->swiftKey
1648 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1649 $this->authCreds
= array(
1650 'auth_token' => $rhdrs['x-auth-token'],
1651 'storage_url' => $rhdrs['x-storage-url']
1653 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1654 $this->authSessionTimestamp
= time();
1655 } elseif ( $rcode === 401 ) {
1656 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1657 $this->authErrorTimestamp
= time();
1661 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1662 $this->authErrorTimestamp
= time();
1667 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1668 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1669 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1673 return $this->authCreds
;
1677 * @param array $creds From getAuthentication()
1678 * @param string $container
1679 * @param string $object
1682 protected function storageUrl( array $creds, $container = null, $object = null ) {
1683 $parts = array( $creds['storage_url'] );
1684 if ( strlen( $container ) ) {
1685 $parts[] = rawurlencode( $container );
1687 if ( strlen( $object ) ) {
1688 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1691 return implode( '/', $parts );
1695 * @param array $creds From getAuthentication()
1698 protected function authTokenHeaders( array $creds ) {
1699 return array( 'x-auth-token' => $creds['auth_token'] );
1703 * Get the cache key for a container
1705 * @param string $username
1708 private function getCredsCacheKey( $username ) {
1709 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1713 * Log an unexpected exception for this backend.
1714 * This also sets the Status object to have a fatal error.
1716 * @param Status|null $status
1717 * @param string $func
1718 * @param array $params
1719 * @param string $err Error string
1720 * @param int $code HTTP status
1721 * @param string $desc HTTP status description
1723 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1724 if ( $status instanceof Status
) {
1725 $status->fatal( 'backend-fail-internal', $this->name
);
1727 if ( $code == 401 ) { // possibly a stale token
1728 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1730 wfDebugLog( 'SwiftBackend',
1731 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1732 ( $err ?
": $err" : "" )
1738 * @see FileBackendStoreOpHandle
1740 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1741 /** @var array List of Requests for MultiHttpClient */
1747 * @param SwiftFileBackend $backend
1748 * @param Closure $callback Function that takes (HTTP request array, status)
1749 * @param array $httpOp MultiHttpClient op
1751 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1752 $this->backend
= $backend;
1753 $this->callback
= $callback;
1754 $this->httpOp
= $httpOp;
1759 * SwiftFileBackend helper class to page through listings.
1760 * Swift also has a listing limit of 10,000 objects for sanity.
1761 * Do not use this class from places outside SwiftFileBackend.
1763 * @ingroup FileBackend
1765 abstract class SwiftFileBackendList
implements Iterator
{
1766 /** @var array List of path or (path,stat array) entries */
1767 protected $bufferIter = array();
1769 /** @var string List items *after* this path */
1770 protected $bufferAfter = null;
1776 protected $params = array();
1778 /** @var SwiftFileBackend */
1781 /** @var string Container name */
1782 protected $container;
1784 /** @var string Storage directory */
1788 protected $suffixStart;
1790 const PAGE_SIZE
= 9000; // file listing buffer size
1793 * @param SwiftFileBackend $backend
1794 * @param string $fullCont Resolved container name
1795 * @param string $dir Resolved directory relative to container
1796 * @param array $params
1798 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1799 $this->backend
= $backend;
1800 $this->container
= $fullCont;
1802 if ( substr( $this->dir
, -1 ) === '/' ) {
1803 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1805 if ( $this->dir
== '' ) { // whole container
1806 $this->suffixStart
= 0;
1807 } else { // dir within container
1808 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1810 $this->params
= $params;
1814 * @see Iterator::key()
1817 public function key() {
1822 * @see Iterator::next()
1824 public function next() {
1825 // Advance to the next file in the page
1826 next( $this->bufferIter
);
1828 // Check if there are no files left in this page and
1829 // advance to the next page if this page was not empty.
1830 if ( !$this->valid() && count( $this->bufferIter
) ) {
1831 $this->bufferIter
= $this->pageFromList(
1832 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1833 ); // updates $this->bufferAfter
1838 * @see Iterator::rewind()
1840 public function rewind() {
1842 $this->bufferAfter
= null;
1843 $this->bufferIter
= $this->pageFromList(
1844 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1845 ); // updates $this->bufferAfter
1849 * @see Iterator::valid()
1852 public function valid() {
1853 if ( $this->bufferIter
=== null ) {
1854 return false; // some failure?
1856 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1861 * Get the given list portion (page)
1863 * @param string $container Resolved container name
1864 * @param string $dir Resolved path relative to container
1865 * @param string $after
1867 * @param array $params
1868 * @return Traversable|array
1870 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1874 * Iterator for listing directories
1876 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1878 * @see Iterator::current()
1879 * @return string|bool String (relative path) or false
1881 public function current() {
1882 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1885 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1886 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1891 * Iterator for listing regular files
1893 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1895 * @see Iterator::current()
1896 * @return string|bool String (relative path) or false
1898 public function current() {
1899 list( $path, $stat ) = current( $this->bufferIter
);
1900 $relPath = substr( $path, $this->suffixStart
);
1901 if ( is_array( $stat ) ) {
1902 $storageDir = rtrim( $this->params
['dir'], '/' );
1903 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1909 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1910 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );