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;
76 * @see FileBackendStore::__construct()
77 * Additional $config params include:
78 * - swiftAuthUrl : Swift authentication server URL
79 * - swiftUser : Swift user used by MediaWiki (account:username)
80 * - swiftKey : Swift authentication key for the above user
81 * - swiftAuthTTL : Swift authentication TTL (seconds)
82 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
83 * Do not set this until it has been set in the backend.
84 * - shardViaHashLevels : Map of container names to sharding config with:
85 * - base : base of hash characters, 16 or 36
86 * - levels : the number of hash levels (and digits)
87 * - repeat : hash subdirectories are prefixed with all the
88 * parent hash directory names (e.g. "a/ab/abc")
89 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
90 * If those are not available, then the main cache will be used.
91 * This is probably insecure in shared hosting environments.
92 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
93 * Do not set this until it has been set in the backend.
94 * This is used for generating expiring pre-authenticated URLs.
95 * Only use this when using rgw and to work around
96 * http://tracker.newdream.net/issues/3454.
97 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
98 * Do not set this until it has been set in the backend.
99 * This is used for generating expiring pre-authenticated URLs.
100 * Only use this when using rgw and to work around
101 * http://tracker.newdream.net/issues/3454.
103 public function __construct( array $config ) {
104 parent
::__construct( $config );
106 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
107 $this->swiftUser
= $config['swiftUser'];
108 $this->swiftKey
= $config['swiftKey'];
110 $this->authTTL
= isset( $config['swiftAuthTTL'] )
111 ?
$config['swiftAuthTTL']
112 : 5 * 60; // some sane number
113 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
114 ?
$config['swiftTempUrlKey']
116 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
117 ?
$config['shardViaHashLevels']
119 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
120 ?
$config['rgwS3AccessKey']
122 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
123 ?
$config['rgwS3SecretKey']
125 // HTTP helper client
126 $this->http
= new MultiHttpClient( array() );
127 // Cache container information to mask latency
128 $this->memCache
= wfGetMainCache();
129 // Process cache for container info
130 $this->containerStatCache
= new ProcessCacheLRU( 300 );
131 // Cache auth token information to avoid RTTs
132 if ( !empty( $config['cacheAuthInfo'] ) ) {
133 if ( PHP_SAPI
=== 'cli' ) {
134 $this->srvCache
= wfGetMainCache(); // preferrably memcached
136 try { // look for APC, XCache, WinCache, ect...
137 $this->srvCache
= ObjectCache
::newAccelerator( array() );
138 } catch ( Exception
$e ) {
142 $this->srvCache
= $this->srvCache ?
: new EmptyBagOStuff();
145 public function getFeatures() {
146 return ( FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
149 protected function resolveContainerPath( $container, $relStoragePath ) {
150 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
151 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
152 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
153 return null; // too long for Swift
156 return $relStoragePath;
159 public function isPathUsableInternal( $storagePath ) {
160 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
161 if ( $rel === null ) {
162 return false; // invalid
165 return is_array( $this->getContainerStat( $container ) );
169 * Sanitize and filter the custom headers from a $params array.
170 * We only allow certain Content- and X-Content- headers.
172 * @param array $headers
173 * @return array Sanitized value of 'headers' field in $params
175 protected function sanitizeHdrs( array $params ) {
178 // Normalize casing, and strip out illegal headers
179 if ( isset( $params['headers'] ) ) {
180 foreach ( $params['headers'] as $name => $value ) {
181 $name = strtolower( $name );
182 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
183 continue; // blacklisted
184 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
185 $headers[$name] = $value; // allowed
186 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
187 $headers[$name] = $value; // allowed
191 // By default, Swift has annoyingly low maximum header value limits
192 if ( isset( $headers['content-disposition'] ) ) {
194 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
195 $part = trim( $part );
196 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
197 if ( strlen( $new ) <= 255 ) {
200 break; // too long; sigh
203 $headers['content-disposition'] = $disposition;
209 protected function doCreateInternal( array $params ) {
210 $status = Status
::newGood();
212 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
213 if ( $dstRel === null ) {
214 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
219 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
220 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
222 $reqs = array( array(
224 'url' => array( $dstCont, $dstRel ),
226 'content-length' => strlen( $params['content'] ),
227 'etag' => md5( $params['content'] ),
228 'content-type' => $contentType,
229 'x-object-meta-sha1base36' => $sha1Hash
230 ) +
$this->sanitizeHdrs( $params ),
231 'body' => $params['content']
235 $method = __METHOD__
;
236 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
237 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
238 if ( $rcode === 201 ) {
240 } elseif ( $rcode === 412 ) {
241 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
243 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
247 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
248 if ( !empty( $params['async'] ) ) { // deferred
249 $status->value
= $opHandle;
250 } else { // actually write the object in Swift
251 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
257 protected function doStoreInternal( array $params ) {
258 $status = Status
::newGood();
260 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
261 if ( $dstRel === null ) {
262 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
267 wfSuppressWarnings();
268 $sha1Hash = sha1_file( $params['src'] );
270 if ( $sha1Hash === false ) { // source doesn't exist?
271 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
275 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
276 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
278 $handle = fopen( $params['src'], 'rb' );
279 if ( $handle === false ) { // source doesn't exist?
280 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
285 $reqs = array( array(
287 'url' => array( $dstCont, $dstRel ),
289 'content-length' => filesize( $params['src'] ),
290 'etag' => md5_file( $params['src'] ),
291 'content-type' => $contentType,
292 'x-object-meta-sha1base36' => $sha1Hash
293 ) +
$this->sanitizeHdrs( $params ),
294 'body' => $handle // resource
298 $method = __METHOD__
;
299 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
300 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
301 if ( $rcode === 201 ) {
303 } elseif ( $rcode === 412 ) {
304 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
306 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
310 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
311 if ( !empty( $params['async'] ) ) { // deferred
312 $status->value
= $opHandle;
313 } else { // actually write the object in Swift
314 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
320 protected function doCopyInternal( array $params ) {
321 $status = Status
::newGood();
323 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
324 if ( $srcRel === null ) {
325 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
330 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
331 if ( $dstRel === null ) {
332 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
337 $reqs = array( array(
339 'url' => array( $dstCont, $dstRel ),
341 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
342 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
343 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
347 $method = __METHOD__
;
348 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
349 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
350 if ( $rcode === 201 ) {
352 } elseif ( $rcode === 404 ) {
353 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
355 $be->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 doMoveInternal( 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'] );
389 'url' => array( $dstCont, $dstRel ),
391 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
392 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
393 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
396 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
398 'method' => 'DELETE',
399 'url' => array( $srcCont, $srcRel ),
405 $method = __METHOD__
;
406 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
407 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
408 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
410 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
412 } elseif ( $rcode === 404 ) {
413 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
415 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
419 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
420 if ( !empty( $params['async'] ) ) { // deferred
421 $status->value
= $opHandle;
422 } else { // actually move the object in Swift
423 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
429 protected function doDeleteInternal( array $params ) {
430 $status = Status
::newGood();
432 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
433 if ( $srcRel === null ) {
434 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
439 $reqs = array( array(
440 'method' => 'DELETE',
441 'url' => array( $srcCont, $srcRel ),
446 $method = __METHOD__
;
447 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
448 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
449 if ( $rcode === 204 ) {
451 } elseif ( $rcode === 404 ) {
452 if ( empty( $params['ignoreMissingSource'] ) ) {
453 $status->fatal( 'backend-fail-delete', $params['src'] );
456 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
460 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
461 if ( !empty( $params['async'] ) ) { // deferred
462 $status->value
= $opHandle;
463 } else { // actually delete the object in Swift
464 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
470 protected function doDescribeInternal( array $params ) {
471 $status = Status
::newGood();
473 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
474 if ( $srcRel === null ) {
475 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
480 // Fetch the old object headers/metadata...this should be in stat cache by now
481 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
482 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
483 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
486 $status->fatal( 'backend-fail-describe', $params['src'] );
491 // POST clears prior headers, so we need to merge the changes in to the old ones
493 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
494 $metaHdrs["x-object-meta-$name"] = $value;
496 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
498 $reqs = array( array(
500 'url' => array( $srcCont, $srcRel ),
501 'headers' => $metaHdrs +
$customHdrs
505 $method = __METHOD__
;
506 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
507 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
508 if ( $rcode === 202 ) {
510 } elseif ( $rcode === 404 ) {
511 $status->fatal( 'backend-fail-describe', $params['src'] );
513 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
517 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
518 if ( !empty( $params['async'] ) ) { // deferred
519 $status->value
= $opHandle;
520 } else { // actually change the object in Swift
521 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
527 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
528 $status = Status
::newGood();
530 // (a) Check if container already exists
531 $stat = $this->getContainerStat( $fullCont );
532 if ( is_array( $stat ) ) {
533 return $status; // already there
534 } elseif ( $stat === null ) {
535 $status->fatal( 'backend-fail-internal', $this->name
);
540 // (b) Create container as needed with proper ACLs
541 if ( $stat === false ) {
542 $params['op'] = 'prepare';
543 $status->merge( $this->createContainer( $fullCont, $params ) );
549 protected function doSecureInternal( $fullCont, $dir, array $params ) {
550 $status = Status
::newGood();
551 if ( empty( $params['noAccess'] ) ) {
552 return $status; // nothing to do
555 $stat = $this->getContainerStat( $fullCont );
556 if ( is_array( $stat ) ) {
557 // Make container private to end-users...
558 $status->merge( $this->setContainerAccess(
560 array( $this->swiftUser
), // read
561 array( $this->swiftUser
) // write
563 } elseif ( $stat === false ) {
564 $status->fatal( 'backend-fail-usable', $params['dir'] );
566 $status->fatal( 'backend-fail-internal', $this->name
);
572 protected function doPublishInternal( $fullCont, $dir, array $params ) {
573 $status = Status
::newGood();
575 $stat = $this->getContainerStat( $fullCont );
576 if ( is_array( $stat ) ) {
577 // Make container public to end-users...
578 $status->merge( $this->setContainerAccess(
580 array( $this->swiftUser
, '.r:*' ), // read
581 array( $this->swiftUser
) // write
583 } elseif ( $stat === false ) {
584 $status->fatal( 'backend-fail-usable', $params['dir'] );
586 $status->fatal( 'backend-fail-internal', $this->name
);
592 protected function doCleanInternal( $fullCont, $dir, array $params ) {
593 $status = Status
::newGood();
595 // Only containers themselves can be removed, all else is virtual
597 return $status; // nothing to do
600 // (a) Check the container
601 $stat = $this->getContainerStat( $fullCont, true );
602 if ( $stat === false ) {
603 return $status; // ok, nothing to do
604 } elseif ( !is_array( $stat ) ) {
605 $status->fatal( 'backend-fail-internal', $this->name
);
610 // (b) Delete the container if empty
611 if ( $stat['count'] == 0 ) {
612 $params['op'] = 'clean';
613 $status->merge( $this->deleteContainer( $fullCont, $params ) );
619 protected function doGetFileStat( array $params ) {
620 $params['concurrency'] = 1;
621 $stats = $this->doGetFileStatMulti( array( 'srcs' => array( $params['src'] ) ) +
$params );
623 return reset( $stats );
627 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
628 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
629 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
632 * @param int $format Output format (TS_* constant)
634 * @throws FileBackendError
636 protected function convertSwiftDate( $ts, $format = TS_MW
) {
638 $timestamp = new MWTimestamp( $ts );
640 return $timestamp->getTimestamp( $format );
641 } catch ( MWException
$e ) {
642 throw new FileBackendError( $e->getMessage() );
647 * Fill in any missing object metadata and save it to Swift
649 * @param array $objHdrs Object response headers
650 * @param string $path Storage path to object
651 * @return array New headers
653 protected function addMissingMetadata( array $objHdrs, $path ) {
654 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
655 return $objHdrs; // nothing to do
658 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
659 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
661 $auth = $this->getAuthentication();
663 $objHdrs['x-object-meta-sha1base36'] = false;
665 return $objHdrs; // failed
668 $status = Status
::newGood();
669 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
670 if ( $status->isOK() ) {
671 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
673 $hash = $tmpFile->getSha1Base36();
674 if ( $hash !== false ) {
675 $objHdrs['x-object-meta-sha1base36'] = $hash;
676 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
677 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
679 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
680 'headers' => $this->authTokenHeaders( $auth ) +
$objHdrs
682 if ( $rcode >= 200 && $rcode <= 299 ) {
683 return $objHdrs; // success
688 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING
);
689 $objHdrs['x-object-meta-sha1base36'] = false;
691 return $objHdrs; // failed
694 protected function doGetFileContentsMulti( array $params ) {
697 $auth = $this->getAuthentication();
699 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
700 // Blindly create tmp files and stream to them, catching any exception if the file does
701 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
702 $reqs = array(); // (path => op)
704 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
705 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
706 if ( $srcRel === null ||
!$auth ) {
707 $contents[$path] = false;
710 // Create a new temporary memory file...
711 $handle = fopen( 'php://temp', 'wb' );
713 $reqs[$path] = array(
715 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
716 'headers' => $this->authTokenHeaders( $auth )
717 +
$this->headersFromParams( $params ),
721 $contents[$path] = false;
724 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
725 $reqs = $this->http
->runMulti( $reqs, $opts );
726 foreach ( $reqs as $path => $op ) {
727 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
728 if ( $rcode >= 200 && $rcode <= 299 ) {
729 rewind( $op['stream'] ); // start from the beginning
730 $contents[$path] = stream_get_contents( $op['stream'] );
731 } elseif ( $rcode === 404 ) {
732 $contents[$path] = false;
734 $this->onError( null, __METHOD__
,
735 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
737 fclose( $op['stream'] ); // close open handle
743 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
744 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
745 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
746 if ( $status->isOk() ) {
747 return ( count( $status->value
) ) > 0;
750 return null; // error
754 * @see FileBackendStore::getDirectoryListInternal()
755 * @param string $fullCont
757 * @param array $params
758 * @return SwiftFileBackendDirList
760 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
761 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
765 * @see FileBackendStore::getFileListInternal()
766 * @param string $fullCont
768 * @param array $params
769 * @return SwiftFileBackendFileList
771 public function getFileListInternal( $fullCont, $dir, array $params ) {
772 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
776 * Do not call this function outside of SwiftFileBackendFileList
778 * @param string $fullCont Resolved container name
779 * @param string $dir Resolved storage directory with no trailing slash
780 * @param string|null $after Resolved container relative path to list items after
781 * @param int $limit Max number of items to list
782 * @param array $params Parameters for getDirectoryList()
783 * @return array List of container relative resolved paths of directories directly under $dir
784 * @throws FileBackendError
786 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
788 if ( $after === INF
) {
789 return $dirs; // nothing more
792 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
794 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
795 // Non-recursive: only list dirs right under $dir
796 if ( !empty( $params['topOnly'] ) ) {
797 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
798 if ( !$status->isOk() ) {
799 return $dirs; // error
801 $objects = $status->value
;
802 foreach ( $objects as $object ) { // files and directories
803 if ( substr( $object, -1 ) === '/' ) {
804 $dirs[] = $object; // directories end in '/'
808 // Recursive: list all dirs under $dir and its subdirs
809 $getParentDir = function ( $path ) {
810 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
813 // Get directory from last item of prior page
814 $lastDir = $getParentDir( $after ); // must be first page
815 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
817 if ( !$status->isOk() ) {
818 return $dirs; // error
821 $objects = $status->value
;
823 foreach ( $objects as $object ) { // files
824 $objectDir = $getParentDir( $object ); // directory of object
826 if ( $objectDir !== false && $objectDir !== $dir ) {
827 // Swift stores paths in UTF-8, using binary sorting.
828 // See function "create_container_table" in common/db.py.
829 // If a directory is not "greater" than the last one,
830 // then it was already listed by the calling iterator.
831 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
833 do { // add dir and all its parent dirs
834 $dirs[] = "{$pDir}/";
835 $pDir = $getParentDir( $pDir );
836 } while ( $pDir !== false // sanity
837 && strcmp( $pDir, $lastDir ) > 0 // not done already
838 && strlen( $pDir ) > strlen( $dir ) // within $dir
841 $lastDir = $objectDir;
845 // Page on the unfiltered directory listing (what is returned may be filtered)
846 if ( count( $objects ) < $limit ) {
847 $after = INF
; // avoid a second RTT
849 $after = end( $objects ); // update last item
856 * Do not call this function outside of SwiftFileBackendFileList
858 * @param string $fullCont Resolved container name
859 * @param string $dir Resolved storage directory with no trailing slash
860 * @param string|null $after Resolved container relative path of file to list items after
861 * @param int $limit Max number of items to list
862 * @param array $params Parameters for getDirectoryList()
863 * @return array List of resolved container relative paths of files under $dir
864 * @throws FileBackendError
866 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
867 $files = array(); // list of (path, stat array or null) entries
868 if ( $after === INF
) {
869 return $files; // nothing more
872 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
874 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
875 // $objects will contain a list of unfiltered names or CF_Object items
876 // Non-recursive: only list files right under $dir
877 if ( !empty( $params['topOnly'] ) ) {
878 if ( !empty( $params['adviseStat'] ) ) {
879 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
881 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
884 // Recursive: list all files under $dir and its subdirs
885 if ( !empty( $params['adviseStat'] ) ) {
886 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
888 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
892 // Reformat this list into a list of (name, stat array or null) entries
893 if ( !$status->isOk() ) {
894 return $files; // error
897 $objects = $status->value
;
898 $files = $this->buildFileObjectListing( $params, $dir, $objects );
900 // Page on the unfiltered object listing (what is returned may be filtered)
901 if ( count( $objects ) < $limit ) {
902 $after = INF
; // avoid a second RTT
904 $after = end( $objects ); // update last item
905 $after = is_object( $after ) ?
$after->name
: $after;
912 * Build a list of file objects, filtering out any directories
913 * and extracting any stat info if provided in $objects (for CF_Objects)
915 * @param array $params Parameters for getDirectoryList()
916 * @param string $dir Resolved container directory path
917 * @param array $objects List of CF_Object items or object names
918 * @return array List of (names,stat array or null) entries
920 private function buildFileObjectListing( array $params, $dir, array $objects ) {
922 foreach ( $objects as $object ) {
923 if ( is_object( $object ) ) {
924 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
925 continue; // virtual directory entry; ignore
928 // Convert various random Swift dates to TS_MW
929 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
930 'size' => (int)$object->bytes
,
931 // Note: manifiest ETags are not an MD5 of the file
932 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
933 'latest' => false // eventually consistent
935 $names[] = array( $object->name
, $stat );
936 } elseif ( substr( $object, -1 ) !== '/' ) {
937 // Omit directories, which end in '/' in listings
938 $names[] = array( $object, null );
946 * Do not call this function outside of SwiftFileBackendFileList
948 * @param string $path Storage path
949 * @param array $val Stat value
951 public function loadListingStatInternal( $path, array $val ) {
952 $this->cheapCache
->set( $path, 'stat', $val );
955 protected function doGetFileXAttributes( array $params ) {
956 $stat = $this->getFileStat( $params );
958 if ( !isset( $stat['xattr'] ) ) {
959 // Stat entries filled by file listings don't include metadata/headers
960 $this->clearCache( array( $params['src'] ) );
961 $stat = $this->getFileStat( $params );
964 return $stat['xattr'];
970 protected function doGetFileSha1base36( array $params ) {
971 $stat = $this->getFileStat( $params );
973 if ( !isset( $stat['sha1'] ) ) {
974 // Stat entries filled by file listings don't include SHA1
975 $this->clearCache( array( $params['src'] ) );
976 $stat = $this->getFileStat( $params );
979 return $stat['sha1'];
985 protected function doStreamFile( array $params ) {
986 $status = Status
::newGood();
988 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
989 if ( $srcRel === null ) {
990 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
993 $auth = $this->getAuthentication();
994 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
995 $status->fatal( 'backend-fail-stream', $params['src'] );
1000 $handle = fopen( 'php://output', 'wb' );
1002 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1004 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1005 'headers' => $this->authTokenHeaders( $auth )
1006 +
$this->headersFromParams( $params ),
1007 'stream' => $handle,
1010 if ( $rcode >= 200 && $rcode <= 299 ) {
1012 } elseif ( $rcode === 404 ) {
1013 $status->fatal( 'backend-fail-stream', $params['src'] );
1015 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1021 protected function doGetLocalCopyMulti( array $params ) {
1022 $tmpFiles = array();
1024 $auth = $this->getAuthentication();
1026 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1027 // Blindly create tmp files and stream to them, catching any exception if the file does
1028 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1029 $reqs = array(); // (path => op)
1031 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1032 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1033 if ( $srcRel === null ||
!$auth ) {
1034 $tmpFiles[$path] = null;
1037 // Get source file extension
1038 $ext = FileBackend
::extensionFromPath( $path );
1039 // Create a new temporary file...
1040 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1042 $handle = fopen( $tmpFile->getPath(), 'wb' );
1044 $reqs[$path] = array(
1046 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1047 'headers' => $this->authTokenHeaders( $auth )
1048 +
$this->headersFromParams( $params ),
1049 'stream' => $handle,
1055 $tmpFiles[$path] = $tmpFile;
1058 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1059 $reqs = $this->http
->runMulti( $reqs, $opts );
1060 foreach ( $reqs as $path => $op ) {
1061 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1062 fclose( $op['stream'] ); // close open handle
1063 if ( $rcode >= 200 && $rcode <= 299
1064 // double check that the disk is not full/broken
1065 && $tmpFiles[$path]->getSize() == $rhdrs['content-length']
1068 } elseif ( $rcode === 404 ) {
1069 $tmpFiles[$path] = false;
1071 $tmpFiles[$path] = null;
1072 $this->onError( null, __METHOD__
,
1073 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1080 public function getFileHttpUrl( array $params ) {
1081 if ( $this->swiftTempUrlKey
!= '' ||
1082 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1084 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1085 if ( $srcRel === null ) {
1086 return null; // invalid path
1089 $auth = $this->getAuthentication();
1094 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1095 $expires = time() +
$ttl;
1097 if ( $this->swiftTempUrlKey
!= '' ) {
1098 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1099 // Swift wants the signature based on the unencoded object name
1100 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1101 $signature = hash_hmac( 'sha1',
1102 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1103 $this->swiftTempUrlKey
1106 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1107 } else { // give S3 API URL for rgw
1108 // Path for signature starts with the bucket
1109 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1110 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1111 // Calculate the hash
1112 $signature = base64_encode( hash_hmac(
1114 "GET\n\n\n{$expires}\n{$spath}",
1115 $this->rgwS3SecretKey
,
1118 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1119 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1120 return wfAppendQuery(
1121 str_replace( '/swift/v1', '', // S3 API is the rgw default
1122 $this->storageUrl( $auth ) . $spath ),
1124 'Signature' => $signature,
1125 'Expires' => $expires,
1126 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1134 protected function directoriesAreVirtual() {
1139 * Get headers to send to Swift when reading a file based
1140 * on a FileBackend params array, e.g. that of getLocalCopy().
1141 * $params is currently only checked for a 'latest' flag.
1143 * @param array $params
1146 protected function headersFromParams( array $params ) {
1148 if ( !empty( $params['latest'] ) ) {
1149 $hdrs['x-newest'] = 'true';
1155 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1156 $statuses = array();
1158 $auth = $this->getAuthentication();
1160 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1161 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1167 // Split the HTTP requests into stages that can be done concurrently
1168 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1169 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1170 $reqs = $fileOpHandle->httpOp
;
1171 // Convert the 'url' parameter to an actual URL using $auth
1172 foreach ( $reqs as $stage => &$req ) {
1173 list( $container, $relPath ) = $req['url'];
1174 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1175 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1176 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1177 $httpReqsByStage[$stage][$index] = $req;
1179 $statuses[$index] = Status
::newGood();
1182 // Run all requests for the first stage, then the next, and so on
1183 $reqCount = count( $httpReqsByStage );
1184 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1185 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1186 foreach ( $httpReqs as $index => $httpReq ) {
1187 // Run the callback for each request of this operation
1188 $callback = $fileOpHandles[$index]->callback
;
1189 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1190 // On failure, abort all remaining requests for this operation
1191 // (e.g. abort the DELETE request if the COPY request fails for a move)
1192 if ( !$statuses[$index]->isOK() ) {
1193 $stages = count( $fileOpHandles[$index]->httpOp
);
1194 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1195 unset( $httpReqsByStage[$s][$index] );
1205 * Set read/write permissions for a Swift container.
1207 * @see http://swift.openstack.org/misc.html#acls
1209 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1210 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1212 * @param string $container Resolved Swift container
1213 * @param array $readGrps List of the possible criteria for a request to have
1214 * access to read a container. Each item is one of the following formats:
1215 * - account:user : Grants access if the request is by the given user
1216 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1217 * matches the expression and the request is not for a listing.
1218 * Setting this to '*' effectively makes a container public.
1219 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1220 * matches the expression and the request is for a listing.
1221 * @param array $writeGrps A list of the possible criteria for a request to have
1222 * access to write to a container. Each item is of the following format:
1223 * - account:user : Grants access if the request is by the given user
1226 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1227 $status = Status
::newGood();
1228 $auth = $this->getAuthentication();
1231 $status->fatal( 'backend-fail-connect', $this->name
);
1236 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1238 'url' => $this->storageUrl( $auth, $container ),
1239 'headers' => $this->authTokenHeaders( $auth ) +
array(
1240 'x-container-read' => implode( ',', $readGrps ),
1241 'x-container-write' => implode( ',', $writeGrps )
1245 if ( $rcode != 204 && $rcode !== 202 ) {
1246 $status->fatal( 'backend-fail-internal', $this->name
);
1253 * Get a Swift container stat array, possibly from process cache.
1254 * Use $reCache if the file count or byte count is needed.
1256 * @param string $container Container name
1257 * @param bool $bypassCache Bypass all caches and load from Swift
1258 * @return array|bool|null False on 404, null on failure
1260 protected function getContainerStat( $container, $bypassCache = false ) {
1261 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
1263 if ( $bypassCache ) { // purge cache
1264 $this->containerStatCache
->clear( $container );
1265 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1266 $this->primeContainerCache( array( $container ) ); // check persistent cache
1268 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1269 $auth = $this->getAuthentication();
1274 wfProfileIn( __METHOD__
. "-{$this->name}-miss" );
1275 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1277 'url' => $this->storageUrl( $auth, $container ),
1278 'headers' => $this->authTokenHeaders( $auth )
1280 wfProfileOut( __METHOD__
. "-{$this->name}-miss" );
1282 if ( $rcode === 204 ) {
1284 'count' => $rhdrs['x-container-object-count'],
1285 'bytes' => $rhdrs['x-container-bytes-used']
1287 if ( $bypassCache ) {
1290 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1291 $this->setContainerCache( $container, $stat ); // update persistent cache
1293 } elseif ( $rcode === 404 ) {
1296 $this->onError( null, __METHOD__
,
1297 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1303 return $this->containerStatCache
->get( $container, 'stat' );
1307 * Create a Swift container
1309 * @param string $container Container name
1310 * @param array $params
1313 protected function createContainer( $container, array $params ) {
1314 $status = Status
::newGood();
1316 $auth = $this->getAuthentication();
1318 $status->fatal( 'backend-fail-connect', $this->name
);
1323 // @see SwiftFileBackend::setContainerAccess()
1324 if ( empty( $params['noAccess'] ) ) {
1325 $readGrps = array( '.r:*', $this->swiftUser
); // public
1327 $readGrps = array( $this->swiftUser
); // private
1329 $writeGrps = array( $this->swiftUser
); // sanity
1331 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1333 'url' => $this->storageUrl( $auth, $container ),
1334 'headers' => $this->authTokenHeaders( $auth ) +
array(
1335 'x-container-read' => implode( ',', $readGrps ),
1336 'x-container-write' => implode( ',', $writeGrps )
1340 if ( $rcode === 201 ) { // new
1342 } elseif ( $rcode === 202 ) { // already there
1343 // this shouldn't really happen, but is OK
1345 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1352 * Delete a Swift container
1354 * @param string $container Container name
1355 * @param array $params
1358 protected function deleteContainer( $container, array $params ) {
1359 $status = Status
::newGood();
1361 $auth = $this->getAuthentication();
1363 $status->fatal( 'backend-fail-connect', $this->name
);
1368 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1369 'method' => 'DELETE',
1370 'url' => $this->storageUrl( $auth, $container ),
1371 'headers' => $this->authTokenHeaders( $auth )
1374 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1375 $this->containerStatCache
->clear( $container ); // purge
1376 } elseif ( $rcode === 404 ) { // not there
1377 // this shouldn't really happen, but is OK
1378 } elseif ( $rcode === 409 ) { // not empty
1379 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1381 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1388 * Get a list of objects under a container.
1389 * Either just the names or a list of stdClass objects with details can be returned.
1391 * @param string $fullCont
1392 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1393 * @param integer $limit
1394 * @param string|null $after
1395 * @param string|null $prefix
1396 * @param string|null $delim
1397 * @return Status With the list as value
1399 private function objectListing(
1400 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1402 $status = Status
::newGood();
1404 $auth = $this->getAuthentication();
1406 $status->fatal( 'backend-fail-connect', $this->name
);
1411 $query = array( 'limit' => $limit );
1412 if ( $type === 'info' ) {
1413 $query['format'] = 'json';
1415 if ( $after !== null ) {
1416 $query['marker'] = $after;
1418 if ( $prefix !== null ) {
1419 $query['prefix'] = $prefix;
1421 if ( $delim !== null ) {
1422 $query['delimiter'] = $delim;
1425 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1427 'url' => $this->storageUrl( $auth, $fullCont ),
1429 'headers' => $this->authTokenHeaders( $auth )
1432 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1433 if ( $rcode === 200 ) { // good
1434 if ( $type === 'info' ) {
1435 $status->value
= FormatJson
::decode( trim( $rbody ) );
1437 $status->value
= explode( "\n", trim( $rbody ) );
1439 } elseif ( $rcode === 204 ) {
1440 $status->value
= array(); // empty container
1441 } elseif ( $rcode === 404 ) {
1442 $status->value
= array(); // no container
1444 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1450 protected function doPrimeContainerCache( array $containerInfo ) {
1451 foreach ( $containerInfo as $container => $info ) {
1452 $this->containerStatCache
->set( $container, 'stat', $info );
1456 protected function doGetFileStatMulti( array $params ) {
1459 $auth = $this->getAuthentication();
1462 foreach ( $params['srcs'] as $path ) {
1463 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1464 if ( $srcRel === null ) {
1465 $stats[$path] = false;
1466 continue; // invalid storage path
1467 } elseif ( !$auth ) {
1468 $stats[$path] = null;
1472 // (a) Check the container
1473 $cstat = $this->getContainerStat( $srcCont );
1474 if ( $cstat === false ) {
1475 $stats[$path] = false;
1476 continue; // ok, nothing to do
1477 } elseif ( !is_array( $cstat ) ) {
1478 $stats[$path] = null;
1482 $reqs[$path] = array(
1484 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1485 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1489 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1490 $reqs = $this->http
->runMulti( $reqs, $opts );
1492 foreach ( $params['srcs'] as $path ) {
1493 if ( array_key_exists( $path, $stats ) ) {
1494 continue; // some sort of failure above
1496 // (b) Check the file
1497 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1498 if ( $rcode === 200 ||
$rcode === 204 ) {
1499 // Update the object if it is missing some headers
1500 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1501 // Fetch all of the custom metadata headers
1502 $metadata = array();
1503 foreach ( $rhdrs as $name => $value ) {
1504 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
1505 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
1508 // Fetch all of the custom raw HTTP headers
1509 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1511 // Convert various random Swift dates to TS_MW
1512 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1513 // Empty objects actually return no content-length header in Ceph
1514 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1515 'sha1' => $rhdrs[ 'x-object-meta-sha1base36'],
1516 // Note: manifiest ETags are not an MD5 of the file
1517 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1518 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1520 } elseif ( $rcode === 404 ) {
1524 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1526 $stats[$path] = $stat;
1533 * @return array|null Credential map
1535 protected function getAuthentication() {
1536 if ( $this->authErrorTimestamp
!== null ) {
1537 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1538 return null; // failed last attempt; don't bother
1539 } else { // actually retry this time
1540 $this->authErrorTimestamp
= null;
1543 // Session keys expire after a while, so we renew them periodically
1544 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1545 // Authenticate with proxy and get a session key...
1546 if ( !$this->authCreds ||
$reAuth ) {
1547 $this->authSessionTimestamp
= 0;
1548 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1549 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1550 // Try to use the credential cache
1551 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1552 $this->authCreds
= $creds;
1553 // Skew the timestamp for worst case to avoid using stale credentials
1554 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1555 } else { // cache miss
1556 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1558 'url' => "{$this->swiftAuthUrl}/v1.0",
1560 'x-auth-user' => $this->swiftUser
,
1561 'x-auth-key' => $this->swiftKey
1565 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1566 $this->authCreds
= array(
1567 'auth_token' => $rhdrs['x-auth-token'],
1568 'storage_url' => $rhdrs['x-storage-url']
1570 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1571 $this->authSessionTimestamp
= time();
1572 } elseif ( $rcode === 401 ) {
1573 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1574 $this->authErrorTimestamp
= time();
1578 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1579 $this->authErrorTimestamp
= time();
1586 return $this->authCreds
;
1590 * @param array $creds From getAuthentication()
1591 * @param string $container
1592 * @param string $object
1595 protected function storageUrl( array $creds, $container = null, $object = null ) {
1596 $parts = array( $creds['storage_url'] );
1597 if ( strlen( $container ) ) {
1598 $parts[] = rawurlencode( $container );
1600 if ( strlen( $object ) ) {
1601 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1604 return implode( '/', $parts );
1608 * @param array $creds From getAuthentication()
1611 protected function authTokenHeaders( array $creds ) {
1612 return array( 'x-auth-token' => $creds['auth_token'] );
1616 * Get the cache key for a container
1618 * @param string $username
1621 private function getCredsCacheKey( $username ) {
1622 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1626 * Log an unexpected exception for this backend.
1627 * This also sets the Status object to have a fatal error.
1629 * @param Status|null $status
1630 * @param string $func
1631 * @param array $params
1632 * @param string $err Error string
1633 * @param integer $code HTTP status
1634 * @param string $desc HTTP status description
1636 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1637 if ( $status instanceof Status
) {
1638 $status->fatal( 'backend-fail-internal', $this->name
);
1640 if ( $code == 401 ) { // possibly a stale token
1641 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1643 wfDebugLog( 'SwiftBackend',
1644 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1645 ( $err ?
": $err" : "" )
1651 * @see FileBackendStoreOpHandle
1653 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1654 /** @var array List of Requests for MultiHttpClient */
1660 * @param SwiftFileBackend $backend
1661 * @param Closure $callback Function that takes (HTTP request array, status)
1662 * @param array $httpOp MultiHttpClient op
1664 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1665 $this->backend
= $backend;
1666 $this->callback
= $callback;
1667 $this->httpOp
= $httpOp;
1672 * SwiftFileBackend helper class to page through listings.
1673 * Swift also has a listing limit of 10,000 objects for sanity.
1674 * Do not use this class from places outside SwiftFileBackend.
1676 * @ingroup FileBackend
1678 abstract class SwiftFileBackendList
implements Iterator
{
1679 /** @var array List of path or (path,stat array) entries */
1680 protected $bufferIter = array();
1682 /** @var string List items *after* this path */
1683 protected $bufferAfter = null;
1689 protected $params = array();
1691 /** @var SwiftFileBackend */
1694 /** @var string Container name */
1695 protected $container;
1697 /** @var string Storage directory */
1701 protected $suffixStart;
1703 const PAGE_SIZE
= 9000; // file listing buffer size
1706 * @param SwiftFileBackend $backend
1707 * @param string $fullCont Resolved container name
1708 * @param string $dir Resolved directory relative to container
1709 * @param array $params
1711 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1712 $this->backend
= $backend;
1713 $this->container
= $fullCont;
1715 if ( substr( $this->dir
, -1 ) === '/' ) {
1716 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1718 if ( $this->dir
== '' ) { // whole container
1719 $this->suffixStart
= 0;
1720 } else { // dir within container
1721 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1723 $this->params
= $params;
1727 * @see Iterator::key()
1730 public function key() {
1735 * @see Iterator::next()
1737 public function next() {
1738 // Advance to the next file in the page
1739 next( $this->bufferIter
);
1741 // Check if there are no files left in this page and
1742 // advance to the next page if this page was not empty.
1743 if ( !$this->valid() && count( $this->bufferIter
) ) {
1744 $this->bufferIter
= $this->pageFromList(
1745 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1746 ); // updates $this->bufferAfter
1751 * @see Iterator::rewind()
1753 public function rewind() {
1755 $this->bufferAfter
= null;
1756 $this->bufferIter
= $this->pageFromList(
1757 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1758 ); // updates $this->bufferAfter
1762 * @see Iterator::valid()
1765 public function valid() {
1766 if ( $this->bufferIter
=== null ) {
1767 return false; // some failure?
1769 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1774 * Get the given list portion (page)
1776 * @param string $container Resolved container name
1777 * @param string $dir Resolved path relative to container
1778 * @param string $after null
1780 * @param array $params
1781 * @return Traversable|array
1783 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1787 * Iterator for listing directories
1789 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1791 * @see Iterator::current()
1792 * @return string|bool String (relative path) or false
1794 public function current() {
1795 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1798 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1799 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1804 * Iterator for listing regular files
1806 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1808 * @see Iterator::current()
1809 * @return string|bool String (relative path) or false
1811 public function current() {
1812 list( $path, $stat ) = current( $this->bufferIter
);
1813 $relPath = substr( $path, $this->suffixStart
);
1814 if ( is_array( $stat ) ) {
1815 $storageDir = rtrim( $this->params
['dir'], '/' );
1816 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1822 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1823 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );