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 * StatusValue 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;
75 /** @var bool Whether the server is an Ceph RGW */
76 protected $isRGW = false;
79 * @see FileBackendStore::__construct()
80 * Additional $config params include:
81 * - swiftAuthUrl : Swift authentication server URL
82 * - swiftUser : Swift user used by MediaWiki (account:username)
83 * - swiftKey : Swift authentication key for the above user
84 * - swiftAuthTTL : Swift authentication TTL (seconds)
85 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
86 * Do not set this until it has been set in the backend.
87 * - shardViaHashLevels : Map of container names to sharding config with:
88 * - base : base of hash characters, 16 or 36
89 * - levels : the number of hash levels (and digits)
90 * - repeat : hash subdirectories are prefixed with all the
91 * parent hash directory names (e.g. "a/ab/abc")
92 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
93 * If those are not available, then the main cache will be used.
94 * This is probably insecure in shared hosting environments.
95 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
96 * Do not set this until it has been set in the backend.
97 * This is used for generating expiring pre-authenticated URLs.
98 * Only use this when using rgw and to work around
99 * http://tracker.newdream.net/issues/3454.
100 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
101 * Do not set this until it has been set in the backend.
102 * This is used for generating expiring pre-authenticated URLs.
103 * Only use this when using rgw and to work around
104 * http://tracker.newdream.net/issues/3454.
106 public function __construct( array $config ) {
107 parent
::__construct( $config );
109 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
110 $this->swiftUser
= $config['swiftUser'];
111 $this->swiftKey
= $config['swiftKey'];
113 $this->authTTL
= isset( $config['swiftAuthTTL'] )
114 ?
$config['swiftAuthTTL']
115 : 15 * 60; // some sane number
116 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
117 ?
$config['swiftTempUrlKey']
119 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
120 ?
$config['shardViaHashLevels']
122 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
123 ?
$config['rgwS3AccessKey']
125 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
126 ?
$config['rgwS3SecretKey']
128 // HTTP helper client
129 $this->http
= new MultiHttpClient( [] );
130 // Cache container information to mask latency
131 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
132 $this->memCache
= $config['wanCache'];
134 // Process cache for container info
135 $this->containerStatCache
= new ProcessCacheLRU( 300 );
136 // Cache auth token information to avoid RTTs
137 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
138 $this->srvCache
= $config['srvCache'];
140 $this->srvCache
= new EmptyBagOStuff();
144 public function getFeatures() {
145 return ( FileBackend
::ATTR_UNICODE_PATHS |
146 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
149 protected function resolveContainerPath( $container, $relStoragePath ) {
150 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
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 * Only allows certain "standard" Content- and X-Content- headers.
172 * @param array $params
173 * @return array Sanitized value of 'headers' field in $params
175 protected function sanitizeHdrs( array $params ) {
176 return isset( $params['headers'] )
177 ?
$this->getCustomHeaders( $params['headers'] )
183 * @param array $rawHeaders
184 * @return array Custom non-metadata HTTP headers
186 protected function getCustomHeaders( array $rawHeaders ) {
189 // Normalize casing, and strip out illegal headers
190 foreach ( $rawHeaders as $name => $value ) {
191 $name = strtolower( $name );
192 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
193 continue; // blacklisted
194 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
195 $headers[$name] = $value; // allowed
196 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
197 $headers[$name] = $value; // allowed
200 // By default, Swift has annoyingly low maximum header value limits
201 if ( isset( $headers['content-disposition'] ) ) {
203 // @note: assume FileBackend::makeContentDisposition() already used
204 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
205 $part = trim( $part );
206 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
207 if ( strlen( $new ) <= 255 ) {
210 break; // too long; sigh
213 $headers['content-disposition'] = $disposition;
220 * @param array $rawHeaders
221 * @return array Custom metadata headers
223 protected function getMetadataHeaders( array $rawHeaders ) {
225 foreach ( $rawHeaders as $name => $value ) {
226 $name = strtolower( $name );
227 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
228 $headers[$name] = $value;
236 * @param array $rawHeaders
237 * @return array Custom metadata headers with prefix removed
239 protected function getMetadata( array $rawHeaders ) {
241 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
242 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
248 protected function doCreateInternal( array $params ) {
249 $status = $this->newStatus();
251 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
252 if ( $dstRel === null ) {
253 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
258 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
259 $contentType = isset( $params['headers']['content-type'] )
260 ?
$params['headers']['content-type']
261 : $this->getContentType( $params['dst'], $params['content'], null );
265 'url' => [ $dstCont, $dstRel ],
267 'content-length' => strlen( $params['content'] ),
268 'etag' => md5( $params['content'] ),
269 'content-type' => $contentType,
270 'x-object-meta-sha1base36' => $sha1Hash
271 ] +
$this->sanitizeHdrs( $params ),
272 'body' => $params['content']
275 $method = __METHOD__
;
276 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
277 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
278 if ( $rcode === 201 ) {
280 } elseif ( $rcode === 412 ) {
281 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
283 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
287 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
288 if ( !empty( $params['async'] ) ) { // deferred
289 $status->value
= $opHandle;
290 } else { // actually write the object in Swift
291 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
297 protected function doStoreInternal( array $params ) {
298 $status = $this->newStatus();
300 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
301 if ( $dstRel === null ) {
302 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
307 MediaWiki\
suppressWarnings();
308 $sha1Hash = sha1_file( $params['src'] );
309 MediaWiki\restoreWarnings
();
310 if ( $sha1Hash === false ) { // source doesn't exist?
311 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
315 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
316 $contentType = isset( $params['headers']['content-type'] )
317 ?
$params['headers']['content-type']
318 : $this->getContentType( $params['dst'], null, $params['src'] );
320 $handle = fopen( $params['src'], 'rb' );
321 if ( $handle === false ) { // source doesn't exist?
322 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
329 'url' => [ $dstCont, $dstRel ],
331 'content-length' => filesize( $params['src'] ),
332 'etag' => md5_file( $params['src'] ),
333 'content-type' => $contentType,
334 'x-object-meta-sha1base36' => $sha1Hash
335 ] +
$this->sanitizeHdrs( $params ),
336 'body' => $handle // resource
339 $method = __METHOD__
;
340 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
341 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
342 if ( $rcode === 201 ) {
344 } elseif ( $rcode === 412 ) {
345 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
347 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
351 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
352 if ( !empty( $params['async'] ) ) { // deferred
353 $status->value
= $opHandle;
354 } else { // actually write the object in Swift
355 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
361 protected function doCopyInternal( array $params ) {
362 $status = $this->newStatus();
364 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
365 if ( $srcRel === null ) {
366 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
371 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
372 if ( $dstRel === null ) {
373 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
380 'url' => [ $dstCont, $dstRel ],
382 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
383 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
384 ] +
$this->sanitizeHdrs( $params ), // extra headers merged into object
387 $method = __METHOD__
;
388 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
389 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
390 if ( $rcode === 201 ) {
392 } elseif ( $rcode === 404 ) {
393 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
395 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
399 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
400 if ( !empty( $params['async'] ) ) { // deferred
401 $status->value
= $opHandle;
402 } else { // actually write the object in Swift
403 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
409 protected function doMoveInternal( array $params ) {
410 $status = $this->newStatus();
412 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
413 if ( $srcRel === null ) {
414 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
419 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
420 if ( $dstRel === null ) {
421 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
429 'url' => [ $dstCont, $dstRel ],
431 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
432 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
433 ] +
$this->sanitizeHdrs( $params ) // extra headers merged into object
436 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
438 'method' => 'DELETE',
439 'url' => [ $srcCont, $srcRel ],
444 $method = __METHOD__
;
445 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
446 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
447 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
449 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
451 } elseif ( $rcode === 404 ) {
452 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
454 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
458 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
459 if ( !empty( $params['async'] ) ) { // deferred
460 $status->value
= $opHandle;
461 } else { // actually move the object in Swift
462 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
468 protected function doDeleteInternal( array $params ) {
469 $status = $this->newStatus();
471 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
472 if ( $srcRel === null ) {
473 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
479 'method' => 'DELETE',
480 'url' => [ $srcCont, $srcRel ],
484 $method = __METHOD__
;
485 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
486 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
487 if ( $rcode === 204 ) {
489 } elseif ( $rcode === 404 ) {
490 if ( empty( $params['ignoreMissingSource'] ) ) {
491 $status->fatal( 'backend-fail-delete', $params['src'] );
494 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
498 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
499 if ( !empty( $params['async'] ) ) { // deferred
500 $status->value
= $opHandle;
501 } else { // actually delete the object in Swift
502 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
508 protected function doDescribeInternal( array $params ) {
509 $status = $this->newStatus();
511 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
512 if ( $srcRel === null ) {
513 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
518 // Fetch the old object headers/metadata...this should be in stat cache by now
519 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
520 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
521 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
524 $status->fatal( 'backend-fail-describe', $params['src'] );
529 // POST clears prior headers, so we need to merge the changes in to the old ones
531 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
532 $metaHdrs["x-object-meta-$name"] = $value;
534 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
538 'url' => [ $srcCont, $srcRel ],
539 'headers' => $metaHdrs +
$customHdrs
542 $method = __METHOD__
;
543 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
544 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
545 if ( $rcode === 202 ) {
547 } elseif ( $rcode === 404 ) {
548 $status->fatal( 'backend-fail-describe', $params['src'] );
550 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
554 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
555 if ( !empty( $params['async'] ) ) { // deferred
556 $status->value
= $opHandle;
557 } else { // actually change the object in Swift
558 $status->merge( current( $this->doExecuteOpHandlesInternal( [ $opHandle ] ) ) );
564 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
565 $status = $this->newStatus();
567 // (a) Check if container already exists
568 $stat = $this->getContainerStat( $fullCont );
569 if ( is_array( $stat ) ) {
570 return $status; // already there
571 } elseif ( $stat === null ) {
572 $status->fatal( 'backend-fail-internal', $this->name
);
573 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
578 // (b) Create container as needed with proper ACLs
579 if ( $stat === false ) {
580 $params['op'] = 'prepare';
581 $status->merge( $this->createContainer( $fullCont, $params ) );
587 protected function doSecureInternal( $fullCont, $dir, array $params ) {
588 $status = $this->newStatus();
589 if ( empty( $params['noAccess'] ) ) {
590 return $status; // nothing to do
593 $stat = $this->getContainerStat( $fullCont );
594 if ( is_array( $stat ) ) {
595 // Make container private to end-users...
596 $status->merge( $this->setContainerAccess(
598 [ $this->swiftUser
], // read
599 [ $this->swiftUser
] // write
601 } elseif ( $stat === false ) {
602 $status->fatal( 'backend-fail-usable', $params['dir'] );
604 $status->fatal( 'backend-fail-internal', $this->name
);
605 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
611 protected function doPublishInternal( $fullCont, $dir, array $params ) {
612 $status = $this->newStatus();
614 $stat = $this->getContainerStat( $fullCont );
615 if ( is_array( $stat ) ) {
616 // Make container public to end-users...
617 $status->merge( $this->setContainerAccess(
619 [ $this->swiftUser
, '.r:*' ], // read
620 [ $this->swiftUser
] // write
622 } elseif ( $stat === false ) {
623 $status->fatal( 'backend-fail-usable', $params['dir'] );
625 $status->fatal( 'backend-fail-internal', $this->name
);
626 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
632 protected function doCleanInternal( $fullCont, $dir, array $params ) {
633 $status = $this->newStatus();
635 // Only containers themselves can be removed, all else is virtual
637 return $status; // nothing to do
640 // (a) Check the container
641 $stat = $this->getContainerStat( $fullCont, true );
642 if ( $stat === false ) {
643 return $status; // ok, nothing to do
644 } elseif ( !is_array( $stat ) ) {
645 $status->fatal( 'backend-fail-internal', $this->name
);
646 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
651 // (b) Delete the container if empty
652 if ( $stat['count'] == 0 ) {
653 $params['op'] = 'clean';
654 $status->merge( $this->deleteContainer( $fullCont, $params ) );
660 protected function doGetFileStat( array $params ) {
661 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
662 unset( $params['src'] );
663 $stats = $this->doGetFileStatMulti( $params );
665 return reset( $stats );
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 );
682 return $timestamp->getTimestamp( $format );
683 } catch ( Exception
$e ) {
684 throw new FileBackendError( $e->getMessage() );
689 * Fill in any missing object metadata and save it to Swift
691 * @param array $objHdrs Object response headers
692 * @param string $path Storage path to object
693 * @return array New headers
695 protected function addMissingMetadata( array $objHdrs, $path ) {
696 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
697 return $objHdrs; // nothing to do
700 /** @noinspection PhpUnusedLocalVariableInspection */
701 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
702 $this->logger
->error( __METHOD__
. ": $path was not stored with SHA-1 metadata." );
704 $objHdrs['x-object-meta-sha1base36'] = false;
706 $auth = $this->getAuthentication();
708 return $objHdrs; // failed
711 // Find prior custom HTTP headers
712 $postHeaders = $this->getCustomHeaders( $objHdrs );
713 // Find prior metadata headers
714 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
716 $status = $this->newStatus();
717 /** @noinspection PhpUnusedLocalVariableInspection */
718 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
719 if ( $status->isOK() ) {
720 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
722 $hash = $tmpFile->getSha1Base36();
723 if ( $hash !== false ) {
724 $objHdrs['x-object-meta-sha1base36'] = $hash;
725 // Merge new SHA1 header into the old ones
726 $postHeaders['x-object-meta-sha1base36'] = $hash;
727 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
728 list( $rcode ) = $this->http
->run( [
730 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
731 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
733 if ( $rcode >= 200 && $rcode <= 299 ) {
734 $this->deleteFileCache( $path );
736 return $objHdrs; // success
742 $this->logger
->error( __METHOD__
. ": unable to set SHA-1 metadata for $path" );
744 return $objHdrs; // failed
747 protected function doGetFileContentsMulti( array $params ) {
750 $auth = $this->getAuthentication();
752 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
753 // Blindly create tmp files and stream to them, catching any exception if the file does
754 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
755 $reqs = []; // (path => op)
757 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
758 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
759 if ( $srcRel === null ||
!$auth ) {
760 $contents[$path] = false;
763 // Create a new temporary memory file...
764 $handle = fopen( 'php://temp', 'wb' );
768 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
769 'headers' => $this->authTokenHeaders( $auth )
770 +
$this->headersFromParams( $params ),
774 $contents[$path] = false;
777 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
778 $reqs = $this->http
->runMulti( $reqs, $opts );
779 foreach ( $reqs as $path => $op ) {
780 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
781 if ( $rcode >= 200 && $rcode <= 299 ) {
782 rewind( $op['stream'] ); // start from the beginning
783 $contents[$path] = stream_get_contents( $op['stream'] );
784 } elseif ( $rcode === 404 ) {
785 $contents[$path] = false;
787 $this->onError( null, __METHOD__
,
788 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
790 fclose( $op['stream'] ); // close open handle
796 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
797 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
798 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
799 if ( $status->isOK() ) {
800 return ( count( $status->value
) ) > 0;
803 return null; // error
807 * @see FileBackendStore::getDirectoryListInternal()
808 * @param string $fullCont
810 * @param array $params
811 * @return SwiftFileBackendDirList
813 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
814 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
818 * @see FileBackendStore::getFileListInternal()
819 * @param string $fullCont
821 * @param array $params
822 * @return SwiftFileBackendFileList
824 public function getFileListInternal( $fullCont, $dir, array $params ) {
825 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
829 * Do not call this function outside of SwiftFileBackendFileList
831 * @param string $fullCont Resolved container name
832 * @param string $dir Resolved storage directory with no trailing slash
833 * @param string|null $after Resolved container relative path to list items after
834 * @param int $limit Max number of items to list
835 * @param array $params Parameters for getDirectoryList()
836 * @return array List of container relative resolved paths of directories directly under $dir
837 * @throws FileBackendError
839 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
841 if ( $after === INF
) {
842 return $dirs; // nothing more
845 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
847 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
848 // Non-recursive: only list dirs right under $dir
849 if ( !empty( $params['topOnly'] ) ) {
850 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
851 if ( !$status->isOK() ) {
852 throw new FileBackendError( "Iterator page I/O error." );
854 $objects = $status->value
;
855 foreach ( $objects as $object ) { // files and directories
856 if ( substr( $object, -1 ) === '/' ) {
857 $dirs[] = $object; // directories end in '/'
861 // Recursive: list all dirs under $dir and its subdirs
862 $getParentDir = function ( $path ) {
863 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
866 // Get directory from last item of prior page
867 $lastDir = $getParentDir( $after ); // must be first page
868 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
870 if ( !$status->isOK() ) {
871 throw new FileBackendError( "Iterator page I/O error." );
874 $objects = $status->value
;
876 foreach ( $objects as $object ) { // files
877 $objectDir = $getParentDir( $object ); // directory of object
879 if ( $objectDir !== false && $objectDir !== $dir ) {
880 // Swift stores paths in UTF-8, using binary sorting.
881 // See function "create_container_table" in common/db.py.
882 // If a directory is not "greater" than the last one,
883 // then it was already listed by the calling iterator.
884 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
886 do { // add dir and all its parent dirs
887 $dirs[] = "{$pDir}/";
888 $pDir = $getParentDir( $pDir );
889 } while ( $pDir !== false // sanity
890 && strcmp( $pDir, $lastDir ) > 0 // not done already
891 && strlen( $pDir ) > strlen( $dir ) // within $dir
894 $lastDir = $objectDir;
898 // Page on the unfiltered directory listing (what is returned may be filtered)
899 if ( count( $objects ) < $limit ) {
900 $after = INF
; // avoid a second RTT
902 $after = end( $objects ); // update last item
909 * Do not call this function outside of SwiftFileBackendFileList
911 * @param string $fullCont Resolved container name
912 * @param string $dir Resolved storage directory with no trailing slash
913 * @param string|null $after Resolved container relative path of file to list items after
914 * @param int $limit Max number of items to list
915 * @param array $params Parameters for getDirectoryList()
916 * @return array List of resolved container relative paths of files under $dir
917 * @throws FileBackendError
919 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
920 $files = []; // list of (path, stat array or null) entries
921 if ( $after === INF
) {
922 return $files; // nothing more
925 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
927 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
928 // $objects will contain a list of unfiltered names or CF_Object items
929 // Non-recursive: only list files right under $dir
930 if ( !empty( $params['topOnly'] ) ) {
931 if ( !empty( $params['adviseStat'] ) ) {
932 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
934 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
937 // Recursive: list all files under $dir and its subdirs
938 if ( !empty( $params['adviseStat'] ) ) {
939 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
941 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
945 // Reformat this list into a list of (name, stat array or null) entries
946 if ( !$status->isOK() ) {
947 throw new FileBackendError( "Iterator page I/O error." );
950 $objects = $status->value
;
951 $files = $this->buildFileObjectListing( $params, $dir, $objects );
953 // Page on the unfiltered object listing (what is returned may be filtered)
954 if ( count( $objects ) < $limit ) {
955 $after = INF
; // avoid a second RTT
957 $after = end( $objects ); // update last item
958 $after = is_object( $after ) ?
$after->name
: $after;
965 * Build a list of file objects, filtering out any directories
966 * and extracting any stat info if provided in $objects (for CF_Objects)
968 * @param array $params Parameters for getDirectoryList()
969 * @param string $dir Resolved container directory path
970 * @param array $objects List of CF_Object items or object names
971 * @return array List of (names,stat array or null) entries
973 private function buildFileObjectListing( array $params, $dir, array $objects ) {
975 foreach ( $objects as $object ) {
976 if ( is_object( $object ) ) {
977 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
978 continue; // virtual directory entry; ignore
981 // Convert various random Swift dates to TS_MW
982 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
983 'size' => (int)$object->bytes
,
985 // Note: manifiest ETags are not an MD5 of the file
986 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
987 'latest' => false // eventually consistent
989 $names[] = [ $object->name
, $stat ];
990 } elseif ( substr( $object, -1 ) !== '/' ) {
991 // Omit directories, which end in '/' in listings
992 $names[] = [ $object, null ];
1000 * Do not call this function outside of SwiftFileBackendFileList
1002 * @param string $path Storage path
1003 * @param array $val Stat value
1005 public function loadListingStatInternal( $path, array $val ) {
1006 $this->cheapCache
->set( $path, 'stat', $val );
1009 protected function doGetFileXAttributes( array $params ) {
1010 $stat = $this->getFileStat( $params );
1012 if ( !isset( $stat['xattr'] ) ) {
1013 // Stat entries filled by file listings don't include metadata/headers
1014 $this->clearCache( [ $params['src'] ] );
1015 $stat = $this->getFileStat( $params );
1018 return $stat['xattr'];
1024 protected function doGetFileSha1base36( array $params ) {
1025 $stat = $this->getFileStat( $params );
1027 if ( !isset( $stat['sha1'] ) ) {
1028 // Stat entries filled by file listings don't include SHA1
1029 $this->clearCache( [ $params['src'] ] );
1030 $stat = $this->getFileStat( $params );
1033 return $stat['sha1'];
1039 protected function doStreamFile( array $params ) {
1040 $status = $this->newStatus();
1042 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1044 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1045 if ( $srcRel === null ) {
1046 StreamFile
::send404Message( $params['src'], $flags );
1047 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1052 $auth = $this->getAuthentication();
1053 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1054 StreamFile
::send404Message( $params['src'], $flags );
1055 $status->fatal( 'backend-fail-stream', $params['src'] );
1060 // If "headers" is set, we only want to send them if the file is there.
1061 // Do not bother checking if the file exists if headers are not set though.
1062 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1063 StreamFile
::send404Message( $params['src'], $flags );
1064 $status->fatal( 'backend-fail-stream', $params['src'] );
1069 // Send the requested additional headers
1070 foreach ( $params['headers'] as $header ) {
1071 header( $header ); // aways send
1074 if ( empty( $params['allowOB'] ) ) {
1075 // Cancel output buffering and gzipping if set
1076 call_user_func( $this->obResetFunc
);
1079 $handle = fopen( 'php://output', 'wb' );
1080 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1082 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1083 'headers' => $this->authTokenHeaders( $auth )
1084 +
$this->headersFromParams( $params ) +
$params['options'],
1085 'stream' => $handle,
1086 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1089 if ( $rcode >= 200 && $rcode <= 299 ) {
1091 } elseif ( $rcode === 404 ) {
1092 $status->fatal( 'backend-fail-stream', $params['src'] );
1093 // Per bug 41113, nasty things can happen if bad cache entries get
1094 // stuck in cache. It's also possible that this error can come up
1095 // with simple race conditions. Clear out the stat cache to be safe.
1096 $this->clearCache( [ $params['src'] ] );
1097 $this->deleteFileCache( $params['src'] );
1099 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1105 protected function doGetLocalCopyMulti( array $params ) {
1106 /** @var TempFSFile[] $tmpFiles */
1109 $auth = $this->getAuthentication();
1111 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1112 // Blindly create tmp files and stream to them, catching any exception if the file does
1113 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1114 $reqs = []; // (path => op)
1116 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1117 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1118 if ( $srcRel === null ||
!$auth ) {
1119 $tmpFiles[$path] = null;
1122 // Get source file extension
1123 $ext = FileBackend
::extensionFromPath( $path );
1124 // Create a new temporary file...
1125 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext, $this->tmpDirectory
);
1127 $handle = fopen( $tmpFile->getPath(), 'wb' );
1131 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1132 'headers' => $this->authTokenHeaders( $auth )
1133 +
$this->headersFromParams( $params ),
1134 'stream' => $handle,
1140 $tmpFiles[$path] = $tmpFile;
1143 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1144 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1145 $reqs = $this->http
->runMulti( $reqs, $opts );
1146 foreach ( $reqs as $path => $op ) {
1147 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1148 fclose( $op['stream'] ); // close open handle
1149 if ( $rcode >= 200 && $rcode <= 299 ) {
1150 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1151 // Double check that the disk is not full/broken
1152 if ( $size != $rhdrs['content-length'] ) {
1153 $tmpFiles[$path] = null;
1154 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1155 $this->onError( null, __METHOD__
,
1156 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1158 // Set the file stat process cache in passing
1159 $stat = $this->getStatFromHeaders( $rhdrs );
1160 $stat['latest'] = $isLatest;
1161 $this->cheapCache
->set( $path, 'stat', $stat );
1162 } elseif ( $rcode === 404 ) {
1163 $tmpFiles[$path] = false;
1165 $tmpFiles[$path] = null;
1166 $this->onError( null, __METHOD__
,
1167 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1174 public function getFileHttpUrl( array $params ) {
1175 if ( $this->swiftTempUrlKey
!= '' ||
1176 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1178 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1179 if ( $srcRel === null ) {
1180 return null; // invalid path
1183 $auth = $this->getAuthentication();
1188 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1189 $expires = time() +
$ttl;
1191 if ( $this->swiftTempUrlKey
!= '' ) {
1192 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1193 // Swift wants the signature based on the unencoded object name
1194 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1195 $signature = hash_hmac( 'sha1',
1196 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1197 $this->swiftTempUrlKey
1200 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1201 } else { // give S3 API URL for rgw
1202 // Path for signature starts with the bucket
1203 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1204 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1205 // Calculate the hash
1206 $signature = base64_encode( hash_hmac(
1208 "GET\n\n\n{$expires}\n{$spath}",
1209 $this->rgwS3SecretKey
,
1212 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1213 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1214 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1215 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1218 'Signature' => $signature,
1219 'Expires' => $expires,
1220 'AWSAccessKeyId' => $this->rgwS3AccessKey
1228 protected function directoriesAreVirtual() {
1233 * Get headers to send to Swift when reading a file based
1234 * on a FileBackend params array, e.g. that of getLocalCopy().
1235 * $params is currently only checked for a 'latest' flag.
1237 * @param array $params
1240 protected function headersFromParams( array $params ) {
1242 if ( !empty( $params['latest'] ) ) {
1243 $hdrs['x-newest'] = 'true';
1250 * @param FileBackendStoreOpHandle[] $fileOpHandles
1252 * @return StatusValue[]
1254 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1255 /** @var $statuses StatusValue[] */
1258 $auth = $this->getAuthentication();
1260 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1261 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1267 // Split the HTTP requests into stages that can be done concurrently
1268 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1269 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1270 /** @var SwiftFileOpHandle $fileOpHandle */
1271 $reqs = $fileOpHandle->httpOp
;
1272 // Convert the 'url' parameter to an actual URL using $auth
1273 foreach ( $reqs as $stage => &$req ) {
1274 list( $container, $relPath ) = $req['url'];
1275 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1276 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : [];
1277 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1278 $httpReqsByStage[$stage][$index] = $req;
1280 $statuses[$index] = $this->newStatus();
1283 // Run all requests for the first stage, then the next, and so on
1284 $reqCount = count( $httpReqsByStage );
1285 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1286 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1287 foreach ( $httpReqs as $index => $httpReq ) {
1288 // Run the callback for each request of this operation
1289 $callback = $fileOpHandles[$index]->callback
;
1290 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1291 // On failure, abort all remaining requests for this operation
1292 // (e.g. abort the DELETE request if the COPY request fails for a move)
1293 if ( !$statuses[$index]->isOK() ) {
1294 $stages = count( $fileOpHandles[$index]->httpOp
);
1295 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1296 unset( $httpReqsByStage[$s][$index] );
1306 * Set read/write permissions for a Swift container.
1308 * @see http://swift.openstack.org/misc.html#acls
1310 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1311 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1313 * @param string $container Resolved Swift container
1314 * @param array $readGrps List of the possible criteria for a request to have
1315 * access to read a container. Each item is one of the following formats:
1316 * - account:user : Grants access if the request is by the given user
1317 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1318 * matches the expression and the request is not for a listing.
1319 * Setting this to '*' effectively makes a container public.
1320 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1321 * matches the expression and the request is for a listing.
1322 * @param array $writeGrps A list of the possible criteria for a request to have
1323 * access to write to a container. Each item is of the following format:
1324 * - account:user : Grants access if the request is by the given user
1325 * @return StatusValue
1327 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1328 $status = $this->newStatus();
1329 $auth = $this->getAuthentication();
1332 $status->fatal( 'backend-fail-connect', $this->name
);
1337 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1339 'url' => $this->storageUrl( $auth, $container ),
1340 'headers' => $this->authTokenHeaders( $auth ) +
[
1341 'x-container-read' => implode( ',', $readGrps ),
1342 'x-container-write' => implode( ',', $writeGrps )
1346 if ( $rcode != 204 && $rcode !== 202 ) {
1347 $status->fatal( 'backend-fail-internal', $this->name
);
1348 $this->logger
->error( __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1355 * Get a Swift container stat array, possibly from process cache.
1356 * Use $reCache if the file count or byte count is needed.
1358 * @param string $container Container name
1359 * @param bool $bypassCache Bypass all caches and load from Swift
1360 * @return array|bool|null False on 404, null on failure
1362 protected function getContainerStat( $container, $bypassCache = false ) {
1363 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1365 if ( $bypassCache ) { // purge cache
1366 $this->containerStatCache
->clear( $container );
1367 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1368 $this->primeContainerCache( [ $container ] ); // check persistent cache
1370 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1371 $auth = $this->getAuthentication();
1376 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1378 'url' => $this->storageUrl( $auth, $container ),
1379 'headers' => $this->authTokenHeaders( $auth )
1382 if ( $rcode === 204 ) {
1384 'count' => $rhdrs['x-container-object-count'],
1385 'bytes' => $rhdrs['x-container-bytes-used']
1387 if ( $bypassCache ) {
1390 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1391 $this->setContainerCache( $container, $stat ); // update persistent cache
1393 } elseif ( $rcode === 404 ) {
1396 $this->onError( null, __METHOD__
,
1397 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1403 return $this->containerStatCache
->get( $container, 'stat' );
1407 * Create a Swift container
1409 * @param string $container Container name
1410 * @param array $params
1411 * @return StatusValue
1413 protected function createContainer( $container, array $params ) {
1414 $status = $this->newStatus();
1416 $auth = $this->getAuthentication();
1418 $status->fatal( 'backend-fail-connect', $this->name
);
1423 // @see SwiftFileBackend::setContainerAccess()
1424 if ( empty( $params['noAccess'] ) ) {
1425 $readGrps = [ '.r:*', $this->swiftUser
]; // public
1427 $readGrps = [ $this->swiftUser
]; // private
1429 $writeGrps = [ $this->swiftUser
]; // sanity
1431 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1433 'url' => $this->storageUrl( $auth, $container ),
1434 'headers' => $this->authTokenHeaders( $auth ) +
[
1435 'x-container-read' => implode( ',', $readGrps ),
1436 'x-container-write' => implode( ',', $writeGrps )
1440 if ( $rcode === 201 ) { // new
1442 } elseif ( $rcode === 202 ) { // already there
1443 // this shouldn't really happen, but is OK
1445 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1452 * Delete a Swift container
1454 * @param string $container Container name
1455 * @param array $params
1456 * @return StatusValue
1458 protected function deleteContainer( $container, array $params ) {
1459 $status = $this->newStatus();
1461 $auth = $this->getAuthentication();
1463 $status->fatal( 'backend-fail-connect', $this->name
);
1468 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1469 'method' => 'DELETE',
1470 'url' => $this->storageUrl( $auth, $container ),
1471 'headers' => $this->authTokenHeaders( $auth )
1474 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1475 $this->containerStatCache
->clear( $container ); // purge
1476 } elseif ( $rcode === 404 ) { // not there
1477 // this shouldn't really happen, but is OK
1478 } elseif ( $rcode === 409 ) { // not empty
1479 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1481 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1488 * Get a list of objects under a container.
1489 * Either just the names or a list of stdClass objects with details can be returned.
1491 * @param string $fullCont
1492 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1494 * @param string|null $after
1495 * @param string|null $prefix
1496 * @param string|null $delim
1497 * @return StatusValue With the list as value
1499 private function objectListing(
1500 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1502 $status = $this->newStatus();
1504 $auth = $this->getAuthentication();
1506 $status->fatal( 'backend-fail-connect', $this->name
);
1511 $query = [ 'limit' => $limit ];
1512 if ( $type === 'info' ) {
1513 $query['format'] = 'json';
1515 if ( $after !== null ) {
1516 $query['marker'] = $after;
1518 if ( $prefix !== null ) {
1519 $query['prefix'] = $prefix;
1521 if ( $delim !== null ) {
1522 $query['delimiter'] = $delim;
1525 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1527 'url' => $this->storageUrl( $auth, $fullCont ),
1529 'headers' => $this->authTokenHeaders( $auth )
1532 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1533 if ( $rcode === 200 ) { // good
1534 if ( $type === 'info' ) {
1535 $status->value
= FormatJson
::decode( trim( $rbody ) );
1537 $status->value
= explode( "\n", trim( $rbody ) );
1539 } elseif ( $rcode === 204 ) {
1540 $status->value
= []; // empty container
1541 } elseif ( $rcode === 404 ) {
1542 $status->value
= []; // no container
1544 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1550 protected function doPrimeContainerCache( array $containerInfo ) {
1551 foreach ( $containerInfo as $container => $info ) {
1552 $this->containerStatCache
->set( $container, 'stat', $info );
1556 protected function doGetFileStatMulti( array $params ) {
1559 $auth = $this->getAuthentication();
1562 foreach ( $params['srcs'] as $path ) {
1563 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1564 if ( $srcRel === null ) {
1565 $stats[$path] = false;
1566 continue; // invalid storage path
1567 } elseif ( !$auth ) {
1568 $stats[$path] = null;
1572 // (a) Check the container
1573 $cstat = $this->getContainerStat( $srcCont );
1574 if ( $cstat === false ) {
1575 $stats[$path] = false;
1576 continue; // ok, nothing to do
1577 } elseif ( !is_array( $cstat ) ) {
1578 $stats[$path] = null;
1584 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1585 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1589 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1590 $reqs = $this->http
->runMulti( $reqs, $opts );
1592 foreach ( $params['srcs'] as $path ) {
1593 if ( array_key_exists( $path, $stats ) ) {
1594 continue; // some sort of failure above
1596 // (b) Check the file
1597 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1598 if ( $rcode === 200 ||
$rcode === 204 ) {
1599 // Update the object if it is missing some headers
1600 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1601 // Load the stat array from the headers
1602 $stat = $this->getStatFromHeaders( $rhdrs );
1603 if ( $this->isRGW
) {
1604 $stat['latest'] = true; // strong consistency
1606 } elseif ( $rcode === 404 ) {
1610 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1612 $stats[$path] = $stat;
1619 * @param array $rhdrs
1622 protected function getStatFromHeaders( array $rhdrs ) {
1623 // Fetch all of the custom metadata headers
1624 $metadata = $this->getMetadata( $rhdrs );
1625 // Fetch all of the custom raw HTTP headers
1626 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1629 // Convert various random Swift dates to TS_MW
1630 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1631 // Empty objects actually return no content-length header in Ceph
1632 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1633 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1634 // Note: manifiest ETags are not an MD5 of the file
1635 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1636 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1641 * @return array|null Credential map
1643 protected function getAuthentication() {
1644 if ( $this->authErrorTimestamp
!== null ) {
1645 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1646 return null; // failed last attempt; don't bother
1647 } else { // actually retry this time
1648 $this->authErrorTimestamp
= null;
1651 // Session keys expire after a while, so we renew them periodically
1652 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1653 // Authenticate with proxy and get a session key...
1654 if ( !$this->authCreds ||
$reAuth ) {
1655 $this->authSessionTimestamp
= 0;
1656 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1657 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1658 // Try to use the credential cache
1659 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1660 $this->authCreds
= $creds;
1661 // Skew the timestamp for worst case to avoid using stale credentials
1662 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1663 } else { // cache miss
1664 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1666 'url' => "{$this->swiftAuthUrl}/v1.0",
1668 'x-auth-user' => $this->swiftUser
,
1669 'x-auth-key' => $this->swiftKey
1673 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1674 $this->authCreds
= [
1675 'auth_token' => $rhdrs['x-auth-token'],
1676 'storage_url' => $rhdrs['x-storage-url']
1678 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1679 $this->authSessionTimestamp
= time();
1680 } elseif ( $rcode === 401 ) {
1681 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1682 $this->authErrorTimestamp
= time();
1686 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1687 $this->authErrorTimestamp
= time();
1692 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1693 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1694 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1698 return $this->authCreds
;
1702 * @param array $creds From getAuthentication()
1703 * @param string $container
1704 * @param string $object
1707 protected function storageUrl( array $creds, $container = null, $object = null ) {
1708 $parts = [ $creds['storage_url'] ];
1709 if ( strlen( $container ) ) {
1710 $parts[] = rawurlencode( $container );
1712 if ( strlen( $object ) ) {
1713 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1716 return implode( '/', $parts );
1720 * @param array $creds From getAuthentication()
1723 protected function authTokenHeaders( array $creds ) {
1724 return [ 'x-auth-token' => $creds['auth_token'] ];
1728 * Get the cache key for a container
1730 * @param string $username
1733 private function getCredsCacheKey( $username ) {
1734 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1738 * Log an unexpected exception for this backend.
1739 * This also sets the StatusValue object to have a fatal error.
1741 * @param StatusValue|null $status
1742 * @param string $func
1743 * @param array $params
1744 * @param string $err Error string
1745 * @param int $code HTTP status
1746 * @param string $desc HTTP StatusValue description
1748 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1749 if ( $status instanceof StatusValue
) {
1750 $status->fatal( 'backend-fail-internal', $this->name
);
1752 if ( $code == 401 ) { // possibly a stale token
1753 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1755 $this->logger
->error(
1756 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1757 ( $err ?
": $err" : "" )
1763 * @see FileBackendStoreOpHandle
1765 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1766 /** @var array List of Requests for MultiHttpClient */
1772 * @param SwiftFileBackend $backend
1773 * @param Closure $callback Function that takes (HTTP request array, status)
1774 * @param array $httpOp MultiHttpClient op
1776 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1777 $this->backend
= $backend;
1778 $this->callback
= $callback;
1779 $this->httpOp
= $httpOp;
1784 * SwiftFileBackend helper class to page through listings.
1785 * Swift also has a listing limit of 10,000 objects for sanity.
1786 * Do not use this class from places outside SwiftFileBackend.
1788 * @ingroup FileBackend
1790 abstract class SwiftFileBackendList
implements Iterator
{
1791 /** @var array List of path or (path,stat array) entries */
1792 protected $bufferIter = [];
1794 /** @var string List items *after* this path */
1795 protected $bufferAfter = null;
1801 protected $params = [];
1803 /** @var SwiftFileBackend */
1806 /** @var string Container name */
1807 protected $container;
1809 /** @var string Storage directory */
1813 protected $suffixStart;
1815 const PAGE_SIZE
= 9000; // file listing buffer size
1818 * @param SwiftFileBackend $backend
1819 * @param string $fullCont Resolved container name
1820 * @param string $dir Resolved directory relative to container
1821 * @param array $params
1823 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1824 $this->backend
= $backend;
1825 $this->container
= $fullCont;
1827 if ( substr( $this->dir
, -1 ) === '/' ) {
1828 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1830 if ( $this->dir
== '' ) { // whole container
1831 $this->suffixStart
= 0;
1832 } else { // dir within container
1833 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1835 $this->params
= $params;
1839 * @see Iterator::key()
1842 public function key() {
1847 * @see Iterator::next()
1849 public function next() {
1850 // Advance to the next file in the page
1851 next( $this->bufferIter
);
1853 // Check if there are no files left in this page and
1854 // advance to the next page if this page was not empty.
1855 if ( !$this->valid() && count( $this->bufferIter
) ) {
1856 $this->bufferIter
= $this->pageFromList(
1857 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1858 ); // updates $this->bufferAfter
1863 * @see Iterator::rewind()
1865 public function rewind() {
1867 $this->bufferAfter
= null;
1868 $this->bufferIter
= $this->pageFromList(
1869 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1870 ); // updates $this->bufferAfter
1874 * @see Iterator::valid()
1877 public function valid() {
1878 if ( $this->bufferIter
=== null ) {
1879 return false; // some failure?
1881 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1886 * Get the given list portion (page)
1888 * @param string $container Resolved container name
1889 * @param string $dir Resolved path relative to container
1890 * @param string $after
1892 * @param array $params
1893 * @return Traversable|array
1895 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1899 * Iterator for listing directories
1901 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1903 * @see Iterator::current()
1904 * @return string|bool String (relative path) or false
1906 public function current() {
1907 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1910 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1911 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1916 * Iterator for listing regular files
1918 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1920 * @see Iterator::current()
1921 * @return string|bool String (relative path) or false
1923 public function current() {
1924 list( $path, $stat ) = current( $this->bufferIter
);
1925 $relPath = substr( $path, $this->suffixStart
);
1926 if ( is_array( $stat ) ) {
1927 $storageDir = rtrim( $this->params
['dir'], '/' );
1928 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1934 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1935 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );