3 * OpenStack Swift based file backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 * @author Aaron Schulz
27 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
29 * Status messages should avoid mentioning the Swift account name.
30 * Likewise, error suppression should be used to avoid path disclosure.
32 * @ingroup FileBackend
35 class SwiftFileBackend
extends FileBackendStore
{
36 /** @var MultiHttpClient */
39 /** @var int TTL in seconds */
42 /** @var string Authentication base URL (without version) */
43 protected $swiftAuthUrl;
45 /** @var string Swift user (account:user) to authenticate as */
48 /** @var string Secret key for user */
51 /** @var string Shared secret value for making temp URLs */
52 protected $swiftTempUrlKey;
54 /** @var string S3 access key (RADOS Gateway) */
55 protected $rgwS3AccessKey;
57 /** @var string S3 authentication key (RADOS Gateway) */
58 protected $rgwS3SecretKey;
63 /** @var ProcessCacheLRU Container stat cache */
64 protected $containerStatCache;
69 /** @var int UNIX timestamp */
70 protected $authSessionTimestamp = 0;
72 /** @var int UNIX timestamp */
73 protected $authErrorTimestamp = null;
75 /** @var bool Whether the server is an Ceph RGW */
76 protected $isRGW = false;
79 * @see FileBackendStore::__construct()
80 * Additional $config params include:
81 * - swiftAuthUrl : Swift authentication server URL
82 * - swiftUser : Swift user used by MediaWiki (account:username)
83 * - swiftKey : Swift authentication key for the above user
84 * - swiftAuthTTL : Swift authentication TTL (seconds)
85 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
86 * Do not set this until it has been set in the backend.
87 * - shardViaHashLevels : Map of container names to sharding config with:
88 * - base : base of hash characters, 16 or 36
89 * - levels : the number of hash levels (and digits)
90 * - repeat : hash subdirectories are prefixed with all the
91 * parent hash directory names (e.g. "a/ab/abc")
92 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
93 * If those are not available, then the main cache will be used.
94 * This is probably insecure in shared hosting environments.
95 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
96 * Do not set this until it has been set in the backend.
97 * This is used for generating expiring pre-authenticated URLs.
98 * Only use this when using rgw and to work around
99 * http://tracker.newdream.net/issues/3454.
100 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
101 * Do not set this until it has been set in the backend.
102 * This is used for generating expiring pre-authenticated URLs.
103 * Only use this when using rgw and to work around
104 * http://tracker.newdream.net/issues/3454.
106 public function __construct( array $config ) {
107 parent
::__construct( $config );
109 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
110 $this->swiftUser
= $config['swiftUser'];
111 $this->swiftKey
= $config['swiftKey'];
113 $this->authTTL
= isset( $config['swiftAuthTTL'] )
114 ?
$config['swiftAuthTTL']
115 : 15 * 60; // some sane number
116 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
117 ?
$config['swiftTempUrlKey']
119 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
120 ?
$config['shardViaHashLevels']
122 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
123 ?
$config['rgwS3AccessKey']
125 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
126 ?
$config['rgwS3SecretKey']
128 // HTTP helper client
129 $this->http
= new MultiHttpClient( array() );
130 // Cache container information to mask latency
131 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
132 $this->memCache
= $config['wanCache'];
134 // Process cache for container info
135 $this->containerStatCache
= new ProcessCacheLRU( 300 );
136 // Cache auth token information to avoid RTTs
137 if ( !empty( $config['cacheAuthInfo'] ) ) {
138 if ( PHP_SAPI
=== 'cli' ) {
139 $this->srvCache
= wfGetMainCache(); // preferrably memcached
141 // look for APC, XCache, WinCache, ect...
142 $this->srvCache
= ObjectCache
::newAccelerator( CACHE_NONE
);
145 $this->srvCache
= new EmptyBagOStuff();
149 public function getFeatures() {
150 return ( FileBackend
::ATTR_UNICODE_PATHS |
151 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
154 protected function resolveContainerPath( $container, $relStoragePath ) {
155 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
156 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
157 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
158 return null; // too long for Swift
161 return $relStoragePath;
164 public function isPathUsableInternal( $storagePath ) {
165 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
166 if ( $rel === null ) {
167 return false; // invalid
170 return is_array( $this->getContainerStat( $container ) );
174 * Sanitize and filter the custom headers from a $params array.
175 * Only allows certain "standard" Content- and X-Content- headers.
177 * @param array $params
178 * @return array Sanitized value of 'headers' field in $params
180 protected function sanitizeHdrs( array $params ) {
181 return isset( $params['headers'] )
182 ?
$this->getCustomHeaders( $params['headers'] )
188 * @param array $rawHeaders
189 * @return array Custom non-metadata HTTP headers
191 protected function getCustomHeaders( array $rawHeaders ) {
194 // Normalize casing, and strip out illegal headers
195 foreach ( $rawHeaders as $name => $value ) {
196 $name = strtolower( $name );
197 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
198 continue; // blacklisted
199 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
200 $headers[$name] = $value; // allowed
201 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
202 $headers[$name] = $value; // allowed
205 // By default, Swift has annoyingly low maximum header value limits
206 if ( isset( $headers['content-disposition'] ) ) {
208 // @note: assume FileBackend::makeContentDisposition() already used
209 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
210 $part = trim( $part );
211 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
212 if ( strlen( $new ) <= 255 ) {
215 break; // too long; sigh
218 $headers['content-disposition'] = $disposition;
225 * @param array $rawHeaders
226 * @return array Custom metadata headers
228 protected function getMetadataHeaders( array $rawHeaders ) {
230 foreach ( $rawHeaders as $name => $value ) {
231 $name = strtolower( $name );
232 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
233 $headers[$name] = $value;
241 * @param array $rawHeaders
242 * @return array Custom metadata headers with prefix removed
244 protected function getMetadata( array $rawHeaders ) {
246 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
247 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
253 protected function doCreateInternal( array $params ) {
254 $status = Status
::newGood();
256 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
257 if ( $dstRel === null ) {
258 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
263 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
264 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
266 $reqs = array( array(
268 'url' => array( $dstCont, $dstRel ),
270 'content-length' => strlen( $params['content'] ),
271 'etag' => md5( $params['content'] ),
272 'content-type' => $contentType,
273 'x-object-meta-sha1base36' => $sha1Hash
274 ) +
$this->sanitizeHdrs( $params ),
275 'body' => $params['content']
279 $method = __METHOD__
;
280 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
281 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
282 if ( $rcode === 201 ) {
284 } elseif ( $rcode === 412 ) {
285 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
287 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
291 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
292 if ( !empty( $params['async'] ) ) { // deferred
293 $status->value
= $opHandle;
294 } else { // actually write the object in Swift
295 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
301 protected function doStoreInternal( array $params ) {
302 $status = Status
::newGood();
304 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
305 if ( $dstRel === null ) {
306 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
311 MediaWiki\
suppressWarnings();
312 $sha1Hash = sha1_file( $params['src'] );
313 MediaWiki\restoreWarnings
();
314 if ( $sha1Hash === false ) { // source doesn't exist?
315 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
319 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
320 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
322 $handle = fopen( $params['src'], 'rb' );
323 if ( $handle === false ) { // source doesn't exist?
324 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
329 $reqs = array( array(
331 'url' => array( $dstCont, $dstRel ),
333 'content-length' => filesize( $params['src'] ),
334 'etag' => md5_file( $params['src'] ),
335 'content-type' => $contentType,
336 'x-object-meta-sha1base36' => $sha1Hash
337 ) +
$this->sanitizeHdrs( $params ),
338 'body' => $handle // resource
342 $method = __METHOD__
;
343 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
344 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
345 if ( $rcode === 201 ) {
347 } elseif ( $rcode === 412 ) {
348 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
350 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
354 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
355 if ( !empty( $params['async'] ) ) { // deferred
356 $status->value
= $opHandle;
357 } else { // actually write the object in Swift
358 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
364 protected function doCopyInternal( array $params ) {
365 $status = Status
::newGood();
367 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
368 if ( $srcRel === null ) {
369 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
374 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
375 if ( $dstRel === null ) {
376 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
381 $reqs = array( array(
383 'url' => array( $dstCont, $dstRel ),
385 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
386 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
387 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
391 $method = __METHOD__
;
392 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
393 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
394 if ( $rcode === 201 ) {
396 } elseif ( $rcode === 404 ) {
397 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
399 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
403 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
404 if ( !empty( $params['async'] ) ) { // deferred
405 $status->value
= $opHandle;
406 } else { // actually write the object in Swift
407 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
413 protected function doMoveInternal( array $params ) {
414 $status = Status
::newGood();
416 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
417 if ( $srcRel === null ) {
418 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
423 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
424 if ( $dstRel === null ) {
425 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
433 'url' => array( $dstCont, $dstRel ),
435 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
436 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
437 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
440 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
442 'method' => 'DELETE',
443 'url' => array( $srcCont, $srcRel ),
449 $method = __METHOD__
;
450 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
451 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
452 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
454 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
456 } elseif ( $rcode === 404 ) {
457 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
459 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
463 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
464 if ( !empty( $params['async'] ) ) { // deferred
465 $status->value
= $opHandle;
466 } else { // actually move the object in Swift
467 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
473 protected function doDeleteInternal( array $params ) {
474 $status = Status
::newGood();
476 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
477 if ( $srcRel === null ) {
478 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
483 $reqs = array( array(
484 'method' => 'DELETE',
485 'url' => array( $srcCont, $srcRel ),
490 $method = __METHOD__
;
491 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
492 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
493 if ( $rcode === 204 ) {
495 } elseif ( $rcode === 404 ) {
496 if ( empty( $params['ignoreMissingSource'] ) ) {
497 $status->fatal( 'backend-fail-delete', $params['src'] );
500 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
504 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
505 if ( !empty( $params['async'] ) ) { // deferred
506 $status->value
= $opHandle;
507 } else { // actually delete the object in Swift
508 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
514 protected function doDescribeInternal( array $params ) {
515 $status = Status
::newGood();
517 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
518 if ( $srcRel === null ) {
519 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
524 // Fetch the old object headers/metadata...this should be in stat cache by now
525 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
526 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
527 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
530 $status->fatal( 'backend-fail-describe', $params['src'] );
535 // POST clears prior headers, so we need to merge the changes in to the old ones
537 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
538 $metaHdrs["x-object-meta-$name"] = $value;
540 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
542 $reqs = array( array(
544 'url' => array( $srcCont, $srcRel ),
545 'headers' => $metaHdrs +
$customHdrs
549 $method = __METHOD__
;
550 $handler = function ( array $request, Status
$status ) use ( $that, $method, $params ) {
551 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
552 if ( $rcode === 202 ) {
554 } elseif ( $rcode === 404 ) {
555 $status->fatal( 'backend-fail-describe', $params['src'] );
557 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
561 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
562 if ( !empty( $params['async'] ) ) { // deferred
563 $status->value
= $opHandle;
564 } else { // actually change the object in Swift
565 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
571 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
572 $status = Status
::newGood();
574 // (a) Check if container already exists
575 $stat = $this->getContainerStat( $fullCont );
576 if ( is_array( $stat ) ) {
577 return $status; // already there
578 } elseif ( $stat === null ) {
579 $status->fatal( 'backend-fail-internal', $this->name
);
580 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
585 // (b) Create container as needed with proper ACLs
586 if ( $stat === false ) {
587 $params['op'] = 'prepare';
588 $status->merge( $this->createContainer( $fullCont, $params ) );
594 protected function doSecureInternal( $fullCont, $dir, array $params ) {
595 $status = Status
::newGood();
596 if ( empty( $params['noAccess'] ) ) {
597 return $status; // nothing to do
600 $stat = $this->getContainerStat( $fullCont );
601 if ( is_array( $stat ) ) {
602 // Make container private to end-users...
603 $status->merge( $this->setContainerAccess(
605 array( $this->swiftUser
), // read
606 array( $this->swiftUser
) // write
608 } elseif ( $stat === false ) {
609 $status->fatal( 'backend-fail-usable', $params['dir'] );
611 $status->fatal( 'backend-fail-internal', $this->name
);
612 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
618 protected function doPublishInternal( $fullCont, $dir, array $params ) {
619 $status = Status
::newGood();
621 $stat = $this->getContainerStat( $fullCont );
622 if ( is_array( $stat ) ) {
623 // Make container public to end-users...
624 $status->merge( $this->setContainerAccess(
626 array( $this->swiftUser
, '.r:*' ), // read
627 array( $this->swiftUser
) // write
629 } elseif ( $stat === false ) {
630 $status->fatal( 'backend-fail-usable', $params['dir'] );
632 $status->fatal( 'backend-fail-internal', $this->name
);
633 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
639 protected function doCleanInternal( $fullCont, $dir, array $params ) {
640 $status = Status
::newGood();
642 // Only containers themselves can be removed, all else is virtual
644 return $status; // nothing to do
647 // (a) Check the container
648 $stat = $this->getContainerStat( $fullCont, true );
649 if ( $stat === false ) {
650 return $status; // ok, nothing to do
651 } elseif ( !is_array( $stat ) ) {
652 $status->fatal( 'backend-fail-internal', $this->name
);
653 wfDebugLog( 'SwiftBackend', __METHOD__
. ': cannot get container stat' );
658 // (b) Delete the container if empty
659 if ( $stat['count'] == 0 ) {
660 $params['op'] = 'clean';
661 $status->merge( $this->deleteContainer( $fullCont, $params ) );
667 protected function doGetFileStat( array $params ) {
668 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) +
$params;
669 unset( $params['src'] );
670 $stats = $this->doGetFileStatMulti( $params );
672 return reset( $stats );
676 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
677 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
678 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
681 * @param int $format Output format (TS_* constant)
683 * @throws FileBackendError
685 protected function convertSwiftDate( $ts, $format = TS_MW
) {
687 $timestamp = new MWTimestamp( $ts );
689 return $timestamp->getTimestamp( $format );
690 } catch ( Exception
$e ) {
691 throw new FileBackendError( $e->getMessage() );
696 * Fill in any missing object metadata and save it to Swift
698 * @param array $objHdrs Object response headers
699 * @param string $path Storage path to object
700 * @return array New headers
702 protected function addMissingMetadata( array $objHdrs, $path ) {
703 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
704 return $objHdrs; // nothing to do
707 /** @noinspection PhpUnusedLocalVariableInspection */
708 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
709 wfDebugLog( 'SwiftBackend', __METHOD__
. ": $path was not stored with SHA-1 metadata." );
711 $objHdrs['x-object-meta-sha1base36'] = false;
713 $auth = $this->getAuthentication();
715 return $objHdrs; // failed
718 // Find prior custom HTTP headers
719 $postHeaders = $this->getCustomHeaders( $objHdrs );
720 // Find prior metadata headers
721 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
723 $status = Status
::newGood();
724 /** @noinspection PhpUnusedLocalVariableInspection */
725 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
726 if ( $status->isOK() ) {
727 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
729 $hash = $tmpFile->getSha1Base36();
730 if ( $hash !== false ) {
731 $objHdrs['x-object-meta-sha1base36'] = $hash;
732 // Merge new SHA1 header into the old ones
733 $postHeaders['x-object-meta-sha1base36'] = $hash;
734 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
735 list( $rcode ) = $this->http
->run( array(
737 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
738 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
740 if ( $rcode >= 200 && $rcode <= 299 ) {
741 $this->deleteFileCache( $path );
743 return $objHdrs; // success
749 wfDebugLog( 'SwiftBackend', __METHOD__
. ": unable to set SHA-1 metadata for $path" );
751 return $objHdrs; // failed
754 protected function doGetFileContentsMulti( array $params ) {
757 $auth = $this->getAuthentication();
759 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
760 // Blindly create tmp files and stream to them, catching any exception if the file does
761 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
762 $reqs = array(); // (path => op)
764 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
765 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
766 if ( $srcRel === null ||
!$auth ) {
767 $contents[$path] = false;
770 // Create a new temporary memory file...
771 $handle = fopen( 'php://temp', 'wb' );
773 $reqs[$path] = array(
775 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
776 'headers' => $this->authTokenHeaders( $auth )
777 +
$this->headersFromParams( $params ),
781 $contents[$path] = false;
784 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
785 $reqs = $this->http
->runMulti( $reqs, $opts );
786 foreach ( $reqs as $path => $op ) {
787 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
788 if ( $rcode >= 200 && $rcode <= 299 ) {
789 rewind( $op['stream'] ); // start from the beginning
790 $contents[$path] = stream_get_contents( $op['stream'] );
791 } elseif ( $rcode === 404 ) {
792 $contents[$path] = false;
794 $this->onError( null, __METHOD__
,
795 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
797 fclose( $op['stream'] ); // close open handle
803 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
804 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
805 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
806 if ( $status->isOk() ) {
807 return ( count( $status->value
) ) > 0;
810 return null; // error
814 * @see FileBackendStore::getDirectoryListInternal()
815 * @param string $fullCont
817 * @param array $params
818 * @return SwiftFileBackendDirList
820 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
821 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
825 * @see FileBackendStore::getFileListInternal()
826 * @param string $fullCont
828 * @param array $params
829 * @return SwiftFileBackendFileList
831 public function getFileListInternal( $fullCont, $dir, array $params ) {
832 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
836 * Do not call this function outside of SwiftFileBackendFileList
838 * @param string $fullCont Resolved container name
839 * @param string $dir Resolved storage directory with no trailing slash
840 * @param string|null $after Resolved container relative path to list items after
841 * @param int $limit Max number of items to list
842 * @param array $params Parameters for getDirectoryList()
843 * @return array List of container relative resolved paths of directories directly under $dir
844 * @throws FileBackendError
846 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
848 if ( $after === INF
) {
849 return $dirs; // nothing more
852 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
854 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
855 // Non-recursive: only list dirs right under $dir
856 if ( !empty( $params['topOnly'] ) ) {
857 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
858 if ( !$status->isOk() ) {
859 return $dirs; // error
861 $objects = $status->value
;
862 foreach ( $objects as $object ) { // files and directories
863 if ( substr( $object, -1 ) === '/' ) {
864 $dirs[] = $object; // directories end in '/'
868 // Recursive: list all dirs under $dir and its subdirs
869 $getParentDir = function ( $path ) {
870 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
873 // Get directory from last item of prior page
874 $lastDir = $getParentDir( $after ); // must be first page
875 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
877 if ( !$status->isOk() ) {
878 return $dirs; // error
881 $objects = $status->value
;
883 foreach ( $objects as $object ) { // files
884 $objectDir = $getParentDir( $object ); // directory of object
886 if ( $objectDir !== false && $objectDir !== $dir ) {
887 // Swift stores paths in UTF-8, using binary sorting.
888 // See function "create_container_table" in common/db.py.
889 // If a directory is not "greater" than the last one,
890 // then it was already listed by the calling iterator.
891 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
893 do { // add dir and all its parent dirs
894 $dirs[] = "{$pDir}/";
895 $pDir = $getParentDir( $pDir );
896 } while ( $pDir !== false // sanity
897 && strcmp( $pDir, $lastDir ) > 0 // not done already
898 && strlen( $pDir ) > strlen( $dir ) // within $dir
901 $lastDir = $objectDir;
905 // Page on the unfiltered directory listing (what is returned may be filtered)
906 if ( count( $objects ) < $limit ) {
907 $after = INF
; // avoid a second RTT
909 $after = end( $objects ); // update last item
916 * Do not call this function outside of SwiftFileBackendFileList
918 * @param string $fullCont Resolved container name
919 * @param string $dir Resolved storage directory with no trailing slash
920 * @param string|null $after Resolved container relative path of file to list items after
921 * @param int $limit Max number of items to list
922 * @param array $params Parameters for getDirectoryList()
923 * @return array List of resolved container relative paths of files under $dir
924 * @throws FileBackendError
926 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
927 $files = array(); // list of (path, stat array or null) entries
928 if ( $after === INF
) {
929 return $files; // nothing more
932 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
934 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
935 // $objects will contain a list of unfiltered names or CF_Object items
936 // Non-recursive: only list files right under $dir
937 if ( !empty( $params['topOnly'] ) ) {
938 if ( !empty( $params['adviseStat'] ) ) {
939 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
941 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
944 // Recursive: list all files under $dir and its subdirs
945 if ( !empty( $params['adviseStat'] ) ) {
946 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
948 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
952 // Reformat this list into a list of (name, stat array or null) entries
953 if ( !$status->isOk() ) {
954 return $files; // error
957 $objects = $status->value
;
958 $files = $this->buildFileObjectListing( $params, $dir, $objects );
960 // Page on the unfiltered object listing (what is returned may be filtered)
961 if ( count( $objects ) < $limit ) {
962 $after = INF
; // avoid a second RTT
964 $after = end( $objects ); // update last item
965 $after = is_object( $after ) ?
$after->name
: $after;
972 * Build a list of file objects, filtering out any directories
973 * and extracting any stat info if provided in $objects (for CF_Objects)
975 * @param array $params Parameters for getDirectoryList()
976 * @param string $dir Resolved container directory path
977 * @param array $objects List of CF_Object items or object names
978 * @return array List of (names,stat array or null) entries
980 private function buildFileObjectListing( array $params, $dir, array $objects ) {
982 foreach ( $objects as $object ) {
983 if ( is_object( $object ) ) {
984 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
985 continue; // virtual directory entry; ignore
988 // Convert various random Swift dates to TS_MW
989 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
990 'size' => (int)$object->bytes
,
992 // Note: manifiest ETags are not an MD5 of the file
993 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
994 'latest' => false // eventually consistent
996 $names[] = array( $object->name
, $stat );
997 } elseif ( substr( $object, -1 ) !== '/' ) {
998 // Omit directories, which end in '/' in listings
999 $names[] = array( $object, null );
1007 * Do not call this function outside of SwiftFileBackendFileList
1009 * @param string $path Storage path
1010 * @param array $val Stat value
1012 public function loadListingStatInternal( $path, array $val ) {
1013 $this->cheapCache
->set( $path, 'stat', $val );
1016 protected function doGetFileXAttributes( array $params ) {
1017 $stat = $this->getFileStat( $params );
1019 if ( !isset( $stat['xattr'] ) ) {
1020 // Stat entries filled by file listings don't include metadata/headers
1021 $this->clearCache( array( $params['src'] ) );
1022 $stat = $this->getFileStat( $params );
1025 return $stat['xattr'];
1031 protected function doGetFileSha1base36( array $params ) {
1032 $stat = $this->getFileStat( $params );
1034 if ( !isset( $stat['sha1'] ) ) {
1035 // Stat entries filled by file listings don't include SHA1
1036 $this->clearCache( array( $params['src'] ) );
1037 $stat = $this->getFileStat( $params );
1040 return $stat['sha1'];
1046 protected function doStreamFile( array $params ) {
1047 $status = Status
::newGood();
1049 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1050 if ( $srcRel === null ) {
1051 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1054 $auth = $this->getAuthentication();
1055 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1056 $status->fatal( 'backend-fail-stream', $params['src'] );
1061 $handle = fopen( 'php://output', 'wb' );
1063 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1065 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1066 'headers' => $this->authTokenHeaders( $auth )
1067 +
$this->headersFromParams( $params ),
1068 'stream' => $handle,
1071 if ( $rcode >= 200 && $rcode <= 299 ) {
1073 } elseif ( $rcode === 404 ) {
1074 $status->fatal( 'backend-fail-stream', $params['src'] );
1076 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1082 protected function doGetLocalCopyMulti( array $params ) {
1083 $tmpFiles = array();
1085 $auth = $this->getAuthentication();
1087 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1088 // Blindly create tmp files and stream to them, catching any exception if the file does
1089 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1090 $reqs = array(); // (path => op)
1092 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1093 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1094 if ( $srcRel === null ||
!$auth ) {
1095 $tmpFiles[$path] = null;
1098 // Get source file extension
1099 $ext = FileBackend
::extensionFromPath( $path );
1100 // Create a new temporary file...
1101 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1103 $handle = fopen( $tmpFile->getPath(), 'wb' );
1105 $reqs[$path] = array(
1107 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1108 'headers' => $this->authTokenHeaders( $auth )
1109 +
$this->headersFromParams( $params ),
1110 'stream' => $handle,
1116 $tmpFiles[$path] = $tmpFile;
1119 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1120 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1121 $reqs = $this->http
->runMulti( $reqs, $opts );
1122 foreach ( $reqs as $path => $op ) {
1123 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1124 fclose( $op['stream'] ); // close open handle
1125 if ( $rcode >= 200 && $rcode <= 299 ) {
1126 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1127 // Double check that the disk is not full/broken
1128 if ( $size != $rhdrs['content-length'] ) {
1129 $tmpFiles[$path] = null;
1130 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1131 $this->onError( null, __METHOD__
,
1132 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1134 // Set the file stat process cache in passing
1135 $stat = $this->getStatFromHeaders( $rhdrs );
1136 $stat['latest'] = $isLatest;
1137 $this->cheapCache
->set( $path, 'stat', $stat );
1138 } elseif ( $rcode === 404 ) {
1139 $tmpFiles[$path] = false;
1141 $tmpFiles[$path] = null;
1142 $this->onError( null, __METHOD__
,
1143 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1150 public function getFileHttpUrl( array $params ) {
1151 if ( $this->swiftTempUrlKey
!= '' ||
1152 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1154 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1155 if ( $srcRel === null ) {
1156 return null; // invalid path
1159 $auth = $this->getAuthentication();
1164 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1165 $expires = time() +
$ttl;
1167 if ( $this->swiftTempUrlKey
!= '' ) {
1168 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1169 // Swift wants the signature based on the unencoded object name
1170 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1171 $signature = hash_hmac( 'sha1',
1172 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1173 $this->swiftTempUrlKey
1176 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1177 } else { // give S3 API URL for rgw
1178 // Path for signature starts with the bucket
1179 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1180 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1181 // Calculate the hash
1182 $signature = base64_encode( hash_hmac(
1184 "GET\n\n\n{$expires}\n{$spath}",
1185 $this->rgwS3SecretKey
,
1188 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1189 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1190 return wfAppendQuery(
1191 str_replace( '/swift/v1', '', // S3 API is the rgw default
1192 $this->storageUrl( $auth ) . $spath ),
1194 'Signature' => $signature,
1195 'Expires' => $expires,
1196 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1204 protected function directoriesAreVirtual() {
1209 * Get headers to send to Swift when reading a file based
1210 * on a FileBackend params array, e.g. that of getLocalCopy().
1211 * $params is currently only checked for a 'latest' flag.
1213 * @param array $params
1216 protected function headersFromParams( array $params ) {
1218 if ( !empty( $params['latest'] ) ) {
1219 $hdrs['x-newest'] = 'true';
1226 * @param FileBackendStoreOpHandle[] $fileOpHandles
1230 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1231 $statuses = array();
1233 $auth = $this->getAuthentication();
1235 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1236 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1242 // Split the HTTP requests into stages that can be done concurrently
1243 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1244 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1245 $reqs = $fileOpHandle->httpOp
;
1246 // Convert the 'url' parameter to an actual URL using $auth
1247 foreach ( $reqs as $stage => &$req ) {
1248 list( $container, $relPath ) = $req['url'];
1249 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1250 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1251 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1252 $httpReqsByStage[$stage][$index] = $req;
1254 $statuses[$index] = Status
::newGood();
1257 // Run all requests for the first stage, then the next, and so on
1258 $reqCount = count( $httpReqsByStage );
1259 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1260 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1261 foreach ( $httpReqs as $index => $httpReq ) {
1262 // Run the callback for each request of this operation
1263 $callback = $fileOpHandles[$index]->callback
;
1264 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1265 // On failure, abort all remaining requests for this operation
1266 // (e.g. abort the DELETE request if the COPY request fails for a move)
1267 if ( !$statuses[$index]->isOK() ) {
1268 $stages = count( $fileOpHandles[$index]->httpOp
);
1269 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1270 unset( $httpReqsByStage[$s][$index] );
1280 * Set read/write permissions for a Swift container.
1282 * @see http://swift.openstack.org/misc.html#acls
1284 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1285 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1287 * @param string $container Resolved Swift container
1288 * @param array $readGrps List of the possible criteria for a request to have
1289 * access to read a container. Each item is one of the following formats:
1290 * - account:user : Grants access if the request is by the given user
1291 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1292 * matches the expression and the request is not for a listing.
1293 * Setting this to '*' effectively makes a container public.
1294 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1295 * matches the expression and the request is for a listing.
1296 * @param array $writeGrps A list of the possible criteria for a request to have
1297 * access to write to a container. Each item is of the following format:
1298 * - account:user : Grants access if the request is by the given user
1301 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1302 $status = Status
::newGood();
1303 $auth = $this->getAuthentication();
1306 $status->fatal( 'backend-fail-connect', $this->name
);
1311 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1313 'url' => $this->storageUrl( $auth, $container ),
1314 'headers' => $this->authTokenHeaders( $auth ) +
array(
1315 'x-container-read' => implode( ',', $readGrps ),
1316 'x-container-write' => implode( ',', $writeGrps )
1320 if ( $rcode != 204 && $rcode !== 202 ) {
1321 $status->fatal( 'backend-fail-internal', $this->name
);
1322 wfDebugLog( 'SwiftBackend', __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1329 * Get a Swift container stat array, possibly from process cache.
1330 * Use $reCache if the file count or byte count is needed.
1332 * @param string $container Container name
1333 * @param bool $bypassCache Bypass all caches and load from Swift
1334 * @return array|bool|null False on 404, null on failure
1336 protected function getContainerStat( $container, $bypassCache = false ) {
1337 $ps = Profiler
::instance()->scopedProfileIn( __METHOD__
. "-{$this->name}" );
1339 if ( $bypassCache ) { // purge cache
1340 $this->containerStatCache
->clear( $container );
1341 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1342 $this->primeContainerCache( array( $container ) ); // check persistent cache
1344 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1345 $auth = $this->getAuthentication();
1350 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1352 'url' => $this->storageUrl( $auth, $container ),
1353 'headers' => $this->authTokenHeaders( $auth )
1356 if ( $rcode === 204 ) {
1358 'count' => $rhdrs['x-container-object-count'],
1359 'bytes' => $rhdrs['x-container-bytes-used']
1361 if ( $bypassCache ) {
1364 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1365 $this->setContainerCache( $container, $stat ); // update persistent cache
1367 } elseif ( $rcode === 404 ) {
1370 $this->onError( null, __METHOD__
,
1371 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1377 return $this->containerStatCache
->get( $container, 'stat' );
1381 * Create a Swift container
1383 * @param string $container Container name
1384 * @param array $params
1387 protected function createContainer( $container, array $params ) {
1388 $status = Status
::newGood();
1390 $auth = $this->getAuthentication();
1392 $status->fatal( 'backend-fail-connect', $this->name
);
1397 // @see SwiftFileBackend::setContainerAccess()
1398 if ( empty( $params['noAccess'] ) ) {
1399 $readGrps = array( '.r:*', $this->swiftUser
); // public
1401 $readGrps = array( $this->swiftUser
); // private
1403 $writeGrps = array( $this->swiftUser
); // sanity
1405 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1407 'url' => $this->storageUrl( $auth, $container ),
1408 'headers' => $this->authTokenHeaders( $auth ) +
array(
1409 'x-container-read' => implode( ',', $readGrps ),
1410 'x-container-write' => implode( ',', $writeGrps )
1414 if ( $rcode === 201 ) { // new
1416 } elseif ( $rcode === 202 ) { // already there
1417 // this shouldn't really happen, but is OK
1419 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1426 * Delete a Swift container
1428 * @param string $container Container name
1429 * @param array $params
1432 protected function deleteContainer( $container, array $params ) {
1433 $status = Status
::newGood();
1435 $auth = $this->getAuthentication();
1437 $status->fatal( 'backend-fail-connect', $this->name
);
1442 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1443 'method' => 'DELETE',
1444 'url' => $this->storageUrl( $auth, $container ),
1445 'headers' => $this->authTokenHeaders( $auth )
1448 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1449 $this->containerStatCache
->clear( $container ); // purge
1450 } elseif ( $rcode === 404 ) { // not there
1451 // this shouldn't really happen, but is OK
1452 } elseif ( $rcode === 409 ) { // not empty
1453 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1455 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1462 * Get a list of objects under a container.
1463 * Either just the names or a list of stdClass objects with details can be returned.
1465 * @param string $fullCont
1466 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1468 * @param string|null $after
1469 * @param string|null $prefix
1470 * @param string|null $delim
1471 * @return Status With the list as value
1473 private function objectListing(
1474 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1476 $status = Status
::newGood();
1478 $auth = $this->getAuthentication();
1480 $status->fatal( 'backend-fail-connect', $this->name
);
1485 $query = array( 'limit' => $limit );
1486 if ( $type === 'info' ) {
1487 $query['format'] = 'json';
1489 if ( $after !== null ) {
1490 $query['marker'] = $after;
1492 if ( $prefix !== null ) {
1493 $query['prefix'] = $prefix;
1495 if ( $delim !== null ) {
1496 $query['delimiter'] = $delim;
1499 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1501 'url' => $this->storageUrl( $auth, $fullCont ),
1503 'headers' => $this->authTokenHeaders( $auth )
1506 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1507 if ( $rcode === 200 ) { // good
1508 if ( $type === 'info' ) {
1509 $status->value
= FormatJson
::decode( trim( $rbody ) );
1511 $status->value
= explode( "\n", trim( $rbody ) );
1513 } elseif ( $rcode === 204 ) {
1514 $status->value
= array(); // empty container
1515 } elseif ( $rcode === 404 ) {
1516 $status->value
= array(); // no container
1518 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1524 protected function doPrimeContainerCache( array $containerInfo ) {
1525 foreach ( $containerInfo as $container => $info ) {
1526 $this->containerStatCache
->set( $container, 'stat', $info );
1530 protected function doGetFileStatMulti( array $params ) {
1533 $auth = $this->getAuthentication();
1536 foreach ( $params['srcs'] as $path ) {
1537 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1538 if ( $srcRel === null ) {
1539 $stats[$path] = false;
1540 continue; // invalid storage path
1541 } elseif ( !$auth ) {
1542 $stats[$path] = null;
1546 // (a) Check the container
1547 $cstat = $this->getContainerStat( $srcCont );
1548 if ( $cstat === false ) {
1549 $stats[$path] = false;
1550 continue; // ok, nothing to do
1551 } elseif ( !is_array( $cstat ) ) {
1552 $stats[$path] = null;
1556 $reqs[$path] = array(
1558 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1559 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1563 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1564 $reqs = $this->http
->runMulti( $reqs, $opts );
1566 foreach ( $params['srcs'] as $path ) {
1567 if ( array_key_exists( $path, $stats ) ) {
1568 continue; // some sort of failure above
1570 // (b) Check the file
1571 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1572 if ( $rcode === 200 ||
$rcode === 204 ) {
1573 // Update the object if it is missing some headers
1574 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1575 // Load the stat array from the headers
1576 $stat = $this->getStatFromHeaders( $rhdrs );
1577 if ( $this->isRGW
) {
1578 $stat['latest'] = true; // strong consistency
1580 } elseif ( $rcode === 404 ) {
1584 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1586 $stats[$path] = $stat;
1593 * @param array $rhdrs
1596 protected function getStatFromHeaders( array $rhdrs ) {
1597 // Fetch all of the custom metadata headers
1598 $metadata = $this->getMetadata( $rhdrs );
1599 // Fetch all of the custom raw HTTP headers
1600 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1603 // Convert various random Swift dates to TS_MW
1604 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1605 // Empty objects actually return no content-length header in Ceph
1606 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1607 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1608 // Note: manifiest ETags are not an MD5 of the file
1609 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1610 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1615 * @return array|null Credential map
1617 protected function getAuthentication() {
1618 if ( $this->authErrorTimestamp
!== null ) {
1619 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1620 return null; // failed last attempt; don't bother
1621 } else { // actually retry this time
1622 $this->authErrorTimestamp
= null;
1625 // Session keys expire after a while, so we renew them periodically
1626 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1627 // Authenticate with proxy and get a session key...
1628 if ( !$this->authCreds ||
$reAuth ) {
1629 $this->authSessionTimestamp
= 0;
1630 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1631 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1632 // Try to use the credential cache
1633 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1634 $this->authCreds
= $creds;
1635 // Skew the timestamp for worst case to avoid using stale credentials
1636 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1637 } else { // cache miss
1638 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1640 'url' => "{$this->swiftAuthUrl}/v1.0",
1642 'x-auth-user' => $this->swiftUser
,
1643 'x-auth-key' => $this->swiftKey
1647 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1648 $this->authCreds
= array(
1649 'auth_token' => $rhdrs['x-auth-token'],
1650 'storage_url' => $rhdrs['x-storage-url']
1652 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1653 $this->authSessionTimestamp
= time();
1654 } elseif ( $rcode === 401 ) {
1655 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1656 $this->authErrorTimestamp
= time();
1660 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1661 $this->authErrorTimestamp
= time();
1666 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1667 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1668 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1672 return $this->authCreds
;
1676 * @param array $creds From getAuthentication()
1677 * @param string $container
1678 * @param string $object
1681 protected function storageUrl( array $creds, $container = null, $object = null ) {
1682 $parts = array( $creds['storage_url'] );
1683 if ( strlen( $container ) ) {
1684 $parts[] = rawurlencode( $container );
1686 if ( strlen( $object ) ) {
1687 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1690 return implode( '/', $parts );
1694 * @param array $creds From getAuthentication()
1697 protected function authTokenHeaders( array $creds ) {
1698 return array( 'x-auth-token' => $creds['auth_token'] );
1702 * Get the cache key for a container
1704 * @param string $username
1707 private function getCredsCacheKey( $username ) {
1708 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1712 * Log an unexpected exception for this backend.
1713 * This also sets the Status object to have a fatal error.
1715 * @param Status|null $status
1716 * @param string $func
1717 * @param array $params
1718 * @param string $err Error string
1719 * @param int $code HTTP status
1720 * @param string $desc HTTP status description
1722 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1723 if ( $status instanceof Status
) {
1724 $status->fatal( 'backend-fail-internal', $this->name
);
1726 if ( $code == 401 ) { // possibly a stale token
1727 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1729 wfDebugLog( 'SwiftBackend',
1730 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1731 ( $err ?
": $err" : "" )
1737 * @see FileBackendStoreOpHandle
1739 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1740 /** @var array List of Requests for MultiHttpClient */
1746 * @param SwiftFileBackend $backend
1747 * @param Closure $callback Function that takes (HTTP request array, status)
1748 * @param array $httpOp MultiHttpClient op
1750 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1751 $this->backend
= $backend;
1752 $this->callback
= $callback;
1753 $this->httpOp
= $httpOp;
1758 * SwiftFileBackend helper class to page through listings.
1759 * Swift also has a listing limit of 10,000 objects for sanity.
1760 * Do not use this class from places outside SwiftFileBackend.
1762 * @ingroup FileBackend
1764 abstract class SwiftFileBackendList
implements Iterator
{
1765 /** @var array List of path or (path,stat array) entries */
1766 protected $bufferIter = array();
1768 /** @var string List items *after* this path */
1769 protected $bufferAfter = null;
1775 protected $params = array();
1777 /** @var SwiftFileBackend */
1780 /** @var string Container name */
1781 protected $container;
1783 /** @var string Storage directory */
1787 protected $suffixStart;
1789 const PAGE_SIZE
= 9000; // file listing buffer size
1792 * @param SwiftFileBackend $backend
1793 * @param string $fullCont Resolved container name
1794 * @param string $dir Resolved directory relative to container
1795 * @param array $params
1797 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1798 $this->backend
= $backend;
1799 $this->container
= $fullCont;
1801 if ( substr( $this->dir
, -1 ) === '/' ) {
1802 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1804 if ( $this->dir
== '' ) { // whole container
1805 $this->suffixStart
= 0;
1806 } else { // dir within container
1807 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1809 $this->params
= $params;
1813 * @see Iterator::key()
1816 public function key() {
1821 * @see Iterator::next()
1823 public function next() {
1824 // Advance to the next file in the page
1825 next( $this->bufferIter
);
1827 // Check if there are no files left in this page and
1828 // advance to the next page if this page was not empty.
1829 if ( !$this->valid() && count( $this->bufferIter
) ) {
1830 $this->bufferIter
= $this->pageFromList(
1831 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1832 ); // updates $this->bufferAfter
1837 * @see Iterator::rewind()
1839 public function rewind() {
1841 $this->bufferAfter
= null;
1842 $this->bufferIter
= $this->pageFromList(
1843 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1844 ); // updates $this->bufferAfter
1848 * @see Iterator::valid()
1851 public function valid() {
1852 if ( $this->bufferIter
=== null ) {
1853 return false; // some failure?
1855 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1860 * Get the given list portion (page)
1862 * @param string $container Resolved container name
1863 * @param string $dir Resolved path relative to container
1864 * @param string $after
1866 * @param array $params
1867 * @return Traversable|array
1869 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1873 * Iterator for listing directories
1875 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1877 * @see Iterator::current()
1878 * @return string|bool String (relative path) or false
1880 public function current() {
1881 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1884 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1885 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1890 * Iterator for listing regular files
1892 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1894 * @see Iterator::current()
1895 * @return string|bool String (relative path) or false
1897 public function current() {
1898 list( $path, $stat ) = current( $this->bufferIter
);
1899 $relPath = substr( $path, $this->suffixStart
);
1900 if ( is_array( $stat ) ) {
1901 $storageDir = rtrim( $this->params
['dir'], '/' );
1902 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1908 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1909 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );