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-store', $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-store', $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 fclose( $op['stream'] ); // close open handle
1082 if ( $rcode >= 200 && $rcode <= 299
1083 // double check that the disk is not full/broken
1084 && $tmpFile->getSize() == $rhdrs['content-length']
1087 } elseif ( $rcode === 404 ) {
1088 $tmpFiles[$path] = false;
1090 $tmpFiles[$path] = null;
1091 $this->onError( null, __METHOD__
,
1092 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1100 public function getFileHttpUrl( array $params ) {
1101 if ( $this->swiftTempUrlKey
!= '' ||
1102 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1104 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1105 if ( $srcRel === null ) {
1106 return null; // invalid path
1109 $auth = $this->getAuthentication();
1114 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1115 $expires = time() +
$ttl;
1117 if ( $this->swiftTempUrlKey
!= '' ) {
1118 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1119 $signature = hash_hmac( 'sha1',
1120 "GET\n{$expires}\n" . parse_url( $url, PHP_URL_PATH
),
1121 $this->swiftTempUrlKey
1123 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1124 } else { // give S3 API URL for rgw
1125 // Path for signature starts with the bucket
1126 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1127 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1128 // Calculate the hash
1129 $signature = base64_encode( hash_hmac(
1131 "GET\n\n\n{$expires}\n{$spath}",
1132 $this->rgwS3SecretKey
,
1135 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1136 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1137 return wfAppendQuery(
1138 str_replace( '/swift/v1', '', // S3 API is the rgw default
1139 $this->storageUrl( $auth ) . $spath ),
1141 'Signature' => $signature,
1142 'Expires' => $expires,
1143 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1151 protected function directoriesAreVirtual() {
1156 * Get headers to send to Swift when reading a file based
1157 * on a FileBackend params array, e.g. that of getLocalCopy().
1158 * $params is currently only checked for a 'latest' flag.
1160 * @param array $params
1163 protected function headersFromParams( array $params ) {
1165 if ( !empty( $params['latest'] ) ) {
1166 $hdrs[] = 'X-Newest: true';
1172 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1173 $statuses = array();
1175 $auth = $this->getAuthentication();
1177 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1178 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1183 // Split the HTTP requests into stages that can be done concurrently
1184 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1185 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1186 $reqs = $fileOpHandle->httpOp
;
1187 // Convert the 'url' parameter to an actual URL using $auth
1188 foreach ( $reqs as $stage => &$req ) {
1189 list( $container, $relPath ) = $req['url'];
1190 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1191 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1192 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1193 $httpReqsByStage[$stage][$index] = $req;
1195 $statuses[$index] = Status
::newGood();
1198 // Run all requests for the first stage, then the next, and so on
1199 for ( $stage = 0; $stage < count( $httpReqsByStage ); ++
$stage ) {
1200 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1201 foreach ( $httpReqs as $index => $httpReq ) {
1202 // Run the callback for each request of this operation
1203 $callback = $fileOpHandles[$index]->callback
;
1204 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1205 // On failure, abort all remaining requests for this operation
1206 // (e.g. abort the DELETE request if the COPY request fails for a move)
1207 if ( !$statuses[$index]->isOK() ) {
1208 $stages = count( $fileOpHandles[$index]->httpOp
);
1209 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1210 unset( $httpReqsByStage[$s][$index] );
1220 * Set read/write permissions for a Swift container.
1222 * @see http://swift.openstack.org/misc.html#acls
1224 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1225 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1227 * @param string $container Resolved Swift container
1228 * @param array $readGrps List of the possible criteria for a request to have
1229 * access to read a container. Each item is one of the following formats:
1230 * - account:user : Grants access if the request is by the given user
1231 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1232 * matches the expression and the request is not for a listing.
1233 * Setting this to '*' effectively makes a container public.
1234 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1235 * matches the expression and the request is for a listing.
1236 * @param array $writeGrps A list of the possible criteria for a request to have
1237 * access to write to a container. Each item is of the following format:
1238 * - account:user : Grants access if the request is by the given user
1241 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1242 $status = Status
::newGood();
1244 $auth = $this->getAuthentication();
1246 $status->fatal( 'backend-fail-connect', $this->name
);
1250 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1252 'url' => $this->storageUrl( $auth, $container ),
1253 'headers' => $this->authTokenHeaders( $auth ) +
array(
1254 'x-container-read' => implode( ',', $readGrps ),
1255 'x-container-write' => implode( ',', $writeGrps )
1259 if ( $rcode != 204 && $rcode !== 202 ) {
1260 $status->fatal( 'backend-fail-internal', $this->name
);
1267 * Get a Swift container stat array, possibly from process cache.
1268 * Use $reCache if the file count or byte count is needed.
1270 * @param string $container Container name
1271 * @param bool $bypassCache Bypass all caches and load from Swift
1272 * @return array|bool|null False on 404, null on failure
1274 protected function getContainerStat( $container, $bypassCache = false ) {
1275 if ( $bypassCache ) { // purge cache
1276 $this->containerStatCache
->clear( $container );
1277 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1278 $this->primeContainerCache( array( $container ) ); // check persistent cache
1280 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1281 $auth = $this->getAuthentication();
1286 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1288 'url' => $this->storageUrl( $auth, $container ),
1289 'headers' => $this->authTokenHeaders( $auth )
1292 if ( $rcode === 204 ) {
1294 'count' => $rhdrs['x-container-object-count'],
1295 'bytes' => $rhdrs['x-container-bytes-used']
1297 if ( $bypassCache ) {
1300 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1302 } elseif ( $rcode === 404 ) {
1305 $this->onError( null, __METHOD__
,
1306 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1311 return $this->containerStatCache
->get( $container, 'stat' );
1315 * Create a Swift container
1317 * @param string $container Container name
1318 * @param array $params
1321 protected function createContainer( $container, array $params ) {
1322 $status = Status
::newGood();
1324 $auth = $this->getAuthentication();
1326 $status->fatal( 'backend-fail-connect', $this->name
);
1330 // @see SwiftFileBackend::setContainerAccess()
1331 if ( empty( $params['noAccess'] ) ) {
1332 $readGrps = array( '.r:*', $this->swiftUser
); // public
1334 $readGrps = array( $this->swiftUser
); // private
1336 $writeGrps = array( $this->swiftUser
); // sanity
1338 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1340 'url' => $this->storageUrl( $auth, $container ),
1341 'headers' => $this->authTokenHeaders( $auth ) +
array(
1342 'x-container-read' => implode( ',', $readGrps ),
1343 'x-container-write' => implode( ',', $writeGrps )
1347 if ( $rcode === 201 ) { // new
1349 } elseif ( $rcode === 202 ) { // already there
1350 // this shouldn't really happen, but is OK
1352 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1359 * Delete a Swift container
1361 * @param string $container Container name
1362 * @param array $params
1365 protected function deleteContainer( $container, array $params ) {
1366 $status = Status
::newGood();
1368 $auth = $this->getAuthentication();
1370 $status->fatal( 'backend-fail-connect', $this->name
);
1374 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1375 'method' => 'DELETE',
1376 'url' => $this->storageUrl( $auth, $container ),
1377 'headers' => $this->authTokenHeaders( $auth )
1380 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1381 $this->containerStatCache
->clear( $container ); // purge
1382 } elseif ( $rcode === 404 ) { // not there
1383 // this shouldn't really happen, but is OK
1384 } elseif ( $rcode === 409 ) { // not empty
1385 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1387 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1394 * Get a list of objects under a container.
1395 * Either just the names or a list of stdClass objects with details can be returned.
1397 * @param string $fullCont
1398 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1399 * @param integer $limit
1400 * @param string|null $after
1401 * @param string|null $prefix
1402 * @param string|null $delim
1403 * @return Status With the list as value
1405 private function objectListing(
1406 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1408 $status = Status
::newGood();
1410 $auth = $this->getAuthentication();
1412 $status->fatal( 'backend-fail-connect', $this->name
);
1416 $query = array( 'limit' => $limit );
1417 if ( $type === 'info' ) {
1418 $query['format'] = 'json';
1420 if ( $after !== null ) {
1421 $query['marker'] = $after;
1423 if ( $prefix !== null ) {
1424 $query['prefix'] = $prefix;
1426 if ( $delim !== null ) {
1427 $query['delimiter'] = $delim;
1430 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1432 'url' => $this->storageUrl( $auth, $fullCont ),
1434 'headers' => $this->authTokenHeaders( $auth )
1437 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1438 if ( $rcode === 200 ) { // good
1439 if ( $type === 'info' ) {
1440 $status->value
= FormatJson
::decode( trim( $rbody ) );
1442 $status->value
= explode( "\n", trim( $rbody ) );
1444 } elseif ( $rcode === 204 ) {
1445 $status->value
= array(); // empty container
1446 } elseif ( $rcode === 404 ) {
1447 $status->value
= array(); // no container
1449 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1455 protected function doPrimeContainerCache( array $containerInfo ) {
1456 foreach ( $containerInfo as $container => $info ) {
1457 $this->containerStatCache
->set( $container, 'stat', $info );
1462 * @return array|null Credential map
1464 protected function getAuthentication() {
1465 if ( $this->authErrorTimestamp
!== null ) {
1466 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1467 return null; // failed last attempt; don't bother
1468 } else { // actually retry this time
1469 $this->authErrorTimestamp
= null;
1472 // Session keys expire after a while, so we renew them periodically
1473 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1474 // Authenticate with proxy and get a session key...
1475 if ( !$this->authCreds ||
$reAuth ) {
1476 $this->authSessionTimestamp
= 0;
1477 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1478 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1479 // Try to use the credential cache
1480 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1481 $this->authCreds
= $creds;
1482 // Skew the timestamp for worst case to avoid using stale credentials
1483 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1484 } else { // cache miss
1485 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1487 'url' => "{$this->swiftAuthUrl}/v1.0",
1489 'x-auth-user' => $this->swiftUser
, 'x-auth-key' => $this->swiftKey
)
1492 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1493 $this->authCreds
= array(
1494 'auth_token' => $rhdrs['x-auth-token'],
1495 'storage_url' => $rhdrs['x-storage-url']
1497 $this->authSessionTimestamp
= time();
1498 } elseif ( $rcode === 401 ) {
1499 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1500 $this->authErrorTimestamp
= time();
1503 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1504 $this->authErrorTimestamp
= time();
1509 return $this->authCreds
;
1513 * @param array $creds From getAuthentication()
1514 * @param string $container
1515 * @param string $object
1518 protected function storageUrl( array $creds, $container = null, $object = null ) {
1519 $parts = array( $creds['storage_url'] );
1520 if ( strlen( $container ) ) {
1521 $parts[] = rawurlencode( $container );
1523 if ( strlen( $object ) ) {
1524 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1526 return implode( '/', $parts );
1530 * @param array $creds From getAuthentication()
1533 protected function authTokenHeaders( array $creds ) {
1534 return array( 'x-auth-token' => $creds['auth_token'] );
1538 * Get the cache key for a container
1540 * @param string $username
1543 private function getCredsCacheKey( $username ) {
1544 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1548 * Log an unexpected exception for this backend.
1549 * This also sets the Status object to have a fatal error.
1551 * @param Status $code null
1552 * @param string $func
1553 * @param array $params
1554 * @param string $err Error string
1555 * @param integer $status HTTP status
1556 * @param string $desc HTTP status description
1558 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1559 if ( $status instanceof Status
) {
1560 $status->fatal( 'backend-fail-internal', $this->name
);
1562 if ( $code == 401 ) { // possibly a stale token
1563 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1565 wfDebugLog( 'SwiftBackend',
1566 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1567 ( $err ?
": $err" : "" )
1573 * @see FileBackendStoreOpHandle
1575 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1576 /** @var array List of Requests for MultiHttpClient */
1582 * @param SwiftFileBackend $backend
1583 * @param Closure $callback Function that takes (HTTP request array, status)
1584 * @param array $httpOp MultiHttpClient op
1586 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1587 $this->backend
= $backend;
1588 $this->callback
= $callback;
1589 $this->httpOp
= $httpOp;
1594 * SwiftFileBackend helper class to page through listings.
1595 * Swift also has a listing limit of 10,000 objects for sanity.
1596 * Do not use this class from places outside SwiftFileBackend.
1598 * @ingroup FileBackend
1600 abstract class SwiftFileBackendList
implements Iterator
{
1601 /** @var array List of path or (path,stat array) entries */
1602 protected $bufferIter = array();
1604 /** @var string List items *after* this path */
1605 protected $bufferAfter = null;
1611 protected $params = array();
1613 /** @var SwiftFileBackend */
1616 /** @var string Container name */
1617 protected $container;
1619 /** @var string Storage directory */
1623 protected $suffixStart;
1625 const PAGE_SIZE
= 9000; // file listing buffer size
1628 * @param SwiftFileBackend $backend
1629 * @param string $fullCont Resolved container name
1630 * @param string $dir Resolved directory relative to container
1631 * @param array $params
1633 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1634 $this->backend
= $backend;
1635 $this->container
= $fullCont;
1637 if ( substr( $this->dir
, -1 ) === '/' ) {
1638 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1640 if ( $this->dir
== '' ) { // whole container
1641 $this->suffixStart
= 0;
1642 } else { // dir within container
1643 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1645 $this->params
= $params;
1649 * @see Iterator::key()
1652 public function key() {
1657 * @see Iterator::next()
1659 public function next() {
1660 // Advance to the next file in the page
1661 next( $this->bufferIter
);
1663 // Check if there are no files left in this page and
1664 // advance to the next page if this page was not empty.
1665 if ( !$this->valid() && count( $this->bufferIter
) ) {
1666 $this->bufferIter
= $this->pageFromList(
1667 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1668 ); // updates $this->bufferAfter
1673 * @see Iterator::rewind()
1675 public function rewind() {
1677 $this->bufferAfter
= null;
1678 $this->bufferIter
= $this->pageFromList(
1679 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1680 ); // updates $this->bufferAfter
1684 * @see Iterator::valid()
1687 public function valid() {
1688 if ( $this->bufferIter
=== null ) {
1689 return false; // some failure?
1691 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1696 * Get the given list portion (page)
1698 * @param string $container Resolved container name
1699 * @param string $dir Resolved path relative to container
1700 * @param string $after null
1702 * @param array $params
1703 * @return Traversable|array
1705 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1709 * Iterator for listing directories
1711 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1713 * @see Iterator::current()
1714 * @return string|bool String (relative path) or false
1716 public function current() {
1717 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1720 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1721 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1726 * Iterator for listing regular files
1728 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1730 * @see Iterator::current()
1731 * @return string|bool String (relative path) or false
1733 public function current() {
1734 list( $path, $stat ) = current( $this->bufferIter
);
1735 $relPath = substr( $path, $this->suffixStart
);
1736 if ( is_array( $stat ) ) {
1737 $storageDir = rtrim( $this->params
['dir'], '/' );
1738 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1744 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1745 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );