3 * OpenStack Swift based file backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 * @author Aaron Schulz
27 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
29 * Status messages should avoid mentioning the Swift account name.
30 * Likewise, error suppression should be used to avoid path disclosure.
32 * @ingroup FileBackend
35 class SwiftFileBackend
extends FileBackendStore
{
36 /** @var MultiHttpClient */
39 /** @var int TTL in seconds */
42 /** @var string Authentication base URL (without version) */
43 protected $swiftAuthUrl;
45 /** @var string Swift user (account:user) to authenticate as */
48 /** @var string Secret key for user */
51 /** @var string Shared secret value for making temp URLs */
52 protected $swiftTempUrlKey;
54 /** @var string S3 access key (RADOS Gateway) */
55 protected $rgwS3AccessKey;
57 /** @var string S3 authentication key (RADOS Gateway) */
58 protected $rgwS3SecretKey;
63 /** @var ProcessCacheLRU Container stat cache */
64 protected $containerStatCache;
69 /** @var int UNIX timestamp */
70 protected $authSessionTimestamp = 0;
72 /** @var int UNIX timestamp */
73 protected $authErrorTimestamp = null;
76 * @see FileBackendStore::__construct()
77 * Additional $config params include:
78 * - swiftAuthUrl : Swift authentication server URL
79 * - swiftUser : Swift user used by MediaWiki (account:username)
80 * - swiftKey : Swift authentication key for the above user
81 * - swiftAuthTTL : Swift authentication TTL (seconds)
82 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
83 * Do not set this until it has been set in the backend.
84 * - shardViaHashLevels : Map of container names to sharding config with:
85 * - base : base of hash characters, 16 or 36
86 * - levels : the number of hash levels (and digits)
87 * - repeat : hash subdirectories are prefixed with all the
88 * parent hash directory names (e.g. "a/ab/abc")
89 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
90 * If those are not available, then the main cache will be used.
91 * This is probably insecure in shared hosting environments.
92 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
93 * Do not set this until it has been set in the backend.
94 * This is used for generating expiring pre-authenticated URLs.
95 * Only use this when using rgw and to work around
96 * http://tracker.newdream.net/issues/3454.
97 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
98 * Do not set this until it has been set in the backend.
99 * This is used for generating expiring pre-authenticated URLs.
100 * Only use this when using rgw and to work around
101 * http://tracker.newdream.net/issues/3454.
103 public function __construct( array $config ) {
104 parent
::__construct( $config );
106 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
107 $this->swiftUser
= $config['swiftUser'];
108 $this->swiftKey
= $config['swiftKey'];
110 $this->authTTL
= isset( $config['swiftAuthTTL'] )
111 ?
$config['swiftAuthTTL']
112 : 5 * 60; // some sane number
113 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
114 ?
$config['swiftTempUrlKey']
116 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
117 ?
$config['shardViaHashLevels']
119 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
120 ?
$config['rgwS3AccessKey']
122 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
123 ?
$config['rgwS3SecretKey']
125 // HTTP helper client
126 $this->http
= new MultiHttpClient( array() );
127 // Cache container information to mask latency
128 $this->memCache
= wfGetMainCache();
129 // Process cache for container info
130 $this->containerStatCache
= new ProcessCacheLRU( 300 );
131 // Cache auth token information to avoid RTTs
132 if ( !empty( $config['cacheAuthInfo'] ) ) {
133 if ( PHP_SAPI
=== 'cli' ) {
134 $this->srvCache
= wfGetMainCache(); // preferrably memcached
136 try { // look for APC, XCache, WinCache, ect...
137 $this->srvCache
= ObjectCache
::newAccelerator( array() );
138 } catch ( Exception
$e ) {
142 $this->srvCache
= $this->srvCache ?
: new EmptyBagOStuff();
145 public function getFeatures() {
146 return ( FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
149 protected function resolveContainerPath( $container, $relStoragePath ) {
150 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
151 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
152 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
153 return null; // too long for Swift
156 return $relStoragePath;
159 public function isPathUsableInternal( $storagePath ) {
160 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
161 if ( $rel === null ) {
162 return false; // invalid
165 return is_array( $this->getContainerStat( $container ) );
169 * Sanitize and filter the custom headers from a $params array.
170 * We only allow certain Content- and X-Content- headers.
172 * @param array $headers
173 * @return array Sanitized value of 'headers' field in $params
175 protected function sanitizeHdrs( array $params ) {
178 // Normalize casing, and strip out illegal headers
179 if ( isset( $params['headers'] ) ) {
180 foreach ( $params['headers'] as $name => $value ) {
181 $name = strtolower( $name );
182 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
183 continue; // blacklisted
184 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
185 $headers[$name] = $value; // allowed
186 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
187 $headers[$name] = $value; // allowed
191 // By default, Swift has annoyingly low maximum header value limits
192 if ( isset( $headers['content-disposition'] ) ) {
194 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
195 $part = trim( $part );
196 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
197 if ( strlen( $new ) <= 255 ) {
200 break; // too long; sigh
203 $headers['content-disposition'] = $disposition;
209 protected function doCreateInternal( array $params ) {
210 $status = Status
::newGood();
212 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
213 if ( $dstRel === null ) {
214 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
219 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
220 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
222 $reqs = array( array(
224 'url' => array( $dstCont, $dstRel ),
226 'content-length' => strlen( $params['content'] ),
227 'etag' => md5( $params['content'] ),
228 'content-type' => $contentType,
229 'x-object-meta-sha1base36' => $sha1Hash
230 ) +
$this->sanitizeHdrs( $params ),
231 'body' => $params['content']
235 $method = __METHOD__
;
236 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
237 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
238 if ( $rcode === 201 ) {
240 } elseif ( $rcode === 412 ) {
241 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
243 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
247 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
248 if ( !empty( $params['async'] ) ) { // deferred
249 $status->value
= $opHandle;
250 } else { // actually write the object in Swift
251 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
257 protected function doStoreInternal( array $params ) {
258 $status = Status
::newGood();
260 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
261 if ( $dstRel === null ) {
262 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
267 wfSuppressWarnings();
268 $sha1Hash = sha1_file( $params['src'] );
270 if ( $sha1Hash === false ) { // source doesn't exist?
271 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
275 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
276 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
278 $handle = fopen( $params['src'], 'rb' );
279 if ( $handle === false ) { // source doesn't exist?
280 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
285 $reqs = array( array(
287 'url' => array( $dstCont, $dstRel ),
289 'content-length' => filesize( $params['src'] ),
290 'etag' => md5_file( $params['src'] ),
291 'content-type' => $contentType,
292 'x-object-meta-sha1base36' => $sha1Hash
293 ) +
$this->sanitizeHdrs( $params ),
294 'body' => $handle // resource
298 $method = __METHOD__
;
299 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
300 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
301 if ( $rcode === 201 ) {
303 } elseif ( $rcode === 412 ) {
304 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
306 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
310 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
311 if ( !empty( $params['async'] ) ) { // deferred
312 $status->value
= $opHandle;
313 } else { // actually write the object in Swift
314 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
320 protected function doCopyInternal( array $params ) {
321 $status = Status
::newGood();
323 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
324 if ( $srcRel === null ) {
325 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
330 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
331 if ( $dstRel === null ) {
332 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
337 $reqs = array( array(
339 'url' => array( $dstCont, $dstRel ),
341 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
342 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
343 ) +
$this->sanitizeHdrs( $params ), // extra headers merged into object
347 $method = __METHOD__
;
348 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
349 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
350 if ( $rcode === 201 ) {
352 } elseif ( $rcode === 404 ) {
353 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
355 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
359 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
360 if ( !empty( $params['async'] ) ) { // deferred
361 $status->value
= $opHandle;
362 } else { // actually write the object in Swift
363 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
369 protected function doMoveInternal( array $params ) {
370 $status = Status
::newGood();
372 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
373 if ( $srcRel === null ) {
374 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
379 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
380 if ( $dstRel === null ) {
381 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
389 'url' => array( $dstCont, $dstRel ),
391 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
392 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
393 ) +
$this->sanitizeHdrs( $params ) // extra headers merged into object
396 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
398 'method' => 'DELETE',
399 'url' => array( $srcCont, $srcRel ),
405 $method = __METHOD__
;
406 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
407 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
408 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
410 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
412 } elseif ( $rcode === 404 ) {
413 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
415 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
419 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
420 if ( !empty( $params['async'] ) ) { // deferred
421 $status->value
= $opHandle;
422 } else { // actually move the object in Swift
423 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
429 protected function doDeleteInternal( array $params ) {
430 $status = Status
::newGood();
432 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
433 if ( $srcRel === null ) {
434 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
439 $reqs = array( array(
440 'method' => 'DELETE',
441 'url' => array( $srcCont, $srcRel ),
446 $method = __METHOD__
;
447 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
448 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
449 if ( $rcode === 204 ) {
451 } elseif ( $rcode === 404 ) {
452 if ( empty( $params['ignoreMissingSource'] ) ) {
453 $status->fatal( 'backend-fail-delete', $params['src'] );
456 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
460 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
461 if ( !empty( $params['async'] ) ) { // deferred
462 $status->value
= $opHandle;
463 } else { // actually delete the object in Swift
464 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
470 protected function doDescribeInternal( array $params ) {
471 $status = Status
::newGood();
473 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
474 if ( $srcRel === null ) {
475 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
480 // Fetch the old object headers/metadata...this should be in stat cache by now
481 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
482 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
483 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
486 $status->fatal( 'backend-fail-describe', $params['src'] );
491 // POST clears prior headers, so we need to merge the changes in to the old ones
493 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
494 $metaHdrs["x-object-meta-$name"] = $value;
496 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
498 $reqs = array( array(
500 'url' => array( $srcCont, $srcRel ),
501 'headers' => $metaHdrs +
$customHdrs
505 $method = __METHOD__
;
506 $handler = function ( array $request, Status
$status ) use ( $be, $method, $params ) {
507 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
508 if ( $rcode === 202 ) {
510 } elseif ( $rcode === 404 ) {
511 $status->fatal( 'backend-fail-describe', $params['src'] );
513 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
517 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
518 if ( !empty( $params['async'] ) ) { // deferred
519 $status->value
= $opHandle;
520 } else { // actually change the object in Swift
521 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
527 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
528 $status = Status
::newGood();
530 // (a) Check if container already exists
531 $stat = $this->getContainerStat( $fullCont );
532 if ( is_array( $stat ) ) {
533 return $status; // already there
534 } elseif ( $stat === null ) {
535 $status->fatal( 'backend-fail-internal', $this->name
);
540 // (b) Create container as needed with proper ACLs
541 if ( $stat === false ) {
542 $params['op'] = 'prepare';
543 $status->merge( $this->createContainer( $fullCont, $params ) );
549 protected function doSecureInternal( $fullCont, $dir, array $params ) {
550 $status = Status
::newGood();
551 if ( empty( $params['noAccess'] ) ) {
552 return $status; // nothing to do
555 $stat = $this->getContainerStat( $fullCont );
556 if ( is_array( $stat ) ) {
557 // Make container private to end-users...
558 $status->merge( $this->setContainerAccess(
560 array( $this->swiftUser
), // read
561 array( $this->swiftUser
) // write
563 } elseif ( $stat === false ) {
564 $status->fatal( 'backend-fail-usable', $params['dir'] );
566 $status->fatal( 'backend-fail-internal', $this->name
);
572 protected function doPublishInternal( $fullCont, $dir, array $params ) {
573 $status = Status
::newGood();
575 $stat = $this->getContainerStat( $fullCont );
576 if ( is_array( $stat ) ) {
577 // Make container public to end-users...
578 $status->merge( $this->setContainerAccess(
580 array( $this->swiftUser
, '.r:*' ), // read
581 array( $this->swiftUser
) // write
583 } elseif ( $stat === false ) {
584 $status->fatal( 'backend-fail-usable', $params['dir'] );
586 $status->fatal( 'backend-fail-internal', $this->name
);
592 protected function doCleanInternal( $fullCont, $dir, array $params ) {
593 $status = Status
::newGood();
595 // Only containers themselves can be removed, all else is virtual
597 return $status; // nothing to do
600 // (a) Check the container
601 $stat = $this->getContainerStat( $fullCont, true );
602 if ( $stat === false ) {
603 return $status; // ok, nothing to do
604 } elseif ( !is_array( $stat ) ) {
605 $status->fatal( 'backend-fail-internal', $this->name
);
610 // (b) Delete the container if empty
611 if ( $stat['count'] == 0 ) {
612 $params['op'] = 'clean';
613 $status->merge( $this->deleteContainer( $fullCont, $params ) );
619 protected function doGetFileStat( array $params ) {
620 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
621 if ( $srcRel === null ) {
622 return false; // invalid storage path
625 $auth = $this->getAuthentication();
630 // (a) Check the container
631 $cstat = $this->getContainerStat( $srcCont, true );
632 if ( $cstat === false ) {
633 return false; // ok, nothing to do
634 } elseif ( !is_array( $cstat ) ) {
638 // (b) Check the file
639 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
641 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
642 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
644 if ( $rcode === 200 ||
$rcode === 204 ) {
645 // Update the object if it is missing some headers
646 $rhdrs = $this->addMissingMetadata( $rhdrs, $params['src'] );
647 // Fetch all of the custom metadata headers
649 foreach ( $rhdrs as $name => $value ) {
650 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
651 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
654 // Fetch all of the custom raw HTTP headers
655 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
657 // Convert various random Swift dates to TS_MW
658 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
659 // Empty objects actually return no content-length header in Ceph
660 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
661 'sha1' => $rhdrs['x-object-meta-sha1base36'],
662 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
663 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
665 } elseif ( $rcode === 404 ) {
669 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
676 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
677 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
678 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
681 * @param int $format Output format (TS_* constant)
683 * @throws FileBackendError
685 protected function convertSwiftDate( $ts, $format = TS_MW
) {
687 $timestamp = new MWTimestamp( $ts );
689 return $timestamp->getTimestamp( $format );
690 } catch ( MWException
$e ) {
691 throw new FileBackendError( $e->getMessage() );
696 * Fill in any missing object metadata and save it to Swift
698 * @param array $objHdrs Object response headers
699 * @param string $path Storage path to object
700 * @return array New headers
702 protected function addMissingMetadata( array $objHdrs, $path ) {
703 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
704 return $objHdrs; // nothing to do
707 $section = new ProfileSection( __METHOD__
);
708 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
710 $auth = $this->getAuthentication();
712 $objHdrs['x-object-meta-sha1base36'] = false;
714 return $objHdrs; // failed
717 $status = Status
::newGood();
718 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
719 if ( $status->isOK() ) {
720 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
722 $hash = $tmpFile->getSha1Base36();
723 if ( $hash !== false ) {
724 $objHdrs['x-object-meta-sha1base36'] = $hash;
725 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
726 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
728 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
729 'headers' => $this->authTokenHeaders( $auth ) +
$objHdrs
731 if ( $rcode >= 200 && $rcode <= 299 ) {
732 return $objHdrs; // success
737 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING
);
738 $objHdrs['x-object-meta-sha1base36'] = false;
740 return $objHdrs; // failed
743 protected function doGetFileContentsMulti( array $params ) {
746 $auth = $this->getAuthentication();
748 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
749 // Blindly create tmp files and stream to them, catching any exception if the file does
750 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
751 $reqs = array(); // (path => op)
753 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
754 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
755 if ( $srcRel === null ||
!$auth ) {
756 $contents[$path] = false;
759 // Create a new temporary memory file...
760 $handle = fopen( 'php://temp', 'wb' );
762 $reqs[$path] = array(
764 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
765 'headers' => $this->authTokenHeaders( $auth )
766 +
$this->headersFromParams( $params ),
770 $contents[$path] = false;
773 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
774 $reqs = $this->http
->runMulti( $reqs, $opts );
775 foreach ( $reqs as $path => $op ) {
776 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
777 if ( $rcode >= 200 && $rcode <= 299 ) {
778 rewind( $op['stream'] ); // start from the beginning
779 $contents[$path] = stream_get_contents( $op['stream'] );
780 } elseif ( $rcode === 404 ) {
781 $contents[$path] = false;
783 $this->onError( null, __METHOD__
,
784 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
786 fclose( $op['stream'] ); // close open handle
792 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
793 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
794 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
795 if ( $status->isOk() ) {
796 return ( count( $status->value
) );
799 return null; // error
803 * @see FileBackendStore::getDirectoryListInternal()
804 * @param string $fullCont
806 * @param array $params
807 * @return SwiftFileBackendDirList
809 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
810 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
814 * @see FileBackendStore::getFileListInternal()
815 * @param string $fullCont
817 * @param array $params
818 * @return SwiftFileBackendFileList
820 public function getFileListInternal( $fullCont, $dir, array $params ) {
821 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
825 * Do not call this function outside of SwiftFileBackendFileList
827 * @param string $fullCont Resolved container name
828 * @param string $dir Resolved storage directory with no trailing slash
829 * @param string|null $after Resolved container relative path to list items after
830 * @param int $limit Max number of items to list
831 * @param array $params Parameters for getDirectoryList()
832 * @return array List of container relative resolved paths of directories directly under $dir
833 * @throws FileBackendError
835 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
837 if ( $after === INF
) {
838 return $dirs; // nothing more
841 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
843 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
844 // Non-recursive: only list dirs right under $dir
845 if ( !empty( $params['topOnly'] ) ) {
846 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
847 if ( !$status->isOk() ) {
848 return $dirs; // error
850 $objects = $status->value
;
851 foreach ( $objects as $object ) { // files and directories
852 if ( substr( $object, -1 ) === '/' ) {
853 $dirs[] = $object; // directories end in '/'
857 // Recursive: list all dirs under $dir and its subdirs
858 $getParentDir = function ( $path ) {
859 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
862 // Get directory from last item of prior page
863 $lastDir = $getParentDir( $after ); // must be first page
864 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
866 if ( !$status->isOk() ) {
867 return $dirs; // error
870 $objects = $status->value
;
872 foreach ( $objects as $object ) { // files
873 $objectDir = $getParentDir( $object ); // directory of object
875 if ( $objectDir !== false && $objectDir !== $dir ) {
876 // Swift stores paths in UTF-8, using binary sorting.
877 // See function "create_container_table" in common/db.py.
878 // If a directory is not "greater" than the last one,
879 // then it was already listed by the calling iterator.
880 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
882 do { // add dir and all its parent dirs
883 $dirs[] = "{$pDir}/";
884 $pDir = $getParentDir( $pDir );
885 } while ( $pDir !== false // sanity
886 && strcmp( $pDir, $lastDir ) > 0 // not done already
887 && strlen( $pDir ) > strlen( $dir ) // within $dir
890 $lastDir = $objectDir;
894 // Page on the unfiltered directory listing (what is returned may be filtered)
895 if ( count( $objects ) < $limit ) {
896 $after = INF
; // avoid a second RTT
898 $after = end( $objects ); // update last item
905 * Do not call this function outside of SwiftFileBackendFileList
907 * @param string $fullCont Resolved container name
908 * @param string $dir Resolved storage directory with no trailing slash
909 * @param string|null $after Resolved container relative path of file to list items after
910 * @param int $limit Max number of items to list
911 * @param array $params Parameters for getDirectoryList()
912 * @return array List of resolved container relative paths of files under $dir
913 * @throws FileBackendError
915 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
916 $files = array(); // list of (path, stat array or null) entries
917 if ( $after === INF
) {
918 return $files; // nothing more
921 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
923 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
924 // $objects will contain a list of unfiltered names or CF_Object items
925 // Non-recursive: only list files right under $dir
926 if ( !empty( $params['topOnly'] ) ) {
927 if ( !empty( $params['adviseStat'] ) ) {
928 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
930 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
933 // Recursive: list all files under $dir and its subdirs
934 if ( !empty( $params['adviseStat'] ) ) {
935 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
937 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
941 // Reformat this list into a list of (name, stat array or null) entries
942 if ( !$status->isOk() ) {
943 return $files; // error
946 $objects = $status->value
;
947 $files = $this->buildFileObjectListing( $params, $dir, $objects );
949 // Page on the unfiltered object listing (what is returned may be filtered)
950 if ( count( $objects ) < $limit ) {
951 $after = INF
; // avoid a second RTT
953 $after = end( $objects ); // update last item
954 $after = is_object( $after ) ?
$after->name
: $after;
961 * Build a list of file objects, filtering out any directories
962 * and extracting any stat info if provided in $objects (for CF_Objects)
964 * @param array $params Parameters for getDirectoryList()
965 * @param string $dir Resolved container directory path
966 * @param array $objects List of CF_Object items or object names
967 * @return array List of (names,stat array or null) entries
969 private function buildFileObjectListing( array $params, $dir, array $objects ) {
971 foreach ( $objects as $object ) {
972 if ( is_object( $object ) ) {
973 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
974 continue; // virtual directory entry; ignore
977 // Convert various random Swift dates to TS_MW
978 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
979 'size' => (int)$object->bytes
,
980 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
981 'latest' => false // eventually consistent
983 $names[] = array( $object->name
, $stat );
984 } elseif ( substr( $object, -1 ) !== '/' ) {
985 // Omit directories, which end in '/' in listings
986 $names[] = array( $object, null );
994 * Do not call this function outside of SwiftFileBackendFileList
996 * @param string $path Storage path
997 * @param array $val Stat value
999 public function loadListingStatInternal( $path, array $val ) {
1000 $this->cheapCache
->set( $path, 'stat', $val );
1003 protected function doGetFileXAttributes( array $params ) {
1004 $stat = $this->getFileStat( $params );
1006 if ( !isset( $stat['xattr'] ) ) {
1007 // Stat entries filled by file listings don't include metadata/headers
1008 $this->clearCache( array( $params['src'] ) );
1009 $stat = $this->getFileStat( $params );
1012 return $stat['xattr'];
1018 protected function doGetFileSha1base36( array $params ) {
1019 $stat = $this->getFileStat( $params );
1021 if ( !isset( $stat['sha1'] ) ) {
1022 // Stat entries filled by file listings don't include SHA1
1023 $this->clearCache( array( $params['src'] ) );
1024 $stat = $this->getFileStat( $params );
1027 return $stat['sha1'];
1033 protected function doStreamFile( array $params ) {
1034 $status = Status
::newGood();
1036 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1037 if ( $srcRel === null ) {
1038 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1041 $auth = $this->getAuthentication();
1042 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1043 $status->fatal( 'backend-fail-stream', $params['src'] );
1048 $handle = fopen( 'php://output', 'wb' );
1050 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1052 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1053 'headers' => $this->authTokenHeaders( $auth )
1054 +
$this->headersFromParams( $params ),
1055 'stream' => $handle,
1058 if ( $rcode >= 200 && $rcode <= 299 ) {
1060 } elseif ( $rcode === 404 ) {
1061 $status->fatal( 'backend-fail-stream', $params['src'] );
1063 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1069 protected function doGetLocalCopyMulti( array $params ) {
1070 $tmpFiles = array();
1072 $auth = $this->getAuthentication();
1074 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1075 // Blindly create tmp files and stream to them, catching any exception if the file does
1076 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1077 $reqs = array(); // (path => op)
1079 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1080 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1081 if ( $srcRel === null ||
!$auth ) {
1082 $tmpFiles[$path] = null;
1085 // Get source file extension
1086 $ext = FileBackend
::extensionFromPath( $path );
1087 // Create a new temporary file...
1088 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1090 $handle = fopen( $tmpFile->getPath(), 'wb' );
1092 $reqs[$path] = array(
1094 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1095 'headers' => $this->authTokenHeaders( $auth )
1096 +
$this->headersFromParams( $params ),
1097 'stream' => $handle,
1103 $tmpFiles[$path] = $tmpFile;
1106 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1107 $reqs = $this->http
->runMulti( $reqs, $opts );
1108 foreach ( $reqs as $path => $op ) {
1109 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1110 fclose( $op['stream'] ); // close open handle
1111 if ( $rcode >= 200 && $rcode <= 299
1112 // double check that the disk is not full/broken
1113 && $tmpFiles[$path]->getSize() == $rhdrs['content-length']
1116 } elseif ( $rcode === 404 ) {
1117 $tmpFiles[$path] = false;
1119 $tmpFiles[$path] = null;
1120 $this->onError( null, __METHOD__
,
1121 array( 'src' => $path ) +
$ep, $rerr, $rcode, $rdesc );
1128 public function getFileHttpUrl( array $params ) {
1129 if ( $this->swiftTempUrlKey
!= '' ||
1130 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1132 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1133 if ( $srcRel === null ) {
1134 return null; // invalid path
1137 $auth = $this->getAuthentication();
1142 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1143 $expires = time() +
$ttl;
1145 if ( $this->swiftTempUrlKey
!= '' ) {
1146 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1147 // Swift wants the signature based on the unencoded object name
1148 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1149 $signature = hash_hmac( 'sha1',
1150 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1151 $this->swiftTempUrlKey
1154 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1155 } else { // give S3 API URL for rgw
1156 // Path for signature starts with the bucket
1157 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1158 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1159 // Calculate the hash
1160 $signature = base64_encode( hash_hmac(
1162 "GET\n\n\n{$expires}\n{$spath}",
1163 $this->rgwS3SecretKey
,
1166 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1167 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1168 return wfAppendQuery(
1169 str_replace( '/swift/v1', '', // S3 API is the rgw default
1170 $this->storageUrl( $auth ) . $spath ),
1172 'Signature' => $signature,
1173 'Expires' => $expires,
1174 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1182 protected function directoriesAreVirtual() {
1187 * Get headers to send to Swift when reading a file based
1188 * on a FileBackend params array, e.g. that of getLocalCopy().
1189 * $params is currently only checked for a 'latest' flag.
1191 * @param array $params
1194 protected function headersFromParams( array $params ) {
1196 if ( !empty( $params['latest'] ) ) {
1197 $hdrs['x-newest'] = 'true';
1203 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1204 $statuses = array();
1206 $auth = $this->getAuthentication();
1208 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1209 $statuses[$index] = Status
::newFatal( 'backend-fail-connect', $this->name
);
1215 // Split the HTTP requests into stages that can be done concurrently
1216 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1217 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1218 $reqs = $fileOpHandle->httpOp
;
1219 // Convert the 'url' parameter to an actual URL using $auth
1220 foreach ( $reqs as $stage => &$req ) {
1221 list( $container, $relPath ) = $req['url'];
1222 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1223 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : array();
1224 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1225 $httpReqsByStage[$stage][$index] = $req;
1227 $statuses[$index] = Status
::newGood();
1230 // Run all requests for the first stage, then the next, and so on
1231 $reqCount = count( $httpReqsByStage );
1232 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1233 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1234 foreach ( $httpReqs as $index => $httpReq ) {
1235 // Run the callback for each request of this operation
1236 $callback = $fileOpHandles[$index]->callback
;
1237 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1238 // On failure, abort all remaining requests for this operation
1239 // (e.g. abort the DELETE request if the COPY request fails for a move)
1240 if ( !$statuses[$index]->isOK() ) {
1241 $stages = count( $fileOpHandles[$index]->httpOp
);
1242 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1243 unset( $httpReqsByStage[$s][$index] );
1253 * Set read/write permissions for a Swift container.
1255 * @see http://swift.openstack.org/misc.html#acls
1257 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1258 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1260 * @param string $container Resolved Swift container
1261 * @param array $readGrps List of the possible criteria for a request to have
1262 * access to read a container. Each item is one of the following formats:
1263 * - account:user : Grants access if the request is by the given user
1264 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1265 * matches the expression and the request is not for a listing.
1266 * Setting this to '*' effectively makes a container public.
1267 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1268 * matches the expression and the request is for a listing.
1269 * @param array $writeGrps A list of the possible criteria for a request to have
1270 * access to write to a container. Each item is of the following format:
1271 * - account:user : Grants access if the request is by the given user
1274 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1275 $status = Status
::newGood();
1276 $auth = $this->getAuthentication();
1279 $status->fatal( 'backend-fail-connect', $this->name
);
1284 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1286 'url' => $this->storageUrl( $auth, $container ),
1287 'headers' => $this->authTokenHeaders( $auth ) +
array(
1288 'x-container-read' => implode( ',', $readGrps ),
1289 'x-container-write' => implode( ',', $writeGrps )
1293 if ( $rcode != 204 && $rcode !== 202 ) {
1294 $status->fatal( 'backend-fail-internal', $this->name
);
1301 * Get a Swift container stat array, possibly from process cache.
1302 * Use $reCache if the file count or byte count is needed.
1304 * @param string $container Container name
1305 * @param bool $bypassCache Bypass all caches and load from Swift
1306 * @return array|bool|null False on 404, null on failure
1308 protected function getContainerStat( $container, $bypassCache = false ) {
1309 if ( $bypassCache ) { // purge cache
1310 $this->containerStatCache
->clear( $container );
1311 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1312 $this->primeContainerCache( array( $container ) ); // check persistent cache
1314 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1315 $auth = $this->getAuthentication();
1320 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1322 'url' => $this->storageUrl( $auth, $container ),
1323 'headers' => $this->authTokenHeaders( $auth )
1326 if ( $rcode === 204 ) {
1328 'count' => $rhdrs['x-container-object-count'],
1329 'bytes' => $rhdrs['x-container-bytes-used']
1331 if ( $bypassCache ) {
1334 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1336 } elseif ( $rcode === 404 ) {
1339 $this->onError( null, __METHOD__
,
1340 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1346 return $this->containerStatCache
->get( $container, 'stat' );
1350 * Create a Swift container
1352 * @param string $container Container name
1353 * @param array $params
1356 protected function createContainer( $container, array $params ) {
1357 $status = Status
::newGood();
1359 $auth = $this->getAuthentication();
1361 $status->fatal( 'backend-fail-connect', $this->name
);
1366 // @see SwiftFileBackend::setContainerAccess()
1367 if ( empty( $params['noAccess'] ) ) {
1368 $readGrps = array( '.r:*', $this->swiftUser
); // public
1370 $readGrps = array( $this->swiftUser
); // private
1372 $writeGrps = array( $this->swiftUser
); // sanity
1374 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1376 'url' => $this->storageUrl( $auth, $container ),
1377 'headers' => $this->authTokenHeaders( $auth ) +
array(
1378 'x-container-read' => implode( ',', $readGrps ),
1379 'x-container-write' => implode( ',', $writeGrps )
1383 if ( $rcode === 201 ) { // new
1385 } elseif ( $rcode === 202 ) { // already there
1386 // this shouldn't really happen, but is OK
1388 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1395 * Delete a Swift container
1397 * @param string $container Container name
1398 * @param array $params
1401 protected function deleteContainer( $container, array $params ) {
1402 $status = Status
::newGood();
1404 $auth = $this->getAuthentication();
1406 $status->fatal( 'backend-fail-connect', $this->name
);
1411 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1412 'method' => 'DELETE',
1413 'url' => $this->storageUrl( $auth, $container ),
1414 'headers' => $this->authTokenHeaders( $auth )
1417 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1418 $this->containerStatCache
->clear( $container ); // purge
1419 } elseif ( $rcode === 404 ) { // not there
1420 // this shouldn't really happen, but is OK
1421 } elseif ( $rcode === 409 ) { // not empty
1422 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1424 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1431 * Get a list of objects under a container.
1432 * Either just the names or a list of stdClass objects with details can be returned.
1434 * @param string $fullCont
1435 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1436 * @param integer $limit
1437 * @param string|null $after
1438 * @param string|null $prefix
1439 * @param string|null $delim
1440 * @return Status With the list as value
1442 private function objectListing(
1443 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1445 $status = Status
::newGood();
1447 $auth = $this->getAuthentication();
1449 $status->fatal( 'backend-fail-connect', $this->name
);
1454 $query = array( 'limit' => $limit );
1455 if ( $type === 'info' ) {
1456 $query['format'] = 'json';
1458 if ( $after !== null ) {
1459 $query['marker'] = $after;
1461 if ( $prefix !== null ) {
1462 $query['prefix'] = $prefix;
1464 if ( $delim !== null ) {
1465 $query['delimiter'] = $delim;
1468 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1470 'url' => $this->storageUrl( $auth, $fullCont ),
1472 'headers' => $this->authTokenHeaders( $auth )
1475 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1476 if ( $rcode === 200 ) { // good
1477 if ( $type === 'info' ) {
1478 $status->value
= FormatJson
::decode( trim( $rbody ) );
1480 $status->value
= explode( "\n", trim( $rbody ) );
1482 } elseif ( $rcode === 204 ) {
1483 $status->value
= array(); // empty container
1484 } elseif ( $rcode === 404 ) {
1485 $status->value
= array(); // no container
1487 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1493 protected function doPrimeContainerCache( array $containerInfo ) {
1494 foreach ( $containerInfo as $container => $info ) {
1495 $this->containerStatCache
->set( $container, 'stat', $info );
1500 * @return array|null Credential map
1502 protected function getAuthentication() {
1503 if ( $this->authErrorTimestamp
!== null ) {
1504 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1505 return null; // failed last attempt; don't bother
1506 } else { // actually retry this time
1507 $this->authErrorTimestamp
= null;
1510 // Session keys expire after a while, so we renew them periodically
1511 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1512 // Authenticate with proxy and get a session key...
1513 if ( !$this->authCreds ||
$reAuth ) {
1514 $this->authSessionTimestamp
= 0;
1515 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1516 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1517 // Try to use the credential cache
1518 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1519 $this->authCreds
= $creds;
1520 // Skew the timestamp for worst case to avoid using stale credentials
1521 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1522 } else { // cache miss
1523 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( array(
1525 'url' => "{$this->swiftAuthUrl}/v1.0",
1527 'x-auth-user' => $this->swiftUser
,
1528 'x-auth-key' => $this->swiftKey
1532 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1533 $this->authCreds
= array(
1534 'auth_token' => $rhdrs['x-auth-token'],
1535 'storage_url' => $rhdrs['x-storage-url']
1537 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1538 $this->authSessionTimestamp
= time();
1539 } elseif ( $rcode === 401 ) {
1540 $this->onError( null, __METHOD__
, array(), "Authentication failed.", $rcode );
1541 $this->authErrorTimestamp
= time();
1545 $this->onError( null, __METHOD__
, array(), "HTTP return code: $rcode", $rcode );
1546 $this->authErrorTimestamp
= time();
1553 return $this->authCreds
;
1557 * @param array $creds From getAuthentication()
1558 * @param string $container
1559 * @param string $object
1562 protected function storageUrl( array $creds, $container = null, $object = null ) {
1563 $parts = array( $creds['storage_url'] );
1564 if ( strlen( $container ) ) {
1565 $parts[] = rawurlencode( $container );
1567 if ( strlen( $object ) ) {
1568 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1571 return implode( '/', $parts );
1575 * @param array $creds From getAuthentication()
1578 protected function authTokenHeaders( array $creds ) {
1579 return array( 'x-auth-token' => $creds['auth_token'] );
1583 * Get the cache key for a container
1585 * @param string $username
1588 private function getCredsCacheKey( $username ) {
1589 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1593 * Log an unexpected exception for this backend.
1594 * This also sets the Status object to have a fatal error.
1596 * @param Status|null $status
1597 * @param string $func
1598 * @param array $params
1599 * @param string $err Error string
1600 * @param integer $code HTTP status
1601 * @param string $desc HTTP status description
1603 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1604 if ( $status instanceof Status
) {
1605 $status->fatal( 'backend-fail-internal', $this->name
);
1607 if ( $code == 401 ) { // possibly a stale token
1608 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1610 wfDebugLog( 'SwiftBackend',
1611 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1612 ( $err ?
": $err" : "" )
1618 * @see FileBackendStoreOpHandle
1620 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1621 /** @var array List of Requests for MultiHttpClient */
1627 * @param SwiftFileBackend $backend
1628 * @param Closure $callback Function that takes (HTTP request array, status)
1629 * @param array $httpOp MultiHttpClient op
1631 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1632 $this->backend
= $backend;
1633 $this->callback
= $callback;
1634 $this->httpOp
= $httpOp;
1639 * SwiftFileBackend helper class to page through listings.
1640 * Swift also has a listing limit of 10,000 objects for sanity.
1641 * Do not use this class from places outside SwiftFileBackend.
1643 * @ingroup FileBackend
1645 abstract class SwiftFileBackendList
implements Iterator
{
1646 /** @var array List of path or (path,stat array) entries */
1647 protected $bufferIter = array();
1649 /** @var string List items *after* this path */
1650 protected $bufferAfter = null;
1656 protected $params = array();
1658 /** @var SwiftFileBackend */
1661 /** @var string Container name */
1662 protected $container;
1664 /** @var string Storage directory */
1668 protected $suffixStart;
1670 const PAGE_SIZE
= 9000; // file listing buffer size
1673 * @param SwiftFileBackend $backend
1674 * @param string $fullCont Resolved container name
1675 * @param string $dir Resolved directory relative to container
1676 * @param array $params
1678 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1679 $this->backend
= $backend;
1680 $this->container
= $fullCont;
1682 if ( substr( $this->dir
, -1 ) === '/' ) {
1683 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1685 if ( $this->dir
== '' ) { // whole container
1686 $this->suffixStart
= 0;
1687 } else { // dir within container
1688 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1690 $this->params
= $params;
1694 * @see Iterator::key()
1697 public function key() {
1702 * @see Iterator::next()
1704 public function next() {
1705 // Advance to the next file in the page
1706 next( $this->bufferIter
);
1708 // Check if there are no files left in this page and
1709 // advance to the next page if this page was not empty.
1710 if ( !$this->valid() && count( $this->bufferIter
) ) {
1711 $this->bufferIter
= $this->pageFromList(
1712 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1713 ); // updates $this->bufferAfter
1718 * @see Iterator::rewind()
1720 public function rewind() {
1722 $this->bufferAfter
= null;
1723 $this->bufferIter
= $this->pageFromList(
1724 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1725 ); // updates $this->bufferAfter
1729 * @see Iterator::valid()
1732 public function valid() {
1733 if ( $this->bufferIter
=== null ) {
1734 return false; // some failure?
1736 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1741 * Get the given list portion (page)
1743 * @param string $container Resolved container name
1744 * @param string $dir Resolved path relative to container
1745 * @param string $after null
1747 * @param array $params
1748 * @return Traversable|array
1750 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1754 * Iterator for listing directories
1756 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1758 * @see Iterator::current()
1759 * @return string|bool String (relative path) or false
1761 public function current() {
1762 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1765 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1766 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1771 * Iterator for listing regular files
1773 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1775 * @see Iterator::current()
1776 * @return string|bool String (relative path) or false
1778 public function current() {
1779 list( $path, $stat ) = current( $this->bufferIter
);
1780 $relPath = substr( $path, $this->suffixStart
);
1781 if ( is_array( $stat ) ) {
1782 $storageDir = rtrim( $this->params
['dir'], '/' );
1783 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1789 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1790 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );