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
::getLocalServerInstance( 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 = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
265 $contentType = isset( $params['headers']['content-type'] )
266 ?
$params['headers']['content-type']
267 : $this->getContentType( $params['dst'], $params['content'], null );
269 $reqs = array( array(
271 'url' => array( $dstCont, $dstRel ),
273 'content-length' => strlen( $params['content'] ),
274 'etag' => md5( $params['content'] ),
275 'content-type' => $contentType,
276 'x-object-meta-sha1base36' => $sha1Hash
277 ) +
$this->sanitizeHdrs( $params ),
278 'body' => $params['content']
282 $method = __METHOD__
;
283 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
284 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
285 if ( $rcode === 201 ) {
287 } elseif ( $rcode === 412 ) {
288 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
290 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
294 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
295 if ( !empty( $params['async'] ) ) { // deferred
296 $status->value
= $opHandle;
297 } else { // actually write the object in Swift
298 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
304 protected function doStoreInternal( array $params ) {
305 $status = Status
::newGood();
307 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
308 if ( $dstRel === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
314 MediaWiki\
suppressWarnings();
315 $sha1Hash = sha1_file( $params['src'] );
316 MediaWiki\restoreWarnings
();
317 if ( $sha1Hash === false ) { // source doesn't exist?
318 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
322 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
323 $contentType = isset( $params['headers']['content-type'] )
324 ?
$params['headers']['content-type']
325 : $this->getContentType( $params['dst'], null, $params['src'] );
327 $handle = fopen( $params['src'], 'rb' );
328 if ( $handle === false ) { // source doesn't exist?
329 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
334 $reqs = array( array(
336 'url' => array( $dstCont, $dstRel ),
338 'content-length' => filesize( $params['src'] ),
339 'etag' => md5_file( $params['src'] ),
340 'content-type' => $contentType,
341 'x-object-meta-sha1base36' => $sha1Hash
342 ) +
$this->sanitizeHdrs( $params ),
343 'body' => $handle // resource
347 $method = __METHOD__
;
348 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
349 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
350 if ( $rcode === 201 ) {
352 } elseif ( $rcode === 412 ) {
353 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
355 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
359 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
360 if ( !empty( $params['async'] ) ) { // deferred
361 $status->value
= $opHandle;
362 } else { // actually write the object in Swift
363 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
369 protected function doCopyInternal( array $params ) {
370 $status = Status
::newGood();
372 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
373 if ( $srcRel === null ) {
374 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
379 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
380 if ( $dstRel === null ) {
381 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
386 $reqs = array( array(
388 'url' => array( $dstCont, $dstRel ),
390 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
391 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
392 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
396 $method = __METHOD__
;
397 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
398 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
399 if ( $rcode === 201 ) {
401 } elseif ( $rcode === 404 ) {
402 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
404 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
408 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
409 if ( !empty( $params['async'] ) ) { // deferred
410 $status->value
= $opHandle;
411 } else { // actually write the object in Swift
412 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
418 protected function doMoveInternal( array $params ) {
419 $status = Status
::newGood();
421 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
422 if ( $srcRel === null ) {
423 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
428 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
429 if ( $dstRel === null ) {
430 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
438 'url' => array( $dstCont, $dstRel ),
440 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
441 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
442 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
445 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
447 'method' => 'DELETE',
448 'url' => array( $srcCont, $srcRel ),
454 $method = __METHOD__
;
455 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
456 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
457 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
459 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
461 } elseif ( $rcode === 404 ) {
462 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
464 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
468 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
469 if ( !empty( $params['async'] ) ) { // deferred
470 $status->value
= $opHandle;
471 } else { // actually move the object in Swift
472 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
478 protected function doDeleteInternal( array $params ) {
479 $status = Status
::newGood();
481 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
482 if ( $srcRel === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
488 $reqs = array( array(
489 'method' => 'DELETE',
490 'url' => array( $srcCont, $srcRel ),
495 $method = __METHOD__
;
496 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
497 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
498 if ( $rcode === 204 ) {
500 } elseif ( $rcode === 404 ) {
501 if ( empty( $params['ignoreMissingSource'] ) ) {
502 $status->fatal( 'backend-fail-delete', $params['src'] );
505 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
509 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
510 if ( !empty( $params['async'] ) ) { // deferred
511 $status->value
= $opHandle;
512 } else { // actually delete the object in Swift
513 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
519 protected function doDescribeInternal( array $params ) {
520 $status = Status
::newGood();
522 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
523 if ( $srcRel === null ) {
524 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
529 // Fetch the old object headers/metadata...this should be in stat cache by now
530 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
531 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
532 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
535 $status->fatal( 'backend-fail-describe', $params['src'] );
540 // POST clears prior headers, so we need to merge the changes in to the old ones
542 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
543 $metaHdrs["x-object-meta-$name"] = $value;
545 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
547 $reqs = array( array(
549 'url' => array( $srcCont, $srcRel ),
550 'headers' => $metaHdrs +
$customHdrs
554 $method = __METHOD__
;
555 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
556 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
557 if ( $rcode === 202 ) {
559 } elseif ( $rcode === 404 ) {
560 $status->fatal( 'backend-fail-describe', $params['src'] );
562 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
566 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
567 if ( !empty( $params['async'] ) ) { // deferred
568 $status->value
= $opHandle;
569 } else { // actually change the object in Swift
570 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
576 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
577 $status = Status
::newGood();
579 // (a) Check if container already exists
580 $stat = $this->getContainerStat( $fullCont );
581 if ( is_array( $stat ) ) {
582 return $status; // already there
583 } elseif ( $stat === null ) {
584 $status->fatal( 'backend-fail-internal', $this->name
);
585 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
590 // (b) Create container as needed with proper ACLs
591 if ( $stat === false ) {
592 $params['op'] = 'prepare';
593 $status->merge( $this->createContainer( $fullCont, $params ) );
599 protected function doSecureInternal( $fullCont, $dir, array $params ) {
600 $status = Status
::newGood();
601 if ( empty( $params['noAccess'] ) ) {
602 return $status; // nothing to do
605 $stat = $this->getContainerStat( $fullCont );
606 if ( is_array( $stat ) ) {
607 // Make container private to end-users...
608 $status->merge( $this->setContainerAccess(
610 array( $this->swiftUser
), // read
611 array( $this->swiftUser
) // write
613 } elseif ( $stat === false ) {
614 $status->fatal( 'backend-fail-usable', $params['dir'] );
616 $status->fatal( 'backend-fail-internal', $this->name
);
617 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
623 protected function doPublishInternal( $fullCont, $dir, array $params ) {
624 $status = Status
::newGood();
626 $stat = $this->getContainerStat( $fullCont );
627 if ( is_array( $stat ) ) {
628 // Make container public to end-users...
629 $status->merge( $this->setContainerAccess(
631 array( $this->swiftUser
, '.r:*' ), // read
632 array( $this->swiftUser
) // write
634 } elseif ( $stat === false ) {
635 $status->fatal( 'backend-fail-usable', $params['dir'] );
637 $status->fatal( 'backend-fail-internal', $this->name
);
638 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
644 protected function doCleanInternal( $fullCont, $dir, array $params ) {
645 $status = Status
::newGood();
647 // Only containers themselves can be removed, all else is virtual
649 return $status; // nothing to do
652 // (a) Check the container
653 $stat = $this->getContainerStat( $fullCont, true );
654 if ( $stat === false ) {
655 return $status; // ok, nothing to do
656 } elseif ( !is_array( $stat ) ) {
657 $status->fatal( 'backend-fail-internal', $this->name
);
658 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
663 // (b) Delete the container if empty
664 if ( $stat['count'] == 0 ) {
665 $params['op'] = 'clean';
666 $status->merge( $this->deleteContainer( $fullCont, $params ) );
672 protected function doGetFileStat( array $params ) {
673 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) +
$params;
674 unset( $params['src'] );
675 $stats = $this->doGetFileStatMulti( $params );
677 return reset( $stats );
681 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
682 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
683 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
686 * @param int $format Output format (TS_* constant)
688 * @throws FileBackendError
690 protected function convertSwiftDate( $ts, $format = TS_MW
) {
692 $timestamp = new MWTimestamp( $ts );
694 return $timestamp->getTimestamp( $format );
695 } catch ( Exception
$e ) {
696 throw new FileBackendError( $e->getMessage() );
701 * Fill in any missing object metadata and save it to Swift
703 * @param array $objHdrs Object response headers
704 * @param string $path Storage path to object
705 * @return array New headers
707 protected function addMissingMetadata( array $objHdrs, $path ) {
708 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
709 return $objHdrs; // nothing to do
712 /** @noinspection PhpUnusedLocalVariableInspection */
713 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
714 wfDebugLog( 'SwiftBackend', __METHOD__
. ": $path was not stored with SHA-1 metadata." );
716 $objHdrs['x-object-meta-sha1base36'] = false;
718 $auth = $this->getAuthentication();
720 return $objHdrs; // failed
723 // Find prior custom HTTP headers
724 $postHeaders = $this->getCustomHeaders( $objHdrs );
725 // Find prior metadata headers
726 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
728 $status = Status
::newGood();
729 /** @noinspection PhpUnusedLocalVariableInspection */
730 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
731 if ( $status->isOK() ) {
732 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
734 $hash = $tmpFile->getSha1Base36();
735 if ( $hash !== false ) {
736 $objHdrs['x-object-meta-sha1base36'] = $hash;
737 // Merge new SHA1 header into the old ones
738 $postHeaders['x-object-meta-sha1base36'] = $hash;
739 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
740 list( $rcode ) = $this->http
->run( array(
742 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
743 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
745 if ( $rcode >= 200 && $rcode <= 299 ) {
746 $this->deleteFileCache( $path );
748 return $objHdrs; // success
754 wfDebugLog( 'SwiftBackend', __METHOD__
. ": unable to set SHA-1 metadata for $path" );
756 return $objHdrs; // failed
759 protected function doGetFileContentsMulti( array $params ) {
762 $auth = $this->getAuthentication();
764 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
765 // Blindly create tmp files and stream to them, catching any exception if the file does
766 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
767 $reqs = array(); // (path => op)
769 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
770 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
771 if ( $srcRel === null ||
!$auth ) {
772 $contents[$path] = false;
775 // Create a new temporary memory file...
776 $handle = fopen( 'php://temp', 'wb' );
778 $reqs[$path] = array(
780 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
781 'headers' => $this->authTokenHeaders( $auth )
782 +
$this->headersFromParams( $params ),
786 $contents[$path] = false;
789 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
790 $reqs = $this->http
->runMulti( $reqs, $opts );
791 foreach ( $reqs as $path => $op ) {
792 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
793 if ( $rcode >= 200 && $rcode <= 299 ) {
794 rewind( $op['stream'] ); // start from the beginning
795 $contents[$path] = stream_get_contents( $op['stream'] );
796 } elseif ( $rcode === 404 ) {
797 $contents[$path] = false;
799 $this->onError( null, __METHOD__
,
800 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
802 fclose( $op['stream'] ); // close open handle
808 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
809 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
810 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
811 if ( $status->isOk() ) {
812 return ( count( $status->value
) ) > 0;
815 return null; // error
819 * @see FileBackendStore::getDirectoryListInternal()
820 * @param string $fullCont
822 * @param array $params
823 * @return SwiftFileBackendDirList
825 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
826 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
830 * @see FileBackendStore::getFileListInternal()
831 * @param string $fullCont
833 * @param array $params
834 * @return SwiftFileBackendFileList
836 public function getFileListInternal( $fullCont, $dir, array $params ) {
837 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
841 * Do not call this function outside of SwiftFileBackendFileList
843 * @param string $fullCont Resolved container name
844 * @param string $dir Resolved storage directory with no trailing slash
845 * @param string|null $after Resolved container relative path to list items after
846 * @param int $limit Max number of items to list
847 * @param array $params Parameters for getDirectoryList()
848 * @return array List of container relative resolved paths of directories directly under $dir
849 * @throws FileBackendError
851 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
853 if ( $after === INF
) {
854 return $dirs; // nothing more
857 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
859 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
860 // Non-recursive: only list dirs right under $dir
861 if ( !empty( $params['topOnly'] ) ) {
862 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
863 if ( !$status->isOk() ) {
864 throw new FileBackendError( "Iterator page I/O error: {$status->getMessage()}" );
866 $objects = $status->value
;
867 foreach ( $objects as $object ) { // files and directories
868 if ( substr( $object, -1 ) === '/' ) {
869 $dirs[] = $object; // directories end in '/'
873 // Recursive: list all dirs under $dir and its subdirs
874 $getParentDir = function ( $path ) {
875 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
878 // Get directory from last item of prior page
879 $lastDir = $getParentDir( $after ); // must be first page
880 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
882 if ( !$status->isOk() ) {
883 throw new FileBackendError( "Iterator page I/O error: {$status->getMessage()}" );
886 $objects = $status->value
;
888 foreach ( $objects as $object ) { // files
889 $objectDir = $getParentDir( $object ); // directory of object
891 if ( $objectDir !== false && $objectDir !== $dir ) {
892 // Swift stores paths in UTF-8, using binary sorting.
893 // See function "create_container_table" in common/db.py.
894 // If a directory is not "greater" than the last one,
895 // then it was already listed by the calling iterator.
896 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
898 do { // add dir and all its parent dirs
899 $dirs[] = "{$pDir}/";
900 $pDir = $getParentDir( $pDir );
901 } while ( $pDir !== false // sanity
902 && strcmp( $pDir, $lastDir ) > 0 // not done already
903 && strlen( $pDir ) > strlen( $dir ) // within $dir
906 $lastDir = $objectDir;
910 // Page on the unfiltered directory listing (what is returned may be filtered)
911 if ( count( $objects ) < $limit ) {
912 $after = INF
; // avoid a second RTT
914 $after = end( $objects ); // update last item
921 * Do not call this function outside of SwiftFileBackendFileList
923 * @param string $fullCont Resolved container name
924 * @param string $dir Resolved storage directory with no trailing slash
925 * @param string|null $after Resolved container relative path of file to list items after
926 * @param int $limit Max number of items to list
927 * @param array $params Parameters for getDirectoryList()
928 * @return array List of resolved container relative paths of files under $dir
929 * @throws FileBackendError
931 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
932 $files = array(); // list of (path, stat array or null) entries
933 if ( $after === INF
) {
934 return $files; // nothing more
937 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
939 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
940 // $objects will contain a list of unfiltered names or CF_Object items
941 // Non-recursive: only list files right under $dir
942 if ( !empty( $params['topOnly'] ) ) {
943 if ( !empty( $params['adviseStat'] ) ) {
944 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
946 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
949 // Recursive: list all files under $dir and its subdirs
950 if ( !empty( $params['adviseStat'] ) ) {
951 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
953 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
957 // Reformat this list into a list of (name, stat array or null) entries
958 if ( !$status->isOk() ) {
959 throw new FileBackendError( "Iterator page I/O error: {$status->getMessage()}" );
962 $objects = $status->value
;
963 $files = $this->buildFileObjectListing( $params, $dir, $objects );
965 // Page on the unfiltered object listing (what is returned may be filtered)
966 if ( count( $objects ) < $limit ) {
967 $after = INF
; // avoid a second RTT
969 $after = end( $objects ); // update last item
970 $after = is_object( $after ) ?
$after->name
: $after;
977 * Build a list of file objects, filtering out any directories
978 * and extracting any stat info if provided in $objects (for CF_Objects)
980 * @param array $params Parameters for getDirectoryList()
981 * @param string $dir Resolved container directory path
982 * @param array $objects List of CF_Object items or object names
983 * @return array List of (names,stat array or null) entries
985 private function buildFileObjectListing( array $params, $dir, array $objects ) {
987 foreach ( $objects as $object ) {
988 if ( is_object( $object ) ) {
989 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
990 continue; // virtual directory entry; ignore
993 // Convert various random Swift dates to TS_MW
994 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
995 'size' => (int)$object->bytes
,
997 // Note: manifiest ETags are not an MD5 of the file
998 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
999 'latest' => false // eventually consistent
1001 $names[] = array( $object->name
, $stat );
1002 } elseif ( substr( $object, -1 ) !== '/' ) {
1003 // Omit directories, which end in '/' in listings
1004 $names[] = array( $object, null );
1012 * Do not call this function outside of SwiftFileBackendFileList
1014 * @param string $path Storage path
1015 * @param array $val Stat value
1017 public function loadListingStatInternal( $path, array $val ) {
1018 $this->cheapCache
->set( $path, 'stat', $val );
1021 protected function doGetFileXAttributes( array $params ) {
1022 $stat = $this->getFileStat( $params );
1024 if ( !isset( $stat['xattr'] ) ) {
1025 // Stat entries filled by file listings don't include metadata/headers
1026 $this->clearCache( array( $params['src'] ) );
1027 $stat = $this->getFileStat( $params );
1030 return $stat['xattr'];
1036 protected function doGetFileSha1base36( array $params ) {
1037 $stat = $this->getFileStat( $params );
1039 if ( !isset( $stat['sha1'] ) ) {
1040 // Stat entries filled by file listings don't include SHA1
1041 $this->clearCache( array( $params['src'] ) );
1042 $stat = $this->getFileStat( $params );
1045 return $stat['sha1'];
1051 protected function doStreamFile( array $params ) {
1052 $status = Status
::newGood();
1054 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1055 if ( $srcRel === null ) {
1056 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1059 $auth = $this->getAuthentication();
1060 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1061 $status->fatal( 'backend-fail-stream', $params['src'] );
1066 $handle = fopen( 'php://output', 'wb' );
1068 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1070 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1071 'headers' => $this->authTokenHeaders( $auth )
1072 +
$this->headersFromParams( $params ),
1073 'stream' => $handle,
1076 if ( $rcode >= 200 && $rcode <= 299 ) {
1078 } elseif ( $rcode === 404 ) {
1079 $status->fatal( 'backend-fail-stream', $params['src'] );
1081 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1087 protected function doGetLocalCopyMulti( array $params ) {
1088 $tmpFiles = array();
1090 $auth = $this->getAuthentication();
1092 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1093 // Blindly create tmp files and stream to them, catching any exception if the file does
1094 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1095 $reqs = array(); // (path => op)
1097 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1098 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1099 if ( $srcRel === null ||
!$auth ) {
1100 $tmpFiles[$path] = null;
1103 // Get source file extension
1104 $ext = FileBackend
::extensionFromPath( $path );
1105 // Create a new temporary file...
1106 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1108 $handle = fopen( $tmpFile->getPath(), 'wb' );
1110 $reqs[$path] = array(
1112 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1113 'headers' => $this->authTokenHeaders( $auth )
1114 +
$this->headersFromParams( $params ),
1115 'stream' => $handle,
1121 $tmpFiles[$path] = $tmpFile;
1124 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1125 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1126 $reqs = $this->http
->runMulti( $reqs, $opts );
1127 foreach ( $reqs as $path => $op ) {
1128 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1129 fclose( $op['stream'] ); // close open handle
1130 if ( $rcode >= 200 && $rcode <= 299 ) {
1131 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1132 // Double check that the disk is not full/broken
1133 if ( $size != $rhdrs['content-length'] ) {
1134 $tmpFiles[$path] = null;
1135 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1136 $this->onError( null, __METHOD__
,
1137 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1139 // Set the file stat process cache in passing
1140 $stat = $this->getStatFromHeaders( $rhdrs );
1141 $stat['latest'] = $isLatest;
1142 $this->cheapCache
->set( $path, 'stat', $stat );
1143 } elseif ( $rcode === 404 ) {
1144 $tmpFiles[$path] = false;
1146 $tmpFiles[$path] = null;
1147 $this->onError( null, __METHOD__
,
1148 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1155 public function getFileHttpUrl( array $params ) {
1156 if ( $this->swiftTempUrlKey
!= '' ||
1157 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1159 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1160 if ( $srcRel === null ) {
1161 return null; // invalid path
1164 $auth = $this->getAuthentication();
1169 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1170 $expires = time() +
$ttl;
1172 if ( $this->swiftTempUrlKey
!= '' ) {
1173 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1174 // Swift wants the signature based on the unencoded object name
1175 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1176 $signature = hash_hmac( 'sha1',
1177 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1178 $this->swiftTempUrlKey
1181 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1182 } else { // give S3 API URL for rgw
1183 // Path for signature starts with the bucket
1184 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1185 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1186 // Calculate the hash
1187 $signature = base64_encode( hash_hmac(
1189 "GET\n\n\n{$expires}\n{$spath}",
1190 $this->rgwS3SecretKey
,
1193 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1194 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1195 return wfAppendQuery(
1196 str_replace( '/swift/v1', '', // S3 API is the rgw default
1197 $this->storageUrl( $auth ) . $spath ),
1199 'Signature' => $signature,
1200 'Expires' => $expires,
1201 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1209 protected function directoriesAreVirtual() {
1214 * Get headers to send to Swift when reading a file based
1215 * on a FileBackend params array, e.g. that of getLocalCopy().
1216 * $params is currently only checked for a 'latest' flag.
1218 * @param array $params
1221 protected function headersFromParams( array $params ) {
1223 if ( !empty( $params['latest'] ) ) {
1224 $hdrs['x-newest'] = 'true';
1231 * @param FileBackendStoreOpHandle[] $fileOpHandles
1235 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1236 $statuses = array();
1238 $auth = $this->getAuthentication();
1240 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1241 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1247 // Split the HTTP requests into stages that can be done concurrently
1248 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1249 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1250 $reqs = $fileOpHandle->httpOp
;
1251 // Convert the 'url' parameter to an actual URL using $auth
1252 foreach ( $reqs as $stage => &$req ) {
1253 list( $container, $relPath ) = $req['url'];
1254 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1255 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1256 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1257 $httpReqsByStage[$stage][$index] = $req;
1259 $statuses[$index] = Status
::newGood();
1262 // Run all requests for the first stage, then the next, and so on
1263 $reqCount = count( $httpReqsByStage );
1264 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1265 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1266 foreach ( $httpReqs as $index => $httpReq ) {
1267 // Run the callback for each request of this operation
1268 $callback = $fileOpHandles[$index]->callback
;
1269 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1270 // On failure, abort all remaining requests for this operation
1271 // (e.g. abort the DELETE request if the COPY request fails for a move)
1272 if ( !$statuses[$index]->isOK() ) {
1273 $stages = count( $fileOpHandles[$index]->httpOp
);
1274 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1275 unset( $httpReqsByStage[$s][$index] );
1285 * Set read/write permissions for a Swift container.
1287 * @see http://swift.openstack.org/misc.html#acls
1289 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1290 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1292 * @param string $container Resolved Swift container
1293 * @param array $readGrps List of the possible criteria for a request to have
1294 * access to read a container. Each item is one of the following formats:
1295 * - account:user : Grants access if the request is by the given user
1296 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1297 * matches the expression and the request is not for a listing.
1298 * Setting this to '*' effectively makes a container public.
1299 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1300 * matches the expression and the request is for a listing.
1301 * @param array $writeGrps A list of the possible criteria for a request to have
1302 * access to write to a container. Each item is of the following format:
1303 * - account:user : Grants access if the request is by the given user
1306 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1307 $status = Status
::newGood();
1308 $auth = $this->getAuthentication();
1311 $status->fatal( 'backend-fail-connect', $this->name
);
1316 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1318 'url' => $this->storageUrl( $auth, $container ),
1319 'headers' => $this->authTokenHeaders( $auth ) +
array(
1320 'x-container-read' => implode( ',', $readGrps ),
1321 'x-container-write' => implode( ',', $writeGrps )
1325 if ( $rcode != 204 && $rcode !== 202 ) {
1326 $status->fatal( 'backend-fail-internal', $this->name
);
1327 wfDebugLog( 'SwiftBackend', __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1334 * Get a Swift container stat array, possibly from process cache.
1335 * Use $reCache if the file count or byte count is needed.
1337 * @param string $container Container name
1338 * @param bool $bypassCache Bypass all caches and load from Swift
1339 * @return array|bool|null False on 404, null on failure
1341 protected function getContainerStat( $container, $bypassCache = false ) {
1342 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1344 if ( $bypassCache ) { // purge cache
1345 $this->containerStatCache
->clear( $container );
1346 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1347 $this->primeContainerCache( array( $container ) ); // check persistent cache
1349 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1350 $auth = $this->getAuthentication();
1355 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1357 'url' => $this->storageUrl( $auth, $container ),
1358 'headers' => $this->authTokenHeaders( $auth )
1361 if ( $rcode === 204 ) {
1363 'count' => $rhdrs['x-container-object-count'],
1364 'bytes' => $rhdrs['x-container-bytes-used']
1366 if ( $bypassCache ) {
1369 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1370 $this->setContainerCache( $container, $stat ); // update persistent cache
1372 } elseif ( $rcode === 404 ) {
1375 $this->onError( null, __METHOD__
,
1376 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1382 return $this->containerStatCache
->get( $container, 'stat' );
1386 * Create a Swift container
1388 * @param string $container Container name
1389 * @param array $params
1392 protected function createContainer( $container, array $params ) {
1393 $status = Status
::newGood();
1395 $auth = $this->getAuthentication();
1397 $status->fatal( 'backend-fail-connect', $this->name
);
1402 // @see SwiftFileBackend::setContainerAccess()
1403 if ( empty( $params['noAccess'] ) ) {
1404 $readGrps = array( '.r:*', $this->swiftUser
); // public
1406 $readGrps = array( $this->swiftUser
); // private
1408 $writeGrps = array( $this->swiftUser
); // sanity
1410 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1412 'url' => $this->storageUrl( $auth, $container ),
1413 'headers' => $this->authTokenHeaders( $auth ) +
array(
1414 'x-container-read' => implode( ',', $readGrps ),
1415 'x-container-write' => implode( ',', $writeGrps )
1419 if ( $rcode === 201 ) { // new
1421 } elseif ( $rcode === 202 ) { // already there
1422 // this shouldn't really happen, but is OK
1424 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1431 * Delete a Swift container
1433 * @param string $container Container name
1434 * @param array $params
1437 protected function deleteContainer( $container, array $params ) {
1438 $status = Status
::newGood();
1440 $auth = $this->getAuthentication();
1442 $status->fatal( 'backend-fail-connect', $this->name
);
1447 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1448 'method' => 'DELETE',
1449 'url' => $this->storageUrl( $auth, $container ),
1450 'headers' => $this->authTokenHeaders( $auth )
1453 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1454 $this->containerStatCache
->clear( $container ); // purge
1455 } elseif ( $rcode === 404 ) { // not there
1456 // this shouldn't really happen, but is OK
1457 } elseif ( $rcode === 409 ) { // not empty
1458 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1460 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1467 * Get a list of objects under a container.
1468 * Either just the names or a list of stdClass objects with details can be returned.
1470 * @param string $fullCont
1471 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1473 * @param string|null $after
1474 * @param string|null $prefix
1475 * @param string|null $delim
1476 * @return Status With the list as value
1478 private function objectListing(
1479 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1481 $status = Status
::newGood();
1483 $auth = $this->getAuthentication();
1485 $status->fatal( 'backend-fail-connect', $this->name
);
1490 $query = array( 'limit' => $limit );
1491 if ( $type === 'info' ) {
1492 $query['format'] = 'json';
1494 if ( $after !== null ) {
1495 $query['marker'] = $after;
1497 if ( $prefix !== null ) {
1498 $query['prefix'] = $prefix;
1500 if ( $delim !== null ) {
1501 $query['delimiter'] = $delim;
1504 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1506 'url' => $this->storageUrl( $auth, $fullCont ),
1508 'headers' => $this->authTokenHeaders( $auth )
1511 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1512 if ( $rcode === 200 ) { // good
1513 if ( $type === 'info' ) {
1514 $status->value
= FormatJson
::decode( trim( $rbody ) );
1516 $status->value
= explode( "\n", trim( $rbody ) );
1518 } elseif ( $rcode === 204 ) {
1519 $status->value
= array(); // empty container
1520 } elseif ( $rcode === 404 ) {
1521 $status->value
= array(); // no container
1523 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1529 protected function doPrimeContainerCache( array $containerInfo ) {
1530 foreach ( $containerInfo as $container => $info ) {
1531 $this->containerStatCache
->set( $container, 'stat', $info );
1535 protected function doGetFileStatMulti( array $params ) {
1538 $auth = $this->getAuthentication();
1541 foreach ( $params['srcs'] as $path ) {
1542 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1543 if ( $srcRel === null ) {
1544 $stats[$path] = false;
1545 continue; // invalid storage path
1546 } elseif ( !$auth ) {
1547 $stats[$path] = null;
1551 // (a) Check the container
1552 $cstat = $this->getContainerStat( $srcCont );
1553 if ( $cstat === false ) {
1554 $stats[$path] = false;
1555 continue; // ok, nothing to do
1556 } elseif ( !is_array( $cstat ) ) {
1557 $stats[$path] = null;
1561 $reqs[$path] = array(
1563 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1564 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1568 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1569 $reqs = $this->http
->runMulti( $reqs, $opts );
1571 foreach ( $params['srcs'] as $path ) {
1572 if ( array_key_exists( $path, $stats ) ) {
1573 continue; // some sort of failure above
1575 // (b) Check the file
1576 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1577 if ( $rcode === 200 ||
$rcode === 204 ) {
1578 // Update the object if it is missing some headers
1579 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1580 // Load the stat array from the headers
1581 $stat = $this->getStatFromHeaders( $rhdrs );
1582 if ( $this->isRGW
) {
1583 $stat['latest'] = true; // strong consistency
1585 } elseif ( $rcode === 404 ) {
1589 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1591 $stats[$path] = $stat;
1598 * @param array $rhdrs
1601 protected function getStatFromHeaders( array $rhdrs ) {
1602 // Fetch all of the custom metadata headers
1603 $metadata = $this->getMetadata( $rhdrs );
1604 // Fetch all of the custom raw HTTP headers
1605 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1608 // Convert various random Swift dates to TS_MW
1609 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1610 // Empty objects actually return no content-length header in Ceph
1611 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1612 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1613 // Note: manifiest ETags are not an MD5 of the file
1614 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1615 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1620 * @return array|null Credential map
1622 protected function getAuthentication() {
1623 if ( $this->authErrorTimestamp
!== null ) {
1624 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1625 return null; // failed last attempt; don't bother
1626 } else { // actually retry this time
1627 $this->authErrorTimestamp
= null;
1630 // Session keys expire after a while, so we renew them periodically
1631 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1632 // Authenticate with proxy and get a session key...
1633 if ( !$this->authCreds ||
$reAuth ) {
1634 $this->authSessionTimestamp
= 0;
1635 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1636 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1637 // Try to use the credential cache
1638 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1639 $this->authCreds
= $creds;
1640 // Skew the timestamp for worst case to avoid using stale credentials
1641 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1642 } else { // cache miss
1643 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1645 'url' => "{$this->swiftAuthUrl}/v1.0",
1647 'x-auth-user' => $this->swiftUser
,
1648 'x-auth-key' => $this->swiftKey
1652 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1653 $this->authCreds
= array(
1654 'auth_token' => $rhdrs['x-auth-token'],
1655 'storage_url' => $rhdrs['x-storage-url']
1657 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1658 $this->authSessionTimestamp
= time();
1659 } elseif ( $rcode === 401 ) {
1660 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1661 $this->authErrorTimestamp
= time();
1665 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1666 $this->authErrorTimestamp
= time();
1671 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1672 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1673 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1677 return $this->authCreds
;
1681 * @param array $creds From getAuthentication()
1682 * @param string $container
1683 * @param string $object
1686 protected function storageUrl( array $creds, $container = null, $object = null ) {
1687 $parts = array( $creds['storage_url'] );
1688 if ( strlen( $container ) ) {
1689 $parts[] = rawurlencode( $container );
1691 if ( strlen( $object ) ) {
1692 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1695 return implode( '/', $parts );
1699 * @param array $creds From getAuthentication()
1702 protected function authTokenHeaders( array $creds ) {
1703 return array( 'x-auth-token' => $creds['auth_token'] );
1707 * Get the cache key for a container
1709 * @param string $username
1712 private function getCredsCacheKey( $username ) {
1713 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1717 * Log an unexpected exception for this backend.
1718 * This also sets the Status object to have a fatal error.
1720 * @param Status|null $status
1721 * @param string $func
1722 * @param array $params
1723 * @param string $err Error string
1724 * @param int $code HTTP status
1725 * @param string $desc HTTP status description
1727 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1728 if ( $status instanceof Status
) {
1729 $status->fatal( 'backend-fail-internal', $this->name
);
1731 if ( $code == 401 ) { // possibly a stale token
1732 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1734 wfDebugLog( 'SwiftBackend',
1735 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1736 ( $err ?
": $err" : "" )
1742 * @see FileBackendStoreOpHandle
1744 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1745 /** @var array List of Requests for MultiHttpClient */
1751 * @param SwiftFileBackend $backend
1752 * @param Closure $callback Function that takes (HTTP request array, status)
1753 * @param array $httpOp MultiHttpClient op
1755 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1756 $this->backend
= $backend;
1757 $this->callback
= $callback;
1758 $this->httpOp
= $httpOp;
1763 * SwiftFileBackend helper class to page through listings.
1764 * Swift also has a listing limit of 10,000 objects for sanity.
1765 * Do not use this class from places outside SwiftFileBackend.
1767 * @ingroup FileBackend
1769 abstract class SwiftFileBackendList
implements Iterator
{
1770 /** @var array List of path or (path,stat array) entries */
1771 protected $bufferIter = array();
1773 /** @var string List items *after* this path */
1774 protected $bufferAfter = null;
1780 protected $params = array();
1782 /** @var SwiftFileBackend */
1785 /** @var string Container name */
1786 protected $container;
1788 /** @var string Storage directory */
1792 protected $suffixStart;
1794 const PAGE_SIZE
= 9000; // file listing buffer size
1797 * @param SwiftFileBackend $backend
1798 * @param string $fullCont Resolved container name
1799 * @param string $dir Resolved directory relative to container
1800 * @param array $params
1802 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1803 $this->backend
= $backend;
1804 $this->container
= $fullCont;
1806 if ( substr( $this->dir
, -1 ) === '/' ) {
1807 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1809 if ( $this->dir
== '' ) { // whole container
1810 $this->suffixStart
= 0;
1811 } else { // dir within container
1812 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1814 $this->params
= $params;
1818 * @see Iterator::key()
1821 public function key() {
1826 * @see Iterator::next()
1828 public function next() {
1829 // Advance to the next file in the page
1830 next( $this->bufferIter
);
1832 // Check if there are no files left in this page and
1833 // advance to the next page if this page was not empty.
1834 if ( !$this->valid() && count( $this->bufferIter
) ) {
1835 $this->bufferIter
= $this->pageFromList(
1836 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1837 ); // updates $this->bufferAfter
1842 * @see Iterator::rewind()
1844 public function rewind() {
1846 $this->bufferAfter
= null;
1847 $this->bufferIter
= $this->pageFromList(
1848 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1849 ); // updates $this->bufferAfter
1853 * @see Iterator::valid()
1856 public function valid() {
1857 if ( $this->bufferIter
=== null ) {
1858 return false; // some failure?
1860 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1865 * Get the given list portion (page)
1867 * @param string $container Resolved container name
1868 * @param string $dir Resolved path relative to container
1869 * @param string $after
1871 * @param array $params
1872 * @return Traversable|array
1874 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1878 * Iterator for listing directories
1880 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1882 * @see Iterator::current()
1883 * @return string|bool String (relative path) or false
1885 public function current() {
1886 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1889 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1890 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1895 * Iterator for listing regular files
1897 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1899 * @see Iterator::current()
1900 * @return string|bool String (relative path) or false
1902 public function current() {
1903 list( $path, $stat ) = current( $this->bufferIter
);
1904 $relPath = substr( $path, $this->suffixStart
);
1905 if ( is_array( $stat ) ) {
1906 $storageDir = rtrim( $this->params
['dir'], '/' );
1907 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1913 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1914 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );