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 : Ragos 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 : Ragos 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 protected function resolveContainerPath( $container, $relStoragePath ) {
146 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
147 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
148 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
149 return null; // too long for Swift
152 return $relStoragePath;
155 public function isPathUsableInternal( $storagePath ) {
156 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
157 if ( $rel === null ) {
158 return false; // invalid
161 return is_array( $this->getContainerStat( $container ) );
165 * Sanitize and filter the custom headers from a $params array.
166 * We only allow certain Content- and X-Content- headers.
168 * @param array $headers
169 * @return array Sanitized value of 'headers' field in $params
171 protected function sanitizeHdrs( array $params ) {
174 // Normalize casing, and strip out illegal headers
175 if ( isset( $params['headers'] ) ) {
176 foreach ( $params['headers'] as $name => $value ) {
177 $name = strtolower( $name );
178 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
179 continue; // blacklisted
180 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
181 $headers[$name] = $value; // allowed
185 // By default, Swift has annoyingly low maximum header value limits
186 if ( isset( $headers['content-disposition'] ) ) {
188 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
189 $part = trim( $part );
190 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
191 if ( strlen( $new ) <= 255 ) {
194 break; // too long; sigh
197 $headers['content-disposition'] = $disposition;
203 protected function doCreateInternal( array $params ) {
204 $status = Status
::newGood();
206 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
207 if ( $dstRel === null ) {
208 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
213 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
214 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
216 $reqs = array( array(
218 'url' => array( $dstCont, $dstRel ),
220 'content-length' => strlen( $params['content'] ),
221 'etag' => md5( $params['content'] ),
222 'content-type' => $contentType,
223 'x-object-meta-sha1base36' => $sha1Hash
224 ) +
$this->sanitizeHdrs( $params ),
225 'body' => $params['content']
229 $method = __METHOD__
;
230 $handler = function( array $request, Status
$status ) use ( $be, $method, $params ) {
231 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
232 if ( $rcode === 201 ) {
234 } elseif ( $rcode === 412 ) {
235 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
237 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
241 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
242 if ( !empty( $params['async'] ) ) { // deferred
243 $status->value
= $opHandle;
244 } else { // actually write the object in Swift
245 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
251 protected function doStoreInternal( array $params ) {
252 $status = Status
::newGood();
254 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
255 if ( $dstRel === null ) {
256 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
261 wfSuppressWarnings();
262 $sha1Hash = sha1_file( $params['src'] );
264 if ( $sha1Hash === false ) { // source doesn't exist?
265 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
269 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
270 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
272 $handle = fopen( $params['src'], 'rb+' );
273 if ( $handle === false ) { // source doesn't exist?
274 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
279 $reqs = array( array(
281 'url' => array( $dstCont, $dstRel ),
283 'content-length' => filesize( $params['src'] ),
284 'etag' => md5_file( $params['src'] ),
285 'content-type' => $contentType,
286 'x-object-meta-sha1base36' => $sha1Hash
287 ) +
$this->sanitizeHdrs( $params ),
288 'body' => $handle // resource
292 $method = __METHOD__
;
293 $handler = function( array $request, Status
$status ) use ( $be, $method, $params ) {
294 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
295 if ( $rcode === 201 ) {
297 } elseif ( $rcode === 412 ) {
298 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
300 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
304 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
305 if ( !empty( $params['async'] ) ) { // deferred
306 $status->value
= $opHandle;
307 } else { // actually write the object in Swift
308 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
314 protected function doCopyInternal( array $params ) {
315 $status = Status
::newGood();
317 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
318 if ( $srcRel === null ) {
319 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
324 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
325 if ( $dstRel === null ) {
326 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
331 $reqs = array( array(
333 'url' => array( $dstCont, $dstRel ),
335 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
336 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
337 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
341 $method = __METHOD__
;
342 $handler = function( array $request, Status
$status ) use ( $be, $method, $params ) {
343 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
344 if ( $rcode === 201 ) {
346 } elseif ( $rcode === 404 ) {
347 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
349 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
353 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
354 if ( !empty( $params['async'] ) ) { // deferred
355 $status->value
= $opHandle;
356 } else { // actually write the object in Swift
357 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
363 protected function doMoveInternal( array $params ) {
364 $status = Status
::newGood();
366 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
367 if ( $srcRel === null ) {
368 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
373 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
374 if ( $dstRel === null ) {
375 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
383 'url' => array( $dstCont, $dstRel ),
385 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
386 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
387 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
390 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
392 'method' => 'DELETE',
393 'url' => array( $srcCont, $srcRel ),
399 $method = __METHOD__
;
400 $handler = function( array $request, Status
$status ) use ( $be, $method, $params ) {
401 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
402 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
404 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
406 } elseif ( $rcode === 404 ) {
407 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
409 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
413 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
414 if ( !empty( $params['async'] ) ) { // deferred
415 $status->value
= $opHandle;
416 } else { // actually move the object in Swift
417 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
423 protected function doDeleteInternal( array $params ) {
424 $status = Status
::newGood();
426 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
427 if ( $srcRel === null ) {
428 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
435 'method' => 'DELETE',
436 'url' => array( $srcCont, $srcRel ),
441 $method = __METHOD__
;
442 $handler = function( array $request, Status
$status ) use ( $be, $method, $params ) {
443 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
444 if ( $rcode === 204 ) {
446 } elseif ( $rcode === 404 ) {
447 if ( empty( $params['ignoreMissingSource'] ) ) {
448 $status->fatal( 'backend-fail-delete', $params['src'] );
451 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
455 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
456 if ( !empty( $params['async'] ) ) { // deferred
457 $status->value
= $opHandle;
458 } else { // actually delete the object in Swift
459 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
465 protected function doDescribeInternal( array $params ) {
466 $status = Status
::newGood();
468 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
469 if ( $srcRel === null ) {
470 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
475 // Fetch the old object headers/metadata...this should be in stat cache by now
476 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
477 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
478 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
481 $status->fatal( 'backend-fail-describe', $params['src'] );
486 // POST clears prior headers, so we need to merge the changes in to the old ones
488 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
489 $metaHdrs["x-object-meta-$name"] = $value;
491 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
493 $reqs = array( array(
495 'url' => array( $srcCont, $srcRel ),
496 'headers' => $metaHdrs +
$customHdrs
500 $method = __METHOD__
;
501 $handler = function( array $request, Status
$status ) use ( $be, $method, $params ) {
502 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
503 if ( $rcode === 202 ) {
505 } elseif ( $rcode === 404 ) {
506 $status->fatal( 'backend-fail-describe', $params['src'] );
508 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
512 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
513 if ( !empty( $params['async'] ) ) { // deferred
514 $status->value
= $opHandle;
515 } else { // actually change the object in Swift
516 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
522 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
523 $status = Status
::newGood();
525 // (a) Check if container already exists
526 $stat = $this->getContainerStat( $fullCont );
527 if ( is_array( $stat ) ) {
528 return $status; // already there
529 } elseif ( $stat === null ) {
530 $status->fatal( 'backend-fail-internal', $this->name
);
534 // (b) Create container as needed with proper ACLs
535 if ( $stat === false ) {
536 $params['op'] = 'prepare';
537 $status->merge( $this->createContainer( $fullCont, $params ) );
543 protected function doSecureInternal( $fullCont, $dir, array $params ) {
544 $status = Status
::newGood();
545 if ( empty( $params['noAccess'] ) ) {
546 return $status; // nothing to do
549 $stat = $this->getContainerStat( $fullCont );
550 if ( is_array( $stat ) ) {
551 // Make container private to end-users...
552 $status->merge( $this->setContainerAccess(
554 array( $this->swiftUser
), // read
555 array( $this->swiftUser
) // write
557 } elseif ( $stat === false ) {
558 $status->fatal( 'backend-fail-usable', $params['dir'] );
560 $status->fatal( 'backend-fail-internal', $this->name
);
566 protected function doPublishInternal( $fullCont, $dir, array $params ) {
567 $status = Status
::newGood();
569 $stat = $this->getContainerStat( $fullCont );
570 if ( is_array( $stat ) ) {
571 // Make container public to end-users...
572 $status->merge( $this->setContainerAccess(
574 array( $this->swiftUser
, '.r:*' ), // read
575 array( $this->swiftUser
) // write
577 } elseif ( $stat === false ) {
578 $status->fatal( 'backend-fail-usable', $params['dir'] );
580 $status->fatal( 'backend-fail-internal', $this->name
);
586 protected function doCleanInternal( $fullCont, $dir, array $params ) {
587 $status = Status
::newGood();
589 // Only containers themselves can be removed, all else is virtual
591 return $status; // nothing to do
594 // (a) Check the container
595 $stat = $this->getContainerStat( $fullCont, true );
596 if ( $stat === false ) {
597 return $status; // ok, nothing to do
598 } elseif ( !is_array( $stat ) ) {
599 $status->fatal( 'backend-fail-internal', $this->name
);
603 // (b) Delete the container if empty
604 if ( $stat['count'] == 0 ) {
605 $params['op'] = 'clean';
606 $status->merge( $this->deleteContainer( $fullCont, $params ) );
612 protected function doGetFileStat( array $params ) {
613 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
614 if ( $srcRel === null ) {
615 return false; // invalid storage path
618 $auth = $this->getAuthentication();
623 // (a) Check the container
624 $cstat = $this->getContainerStat( $srcCont, true );
625 if ( $cstat === false ) {
626 return false; // ok, nothing to do
627 } elseif ( !is_array( $cstat ) ) {
631 // (b) Check the file
632 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
634 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
635 'headers' => $this->authTokenHeaders( $auth )
637 if ( $rcode === 200 ||
$rcode === 204 ) {
638 // Update the object if it is missing some headers
639 $rhdrs = $this->addMissingMetadata( $rhdrs, $params['src'] );
640 // Fetch all of the custom metadata headers
642 foreach ( $rhdrs as $name => $value ) {
643 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
644 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
647 // Fetch all of the custom raw HTTP headers
648 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
650 // Convert various random Swift dates to TS_MW
651 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
652 // Empty objects actually return no content-length header in Ceph
653 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
654 'sha1' => $rhdrs[ 'x-object-meta-sha1base36'],
655 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
656 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
658 } elseif ( $rcode === 404 ) {
662 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
669 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
670 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
671 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
674 * @param int $format Output format (TS_* constant)
676 * @throws FileBackendError
678 protected function convertSwiftDate( $ts, $format = TS_MW
) {
680 $timestamp = new MWTimestamp( $ts );
681 return $timestamp->getTimestamp( $format );
682 } catch ( MWException
$e ) {
683 throw new FileBackendError( $e->getMessage() );
688 * Fill in any missing object metadata and save it to Swift
690 * @param array $objHdrs Object response headers
691 * @param string $path Storage path to object
692 * @return array New headers
694 protected function addMissingMetadata( array $objHdrs, $path ) {
695 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
696 return $objHdrs; // nothing to do
699 $section = new ProfileSection( __METHOD__
);
700 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
702 $auth = $this->getAuthentication();
704 $objHdrs['x-object-meta-sha1base36'] = false;
705 return false; // failed
708 $status = Status
::newGood();
709 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
710 if ( $status->isOK() ) {
711 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
713 $hash = $tmpFile->getSha1Base36();
714 if ( $hash !== false ) {
715 $objHdrs['x-object-meta-sha1base36'] = $hash;
716 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
717 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
719 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
720 'headers' => $this->authTokenHeaders( $auth ) +
$objHdrs
722 if ( $rcode >= 200 && $rcode <= 299 ) {
723 return true; // success
728 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING
);
729 $objHdrs['x-object-meta-sha1base36'] = false;
731 return false; // failed
734 protected function doGetFileContentsMulti( array $params ) {
737 $auth = $this->getAuthentication();
739 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
740 // Blindly create tmp files and stream to them, catching any exception if the file does
741 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
742 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
743 $reqs = array(); // (path => op)
745 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
746 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
747 if ( $srcRel === null ||
!$auth ) {
748 $contents[$path] = false;
752 // Create a new temporary memory file...
753 $handle = fopen( 'php://temp', 'wb' );
755 $reqs[$path] = array(
757 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
758 'headers' => $this->authTokenHeaders( $auth )
759 +
$this->headersFromParams( $params ),
765 $contents[$path] = $data;
768 $reqs = $this->http
->runMulti( $reqs );
769 foreach ( $reqs as $path => $op ) {
770 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
771 if ( $rcode >= 200 && $rcode <= 299 ) {
772 rewind( $op['stream'] ); // start from the beginning
773 $contents[$path] = stream_get_contents( $op['stream'] );
774 } elseif ( $rcode === 404 ) {
775 $contents[$path] = false;
777 $this->onError( null, __METHOD__
,
778 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
780 fclose( $op['stream'] ); // close open handle
787 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
788 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
789 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
790 if ( $status->isOk() ) {
791 return ( count( $status->value
) );
793 return null; // error
797 * @see FileBackendStore::getDirectoryListInternal()
798 * @param string $fullCont
800 * @param array $params
801 * @return SwiftFileBackendDirList
803 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
804 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
808 * @see FileBackendStore::getFileListInternal()
809 * @param string $fullCont
811 * @param array $params
812 * @return SwiftFileBackendFileList
814 public function getFileListInternal( $fullCont, $dir, array $params ) {
815 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
819 * Do not call this function outside of SwiftFileBackendFileList
821 * @param string $fullCont Resolved container name
822 * @param string $dir Resolved storage directory with no trailing slash
823 * @param string|null $after Resolved container relative path to list items after
824 * @param int $limit Max number of items to list
825 * @param array $params Parameters for getDirectoryList()
826 * @return array List of container relative resolved paths of directories directly under $dir
827 * @throws FileBackendError
829 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
831 if ( $after === INF
) {
832 return $dirs; // nothing more
835 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
837 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
838 // Non-recursive: only list dirs right under $dir
839 if ( !empty( $params['topOnly'] ) ) {
840 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
841 if ( !$status->isOk() ) {
842 return $dirs; // error
844 $objects = $status->value
;
845 foreach ( $objects as $object ) { // files and directories
846 if ( substr( $object, -1 ) === '/' ) {
847 $dirs[] = $object; // directories end in '/'
850 // Recursive: list all dirs under $dir and its subdirs
852 $getParentDir = function( $path ) {
853 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
855 // Get directory from last item of prior page
856 $lastDir = $getParentDir( $after ); // must be first page
857 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
858 if ( !$status->isOk() ) {
859 return $dirs; // error
861 $objects = $status->value
;
862 foreach ( $objects as $object ) { // files
863 $objectDir = $getParentDir( $object ); // directory of object
864 if ( $objectDir !== false && $objectDir !== $dir ) {
865 // Swift stores paths in UTF-8, using binary sorting.
866 // See function "create_container_table" in common/db.py.
867 // If a directory is not "greater" than the last one,
868 // then it was already listed by the calling iterator.
869 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
871 do { // add dir and all its parent dirs
872 $dirs[] = "{$pDir}/";
873 $pDir = $getParentDir( $pDir );
874 } while ( $pDir !== false // sanity
875 && strcmp( $pDir, $lastDir ) > 0 // not done already
876 && strlen( $pDir ) > strlen( $dir ) // within $dir
879 $lastDir = $objectDir;
883 // Page on the unfiltered directory listing (what is returned may be filtered)
884 if ( count( $objects ) < $limit ) {
885 $after = INF
; // avoid a second RTT
887 $after = end( $objects ); // update last item
894 * Do not call this function outside of SwiftFileBackendFileList
896 * @param string $fullCont Resolved container name
897 * @param string $dir Resolved storage directory with no trailing slash
898 * @param string|null $after Resolved container relative path of file to list items after
899 * @param int $limit Max number of items to list
900 * @param array $params Parameters for getDirectoryList()
901 * @return array List of resolved container relative paths of files under $dir
902 * @throws FileBackendError
904 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
905 $files = array(); // list of (path, stat array or null) entries
906 if ( $after === INF
) {
907 return $files; // nothing more
910 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
912 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
913 // $objects will contain a list of unfiltered names or CF_Object items
914 // Non-recursive: only list files right under $dir
915 if ( !empty( $params['topOnly'] ) ) {
916 if ( !empty( $params['adviseStat'] ) ) {
917 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
919 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
921 // Recursive: list all files under $dir and its subdirs
923 if ( !empty( $params['adviseStat'] ) ) {
924 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
926 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
929 // Reformat this list into a list of (name, stat array or null) entries
930 if ( !$status->isOk() ) {
931 return $files; // error
933 $objects = $status->value
;
934 $files = $this->buildFileObjectListing( $params, $dir, $objects );
935 // Page on the unfiltered object listing (what is returned may be filtered)
936 if ( count( $objects ) < $limit ) {
937 $after = INF
; // avoid a second RTT
939 $after = end( $objects ); // update last item
940 $after = is_object( $after ) ?
$after->name
: $after;
947 * Build a list of file objects, filtering out any directories
948 * and extracting any stat info if provided in $objects (for CF_Objects)
950 * @param array $params Parameters for getDirectoryList()
951 * @param string $dir Resolved container directory path
952 * @param array $objects List of CF_Object items or object names
953 * @return array List of (names,stat array or null) entries
955 private function buildFileObjectListing( array $params, $dir, array $objects ) {
957 foreach ( $objects as $object ) {
958 if ( is_object( $object ) ) {
959 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
960 continue; // virtual directory entry; ignore
963 // Convert various random Swift dates to TS_MW
964 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
965 'size' => (int)$object->bytes
,
966 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
967 'latest' => false // eventually consistent
969 $names[] = array( $object->name
, $stat );
970 } elseif ( substr( $object, -1 ) !== '/' ) {
971 // Omit directories, which end in '/' in listings
972 $names[] = array( $object, null );
980 * Do not call this function outside of SwiftFileBackendFileList
982 * @param string $path Storage path
983 * @param array $val Stat value
985 public function loadListingStatInternal( $path, array $val ) {
986 $this->cheapCache
->set( $path, 'stat', $val );
989 protected function doGetFileSha1base36( array $params ) {
990 $stat = $this->getFileStat( $params );
992 if ( !isset( $stat['sha1'] ) ) {
993 // Stat entries filled by file listings don't include SHA1
994 $this->clearCache( array( $params['src'] ) );
995 $stat = $this->getFileStat( $params );
998 return $stat['sha1'];
1004 protected function doStreamFile( array $params ) {
1005 $status = Status
::newGood();
1007 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1008 if ( $srcRel === null ) {
1009 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1012 $auth = $this->getAuthentication();
1013 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1014 $status->fatal( 'backend-fail-stream', $params['src'] );
1018 $handle = fopen( 'php://output', 'wb' );
1020 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1022 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1023 'headers' => $this->authTokenHeaders( $auth )
1024 +
$this->headersFromParams( $params ),
1025 'stream' => $handle,
1028 if ( $rcode >= 200 && $rcode <= 299 ) {
1030 } elseif ( $rcode === 404 ) {
1031 $status->fatal( 'backend-fail-stream', $params['src'] );
1033 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1039 protected function doGetLocalCopyMulti( array $params ) {
1040 $tmpFiles = array();
1042 $auth = $this->getAuthentication();
1044 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1045 // Blindly create tmp files and stream to them, catching any exception if the file does
1046 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1047 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1048 $reqs = array(); // (path => op)
1050 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1051 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1052 if ( $srcRel === null ||
!$auth ) {
1053 $tmpFiles[$path] = null;
1057 // Get source file extension
1058 $ext = FileBackend
::extensionFromPath( $path );
1059 // Create a new temporary file...
1060 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1062 $handle = fopen( $tmpFile->getPath(), 'wb' );
1064 $reqs[$path] = array(
1066 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1067 'headers' => $this->authTokenHeaders( $auth )
1068 +
$this->headersFromParams( $params ),
1069 'stream' => $handle,
1075 $tmpFiles[$path] = $tmpFile;
1078 $reqs = $this->http
->runMulti( $reqs );
1079 foreach ( $reqs as $path => $op ) {
1080 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1081 if ( $rcode >= 200 && $rcode <= 299 ) {
1083 } elseif ( $rcode === 404 ) {
1084 $tmpFiles[$path] = false;
1086 $tmpFiles[$path] = null;
1087 $this->onError( null, __METHOD__
,
1088 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1090 fclose( $op['stream'] ); // close open handle
1097 public function getFileHttpUrl( array $params ) {
1098 if ( $this->swiftTempUrlKey
!= '' ||
1099 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1101 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1102 if ( $srcRel === null ) {
1103 return null; // invalid path
1106 $auth = $this->getAuthentication();
1111 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1112 $expires = time() +
$ttl;
1114 if ( $this->swiftTempUrlKey
!= '' ) {
1115 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1116 $signature = hash_hmac( 'sha1',
1117 "GET\n{$expires}\n" . parse_url( $url, PHP_URL_PATH
),
1118 $this->swiftTempUrlKey
1120 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1121 } else { // give S3 API URL for rgw
1122 // Path for signature starts with the bucket
1123 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1124 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1125 // Calculate the hash
1126 $signature = base64_encode( hash_hmac(
1128 "GET\n\n\n{$expires}\n{$spath}",
1129 $this->rgwS3SecretKey
,
1132 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1133 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1134 return wfAppendQuery(
1135 str_replace( '/swift/v1', '', // S3 API is the rgw default
1136 $this->storageUrl( $auth ) . $spath ),
1138 'Signature' => $signature,
1139 'Expires' => $expires,
1140 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1148 protected function directoriesAreVirtual() {
1153 * Get headers to send to Swift when reading a file based
1154 * on a FileBackend params array, e.g. that of getLocalCopy().
1155 * $params is currently only checked for a 'latest' flag.
1157 * @param array $params
1160 protected function headersFromParams( array $params ) {
1162 if ( !empty( $params['latest'] ) ) {
1163 $hdrs[] = 'X-Newest: true';
1169 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1170 $statuses = array();
1172 $auth = $this->getAuthentication();
1174 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1175 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1180 // Split the HTTP requests into stages that can be done concurrently
1181 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1182 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1183 $reqs = $fileOpHandle->httpOp
;
1184 // Convert the 'url' parameter to an actual URL using $auth
1185 foreach ( $reqs as $stage => &$req ) {
1186 list( $container, $relPath ) = $req['url'];
1187 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1188 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1189 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1190 $httpReqsByStage[$stage][$index] = $req;
1192 $statuses[$index] = Status
::newGood();
1195 // Run all requests for the first stage, then the next, and so on
1196 for ( $stage = 0; $stage < count( $httpReqsByStage ); ++
$stage ) {
1197 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1198 foreach ( $httpReqs as $index => $httpReq ) {
1199 // Run the callback for each request of this operation
1200 $callback = $fileOpHandles[$index]->callback
;
1201 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1202 // On failure, abort all remaining requests for this operation
1203 // (e.g. abort the DELETE request if the COPY request fails for a move)
1204 if ( !$statuses[$index]->isOK() ) {
1205 $stages = count( $fileOpHandles[$index]->httpOp
);
1206 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1207 unset( $httpReqsByStage[$s][$index] );
1217 * Set read/write permissions for a Swift container.
1219 * @see http://swift.openstack.org/misc.html#acls
1221 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1222 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1224 * @param string $container Resolved Swift container
1225 * @param array $readGrps List of the possible criteria for a request to have
1226 * access to read a container. Each item is one of the following formats:
1227 * - account:user : Grants access if the request is by the given user
1228 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1229 * matches the expression and the request is not for a listing.
1230 * Setting this to '*' effectively makes a container public.
1231 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1232 * matches the expression and the request is for a listing.
1233 * @param array $writeGrps A list of the possible criteria for a request to have
1234 * access to write to a container. Each item is of the following format:
1235 * - account:user : Grants access if the request is by the given user
1238 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1239 $status = Status
::newGood();
1241 $auth = $this->getAuthentication();
1243 $status->fatal( 'backend-fail-connect', $this->name
);
1247 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1249 'url' => $this->storageUrl( $auth, $container ),
1250 'headers' => $this->authTokenHeaders( $auth ) +
array(
1251 'x-container-read' => implode( ',', $readGrps ),
1252 'x-container-write' => implode( ',', $writeGrps )
1256 if ( $rcode != 204 && $rcode !== 202 ) {
1257 $status->fatal( 'backend-fail-internal', $this->name
);
1264 * Get a Swift container stat array, possibly from process cache.
1265 * Use $reCache if the file count or byte count is needed.
1267 * @param string $container Container name
1268 * @param bool $bypassCache Bypass all caches and load from Swift
1269 * @return array|bool|null False on 404, null on failure
1271 protected function getContainerStat( $container, $bypassCache = false ) {
1272 if ( $bypassCache ) { // purge cache
1273 $this->containerStatCache
->clear( $container );
1274 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1275 $this->primeContainerCache( array( $container ) ); // check persistent cache
1277 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1278 $auth = $this->getAuthentication();
1283 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1285 'url' => $this->storageUrl( $auth, $container ),
1286 'headers' => $this->authTokenHeaders( $auth )
1289 if ( $rcode === 204 ) {
1291 'count' => $rhdrs['x-container-object-count'],
1292 'bytes' => $rhdrs['x-container-bytes-used']
1294 if ( $bypassCache ) {
1297 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1299 } elseif ( $rcode === 404 ) {
1302 $this->onError( null, __METHOD__
,
1303 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1308 return $this->containerStatCache
->get( $container, 'stat' );
1312 * Create a Swift container
1314 * @param string $container Container name
1315 * @param array $params
1318 protected function createContainer( $container, array $params ) {
1319 $status = Status
::newGood();
1321 $auth = $this->getAuthentication();
1323 $status->fatal( 'backend-fail-connect', $this->name
);
1327 // @see SwiftFileBackend::setContainerAccess()
1328 if ( empty( $params['noAccess'] ) ) {
1329 $readGrps = array( '.r:*', $this->swiftUser
); // public
1331 $readGrps = array( $this->swiftUser
); // private
1333 $writeGrps = array( $this->swiftUser
); // sanity
1335 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1337 'url' => $this->storageUrl( $auth, $container ),
1338 'headers' => $this->authTokenHeaders( $auth ) +
array(
1339 'x-container-read' => implode( ',', $readGrps ),
1340 'x-container-write' => implode( ',', $writeGrps )
1344 if ( $rcode === 201 ) { // new
1346 } elseif ( $rcode === 202 ) { // already there
1347 // this shouldn't really happen, but is OK
1349 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1356 * Delete a Swift container
1358 * @param string $container Container name
1359 * @param array $params
1362 protected function deleteContainer( $container, array $params ) {
1363 $status = Status
::newGood();
1365 $auth = $this->getAuthentication();
1367 $status->fatal( 'backend-fail-connect', $this->name
);
1371 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1372 'method' => 'DELETE',
1373 'url' => $this->storageUrl( $auth, $container ),
1374 'headers' => $this->authTokenHeaders( $auth )
1377 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1378 $this->containerStatCache
->clear( $container ); // purge
1379 } elseif ( $rcode === 404 ) { // not there
1380 // this shouldn't really happen, but is OK
1381 } elseif ( $rcode === 409 ) { // not empty
1382 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1384 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1391 * Get a list of objects under a container.
1392 * Either just the names or a list of stdClass objects with details can be returned.
1394 * @param string $fullCont
1395 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1396 * @param integer $limit
1397 * @param string|null $after
1398 * @param string|null $prefix
1399 * @param string|null $delim
1400 * @return Status With the list as value
1402 private function objectListing(
1403 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1405 $status = Status
::newGood();
1407 $auth = $this->getAuthentication();
1409 $status->fatal( 'backend-fail-connect', $this->name
);
1413 $query = array( 'limit' => $limit );
1414 if ( $type === 'info' ) {
1415 $query['format'] = 'json';
1417 if ( $after !== null ) {
1418 $query['marker'] = $after;
1420 if ( $prefix !== null ) {
1421 $query['prefix'] = $prefix;
1423 if ( $delim !== null ) {
1424 $query['delimiter'] = $delim;
1427 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1429 'url' => $this->storageUrl( $auth, $fullCont ),
1431 'headers' => $this->authTokenHeaders( $auth )
1434 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1435 if ( $rcode === 200 ) { // good
1436 if ( $type === 'info' ) {
1437 $status->value
= FormatJson
::decode( trim( $rbody ) );
1439 $status->value
= explode( "\n", trim( $rbody ) );
1441 } elseif ( $rcode === 204 ) {
1442 $status->value
= array(); // empty container
1443 } elseif ( $rcode === 404 ) {
1444 $status->value
= array(); // no container
1446 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1452 protected function doPrimeContainerCache( array $containerInfo ) {
1453 foreach ( $containerInfo as $container => $info ) {
1454 $this->containerStatCache
->set( $container, 'stat', $info );
1459 * @return array|null Credential map
1461 protected function getAuthentication() {
1462 if ( $this->authErrorTimestamp
!== null ) {
1463 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1464 return null; // failed last attempt; don't bother
1465 } else { // actually retry this time
1466 $this->authErrorTimestamp
= null;
1469 // Session keys expire after a while, so we renew them periodically
1470 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1471 // Authenticate with proxy and get a session key...
1472 if ( !$this->authCreds ||
$reAuth ) {
1473 $this->authSessionTimestamp
= 0;
1474 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1475 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1476 // Try to use the credential cache
1477 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1478 $this->authCreds
= $creds;
1479 // Skew the timestamp for worst case to avoid using stale credentials
1480 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1481 } else { // cache miss
1482 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1484 'url' => "{$this->swiftAuthUrl}/v1.0",
1486 'x-auth-user' => $this->swiftUser
, 'x-auth-key' => $this->swiftKey
)
1489 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1490 $this->authCreds
= array(
1491 'auth_token' => $rhdrs['x-auth-token'],
1492 'storage_url' => $rhdrs['x-storage-url']
1494 $this->authSessionTimestamp
= time();
1495 } elseif ( $rcode === 401 ) {
1496 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1497 $this->authErrorTimestamp
= time();
1500 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1501 $this->authErrorTimestamp
= time();
1506 return $this->authCreds
;
1510 * @param array $creds From getAuthentication()
1511 * @param string $container
1512 * @param string $object
1515 protected function storageUrl( array $creds, $container = null, $object = null ) {
1516 $parts = array( $creds['storage_url'] );
1517 if ( strlen( $container ) ) {
1518 $parts[] = rawurlencode( $container );
1520 if ( strlen( $object ) ) {
1521 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1523 return implode( '/', $parts );
1527 * @param array $creds From getAuthentication()
1530 protected function authTokenHeaders( array $creds ) {
1531 return array( 'x-auth-token' => $creds['auth_token'] );
1535 * Get the cache key for a container
1537 * @param string $username
1540 private function getCredsCacheKey( $username ) {
1541 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1545 * Log an unexpected exception for this backend.
1546 * This also sets the Status object to have a fatal error.
1548 * @param Status $code null
1549 * @param string $func
1550 * @param array $params
1551 * @param string $err Error string
1552 * @param integer $status HTTP status
1553 * @param string $desc HTTP status description
1555 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1556 if ( $status instanceof Status
) {
1557 $status->fatal( 'backend-fail-internal', $this->name
);
1559 if ( $code == 401 ) { // possibly a stale token
1560 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1562 wfDebugLog( 'SwiftBackend',
1563 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1564 ( $err ?
": $err" : "" )
1570 * @see FileBackendStoreOpHandle
1572 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1573 /** @var array List of Requests for MultiHttpClient */
1579 * @param SwiftFileBackend $backend
1580 * @param Closure $callback Function that takes (HTTP request array, status)
1581 * @param array $httpOp MultiHttpClient op
1583 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1584 $this->backend
= $backend;
1585 $this->callback
= $callback;
1586 $this->httpOp
= $httpOp;
1591 * SwiftFileBackend helper class to page through listings.
1592 * Swift also has a listing limit of 10,000 objects for sanity.
1593 * Do not use this class from places outside SwiftFileBackend.
1595 * @ingroup FileBackend
1597 abstract class SwiftFileBackendList
implements Iterator
{
1598 /** @var array List of path or (path,stat array) entries */
1599 protected $bufferIter = array();
1601 /** @var string List items *after* this path */
1602 protected $bufferAfter = null;
1608 protected $params = array();
1610 /** @var SwiftFileBackend */
1613 /** @var string Container name */
1614 protected $container;
1616 /** @var string Storage directory */
1620 protected $suffixStart;
1622 const PAGE_SIZE
= 9000; // file listing buffer size
1625 * @param SwiftFileBackend $backend
1626 * @param string $fullCont Resolved container name
1627 * @param string $dir Resolved directory relative to container
1628 * @param array $params
1630 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1631 $this->backend
= $backend;
1632 $this->container
= $fullCont;
1634 if ( substr( $this->dir
, -1 ) === '/' ) {
1635 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1637 if ( $this->dir
== '' ) { // whole container
1638 $this->suffixStart
= 0;
1639 } else { // dir within container
1640 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1642 $this->params
= $params;
1646 * @see Iterator::key()
1649 public function key() {
1654 * @see Iterator::next()
1656 public function next() {
1657 // Advance to the next file in the page
1658 next( $this->bufferIter
);
1660 // Check if there are no files left in this page and
1661 // advance to the next page if this page was not empty.
1662 if ( !$this->valid() && count( $this->bufferIter
) ) {
1663 $this->bufferIter
= $this->pageFromList(
1664 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1665 ); // updates $this->bufferAfter
1670 * @see Iterator::rewind()
1672 public function rewind() {
1674 $this->bufferAfter
= null;
1675 $this->bufferIter
= $this->pageFromList(
1676 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1677 ); // updates $this->bufferAfter
1681 * @see Iterator::valid()
1684 public function valid() {
1685 if ( $this->bufferIter
=== null ) {
1686 return false; // some failure?
1688 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1693 * Get the given list portion (page)
1695 * @param string $container Resolved container name
1696 * @param string $dir Resolved path relative to container
1697 * @param string $after null
1699 * @param array $params
1700 * @return Traversable|array
1702 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1706 * Iterator for listing directories
1708 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1710 * @see Iterator::current()
1711 * @return string|bool String (relative path) or false
1713 public function current() {
1714 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1717 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1718 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1723 * Iterator for listing regular files
1725 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1727 * @see Iterator::current()
1728 * @return string|bool String (relative path) or false
1730 public function current() {
1731 list( $path, $stat ) = current( $this->bufferIter
);
1732 $relPath = substr( $path, $this->suffixStart
);
1733 if ( is_array( $stat ) ) {
1734 $storageDir = rtrim( $this->params
['dir'], '/' );
1735 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1741 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1742 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );