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 = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) +
$params;
621 unset( $params['src'] );
622 $stats = $this->doGetFileStatMulti( $params );
624 return reset( $stats );
628 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
629 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
630 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
633 * @param int $format Output format (TS_* constant)
635 * @throws FileBackendError
637 protected function convertSwiftDate( $ts, $format = TS_MW
) {
639 $timestamp = new MWTimestamp( $ts );
641 return $timestamp->getTimestamp( $format );
642 } catch ( MWException
$e ) {
643 throw new FileBackendError( $e->getMessage() );
648 * Fill in any missing object metadata and save it to Swift
650 * @param array $objHdrs Object response headers
651 * @param string $path Storage path to object
652 * @return array New headers
654 protected function addMissingMetadata( array $objHdrs, $path ) {
655 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
656 return $objHdrs; // nothing to do
659 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
660 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
662 $auth = $this->getAuthentication();
664 $objHdrs['x-object-meta-sha1base36'] = false;
666 return $objHdrs; // failed
669 $status = Status
::newGood();
670 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
671 if ( $status->isOK() ) {
672 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
674 $hash = $tmpFile->getSha1Base36();
675 if ( $hash !== false ) {
676 $objHdrs['x-object-meta-sha1base36'] = $hash;
677 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
678 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
680 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
681 'headers' => $this->authTokenHeaders( $auth ) +
$objHdrs
683 if ( $rcode >= 200 && $rcode <= 299 ) {
684 return $objHdrs; // success
689 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING
);
690 $objHdrs['x-object-meta-sha1base36'] = false;
692 return $objHdrs; // failed
695 protected function doGetFileContentsMulti( array $params ) {
698 $auth = $this->getAuthentication();
700 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
701 // Blindly create tmp files and stream to them, catching any exception if the file does
702 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
703 $reqs = array(); // (path => op)
705 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
706 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
707 if ( $srcRel === null ||
!$auth ) {
708 $contents[$path] = false;
711 // Create a new temporary memory file...
712 $handle = fopen( 'php://temp', 'wb' );
714 $reqs[$path] = array(
716 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
717 'headers' => $this->authTokenHeaders( $auth )
718 +
$this->headersFromParams( $params ),
722 $contents[$path] = false;
725 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
726 $reqs = $this->http
->runMulti( $reqs, $opts );
727 foreach ( $reqs as $path => $op ) {
728 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
729 if ( $rcode >= 200 && $rcode <= 299 ) {
730 rewind( $op['stream'] ); // start from the beginning
731 $contents[$path] = stream_get_contents( $op['stream'] );
732 } elseif ( $rcode === 404 ) {
733 $contents[$path] = false;
735 $this->onError( null, __METHOD__
,
736 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
738 fclose( $op['stream'] ); // close open handle
744 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
745 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
746 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
747 if ( $status->isOk() ) {
748 return ( count( $status->value
) ) > 0;
751 return null; // error
755 * @see FileBackendStore::getDirectoryListInternal()
756 * @param string $fullCont
758 * @param array $params
759 * @return SwiftFileBackendDirList
761 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
762 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
766 * @see FileBackendStore::getFileListInternal()
767 * @param string $fullCont
769 * @param array $params
770 * @return SwiftFileBackendFileList
772 public function getFileListInternal( $fullCont, $dir, array $params ) {
773 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
777 * Do not call this function outside of SwiftFileBackendFileList
779 * @param string $fullCont Resolved container name
780 * @param string $dir Resolved storage directory with no trailing slash
781 * @param string|null $after Resolved container relative path to list items after
782 * @param int $limit Max number of items to list
783 * @param array $params Parameters for getDirectoryList()
784 * @return array List of container relative resolved paths of directories directly under $dir
785 * @throws FileBackendError
787 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
789 if ( $after === INF
) {
790 return $dirs; // nothing more
793 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
795 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
796 // Non-recursive: only list dirs right under $dir
797 if ( !empty( $params['topOnly'] ) ) {
798 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
799 if ( !$status->isOk() ) {
800 return $dirs; // error
802 $objects = $status->value
;
803 foreach ( $objects as $object ) { // files and directories
804 if ( substr( $object, -1 ) === '/' ) {
805 $dirs[] = $object; // directories end in '/'
809 // Recursive: list all dirs under $dir and its subdirs
810 $getParentDir = function ( $path ) {
811 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
814 // Get directory from last item of prior page
815 $lastDir = $getParentDir( $after ); // must be first page
816 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
818 if ( !$status->isOk() ) {
819 return $dirs; // error
822 $objects = $status->value
;
824 foreach ( $objects as $object ) { // files
825 $objectDir = $getParentDir( $object ); // directory of object
827 if ( $objectDir !== false && $objectDir !== $dir ) {
828 // Swift stores paths in UTF-8, using binary sorting.
829 // See function "create_container_table" in common/db.py.
830 // If a directory is not "greater" than the last one,
831 // then it was already listed by the calling iterator.
832 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
834 do { // add dir and all its parent dirs
835 $dirs[] = "{$pDir}/";
836 $pDir = $getParentDir( $pDir );
837 } while ( $pDir !== false // sanity
838 && strcmp( $pDir, $lastDir ) > 0 // not done already
839 && strlen( $pDir ) > strlen( $dir ) // within $dir
842 $lastDir = $objectDir;
846 // Page on the unfiltered directory listing (what is returned may be filtered)
847 if ( count( $objects ) < $limit ) {
848 $after = INF
; // avoid a second RTT
850 $after = end( $objects ); // update last item
857 * Do not call this function outside of SwiftFileBackendFileList
859 * @param string $fullCont Resolved container name
860 * @param string $dir Resolved storage directory with no trailing slash
861 * @param string|null $after Resolved container relative path of file to list items after
862 * @param int $limit Max number of items to list
863 * @param array $params Parameters for getDirectoryList()
864 * @return array List of resolved container relative paths of files under $dir
865 * @throws FileBackendError
867 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
868 $files = array(); // list of (path, stat array or null) entries
869 if ( $after === INF
) {
870 return $files; // nothing more
873 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
875 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
876 // $objects will contain a list of unfiltered names or CF_Object items
877 // Non-recursive: only list files right under $dir
878 if ( !empty( $params['topOnly'] ) ) {
879 if ( !empty( $params['adviseStat'] ) ) {
880 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
882 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
885 // Recursive: list all files under $dir and its subdirs
886 if ( !empty( $params['adviseStat'] ) ) {
887 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
889 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
893 // Reformat this list into a list of (name, stat array or null) entries
894 if ( !$status->isOk() ) {
895 return $files; // error
898 $objects = $status->value
;
899 $files = $this->buildFileObjectListing( $params, $dir, $objects );
901 // Page on the unfiltered object listing (what is returned may be filtered)
902 if ( count( $objects ) < $limit ) {
903 $after = INF
; // avoid a second RTT
905 $after = end( $objects ); // update last item
906 $after = is_object( $after ) ?
$after->name
: $after;
913 * Build a list of file objects, filtering out any directories
914 * and extracting any stat info if provided in $objects (for CF_Objects)
916 * @param array $params Parameters for getDirectoryList()
917 * @param string $dir Resolved container directory path
918 * @param array $objects List of CF_Object items or object names
919 * @return array List of (names,stat array or null) entries
921 private function buildFileObjectListing( array $params, $dir, array $objects ) {
923 foreach ( $objects as $object ) {
924 if ( is_object( $object ) ) {
925 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
926 continue; // virtual directory entry; ignore
929 // Convert various random Swift dates to TS_MW
930 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
931 'size' => (int)$object->bytes
,
932 // Note: manifiest ETags are not an MD5 of the file
933 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
934 'latest' => false // eventually consistent
936 $names[] = array( $object->name
, $stat );
937 } elseif ( substr( $object, -1 ) !== '/' ) {
938 // Omit directories, which end in '/' in listings
939 $names[] = array( $object, null );
947 * Do not call this function outside of SwiftFileBackendFileList
949 * @param string $path Storage path
950 * @param array $val Stat value
952 public function loadListingStatInternal( $path, array $val ) {
953 $this->cheapCache
->set( $path, 'stat', $val );
956 protected function doGetFileXAttributes( array $params ) {
957 $stat = $this->getFileStat( $params );
959 if ( !isset( $stat['xattr'] ) ) {
960 // Stat entries filled by file listings don't include metadata/headers
961 $this->clearCache( array( $params['src'] ) );
962 $stat = $this->getFileStat( $params );
965 return $stat['xattr'];
971 protected function doGetFileSha1base36( array $params ) {
972 $stat = $this->getFileStat( $params );
974 if ( !isset( $stat['sha1'] ) ) {
975 // Stat entries filled by file listings don't include SHA1
976 $this->clearCache( array( $params['src'] ) );
977 $stat = $this->getFileStat( $params );
980 return $stat['sha1'];
986 protected function doStreamFile( array $params ) {
987 $status = Status
::newGood();
989 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
990 if ( $srcRel === null ) {
991 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
994 $auth = $this->getAuthentication();
995 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
996 $status->fatal( 'backend-fail-stream', $params['src'] );
1001 $handle = fopen( 'php://output', 'wb' );
1003 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1005 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1006 'headers' => $this->authTokenHeaders( $auth )
1007 +
$this->headersFromParams( $params ),
1008 'stream' => $handle,
1011 if ( $rcode >= 200 && $rcode <= 299 ) {
1013 } elseif ( $rcode === 404 ) {
1014 $status->fatal( 'backend-fail-stream', $params['src'] );
1016 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1022 protected function doGetLocalCopyMulti( array $params ) {
1023 $tmpFiles = array();
1025 $auth = $this->getAuthentication();
1027 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1028 // Blindly create tmp files and stream to them, catching any exception if the file does
1029 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1030 $reqs = array(); // (path => op)
1032 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1033 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1034 if ( $srcRel === null ||
!$auth ) {
1035 $tmpFiles[$path] = null;
1038 // Get source file extension
1039 $ext = FileBackend
::extensionFromPath( $path );
1040 // Create a new temporary file...
1041 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1043 $handle = fopen( $tmpFile->getPath(), 'wb' );
1045 $reqs[$path] = array(
1047 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1048 'headers' => $this->authTokenHeaders( $auth )
1049 +
$this->headersFromParams( $params ),
1050 'stream' => $handle,
1056 $tmpFiles[$path] = $tmpFile;
1059 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1060 $reqs = $this->http
->runMulti( $reqs, $opts );
1061 foreach ( $reqs as $path => $op ) {
1062 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1063 fclose( $op['stream'] ); // close open handle
1064 if ( $rcode >= 200 && $rcode <= 299
1065 // double check that the disk is not full/broken
1066 && $tmpFiles[$path]->getSize() == $rhdrs['content-length']
1069 } elseif ( $rcode === 404 ) {
1070 $tmpFiles[$path] = false;
1072 $tmpFiles[$path] = null;
1073 $this->onError( null, __METHOD__
,
1074 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1081 public function getFileHttpUrl( array $params ) {
1082 if ( $this->swiftTempUrlKey
!= '' ||
1083 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1085 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1086 if ( $srcRel === null ) {
1087 return null; // invalid path
1090 $auth = $this->getAuthentication();
1095 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1096 $expires = time() +
$ttl;
1098 if ( $this->swiftTempUrlKey
!= '' ) {
1099 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1100 // Swift wants the signature based on the unencoded object name
1101 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1102 $signature = hash_hmac( 'sha1',
1103 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1104 $this->swiftTempUrlKey
1107 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1108 } else { // give S3 API URL for rgw
1109 // Path for signature starts with the bucket
1110 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1111 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1112 // Calculate the hash
1113 $signature = base64_encode( hash_hmac(
1115 "GET\n\n\n{$expires}\n{$spath}",
1116 $this->rgwS3SecretKey
,
1119 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1120 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1121 return wfAppendQuery(
1122 str_replace( '/swift/v1', '', // S3 API is the rgw default
1123 $this->storageUrl( $auth ) . $spath ),
1125 'Signature' => $signature,
1126 'Expires' => $expires,
1127 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1135 protected function directoriesAreVirtual() {
1140 * Get headers to send to Swift when reading a file based
1141 * on a FileBackend params array, e.g. that of getLocalCopy().
1142 * $params is currently only checked for a 'latest' flag.
1144 * @param array $params
1147 protected function headersFromParams( array $params ) {
1149 if ( !empty( $params['latest'] ) ) {
1150 $hdrs['x-newest'] = 'true';
1156 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1157 $statuses = array();
1159 $auth = $this->getAuthentication();
1161 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1162 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1168 // Split the HTTP requests into stages that can be done concurrently
1169 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1170 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1171 $reqs = $fileOpHandle->httpOp
;
1172 // Convert the 'url' parameter to an actual URL using $auth
1173 foreach ( $reqs as $stage => &$req ) {
1174 list( $container, $relPath ) = $req['url'];
1175 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1176 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1177 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1178 $httpReqsByStage[$stage][$index] = $req;
1180 $statuses[$index] = Status
::newGood();
1183 // Run all requests for the first stage, then the next, and so on
1184 $reqCount = count( $httpReqsByStage );
1185 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1186 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1187 foreach ( $httpReqs as $index => $httpReq ) {
1188 // Run the callback for each request of this operation
1189 $callback = $fileOpHandles[$index]->callback
;
1190 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1191 // On failure, abort all remaining requests for this operation
1192 // (e.g. abort the DELETE request if the COPY request fails for a move)
1193 if ( !$statuses[$index]->isOK() ) {
1194 $stages = count( $fileOpHandles[$index]->httpOp
);
1195 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1196 unset( $httpReqsByStage[$s][$index] );
1206 * Set read/write permissions for a Swift container.
1208 * @see http://swift.openstack.org/misc.html#acls
1210 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1211 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1213 * @param string $container Resolved Swift container
1214 * @param array $readGrps List of the possible criteria for a request to have
1215 * access to read a container. Each item is one of the following formats:
1216 * - account:user : Grants access if the request is by the given user
1217 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1218 * matches the expression and the request is not for a listing.
1219 * Setting this to '*' effectively makes a container public.
1220 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1221 * matches the expression and the request is for a listing.
1222 * @param array $writeGrps A list of the possible criteria for a request to have
1223 * access to write to a container. Each item is of the following format:
1224 * - account:user : Grants access if the request is by the given user
1227 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1228 $status = Status
::newGood();
1229 $auth = $this->getAuthentication();
1232 $status->fatal( 'backend-fail-connect', $this->name
);
1237 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1239 'url' => $this->storageUrl( $auth, $container ),
1240 'headers' => $this->authTokenHeaders( $auth ) +
array(
1241 'x-container-read' => implode( ',', $readGrps ),
1242 'x-container-write' => implode( ',', $writeGrps )
1246 if ( $rcode != 204 && $rcode !== 202 ) {
1247 $status->fatal( 'backend-fail-internal', $this->name
);
1254 * Get a Swift container stat array, possibly from process cache.
1255 * Use $reCache if the file count or byte count is needed.
1257 * @param string $container Container name
1258 * @param bool $bypassCache Bypass all caches and load from Swift
1259 * @return array|bool|null False on 404, null on failure
1261 protected function getContainerStat( $container, $bypassCache = false ) {
1262 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
1264 if ( $bypassCache ) { // purge cache
1265 $this->containerStatCache
->clear( $container );
1266 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1267 $this->primeContainerCache( array( $container ) ); // check persistent cache
1269 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1270 $auth = $this->getAuthentication();
1275 wfProfileIn( __METHOD__
. "-{$this->name}-miss" );
1276 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1278 'url' => $this->storageUrl( $auth, $container ),
1279 'headers' => $this->authTokenHeaders( $auth )
1281 wfProfileOut( __METHOD__
. "-{$this->name}-miss" );
1283 if ( $rcode === 204 ) {
1285 'count' => $rhdrs['x-container-object-count'],
1286 'bytes' => $rhdrs['x-container-bytes-used']
1288 if ( $bypassCache ) {
1291 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1292 $this->setContainerCache( $container, $stat ); // update persistent cache
1294 } elseif ( $rcode === 404 ) {
1297 $this->onError( null, __METHOD__
,
1298 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1304 return $this->containerStatCache
->get( $container, 'stat' );
1308 * Create a Swift container
1310 * @param string $container Container name
1311 * @param array $params
1314 protected function createContainer( $container, array $params ) {
1315 $status = Status
::newGood();
1317 $auth = $this->getAuthentication();
1319 $status->fatal( 'backend-fail-connect', $this->name
);
1324 // @see SwiftFileBackend::setContainerAccess()
1325 if ( empty( $params['noAccess'] ) ) {
1326 $readGrps = array( '.r:*', $this->swiftUser
); // public
1328 $readGrps = array( $this->swiftUser
); // private
1330 $writeGrps = array( $this->swiftUser
); // sanity
1332 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1334 'url' => $this->storageUrl( $auth, $container ),
1335 'headers' => $this->authTokenHeaders( $auth ) +
array(
1336 'x-container-read' => implode( ',', $readGrps ),
1337 'x-container-write' => implode( ',', $writeGrps )
1341 if ( $rcode === 201 ) { // new
1343 } elseif ( $rcode === 202 ) { // already there
1344 // this shouldn't really happen, but is OK
1346 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1353 * Delete a Swift container
1355 * @param string $container Container name
1356 * @param array $params
1359 protected function deleteContainer( $container, array $params ) {
1360 $status = Status
::newGood();
1362 $auth = $this->getAuthentication();
1364 $status->fatal( 'backend-fail-connect', $this->name
);
1369 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1370 'method' => 'DELETE',
1371 'url' => $this->storageUrl( $auth, $container ),
1372 'headers' => $this->authTokenHeaders( $auth )
1375 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1376 $this->containerStatCache
->clear( $container ); // purge
1377 } elseif ( $rcode === 404 ) { // not there
1378 // this shouldn't really happen, but is OK
1379 } elseif ( $rcode === 409 ) { // not empty
1380 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1382 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1389 * Get a list of objects under a container.
1390 * Either just the names or a list of stdClass objects with details can be returned.
1392 * @param string $fullCont
1393 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1394 * @param integer $limit
1395 * @param string|null $after
1396 * @param string|null $prefix
1397 * @param string|null $delim
1398 * @return Status With the list as value
1400 private function objectListing(
1401 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1403 $status = Status
::newGood();
1405 $auth = $this->getAuthentication();
1407 $status->fatal( 'backend-fail-connect', $this->name
);
1412 $query = array( 'limit' => $limit );
1413 if ( $type === 'info' ) {
1414 $query['format'] = 'json';
1416 if ( $after !== null ) {
1417 $query['marker'] = $after;
1419 if ( $prefix !== null ) {
1420 $query['prefix'] = $prefix;
1422 if ( $delim !== null ) {
1423 $query['delimiter'] = $delim;
1426 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1428 'url' => $this->storageUrl( $auth, $fullCont ),
1430 'headers' => $this->authTokenHeaders( $auth )
1433 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1434 if ( $rcode === 200 ) { // good
1435 if ( $type === 'info' ) {
1436 $status->value
= FormatJson
::decode( trim( $rbody ) );
1438 $status->value
= explode( "\n", trim( $rbody ) );
1440 } elseif ( $rcode === 204 ) {
1441 $status->value
= array(); // empty container
1442 } elseif ( $rcode === 404 ) {
1443 $status->value
= array(); // no container
1445 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1451 protected function doPrimeContainerCache( array $containerInfo ) {
1452 foreach ( $containerInfo as $container => $info ) {
1453 $this->containerStatCache
->set( $container, 'stat', $info );
1457 protected function doGetFileStatMulti( array $params ) {
1460 $auth = $this->getAuthentication();
1463 foreach ( $params['srcs'] as $path ) {
1464 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1465 if ( $srcRel === null ) {
1466 $stats[$path] = false;
1467 continue; // invalid storage path
1468 } elseif ( !$auth ) {
1469 $stats[$path] = null;
1473 // (a) Check the container
1474 $cstat = $this->getContainerStat( $srcCont );
1475 if ( $cstat === false ) {
1476 $stats[$path] = false;
1477 continue; // ok, nothing to do
1478 } elseif ( !is_array( $cstat ) ) {
1479 $stats[$path] = null;
1483 $reqs[$path] = array(
1485 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1486 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1490 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1491 $reqs = $this->http
->runMulti( $reqs, $opts );
1493 foreach ( $params['srcs'] as $path ) {
1494 if ( array_key_exists( $path, $stats ) ) {
1495 continue; // some sort of failure above
1497 // (b) Check the file
1498 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1499 if ( $rcode === 200 ||
$rcode === 204 ) {
1500 // Update the object if it is missing some headers
1501 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1502 // Fetch all of the custom metadata headers
1503 $metadata = array();
1504 foreach ( $rhdrs as $name => $value ) {
1505 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
1506 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
1509 // Fetch all of the custom raw HTTP headers
1510 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1512 // Convert various random Swift dates to TS_MW
1513 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1514 // Empty objects actually return no content-length header in Ceph
1515 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1516 'sha1' => $rhdrs[ 'x-object-meta-sha1base36'],
1517 // Note: manifiest ETags are not an MD5 of the file
1518 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1519 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1521 } elseif ( $rcode === 404 ) {
1525 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1527 $stats[$path] = $stat;
1534 * @return array|null Credential map
1536 protected function getAuthentication() {
1537 if ( $this->authErrorTimestamp
!== null ) {
1538 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1539 return null; // failed last attempt; don't bother
1540 } else { // actually retry this time
1541 $this->authErrorTimestamp
= null;
1544 // Session keys expire after a while, so we renew them periodically
1545 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1546 // Authenticate with proxy and get a session key...
1547 if ( !$this->authCreds ||
$reAuth ) {
1548 $this->authSessionTimestamp
= 0;
1549 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1550 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1551 // Try to use the credential cache
1552 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1553 $this->authCreds
= $creds;
1554 // Skew the timestamp for worst case to avoid using stale credentials
1555 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1556 } else { // cache miss
1557 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1559 'url' => "{$this->swiftAuthUrl}/v1.0",
1561 'x-auth-user' => $this->swiftUser
,
1562 'x-auth-key' => $this->swiftKey
1566 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1567 $this->authCreds
= array(
1568 'auth_token' => $rhdrs['x-auth-token'],
1569 'storage_url' => $rhdrs['x-storage-url']
1571 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1572 $this->authSessionTimestamp
= time();
1573 } elseif ( $rcode === 401 ) {
1574 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1575 $this->authErrorTimestamp
= time();
1579 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1580 $this->authErrorTimestamp
= time();
1587 return $this->authCreds
;
1591 * @param array $creds From getAuthentication()
1592 * @param string $container
1593 * @param string $object
1596 protected function storageUrl( array $creds, $container = null, $object = null ) {
1597 $parts = array( $creds['storage_url'] );
1598 if ( strlen( $container ) ) {
1599 $parts[] = rawurlencode( $container );
1601 if ( strlen( $object ) ) {
1602 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1605 return implode( '/', $parts );
1609 * @param array $creds From getAuthentication()
1612 protected function authTokenHeaders( array $creds ) {
1613 return array( 'x-auth-token' => $creds['auth_token'] );
1617 * Get the cache key for a container
1619 * @param string $username
1622 private function getCredsCacheKey( $username ) {
1623 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1627 * Log an unexpected exception for this backend.
1628 * This also sets the Status object to have a fatal error.
1630 * @param Status|null $status
1631 * @param string $func
1632 * @param array $params
1633 * @param string $err Error string
1634 * @param integer $code HTTP status
1635 * @param string $desc HTTP status description
1637 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1638 if ( $status instanceof Status
) {
1639 $status->fatal( 'backend-fail-internal', $this->name
);
1641 if ( $code == 401 ) { // possibly a stale token
1642 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1644 wfDebugLog( 'SwiftBackend',
1645 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1646 ( $err ?
": $err" : "" )
1652 * @see FileBackendStoreOpHandle
1654 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1655 /** @var array List of Requests for MultiHttpClient */
1661 * @param SwiftFileBackend $backend
1662 * @param Closure $callback Function that takes (HTTP request array, status)
1663 * @param array $httpOp MultiHttpClient op
1665 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1666 $this->backend
= $backend;
1667 $this->callback
= $callback;
1668 $this->httpOp
= $httpOp;
1673 * SwiftFileBackend helper class to page through listings.
1674 * Swift also has a listing limit of 10,000 objects for sanity.
1675 * Do not use this class from places outside SwiftFileBackend.
1677 * @ingroup FileBackend
1679 abstract class SwiftFileBackendList
implements Iterator
{
1680 /** @var array List of path or (path,stat array) entries */
1681 protected $bufferIter = array();
1683 /** @var string List items *after* this path */
1684 protected $bufferAfter = null;
1690 protected $params = array();
1692 /** @var SwiftFileBackend */
1695 /** @var string Container name */
1696 protected $container;
1698 /** @var string Storage directory */
1702 protected $suffixStart;
1704 const PAGE_SIZE
= 9000; // file listing buffer size
1707 * @param SwiftFileBackend $backend
1708 * @param string $fullCont Resolved container name
1709 * @param string $dir Resolved directory relative to container
1710 * @param array $params
1712 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1713 $this->backend
= $backend;
1714 $this->container
= $fullCont;
1716 if ( substr( $this->dir
, -1 ) === '/' ) {
1717 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1719 if ( $this->dir
== '' ) { // whole container
1720 $this->suffixStart
= 0;
1721 } else { // dir within container
1722 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1724 $this->params
= $params;
1728 * @see Iterator::key()
1731 public function key() {
1736 * @see Iterator::next()
1738 public function next() {
1739 // Advance to the next file in the page
1740 next( $this->bufferIter
);
1742 // Check if there are no files left in this page and
1743 // advance to the next page if this page was not empty.
1744 if ( !$this->valid() && count( $this->bufferIter
) ) {
1745 $this->bufferIter
= $this->pageFromList(
1746 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1747 ); // updates $this->bufferAfter
1752 * @see Iterator::rewind()
1754 public function rewind() {
1756 $this->bufferAfter
= null;
1757 $this->bufferIter
= $this->pageFromList(
1758 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1759 ); // updates $this->bufferAfter
1763 * @see Iterator::valid()
1766 public function valid() {
1767 if ( $this->bufferIter
=== null ) {
1768 return false; // some failure?
1770 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1775 * Get the given list portion (page)
1777 * @param string $container Resolved container name
1778 * @param string $dir Resolved path relative to container
1779 * @param string $after null
1781 * @param array $params
1782 * @return Traversable|array
1784 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1788 * Iterator for listing directories
1790 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1792 * @see Iterator::current()
1793 * @return string|bool String (relative path) or false
1795 public function current() {
1796 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1799 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1800 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1805 * Iterator for listing regular files
1807 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1809 * @see Iterator::current()
1810 * @return string|bool String (relative path) or false
1812 public function current() {
1813 list( $path, $stat ) = current( $this->bufferIter
);
1814 $relPath = substr( $path, $this->suffixStart
);
1815 if ( is_array( $stat ) ) {
1816 $storageDir = rtrim( $this->params
['dir'], '/' );
1817 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1823 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1824 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );