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
26 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
28 * StatusValue messages should avoid mentioning the Swift account name.
29 * Likewise, error suppression should be used to avoid path disclosure.
31 * @ingroup FileBackend
34 class SwiftFileBackend
extends FileBackendStore
{
35 /** @var MultiHttpClient */
37 /** @var int TTL in seconds */
39 /** @var string Authentication base URL (without version) */
40 protected $swiftAuthUrl;
41 /** @var string Override of storage base URL */
42 protected $swiftStorageUrl;
43 /** @var string Swift user (account:user) to authenticate as */
45 /** @var string Secret key for user */
47 /** @var string Shared secret value for making temp URLs */
48 protected $swiftTempUrlKey;
49 /** @var string S3 access key (RADOS Gateway) */
50 protected $rgwS3AccessKey;
51 /** @var string S3 authentication key (RADOS Gateway) */
52 protected $rgwS3SecretKey;
53 /** @var array Additional users (account:user) to open read permissions for */
55 /** @var array Additional users (account:user) to open write permissions for */
56 protected $writeUsers;
61 /** @var ProcessCacheLRU Container stat cache */
62 protected $containerStatCache;
66 /** @var int UNIX timestamp */
67 protected $authSessionTimestamp = 0;
68 /** @var int UNIX timestamp */
69 protected $authErrorTimestamp = null;
71 /** @var bool Whether the server is an Ceph RGW */
72 protected $isRGW = false;
75 * @see FileBackendStore::__construct()
76 * @param array $config Params include:
77 * - swiftAuthUrl : Swift authentication server URL
78 * - swiftUser : Swift user used by MediaWiki (account:username)
79 * - swiftKey : Swift authentication key for the above user
80 * - swiftAuthTTL : Swift authentication TTL (seconds)
81 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
82 * Do not set this until it has been set in the backend.
83 * - swiftStorageUrl : Swift storage URL (overrides that of the authentication response).
84 * This is useful to set if a TLS proxy is in use.
85 * - shardViaHashLevels : Map of container names to sharding config with:
86 * - base : base of hash characters, 16 or 36
87 * - levels : the number of hash levels (and digits)
88 * - repeat : hash subdirectories are prefixed with all the
89 * parent hash directory names (e.g. "a/ab/abc")
90 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
91 * If those are not available, then the main cache will be used.
92 * This is probably insecure in shared hosting environments.
93 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
94 * Do not set this until it has been set in the backend.
95 * This is used for generating expiring pre-authenticated URLs.
96 * Only use this when using rgw and to work around
97 * http://tracker.newdream.net/issues/3454.
98 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
99 * Do not set this until it has been set in the backend.
100 * This is used for generating expiring pre-authenticated URLs.
101 * Only use this when using rgw and to work around
102 * http://tracker.newdream.net/issues/3454.
103 * - readUsers : Swift users that should have read access (account:username)
104 * - writeUsers : Swift users that should have write access (account:username)
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->swiftStorageUrl
= isset( $config['swiftStorageUrl'] )
120 ?
$config['swiftStorageUrl']
122 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
123 ?
$config['shardViaHashLevels']
125 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
126 ?
$config['rgwS3AccessKey']
128 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
129 ?
$config['rgwS3SecretKey']
131 // HTTP helper client
132 $this->http
= new MultiHttpClient( [] );
133 // Cache container information to mask latency
134 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
135 $this->memCache
= $config['wanCache'];
137 // Process cache for container info
138 $this->containerStatCache
= new ProcessCacheLRU( 300 );
139 // Cache auth token information to avoid RTTs
140 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
141 $this->srvCache
= $config['srvCache'];
143 $this->srvCache
= new EmptyBagOStuff();
145 $this->readUsers
= isset( $config['readUsers'] )
146 ?
$config['readUsers']
148 $this->writeUsers
= isset( $config['writeUsers'] )
149 ?
$config['writeUsers']
153 public function getFeatures() {
154 return ( FileBackend
::ATTR_UNICODE_PATHS |
155 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
158 protected function resolveContainerPath( $container, $relStoragePath ) {
159 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
160 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
161 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
162 return null; // too long for Swift
165 return $relStoragePath;
168 public function isPathUsableInternal( $storagePath ) {
169 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
170 if ( $rel === null ) {
171 return false; // invalid
174 return is_array( $this->getContainerStat( $container ) );
178 * Sanitize and filter the custom headers from a $params array.
179 * Only allows certain "standard" Content- and X-Content- headers.
181 * @param array $params
182 * @return array Sanitized value of 'headers' field in $params
184 protected function sanitizeHdrs( array $params ) {
185 return isset( $params['headers'] )
186 ?
$this->getCustomHeaders( $params['headers'] )
191 * @param array $rawHeaders
192 * @return array Custom non-metadata HTTP headers
194 protected function getCustomHeaders( array $rawHeaders ) {
197 // Normalize casing, and strip out illegal headers
198 foreach ( $rawHeaders as $name => $value ) {
199 $name = strtolower( $name );
200 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
201 continue; // blacklisted
202 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
203 $headers[$name] = $value; // allowed
204 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
205 $headers[$name] = $value; // allowed
208 // By default, Swift has annoyingly low maximum header value limits
209 if ( isset( $headers['content-disposition'] ) ) {
211 // @note: assume FileBackend::makeContentDisposition() already used
212 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
213 $part = trim( $part );
214 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
215 if ( strlen( $new ) <= 255 ) {
218 break; // too long; sigh
221 $headers['content-disposition'] = $disposition;
228 * @param array $rawHeaders
229 * @return array Custom metadata headers
231 protected function getMetadataHeaders( array $rawHeaders ) {
233 foreach ( $rawHeaders as $name => $value ) {
234 $name = strtolower( $name );
235 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
236 $headers[$name] = $value;
244 * @param array $rawHeaders
245 * @return array Custom metadata headers with prefix removed
247 protected function getMetadata( array $rawHeaders ) {
249 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
250 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
256 protected function doCreateInternal( array $params ) {
257 $status = $this->newStatus();
259 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
260 if ( $dstRel === null ) {
261 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
266 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
267 $contentType = isset( $params['headers']['content-type'] )
268 ?
$params['headers']['content-type']
269 : $this->getContentType( $params['dst'], $params['content'], null );
273 'url' => [ $dstCont, $dstRel ],
275 'content-length' => strlen( $params['content'] ),
276 'etag' => md5( $params['content'] ),
277 'content-type' => $contentType,
278 'x-object-meta-sha1base36' => $sha1Hash
279 ] +
$this->sanitizeHdrs( $params ),
280 'body' => $params['content']
283 $method = __METHOD__
;
284 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
285 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
286 if ( $rcode === 201 ) {
288 } elseif ( $rcode === 412 ) {
289 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
291 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
295 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
296 if ( !empty( $params['async'] ) ) { // deferred
297 $status->value
= $opHandle;
298 } else { // actually write the object in Swift
299 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
305 protected function doStoreInternal( array $params ) {
306 $status = $this->newStatus();
308 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
309 if ( $dstRel === null ) {
310 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
315 MediaWiki\
suppressWarnings();
316 $sha1Hash = sha1_file( $params['src'] );
317 MediaWiki\restoreWarnings
();
318 if ( $sha1Hash === false ) { // source doesn't exist?
319 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
323 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
324 $contentType = isset( $params['headers']['content-type'] )
325 ?
$params['headers']['content-type']
326 : $this->getContentType( $params['dst'], null, $params['src'] );
328 $handle = fopen( $params['src'], 'rb' );
329 if ( $handle === false ) { // source doesn't exist?
330 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
337 'url' => [ $dstCont, $dstRel ],
339 'content-length' => filesize( $params['src'] ),
340 'etag' => md5_file( $params['src'] ),
341 'content-type' => $contentType,
342 'x-object-meta-sha1base36' => $sha1Hash
343 ] +
$this->sanitizeHdrs( $params ),
344 'body' => $handle // resource
347 $method = __METHOD__
;
348 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
349 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
350 if ( $rcode === 201 ) {
352 } elseif ( $rcode === 412 ) {
353 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
355 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
359 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
360 $opHandle->resourcesToClose
[] = $handle;
362 if ( !empty( $params['async'] ) ) { // deferred
363 $status->value
= $opHandle;
364 } else { // actually write the object in Swift
365 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
371 protected function doCopyInternal( array $params ) {
372 $status = $this->newStatus();
374 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
375 if ( $srcRel === null ) {
376 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
381 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
382 if ( $dstRel === null ) {
383 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
390 'url' => [ $dstCont, $dstRel ],
392 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
393 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
394 ] +
$this->sanitizeHdrs( $params ), // extra headers merged into object
397 $method = __METHOD__
;
398 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
399 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
400 if ( $rcode === 201 ) {
402 } elseif ( $rcode === 404 ) {
403 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
405 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
409 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
410 if ( !empty( $params['async'] ) ) { // deferred
411 $status->value
= $opHandle;
412 } else { // actually write the object in Swift
413 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
419 protected function doMoveInternal( array $params ) {
420 $status = $this->newStatus();
422 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
423 if ( $srcRel === null ) {
424 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
429 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
430 if ( $dstRel === null ) {
431 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
439 'url' => [ $dstCont, $dstRel ],
441 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
442 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
443 ] +
$this->sanitizeHdrs( $params ) // extra headers merged into object
446 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
448 'method' => 'DELETE',
449 'url' => [ $srcCont, $srcRel ],
454 $method = __METHOD__
;
455 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
456 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
457 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
459 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
461 } elseif ( $rcode === 404 ) {
462 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
464 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
468 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
469 if ( !empty( $params['async'] ) ) { // deferred
470 $status->value
= $opHandle;
471 } else { // actually move the object in Swift
472 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
478 protected function doDeleteInternal( array $params ) {
479 $status = $this->newStatus();
481 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
482 if ( $srcRel === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
489 'method' => 'DELETE',
490 'url' => [ $srcCont, $srcRel ],
494 $method = __METHOD__
;
495 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
496 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
497 if ( $rcode === 204 ) {
499 } elseif ( $rcode === 404 ) {
500 if ( empty( $params['ignoreMissingSource'] ) ) {
501 $status->fatal( 'backend-fail-delete', $params['src'] );
504 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
508 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
509 if ( !empty( $params['async'] ) ) { // deferred
510 $status->value
= $opHandle;
511 } else { // actually delete the object in Swift
512 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
518 protected function doDescribeInternal( array $params ) {
519 $status = $this->newStatus();
521 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
522 if ( $srcRel === null ) {
523 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
528 // Fetch the old object headers/metadata...this should be in stat cache by now
529 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
530 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
531 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
534 $status->fatal( 'backend-fail-describe', $params['src'] );
539 // POST clears prior headers, so we need to merge the changes in to the old ones
541 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
542 $metaHdrs["x-object-meta-$name"] = $value;
544 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
548 'url' => [ $srcCont, $srcRel ],
549 'headers' => $metaHdrs +
$customHdrs
552 $method = __METHOD__
;
553 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
554 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
555 if ( $rcode === 202 ) {
557 } elseif ( $rcode === 404 ) {
558 $status->fatal( 'backend-fail-describe', $params['src'] );
560 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
564 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
565 if ( !empty( $params['async'] ) ) { // deferred
566 $status->value
= $opHandle;
567 } else { // actually change the object in Swift
568 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
574 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
575 $status = $this->newStatus();
577 // (a) Check if container already exists
578 $stat = $this->getContainerStat( $fullCont );
579 if ( is_array( $stat ) ) {
580 return $status; // already there
581 } elseif ( $stat === null ) {
582 $status->fatal( 'backend-fail-internal', $this->name
);
583 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
588 // (b) Create container as needed with proper ACLs
589 if ( $stat === false ) {
590 $params['op'] = 'prepare';
591 $status->merge( $this->createContainer( $fullCont, $params ) );
597 protected function doSecureInternal( $fullCont, $dir, array $params ) {
598 $status = $this->newStatus();
599 if ( empty( $params['noAccess'] ) ) {
600 return $status; // nothing to do
603 $stat = $this->getContainerStat( $fullCont );
604 if ( is_array( $stat ) ) {
605 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
] );
606 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
607 // Make container private to end-users...
608 $status->merge( $this->setContainerAccess(
613 } elseif ( $stat === false ) {
614 $status->fatal( 'backend-fail-usable', $params['dir'] );
616 $status->fatal( 'backend-fail-internal', $this->name
);
617 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
623 protected function doPublishInternal( $fullCont, $dir, array $params ) {
624 $status = $this->newStatus();
626 $stat = $this->getContainerStat( $fullCont );
627 if ( is_array( $stat ) ) {
628 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
629 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
631 // Make container public to end-users...
632 $status->merge( $this->setContainerAccess(
637 } elseif ( $stat === false ) {
638 $status->fatal( 'backend-fail-usable', $params['dir'] );
640 $status->fatal( 'backend-fail-internal', $this->name
);
641 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
647 protected function doCleanInternal( $fullCont, $dir, array $params ) {
648 $status = $this->newStatus();
650 // Only containers themselves can be removed, all else is virtual
652 return $status; // nothing to do
655 // (a) Check the container
656 $stat = $this->getContainerStat( $fullCont, true );
657 if ( $stat === false ) {
658 return $status; // ok, nothing to do
659 } elseif ( !is_array( $stat ) ) {
660 $status->fatal( 'backend-fail-internal', $this->name
);
661 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
666 // (b) Delete the container if empty
667 if ( $stat['count'] == 0 ) {
668 $params['op'] = 'clean';
669 $status->merge( $this->deleteContainer( $fullCont, $params ) );
675 protected function doGetFileStat( array $params ) {
676 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
677 unset( $params['src'] );
678 $stats = $this->doGetFileStatMulti( $params );
680 return reset( $stats );
684 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
685 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
686 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
689 * @param int $format Output format (TS_* constant)
691 * @throws FileBackendError
693 protected function convertSwiftDate( $ts, $format = TS_MW
) {
695 $timestamp = new MWTimestamp( $ts );
697 return $timestamp->getTimestamp( $format );
698 } catch ( Exception
$e ) {
699 throw new FileBackendError( $e->getMessage() );
704 * Fill in any missing object metadata and save it to Swift
706 * @param array $objHdrs Object response headers
707 * @param string $path Storage path to object
708 * @return array New headers
710 protected function addMissingMetadata( array $objHdrs, $path ) {
711 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
712 return $objHdrs; // nothing to do
715 /** @noinspection PhpUnusedLocalVariableInspection */
716 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
717 $this->logger
->error( __METHOD__
. ": $path was not stored with SHA-1 metadata." );
719 $objHdrs['x-object-meta-sha1base36'] = false;
721 $auth = $this->getAuthentication();
723 return $objHdrs; // failed
726 // Find prior custom HTTP headers
727 $postHeaders = $this->getCustomHeaders( $objHdrs );
728 // Find prior metadata headers
729 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
731 $status = $this->newStatus();
732 /** @noinspection PhpUnusedLocalVariableInspection */
733 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
734 if ( $status->isOK() ) {
735 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
737 $hash = $tmpFile->getSha1Base36();
738 if ( $hash !== false ) {
739 $objHdrs['x-object-meta-sha1base36'] = $hash;
740 // Merge new SHA1 header into the old ones
741 $postHeaders['x-object-meta-sha1base36'] = $hash;
742 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
743 list( $rcode ) = $this->http
->run( [
745 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
746 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
748 if ( $rcode >= 200 && $rcode <= 299 ) {
749 $this->deleteFileCache( $path );
751 return $objHdrs; // success
757 $this->logger
->error( __METHOD__
. ": unable to set SHA-1 metadata for $path" );
759 return $objHdrs; // failed
762 protected function doGetFileContentsMulti( array $params ) {
765 $auth = $this->getAuthentication();
767 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
768 // Blindly create tmp files and stream to them, catching any exception if the file does
769 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
770 $reqs = []; // (path => op)
772 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
773 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
774 if ( $srcRel === null ||
!$auth ) {
775 $contents[$path] = false;
778 // Create a new temporary memory file...
779 $handle = fopen( 'php://temp', 'wb' );
783 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
784 'headers' => $this->authTokenHeaders( $auth )
785 +
$this->headersFromParams( $params ),
789 $contents[$path] = false;
792 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
793 $reqs = $this->http
->runMulti( $reqs, $opts );
794 foreach ( $reqs as $path => $op ) {
795 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
796 if ( $rcode >= 200 && $rcode <= 299 ) {
797 rewind( $op['stream'] ); // start from the beginning
798 $contents[$path] = stream_get_contents( $op['stream'] );
799 } elseif ( $rcode === 404 ) {
800 $contents[$path] = false;
802 $this->onError( null, __METHOD__
,
803 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
805 fclose( $op['stream'] ); // close open handle
811 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
812 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
813 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
814 if ( $status->isOK() ) {
815 return ( count( $status->value
) ) > 0;
818 return null; // error
822 * @see FileBackendStore::getDirectoryListInternal()
823 * @param string $fullCont
825 * @param array $params
826 * @return SwiftFileBackendDirList
828 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
829 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
833 * @see FileBackendStore::getFileListInternal()
834 * @param string $fullCont
836 * @param array $params
837 * @return SwiftFileBackendFileList
839 public function getFileListInternal( $fullCont, $dir, array $params ) {
840 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
844 * Do not call this function outside of SwiftFileBackendFileList
846 * @param string $fullCont Resolved container name
847 * @param string $dir Resolved storage directory with no trailing slash
848 * @param string|null &$after Resolved container relative path to list items after
849 * @param int $limit Max number of items to list
850 * @param array $params Parameters for getDirectoryList()
851 * @return array List of container relative resolved paths of directories directly under $dir
852 * @throws FileBackendError
854 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
856 if ( $after === INF
) {
857 return $dirs; // nothing more
860 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
862 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
863 // Non-recursive: only list dirs right under $dir
864 if ( !empty( $params['topOnly'] ) ) {
865 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
866 if ( !$status->isOK() ) {
867 throw new FileBackendError( "Iterator page I/O error." );
869 $objects = $status->value
;
870 foreach ( $objects as $object ) { // files and directories
871 if ( substr( $object, -1 ) === '/' ) {
872 $dirs[] = $object; // directories end in '/'
876 // Recursive: list all dirs under $dir and its subdirs
877 $getParentDir = function ( $path ) {
878 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
881 // Get directory from last item of prior page
882 $lastDir = $getParentDir( $after ); // must be first page
883 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
885 if ( !$status->isOK() ) {
886 throw new FileBackendError( "Iterator page I/O error." );
889 $objects = $status->value
;
891 foreach ( $objects as $object ) { // files
892 $objectDir = $getParentDir( $object ); // directory of object
894 if ( $objectDir !== false && $objectDir !== $dir ) {
895 // Swift stores paths in UTF-8, using binary sorting.
896 // See function "create_container_table" in common/db.py.
897 // If a directory is not "greater" than the last one,
898 // then it was already listed by the calling iterator.
899 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
901 do { // add dir and all its parent dirs
902 $dirs[] = "{$pDir}/";
903 $pDir = $getParentDir( $pDir );
904 } while ( $pDir !== false // sanity
905 && strcmp( $pDir, $lastDir ) > 0 // not done already
906 && strlen( $pDir ) > strlen( $dir ) // within $dir
909 $lastDir = $objectDir;
913 // Page on the unfiltered directory listing (what is returned may be filtered)
914 if ( count( $objects ) < $limit ) {
915 $after = INF
; // avoid a second RTT
917 $after = end( $objects ); // update last item
924 * Do not call this function outside of SwiftFileBackendFileList
926 * @param string $fullCont Resolved container name
927 * @param string $dir Resolved storage directory with no trailing slash
928 * @param string|null &$after Resolved container relative path of file to list items after
929 * @param int $limit Max number of items to list
930 * @param array $params Parameters for getDirectoryList()
931 * @return array List of resolved container relative paths of files under $dir
932 * @throws FileBackendError
934 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
935 $files = []; // list of (path, stat array or null) entries
936 if ( $after === INF
) {
937 return $files; // nothing more
940 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
942 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
943 // $objects will contain a list of unfiltered names or CF_Object items
944 // Non-recursive: only list files right under $dir
945 if ( !empty( $params['topOnly'] ) ) {
946 if ( !empty( $params['adviseStat'] ) ) {
947 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
949 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
952 // Recursive: list all files under $dir and its subdirs
953 if ( !empty( $params['adviseStat'] ) ) {
954 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
956 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
960 // Reformat this list into a list of (name, stat array or null) entries
961 if ( !$status->isOK() ) {
962 throw new FileBackendError( "Iterator page I/O error." );
965 $objects = $status->value
;
966 $files = $this->buildFileObjectListing( $params, $dir, $objects );
968 // Page on the unfiltered object listing (what is returned may be filtered)
969 if ( count( $objects ) < $limit ) {
970 $after = INF
; // avoid a second RTT
972 $after = end( $objects ); // update last item
973 $after = is_object( $after ) ?
$after->name
: $after;
980 * Build a list of file objects, filtering out any directories
981 * and extracting any stat info if provided in $objects (for CF_Objects)
983 * @param array $params Parameters for getDirectoryList()
984 * @param string $dir Resolved container directory path
985 * @param array $objects List of CF_Object items or object names
986 * @return array List of (names,stat array or null) entries
988 private function buildFileObjectListing( array $params, $dir, array $objects ) {
990 foreach ( $objects as $object ) {
991 if ( is_object( $object ) ) {
992 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
993 continue; // virtual directory entry; ignore
996 // Convert various random Swift dates to TS_MW
997 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
998 'size' => (int)$object->bytes
,
1000 // Note: manifiest ETags are not an MD5 of the file
1001 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1002 'latest' => false // eventually consistent
1004 $names[] = [ $object->name
, $stat ];
1005 } elseif ( substr( $object, -1 ) !== '/' ) {
1006 // Omit directories, which end in '/' in listings
1007 $names[] = [ $object, null ];
1015 * Do not call this function outside of SwiftFileBackendFileList
1017 * @param string $path Storage path
1018 * @param array $val Stat value
1020 public function loadListingStatInternal( $path, array $val ) {
1021 $this->cheapCache
->set( $path, 'stat', $val );
1024 protected function doGetFileXAttributes( array $params ) {
1025 $stat = $this->getFileStat( $params );
1027 if ( !isset( $stat['xattr'] ) ) {
1028 // Stat entries filled by file listings don't include metadata/headers
1029 $this->clearCache( [ $params['src'] ] );
1030 $stat = $this->getFileStat( $params );
1033 return $stat['xattr'];
1039 protected function doGetFileSha1base36( array $params ) {
1040 $stat = $this->getFileStat( $params );
1042 if ( !isset( $stat['sha1'] ) ) {
1043 // Stat entries filled by file listings don't include SHA1
1044 $this->clearCache( [ $params['src'] ] );
1045 $stat = $this->getFileStat( $params );
1048 return $stat['sha1'];
1054 protected function doStreamFile( array $params ) {
1055 $status = $this->newStatus();
1057 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1059 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1060 if ( $srcRel === null ) {
1061 StreamFile
::send404Message( $params['src'], $flags );
1062 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1067 $auth = $this->getAuthentication();
1068 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1069 StreamFile
::send404Message( $params['src'], $flags );
1070 $status->fatal( 'backend-fail-stream', $params['src'] );
1075 // If "headers" is set, we only want to send them if the file is there.
1076 // Do not bother checking if the file exists if headers are not set though.
1077 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1078 StreamFile
::send404Message( $params['src'], $flags );
1079 $status->fatal( 'backend-fail-stream', $params['src'] );
1084 // Send the requested additional headers
1085 foreach ( $params['headers'] as $header ) {
1086 header( $header ); // aways send
1089 if ( empty( $params['allowOB'] ) ) {
1090 // Cancel output buffering and gzipping if set
1091 call_user_func( $this->obResetFunc
);
1094 $handle = fopen( 'php://output', 'wb' );
1095 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1097 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1098 'headers' => $this->authTokenHeaders( $auth )
1099 +
$this->headersFromParams( $params ) +
$params['options'],
1100 'stream' => $handle,
1101 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1104 if ( $rcode >= 200 && $rcode <= 299 ) {
1106 } elseif ( $rcode === 404 ) {
1107 $status->fatal( 'backend-fail-stream', $params['src'] );
1108 // Per T43113, nasty things can happen if bad cache entries get
1109 // stuck in cache. It's also possible that this error can come up
1110 // with simple race conditions. Clear out the stat cache to be safe.
1111 $this->clearCache( [ $params['src'] ] );
1112 $this->deleteFileCache( $params['src'] );
1114 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1120 protected function doGetLocalCopyMulti( array $params ) {
1121 /** @var TempFSFile[] $tmpFiles */
1124 $auth = $this->getAuthentication();
1126 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1127 // Blindly create tmp files and stream to them, catching any exception if the file does
1128 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1129 $reqs = []; // (path => op)
1131 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1132 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1133 if ( $srcRel === null ||
!$auth ) {
1134 $tmpFiles[$path] = null;
1137 // Get source file extension
1138 $ext = FileBackend
::extensionFromPath( $path );
1139 // Create a new temporary file...
1140 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext, $this->tmpDirectory
);
1142 $handle = fopen( $tmpFile->getPath(), 'wb' );
1146 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1147 'headers' => $this->authTokenHeaders( $auth )
1148 +
$this->headersFromParams( $params ),
1149 'stream' => $handle,
1155 $tmpFiles[$path] = $tmpFile;
1158 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1159 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1160 $reqs = $this->http
->runMulti( $reqs, $opts );
1161 foreach ( $reqs as $path => $op ) {
1162 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1163 fclose( $op['stream'] ); // close open handle
1164 if ( $rcode >= 200 && $rcode <= 299 ) {
1165 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1166 // Double check that the disk is not full/broken
1167 if ( $size != $rhdrs['content-length'] ) {
1168 $tmpFiles[$path] = null;
1169 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1170 $this->onError( null, __METHOD__
,
1171 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1173 // Set the file stat process cache in passing
1174 $stat = $this->getStatFromHeaders( $rhdrs );
1175 $stat['latest'] = $isLatest;
1176 $this->cheapCache
->set( $path, 'stat', $stat );
1177 } elseif ( $rcode === 404 ) {
1178 $tmpFiles[$path] = false;
1180 $tmpFiles[$path] = null;
1181 $this->onError( null, __METHOD__
,
1182 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1189 public function getFileHttpUrl( array $params ) {
1190 if ( $this->swiftTempUrlKey
!= '' ||
1191 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1193 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1194 if ( $srcRel === null ) {
1195 return null; // invalid path
1198 $auth = $this->getAuthentication();
1203 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1204 $expires = time() +
$ttl;
1206 if ( $this->swiftTempUrlKey
!= '' ) {
1207 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1208 // Swift wants the signature based on the unencoded object name
1209 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1210 $signature = hash_hmac( 'sha1',
1211 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1212 $this->swiftTempUrlKey
1215 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1216 } else { // give S3 API URL for rgw
1217 // Path for signature starts with the bucket
1218 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1219 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1220 // Calculate the hash
1221 $signature = base64_encode( hash_hmac(
1223 "GET\n\n\n{$expires}\n{$spath}",
1224 $this->rgwS3SecretKey
,
1227 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1228 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1229 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1230 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1233 'Signature' => $signature,
1234 'Expires' => $expires,
1235 'AWSAccessKeyId' => $this->rgwS3AccessKey
1243 protected function directoriesAreVirtual() {
1248 * Get headers to send to Swift when reading a file based
1249 * on a FileBackend params array, e.g. that of getLocalCopy().
1250 * $params is currently only checked for a 'latest' flag.
1252 * @param array $params
1255 protected function headersFromParams( array $params ) {
1257 if ( !empty( $params['latest'] ) ) {
1258 $hdrs['x-newest'] = 'true';
1265 * @param FileBackendStoreOpHandle[] $fileOpHandles
1267 * @return StatusValue[]
1269 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1270 /** @var StatusValue[] $statuses */
1273 $auth = $this->getAuthentication();
1275 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1276 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1282 // Split the HTTP requests into stages that can be done concurrently
1283 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1284 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1285 /** @var SwiftFileOpHandle $fileOpHandle */
1286 $reqs = $fileOpHandle->httpOp
;
1287 // Convert the 'url' parameter to an actual URL using $auth
1288 foreach ( $reqs as $stage => &$req ) {
1289 list( $container, $relPath ) = $req['url'];
1290 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1291 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : [];
1292 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1293 $httpReqsByStage[$stage][$index] = $req;
1295 $statuses[$index] = $this->newStatus();
1298 // Run all requests for the first stage, then the next, and so on
1299 $reqCount = count( $httpReqsByStage );
1300 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1301 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1302 foreach ( $httpReqs as $index => $httpReq ) {
1303 // Run the callback for each request of this operation
1304 $callback = $fileOpHandles[$index]->callback
;
1305 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1306 // On failure, abort all remaining requests for this operation
1307 // (e.g. abort the DELETE request if the COPY request fails for a move)
1308 if ( !$statuses[$index]->isOK() ) {
1309 $stages = count( $fileOpHandles[$index]->httpOp
);
1310 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1311 unset( $httpReqsByStage[$s][$index] );
1321 * Set read/write permissions for a Swift container.
1323 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1325 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1326 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1328 * @param string $container Resolved Swift container
1329 * @param array $readUsers List of the possible criteria for a request to have
1330 * access to read a container. Each item is one of the following formats:
1331 * - account:user : Grants access if the request is by the given user
1332 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1333 * matches the expression and the request is not for a listing.
1334 * Setting this to '*' effectively makes a container public.
1335 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1336 * matches the expression and the request is for a listing.
1337 * @param array $writeUsers A list of the possible criteria for a request to have
1338 * access to write to a container. Each item is of the following format:
1339 * - account:user : Grants access if the request is by the given user
1340 * @return StatusValue
1342 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1343 $status = $this->newStatus();
1344 $auth = $this->getAuthentication();
1347 $status->fatal( 'backend-fail-connect', $this->name
);
1352 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1354 'url' => $this->storageUrl( $auth, $container ),
1355 'headers' => $this->authTokenHeaders( $auth ) +
[
1356 'x-container-read' => implode( ',', $readUsers ),
1357 'x-container-write' => implode( ',', $writeUsers )
1361 if ( $rcode != 204 && $rcode !== 202 ) {
1362 $status->fatal( 'backend-fail-internal', $this->name
);
1363 $this->logger
->error( __METHOD__
. ': unexpected rcode value (' . $rcode . ')' );
1370 * Get a Swift container stat array, possibly from process cache.
1371 * Use $reCache if the file count or byte count is needed.
1373 * @param string $container Container name
1374 * @param bool $bypassCache Bypass all caches and load from Swift
1375 * @return array|bool|null False on 404, null on failure
1377 protected function getContainerStat( $container, $bypassCache = false ) {
1378 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1380 if ( $bypassCache ) { // purge cache
1381 $this->containerStatCache
->clear( $container );
1382 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1383 $this->primeContainerCache( [ $container ] ); // check persistent cache
1385 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1386 $auth = $this->getAuthentication();
1391 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1393 'url' => $this->storageUrl( $auth, $container ),
1394 'headers' => $this->authTokenHeaders( $auth )
1397 if ( $rcode === 204 ) {
1399 'count' => $rhdrs['x-container-object-count'],
1400 'bytes' => $rhdrs['x-container-bytes-used']
1402 if ( $bypassCache ) {
1405 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1406 $this->setContainerCache( $container, $stat ); // update persistent cache
1408 } elseif ( $rcode === 404 ) {
1411 $this->onError( null, __METHOD__
,
1412 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1418 return $this->containerStatCache
->get( $container, 'stat' );
1422 * Create a Swift container
1424 * @param string $container Container name
1425 * @param array $params
1426 * @return StatusValue
1428 protected function createContainer( $container, array $params ) {
1429 $status = $this->newStatus();
1431 $auth = $this->getAuthentication();
1433 $status->fatal( 'backend-fail-connect', $this->name
);
1438 // @see SwiftFileBackend::setContainerAccess()
1439 if ( empty( $params['noAccess'] ) ) {
1440 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] ); // public
1442 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
] ); // private
1445 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] ); // sanity
1447 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1449 'url' => $this->storageUrl( $auth, $container ),
1450 'headers' => $this->authTokenHeaders( $auth ) +
[
1451 'x-container-read' => implode( ',', $readUsers ),
1452 'x-container-write' => implode( ',', $writeUsers )
1456 if ( $rcode === 201 ) { // new
1458 } elseif ( $rcode === 202 ) { // already there
1459 // this shouldn't really happen, but is OK
1461 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1468 * Delete a Swift container
1470 * @param string $container Container name
1471 * @param array $params
1472 * @return StatusValue
1474 protected function deleteContainer( $container, array $params ) {
1475 $status = $this->newStatus();
1477 $auth = $this->getAuthentication();
1479 $status->fatal( 'backend-fail-connect', $this->name
);
1484 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1485 'method' => 'DELETE',
1486 'url' => $this->storageUrl( $auth, $container ),
1487 'headers' => $this->authTokenHeaders( $auth )
1490 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1491 $this->containerStatCache
->clear( $container ); // purge
1492 } elseif ( $rcode === 404 ) { // not there
1493 // this shouldn't really happen, but is OK
1494 } elseif ( $rcode === 409 ) { // not empty
1495 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1497 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1504 * Get a list of objects under a container.
1505 * Either just the names or a list of stdClass objects with details can be returned.
1507 * @param string $fullCont
1508 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1510 * @param string|null $after
1511 * @param string|null $prefix
1512 * @param string|null $delim
1513 * @return StatusValue With the list as value
1515 private function objectListing(
1516 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1518 $status = $this->newStatus();
1520 $auth = $this->getAuthentication();
1522 $status->fatal( 'backend-fail-connect', $this->name
);
1527 $query = [ 'limit' => $limit ];
1528 if ( $type === 'info' ) {
1529 $query['format'] = 'json';
1531 if ( $after !== null ) {
1532 $query['marker'] = $after;
1534 if ( $prefix !== null ) {
1535 $query['prefix'] = $prefix;
1537 if ( $delim !== null ) {
1538 $query['delimiter'] = $delim;
1541 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1543 'url' => $this->storageUrl( $auth, $fullCont ),
1545 'headers' => $this->authTokenHeaders( $auth )
1548 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1549 if ( $rcode === 200 ) { // good
1550 if ( $type === 'info' ) {
1551 $status->value
= FormatJson
::decode( trim( $rbody ) );
1553 $status->value
= explode( "\n", trim( $rbody ) );
1555 } elseif ( $rcode === 204 ) {
1556 $status->value
= []; // empty container
1557 } elseif ( $rcode === 404 ) {
1558 $status->value
= []; // no container
1560 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1566 protected function doPrimeContainerCache( array $containerInfo ) {
1567 foreach ( $containerInfo as $container => $info ) {
1568 $this->containerStatCache
->set( $container, 'stat', $info );
1572 protected function doGetFileStatMulti( array $params ) {
1575 $auth = $this->getAuthentication();
1578 foreach ( $params['srcs'] as $path ) {
1579 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1580 if ( $srcRel === null ) {
1581 $stats[$path] = false;
1582 continue; // invalid storage path
1583 } elseif ( !$auth ) {
1584 $stats[$path] = null;
1588 // (a) Check the container
1589 $cstat = $this->getContainerStat( $srcCont );
1590 if ( $cstat === false ) {
1591 $stats[$path] = false;
1592 continue; // ok, nothing to do
1593 } elseif ( !is_array( $cstat ) ) {
1594 $stats[$path] = null;
1600 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1601 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1605 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1606 $reqs = $this->http
->runMulti( $reqs, $opts );
1608 foreach ( $params['srcs'] as $path ) {
1609 if ( array_key_exists( $path, $stats ) ) {
1610 continue; // some sort of failure above
1612 // (b) Check the file
1613 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1614 if ( $rcode === 200 ||
$rcode === 204 ) {
1615 // Update the object if it is missing some headers
1616 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1617 // Load the stat array from the headers
1618 $stat = $this->getStatFromHeaders( $rhdrs );
1619 if ( $this->isRGW
) {
1620 $stat['latest'] = true; // strong consistency
1622 } elseif ( $rcode === 404 ) {
1626 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1628 $stats[$path] = $stat;
1635 * @param array $rhdrs
1638 protected function getStatFromHeaders( array $rhdrs ) {
1639 // Fetch all of the custom metadata headers
1640 $metadata = $this->getMetadata( $rhdrs );
1641 // Fetch all of the custom raw HTTP headers
1642 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1645 // Convert various random Swift dates to TS_MW
1646 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1647 // Empty objects actually return no content-length header in Ceph
1648 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1649 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1650 // Note: manifiest ETags are not an MD5 of the file
1651 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1652 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1657 * @return array|null Credential map
1659 protected function getAuthentication() {
1660 if ( $this->authErrorTimestamp
!== null ) {
1661 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1662 return null; // failed last attempt; don't bother
1663 } else { // actually retry this time
1664 $this->authErrorTimestamp
= null;
1667 // Session keys expire after a while, so we renew them periodically
1668 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1669 // Authenticate with proxy and get a session key...
1670 if ( !$this->authCreds ||
$reAuth ) {
1671 $this->authSessionTimestamp
= 0;
1672 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1673 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1674 // Try to use the credential cache
1675 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1676 $this->authCreds
= $creds;
1677 // Skew the timestamp for worst case to avoid using stale credentials
1678 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1679 } else { // cache miss
1680 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1682 'url' => "{$this->swiftAuthUrl}/v1.0",
1684 'x-auth-user' => $this->swiftUser
,
1685 'x-auth-key' => $this->swiftKey
1689 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1690 $this->authCreds
= [
1691 'auth_token' => $rhdrs['x-auth-token'],
1692 'storage_url' => ( $this->swiftStorageUrl
!== null )
1693 ?
$this->swiftStorageUrl
1694 : $rhdrs['x-storage-url']
1697 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1698 $this->authSessionTimestamp
= time();
1699 } elseif ( $rcode === 401 ) {
1700 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1701 $this->authErrorTimestamp
= time();
1705 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1706 $this->authErrorTimestamp
= time();
1711 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1712 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1713 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1717 return $this->authCreds
;
1721 * @param array $creds From getAuthentication()
1722 * @param string $container
1723 * @param string $object
1726 protected function storageUrl( array $creds, $container = null, $object = null ) {
1727 $parts = [ $creds['storage_url'] ];
1728 if ( strlen( $container ) ) {
1729 $parts[] = rawurlencode( $container );
1731 if ( strlen( $object ) ) {
1732 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1735 return implode( '/', $parts );
1739 * @param array $creds From getAuthentication()
1742 protected function authTokenHeaders( array $creds ) {
1743 return [ 'x-auth-token' => $creds['auth_token'] ];
1747 * Get the cache key for a container
1749 * @param string $username
1752 private function getCredsCacheKey( $username ) {
1753 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1757 * Log an unexpected exception for this backend.
1758 * This also sets the StatusValue object to have a fatal error.
1760 * @param StatusValue|null $status
1761 * @param string $func
1762 * @param array $params
1763 * @param string $err Error string
1764 * @param int $code HTTP status
1765 * @param string $desc HTTP StatusValue description
1767 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1768 if ( $status instanceof StatusValue
) {
1769 $status->fatal( 'backend-fail-internal', $this->name
);
1771 if ( $code == 401 ) { // possibly a stale token
1772 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1774 $this->logger
->error(
1775 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1776 ( $err ?
": $err" : "" )
1782 * @see FileBackendStoreOpHandle
1784 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1785 /** @var array List of Requests for MultiHttpClient */
1791 * @param SwiftFileBackend $backend
1792 * @param Closure $callback Function that takes (HTTP request array, status)
1793 * @param array $httpOp MultiHttpClient op
1795 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1796 $this->backend
= $backend;
1797 $this->callback
= $callback;
1798 $this->httpOp
= $httpOp;
1803 * SwiftFileBackend helper class to page through listings.
1804 * Swift also has a listing limit of 10,000 objects for sanity.
1805 * Do not use this class from places outside SwiftFileBackend.
1807 * @ingroup FileBackend
1809 abstract class SwiftFileBackendList
implements Iterator
{
1810 /** @var array List of path or (path,stat array) entries */
1811 protected $bufferIter = [];
1813 /** @var string List items *after* this path */
1814 protected $bufferAfter = null;
1820 protected $params = [];
1822 /** @var SwiftFileBackend */
1825 /** @var string Container name */
1826 protected $container;
1828 /** @var string Storage directory */
1832 protected $suffixStart;
1834 const PAGE_SIZE
= 9000; // file listing buffer size
1837 * @param SwiftFileBackend $backend
1838 * @param string $fullCont Resolved container name
1839 * @param string $dir Resolved directory relative to container
1840 * @param array $params
1842 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1843 $this->backend
= $backend;
1844 $this->container
= $fullCont;
1846 if ( substr( $this->dir
, -1 ) === '/' ) {
1847 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1849 if ( $this->dir
== '' ) { // whole container
1850 $this->suffixStart
= 0;
1851 } else { // dir within container
1852 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1854 $this->params
= $params;
1858 * @see Iterator::key()
1861 public function key() {
1866 * @see Iterator::next()
1868 public function next() {
1869 // Advance to the next file in the page
1870 next( $this->bufferIter
);
1872 // Check if there are no files left in this page and
1873 // advance to the next page if this page was not empty.
1874 if ( !$this->valid() && count( $this->bufferIter
) ) {
1875 $this->bufferIter
= $this->pageFromList(
1876 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1877 ); // updates $this->bufferAfter
1882 * @see Iterator::rewind()
1884 public function rewind() {
1886 $this->bufferAfter
= null;
1887 $this->bufferIter
= $this->pageFromList(
1888 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1889 ); // updates $this->bufferAfter
1893 * @see Iterator::valid()
1896 public function valid() {
1897 if ( $this->bufferIter
=== null ) {
1898 return false; // some failure?
1900 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1905 * Get the given list portion (page)
1907 * @param string $container Resolved container name
1908 * @param string $dir Resolved path relative to container
1909 * @param string &$after
1911 * @param array $params
1912 * @return Traversable|array
1914 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1918 * Iterator for listing directories
1920 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1922 * @see Iterator::current()
1923 * @return string|bool String (relative path) or false
1925 public function current() {
1926 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1929 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1930 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1935 * Iterator for listing regular files
1937 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1939 * @see Iterator::current()
1940 * @return string|bool String (relative path) or false
1942 public function current() {
1943 list( $path, $stat ) = current( $this->bufferIter
);
1944 $relPath = substr( $path, $this->suffixStart
);
1945 if ( is_array( $stat ) ) {
1946 $storageDir = rtrim( $this->params
['dir'], '/' );
1947 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1953 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1954 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );