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, etc.
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( rawurlencode( $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 sanitizeHdrsStrict( array $params ) {
185 if ( !isset( $params['headers'] ) ) {
189 $headers = $this->getCustomHeaders( $params['headers'] );
190 unset( $headers[ 'content-type' ] );
196 * Sanitize and filter the custom headers from a $params array.
197 * Only allows certain "standard" Content- and X-Content- headers.
199 * When POSTing data, libcurl adds Content-Type: application/x-www-form-urlencoded
200 * if Content-Type is not set, which overwrites the stored Content-Type header
201 * in Swift - therefore for POSTing data do not strip the Content-Type header (the
202 * previously-stored header that has been already read back from swift is sent)
204 * @param array $params
205 * @return array Sanitized value of 'headers' field in $params
207 protected function sanitizeHdrs( array $params ) {
208 return isset( $params['headers'] )
209 ?
$this->getCustomHeaders( $params['headers'] )
214 * @param array $rawHeaders
215 * @return array Custom non-metadata HTTP headers
217 protected function getCustomHeaders( array $rawHeaders ) {
220 // Normalize casing, and strip out illegal headers
221 foreach ( $rawHeaders as $name => $value ) {
222 $name = strtolower( $name );
223 if ( preg_match( '/^content-length$/', $name ) ) {
224 continue; // blacklisted
225 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
226 $headers[$name] = $value; // allowed
227 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
228 $headers[$name] = $value; // allowed
231 // By default, Swift has annoyingly low maximum header value limits
232 if ( isset( $headers['content-disposition'] ) ) {
234 // @note: assume FileBackend::makeContentDisposition() already used
235 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
236 $part = trim( $part );
237 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
238 if ( strlen( $new ) <= 255 ) {
241 break; // too long; sigh
244 $headers['content-disposition'] = $disposition;
251 * @param array $rawHeaders
252 * @return array Custom metadata headers
254 protected function getMetadataHeaders( array $rawHeaders ) {
256 foreach ( $rawHeaders as $name => $value ) {
257 $name = strtolower( $name );
258 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
259 $headers[$name] = $value;
267 * @param array $rawHeaders
268 * @return array Custom metadata headers with prefix removed
270 protected function getMetadata( array $rawHeaders ) {
272 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
273 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
279 protected function doCreateInternal( array $params ) {
280 $status = $this->newStatus();
282 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
283 if ( $dstRel === null ) {
284 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
289 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
290 $contentType = isset( $params['headers']['content-type'] )
291 ?
$params['headers']['content-type']
292 : $this->getContentType( $params['dst'], $params['content'], null );
296 'url' => [ $dstCont, $dstRel ],
298 'content-length' => strlen( $params['content'] ),
299 'etag' => md5( $params['content'] ),
300 'content-type' => $contentType,
301 'x-object-meta-sha1base36' => $sha1Hash
302 ] +
$this->sanitizeHdrsStrict( $params ),
303 'body' => $params['content']
306 $method = __METHOD__
;
307 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
308 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
309 if ( $rcode === 201 ) {
311 } elseif ( $rcode === 412 ) {
312 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
314 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
318 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
319 if ( !empty( $params['async'] ) ) { // deferred
320 $status->value
= $opHandle;
321 } else { // actually write the object in Swift
322 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
328 protected function doStoreInternal( array $params ) {
329 $status = $this->newStatus();
331 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
332 if ( $dstRel === null ) {
333 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
338 Wikimedia\
suppressWarnings();
339 $sha1Hash = sha1_file( $params['src'] );
340 Wikimedia\restoreWarnings
();
341 if ( $sha1Hash === false ) { // source doesn't exist?
342 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
346 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
347 $contentType = isset( $params['headers']['content-type'] )
348 ?
$params['headers']['content-type']
349 : $this->getContentType( $params['dst'], null, $params['src'] );
351 $handle = fopen( $params['src'], 'rb' );
352 if ( $handle === false ) { // source doesn't exist?
353 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
360 'url' => [ $dstCont, $dstRel ],
362 'content-length' => filesize( $params['src'] ),
363 'etag' => md5_file( $params['src'] ),
364 'content-type' => $contentType,
365 'x-object-meta-sha1base36' => $sha1Hash
366 ] +
$this->sanitizeHdrsStrict( $params ),
367 'body' => $handle // resource
370 $method = __METHOD__
;
371 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
372 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
373 if ( $rcode === 201 ) {
375 } elseif ( $rcode === 412 ) {
376 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
378 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
382 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
383 $opHandle->resourcesToClose
[] = $handle;
385 if ( !empty( $params['async'] ) ) { // deferred
386 $status->value
= $opHandle;
387 } else { // actually write the object in Swift
388 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
394 protected function doCopyInternal( array $params ) {
395 $status = $this->newStatus();
397 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
398 if ( $srcRel === null ) {
399 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
404 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
405 if ( $dstRel === null ) {
406 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
413 'url' => [ $dstCont, $dstRel ],
415 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
416 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
417 ] +
$this->sanitizeHdrsStrict( $params ), // extra headers merged into object
420 $method = __METHOD__
;
421 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
422 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
423 if ( $rcode === 201 ) {
425 } elseif ( $rcode === 404 ) {
426 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
428 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
432 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
433 if ( !empty( $params['async'] ) ) { // deferred
434 $status->value
= $opHandle;
435 } else { // actually write the object in Swift
436 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
442 protected function doMoveInternal( array $params ) {
443 $status = $this->newStatus();
445 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
446 if ( $srcRel === null ) {
447 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
452 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
453 if ( $dstRel === null ) {
454 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
462 'url' => [ $dstCont, $dstRel ],
464 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
465 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
466 ] +
$this->sanitizeHdrsStrict( $params ) // extra headers merged into object
469 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
471 'method' => 'DELETE',
472 'url' => [ $srcCont, $srcRel ],
477 $method = __METHOD__
;
478 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
479 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
480 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
482 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
484 } elseif ( $rcode === 404 ) {
485 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
487 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
491 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
492 if ( !empty( $params['async'] ) ) { // deferred
493 $status->value
= $opHandle;
494 } else { // actually move the object in Swift
495 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
501 protected function doDeleteInternal( array $params ) {
502 $status = $this->newStatus();
504 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
505 if ( $srcRel === null ) {
506 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
512 'method' => 'DELETE',
513 'url' => [ $srcCont, $srcRel ],
517 $method = __METHOD__
;
518 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
519 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
520 if ( $rcode === 204 ) {
522 } elseif ( $rcode === 404 ) {
523 if ( empty( $params['ignoreMissingSource'] ) ) {
524 $status->fatal( 'backend-fail-delete', $params['src'] );
527 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
531 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
532 if ( !empty( $params['async'] ) ) { // deferred
533 $status->value
= $opHandle;
534 } else { // actually delete the object in Swift
535 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
541 protected function doDescribeInternal( array $params ) {
542 $status = $this->newStatus();
544 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
545 if ( $srcRel === null ) {
546 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
551 // Fetch the old object headers/metadata...this should be in stat cache by now
552 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
553 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
554 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
557 $status->fatal( 'backend-fail-describe', $params['src'] );
562 // POST clears prior headers, so we need to merge the changes in to the old ones
564 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
565 $metaHdrs["x-object-meta-$name"] = $value;
567 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
571 'url' => [ $srcCont, $srcRel ],
572 'headers' => $metaHdrs +
$customHdrs
575 $method = __METHOD__
;
576 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
577 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
578 if ( $rcode === 202 ) {
580 } elseif ( $rcode === 404 ) {
581 $status->fatal( 'backend-fail-describe', $params['src'] );
583 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
587 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
588 if ( !empty( $params['async'] ) ) { // deferred
589 $status->value
= $opHandle;
590 } else { // actually change the object in Swift
591 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
597 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
598 $status = $this->newStatus();
600 // (a) Check if container already exists
601 $stat = $this->getContainerStat( $fullCont );
602 if ( is_array( $stat ) ) {
603 return $status; // already there
604 } elseif ( $stat === null ) {
605 $status->fatal( 'backend-fail-internal', $this->name
);
606 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
611 // (b) Create container as needed with proper ACLs
612 if ( $stat === false ) {
613 $params['op'] = 'prepare';
614 $status->merge( $this->createContainer( $fullCont, $params ) );
620 protected function doSecureInternal( $fullCont, $dir, array $params ) {
621 $status = $this->newStatus();
622 if ( empty( $params['noAccess'] ) ) {
623 return $status; // nothing to do
626 $stat = $this->getContainerStat( $fullCont );
627 if ( is_array( $stat ) ) {
628 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
] );
629 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
630 // Make container private to end-users...
631 $status->merge( $this->setContainerAccess(
636 } elseif ( $stat === false ) {
637 $status->fatal( 'backend-fail-usable', $params['dir'] );
639 $status->fatal( 'backend-fail-internal', $this->name
);
640 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
646 protected function doPublishInternal( $fullCont, $dir, array $params ) {
647 $status = $this->newStatus();
649 $stat = $this->getContainerStat( $fullCont );
650 if ( is_array( $stat ) ) {
651 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
652 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
654 // Make container public to end-users...
655 $status->merge( $this->setContainerAccess(
660 } elseif ( $stat === false ) {
661 $status->fatal( 'backend-fail-usable', $params['dir'] );
663 $status->fatal( 'backend-fail-internal', $this->name
);
664 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
670 protected function doCleanInternal( $fullCont, $dir, array $params ) {
671 $status = $this->newStatus();
673 // Only containers themselves can be removed, all else is virtual
675 return $status; // nothing to do
678 // (a) Check the container
679 $stat = $this->getContainerStat( $fullCont, true );
680 if ( $stat === false ) {
681 return $status; // ok, nothing to do
682 } elseif ( !is_array( $stat ) ) {
683 $status->fatal( 'backend-fail-internal', $this->name
);
684 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
689 // (b) Delete the container if empty
690 if ( $stat['count'] == 0 ) {
691 $params['op'] = 'clean';
692 $status->merge( $this->deleteContainer( $fullCont, $params ) );
698 protected function doGetFileStat( array $params ) {
699 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
700 unset( $params['src'] );
701 $stats = $this->doGetFileStatMulti( $params );
703 return reset( $stats );
707 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
708 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
709 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
712 * @param int $format Output format (TS_* constant)
714 * @throws FileBackendError
716 protected function convertSwiftDate( $ts, $format = TS_MW
) {
718 $timestamp = new MWTimestamp( $ts );
720 return $timestamp->getTimestamp( $format );
721 } catch ( Exception
$e ) {
722 throw new FileBackendError( $e->getMessage() );
727 * Fill in any missing object metadata and save it to Swift
729 * @param array $objHdrs Object response headers
730 * @param string $path Storage path to object
731 * @return array New headers
733 protected function addMissingMetadata( array $objHdrs, $path ) {
734 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
735 return $objHdrs; // nothing to do
738 /** @noinspection PhpUnusedLocalVariableInspection */
739 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
740 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
741 [ 'path' => $path ] );
743 $objHdrs['x-object-meta-sha1base36'] = false;
745 $auth = $this->getAuthentication();
747 return $objHdrs; // failed
750 // Find prior custom HTTP headers
751 $postHeaders = $this->getCustomHeaders( $objHdrs );
752 // Find prior metadata headers
753 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
755 $status = $this->newStatus();
756 /** @noinspection PhpUnusedLocalVariableInspection */
757 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
758 if ( $status->isOK() ) {
759 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
761 $hash = $tmpFile->getSha1Base36();
762 if ( $hash !== false ) {
763 $objHdrs['x-object-meta-sha1base36'] = $hash;
764 // Merge new SHA1 header into the old ones
765 $postHeaders['x-object-meta-sha1base36'] = $hash;
766 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
767 list( $rcode ) = $this->http
->run( [
769 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
770 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
772 if ( $rcode >= 200 && $rcode <= 299 ) {
773 $this->deleteFileCache( $path );
775 return $objHdrs; // success
781 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
782 [ 'path' => $path ] );
784 return $objHdrs; // failed
787 protected function doGetFileContentsMulti( array $params ) {
790 $auth = $this->getAuthentication();
792 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
793 // Blindly create tmp files and stream to them, catching any exception if the file does
794 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
795 $reqs = []; // (path => op)
797 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
798 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
799 if ( $srcRel === null ||
!$auth ) {
800 $contents[$path] = false;
803 // Create a new temporary memory file...
804 $handle = fopen( 'php://temp', 'wb' );
808 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
809 'headers' => $this->authTokenHeaders( $auth )
810 +
$this->headersFromParams( $params ),
814 $contents[$path] = false;
817 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
818 $reqs = $this->http
->runMulti( $reqs, $opts );
819 foreach ( $reqs as $path => $op ) {
820 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
821 if ( $rcode >= 200 && $rcode <= 299 ) {
822 rewind( $op['stream'] ); // start from the beginning
823 $contents[$path] = stream_get_contents( $op['stream'] );
824 } elseif ( $rcode === 404 ) {
825 $contents[$path] = false;
827 $this->onError( null, __METHOD__
,
828 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
830 fclose( $op['stream'] ); // close open handle
836 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
837 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
838 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
839 if ( $status->isOK() ) {
840 return ( count( $status->value
) ) > 0;
843 return null; // error
847 * @see FileBackendStore::getDirectoryListInternal()
848 * @param string $fullCont
850 * @param array $params
851 * @return SwiftFileBackendDirList
853 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
854 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
858 * @see FileBackendStore::getFileListInternal()
859 * @param string $fullCont
861 * @param array $params
862 * @return SwiftFileBackendFileList
864 public function getFileListInternal( $fullCont, $dir, array $params ) {
865 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
869 * Do not call this function outside of SwiftFileBackendFileList
871 * @param string $fullCont Resolved container name
872 * @param string $dir Resolved storage directory with no trailing slash
873 * @param string|null &$after Resolved container relative path to list items after
874 * @param int $limit Max number of items to list
875 * @param array $params Parameters for getDirectoryList()
876 * @return array List of container relative resolved paths of directories directly under $dir
877 * @throws FileBackendError
879 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
881 if ( $after === INF
) {
882 return $dirs; // nothing more
885 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
887 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
888 // Non-recursive: only list dirs right under $dir
889 if ( !empty( $params['topOnly'] ) ) {
890 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
891 if ( !$status->isOK() ) {
892 throw new FileBackendError( "Iterator page I/O error." );
894 $objects = $status->value
;
895 foreach ( $objects as $object ) { // files and directories
896 if ( substr( $object, -1 ) === '/' ) {
897 $dirs[] = $object; // directories end in '/'
901 // Recursive: list all dirs under $dir and its subdirs
902 $getParentDir = function ( $path ) {
903 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
906 // Get directory from last item of prior page
907 $lastDir = $getParentDir( $after ); // must be first page
908 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
910 if ( !$status->isOK() ) {
911 throw new FileBackendError( "Iterator page I/O error." );
914 $objects = $status->value
;
916 foreach ( $objects as $object ) { // files
917 $objectDir = $getParentDir( $object ); // directory of object
919 if ( $objectDir !== false && $objectDir !== $dir ) {
920 // Swift stores paths in UTF-8, using binary sorting.
921 // See function "create_container_table" in common/db.py.
922 // If a directory is not "greater" than the last one,
923 // then it was already listed by the calling iterator.
924 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
926 do { // add dir and all its parent dirs
927 $dirs[] = "{$pDir}/";
928 $pDir = $getParentDir( $pDir );
929 } while ( $pDir !== false // sanity
930 && strcmp( $pDir, $lastDir ) > 0 // not done already
931 && strlen( $pDir ) > strlen( $dir ) // within $dir
934 $lastDir = $objectDir;
938 // Page on the unfiltered directory listing (what is returned may be filtered)
939 if ( count( $objects ) < $limit ) {
940 $after = INF
; // avoid a second RTT
942 $after = end( $objects ); // update last item
949 * Do not call this function outside of SwiftFileBackendFileList
951 * @param string $fullCont Resolved container name
952 * @param string $dir Resolved storage directory with no trailing slash
953 * @param string|null &$after Resolved container relative path of file to list items after
954 * @param int $limit Max number of items to list
955 * @param array $params Parameters for getDirectoryList()
956 * @return array List of resolved container relative paths of files under $dir
957 * @throws FileBackendError
959 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
960 $files = []; // list of (path, stat array or null) entries
961 if ( $after === INF
) {
962 return $files; // nothing more
965 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
967 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
968 // $objects will contain a list of unfiltered names or CF_Object items
969 // Non-recursive: only list files right under $dir
970 if ( !empty( $params['topOnly'] ) ) {
971 if ( !empty( $params['adviseStat'] ) ) {
972 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
974 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
977 // Recursive: list all files under $dir and its subdirs
978 if ( !empty( $params['adviseStat'] ) ) {
979 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
981 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
985 // Reformat this list into a list of (name, stat array or null) entries
986 if ( !$status->isOK() ) {
987 throw new FileBackendError( "Iterator page I/O error." );
990 $objects = $status->value
;
991 $files = $this->buildFileObjectListing( $params, $dir, $objects );
993 // Page on the unfiltered object listing (what is returned may be filtered)
994 if ( count( $objects ) < $limit ) {
995 $after = INF
; // avoid a second RTT
997 $after = end( $objects ); // update last item
998 $after = is_object( $after ) ?
$after->name
: $after;
1005 * Build a list of file objects, filtering out any directories
1006 * and extracting any stat info if provided in $objects (for CF_Objects)
1008 * @param array $params Parameters for getDirectoryList()
1009 * @param string $dir Resolved container directory path
1010 * @param array $objects List of CF_Object items or object names
1011 * @return array List of (names,stat array or null) entries
1013 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1015 foreach ( $objects as $object ) {
1016 if ( is_object( $object ) ) {
1017 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1018 continue; // virtual directory entry; ignore
1021 // Convert various random Swift dates to TS_MW
1022 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1023 'size' => (int)$object->bytes
,
1025 // Note: manifiest ETags are not an MD5 of the file
1026 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1027 'latest' => false // eventually consistent
1029 $names[] = [ $object->name
, $stat ];
1030 } elseif ( substr( $object, -1 ) !== '/' ) {
1031 // Omit directories, which end in '/' in listings
1032 $names[] = [ $object, null ];
1040 * Do not call this function outside of SwiftFileBackendFileList
1042 * @param string $path Storage path
1043 * @param array $val Stat value
1045 public function loadListingStatInternal( $path, array $val ) {
1046 $this->cheapCache
->set( $path, 'stat', $val );
1049 protected function doGetFileXAttributes( array $params ) {
1050 $stat = $this->getFileStat( $params );
1052 if ( !isset( $stat['xattr'] ) ) {
1053 // Stat entries filled by file listings don't include metadata/headers
1054 $this->clearCache( [ $params['src'] ] );
1055 $stat = $this->getFileStat( $params );
1058 return $stat['xattr'];
1064 protected function doGetFileSha1base36( array $params ) {
1065 $stat = $this->getFileStat( $params );
1067 if ( !isset( $stat['sha1'] ) ) {
1068 // Stat entries filled by file listings don't include SHA1
1069 $this->clearCache( [ $params['src'] ] );
1070 $stat = $this->getFileStat( $params );
1073 return $stat['sha1'];
1079 protected function doStreamFile( array $params ) {
1080 $status = $this->newStatus();
1082 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1084 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1085 if ( $srcRel === null ) {
1086 StreamFile
::send404Message( $params['src'], $flags );
1087 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1092 $auth = $this->getAuthentication();
1093 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1094 StreamFile
::send404Message( $params['src'], $flags );
1095 $status->fatal( 'backend-fail-stream', $params['src'] );
1100 // If "headers" is set, we only want to send them if the file is there.
1101 // Do not bother checking if the file exists if headers are not set though.
1102 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1103 StreamFile
::send404Message( $params['src'], $flags );
1104 $status->fatal( 'backend-fail-stream', $params['src'] );
1109 // Send the requested additional headers
1110 foreach ( $params['headers'] as $header ) {
1111 header( $header ); // aways send
1114 if ( empty( $params['allowOB'] ) ) {
1115 // Cancel output buffering and gzipping if set
1116 call_user_func( $this->obResetFunc
);
1119 $handle = fopen( 'php://output', 'wb' );
1120 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1122 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1123 'headers' => $this->authTokenHeaders( $auth )
1124 +
$this->headersFromParams( $params ) +
$params['options'],
1125 'stream' => $handle,
1126 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1129 if ( $rcode >= 200 && $rcode <= 299 ) {
1131 } elseif ( $rcode === 404 ) {
1132 $status->fatal( 'backend-fail-stream', $params['src'] );
1133 // Per T43113, nasty things can happen if bad cache entries get
1134 // stuck in cache. It's also possible that this error can come up
1135 // with simple race conditions. Clear out the stat cache to be safe.
1136 $this->clearCache( [ $params['src'] ] );
1137 $this->deleteFileCache( $params['src'] );
1139 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1145 protected function doGetLocalCopyMulti( array $params ) {
1146 /** @var TempFSFile[] $tmpFiles */
1149 $auth = $this->getAuthentication();
1151 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1152 // Blindly create tmp files and stream to them, catching any exception if the file does
1153 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1154 $reqs = []; // (path => op)
1156 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1157 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1158 if ( $srcRel === null ||
!$auth ) {
1159 $tmpFiles[$path] = null;
1162 // Get source file extension
1163 $ext = FileBackend
::extensionFromPath( $path );
1164 // Create a new temporary file...
1165 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext, $this->tmpDirectory
);
1167 $handle = fopen( $tmpFile->getPath(), 'wb' );
1171 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1172 'headers' => $this->authTokenHeaders( $auth )
1173 +
$this->headersFromParams( $params ),
1174 'stream' => $handle,
1180 $tmpFiles[$path] = $tmpFile;
1183 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1184 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1185 $reqs = $this->http
->runMulti( $reqs, $opts );
1186 foreach ( $reqs as $path => $op ) {
1187 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1188 fclose( $op['stream'] ); // close open handle
1189 if ( $rcode >= 200 && $rcode <= 299 ) {
1190 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1191 // Double check that the disk is not full/broken
1192 if ( $size != $rhdrs['content-length'] ) {
1193 $tmpFiles[$path] = null;
1194 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1195 $this->onError( null, __METHOD__
,
1196 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1198 // Set the file stat process cache in passing
1199 $stat = $this->getStatFromHeaders( $rhdrs );
1200 $stat['latest'] = $isLatest;
1201 $this->cheapCache
->set( $path, 'stat', $stat );
1202 } elseif ( $rcode === 404 ) {
1203 $tmpFiles[$path] = false;
1205 $tmpFiles[$path] = null;
1206 $this->onError( null, __METHOD__
,
1207 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1214 public function getFileHttpUrl( array $params ) {
1215 if ( $this->swiftTempUrlKey
!= '' ||
1216 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1218 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1219 if ( $srcRel === null ) {
1220 return null; // invalid path
1223 $auth = $this->getAuthentication();
1228 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1229 $expires = time() +
$ttl;
1231 if ( $this->swiftTempUrlKey
!= '' ) {
1232 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1233 // Swift wants the signature based on the unencoded object name
1234 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1235 $signature = hash_hmac( 'sha1',
1236 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1237 $this->swiftTempUrlKey
1240 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1241 } else { // give S3 API URL for rgw
1242 // Path for signature starts with the bucket
1243 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1244 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1245 // Calculate the hash
1246 $signature = base64_encode( hash_hmac(
1248 "GET\n\n\n{$expires}\n{$spath}",
1249 $this->rgwS3SecretKey
,
1252 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1253 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1254 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1255 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1258 'Signature' => $signature,
1259 'Expires' => $expires,
1260 'AWSAccessKeyId' => $this->rgwS3AccessKey
1268 protected function directoriesAreVirtual() {
1273 * Get headers to send to Swift when reading a file based
1274 * on a FileBackend params array, e.g. that of getLocalCopy().
1275 * $params is currently only checked for a 'latest' flag.
1277 * @param array $params
1280 protected function headersFromParams( array $params ) {
1282 if ( !empty( $params['latest'] ) ) {
1283 $hdrs['x-newest'] = 'true';
1290 * @param FileBackendStoreOpHandle[] $fileOpHandles
1292 * @return StatusValue[]
1294 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1295 /** @var StatusValue[] $statuses */
1298 $auth = $this->getAuthentication();
1300 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1301 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1307 // Split the HTTP requests into stages that can be done concurrently
1308 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1309 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1310 /** @var SwiftFileOpHandle $fileOpHandle */
1311 $reqs = $fileOpHandle->httpOp
;
1312 // Convert the 'url' parameter to an actual URL using $auth
1313 foreach ( $reqs as $stage => &$req ) {
1314 list( $container, $relPath ) = $req['url'];
1315 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1316 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : [];
1317 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1318 $httpReqsByStage[$stage][$index] = $req;
1320 $statuses[$index] = $this->newStatus();
1323 // Run all requests for the first stage, then the next, and so on
1324 $reqCount = count( $httpReqsByStage );
1325 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1326 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1327 foreach ( $httpReqs as $index => $httpReq ) {
1328 // Run the callback for each request of this operation
1329 $callback = $fileOpHandles[$index]->callback
;
1330 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1331 // On failure, abort all remaining requests for this operation
1332 // (e.g. abort the DELETE request if the COPY request fails for a move)
1333 if ( !$statuses[$index]->isOK() ) {
1334 $stages = count( $fileOpHandles[$index]->httpOp
);
1335 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1336 unset( $httpReqsByStage[$s][$index] );
1346 * Set read/write permissions for a Swift container.
1348 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1350 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1351 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1353 * @param string $container Resolved Swift container
1354 * @param array $readUsers List of the possible criteria for a request to have
1355 * access to read a container. Each item is one of the following formats:
1356 * - account:user : Grants access if the request is by the given user
1357 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1358 * matches the expression and the request is not for a listing.
1359 * Setting this to '*' effectively makes a container public.
1360 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1361 * matches the expression and the request is for a listing.
1362 * @param array $writeUsers A list of the possible criteria for a request to have
1363 * access to write to a container. Each item is of the following format:
1364 * - account:user : Grants access if the request is by the given user
1365 * @return StatusValue
1367 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1368 $status = $this->newStatus();
1369 $auth = $this->getAuthentication();
1372 $status->fatal( 'backend-fail-connect', $this->name
);
1377 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1379 'url' => $this->storageUrl( $auth, $container ),
1380 'headers' => $this->authTokenHeaders( $auth ) +
[
1381 'x-container-read' => implode( ',', $readUsers ),
1382 'x-container-write' => implode( ',', $writeUsers )
1386 if ( $rcode != 204 && $rcode !== 202 ) {
1387 $status->fatal( 'backend-fail-internal', $this->name
);
1388 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1389 [ 'rcode' => $rcode ] );
1396 * Get a Swift container stat array, possibly from process cache.
1397 * Use $reCache if the file count or byte count is needed.
1399 * @param string $container Container name
1400 * @param bool $bypassCache Bypass all caches and load from Swift
1401 * @return array|bool|null False on 404, null on failure
1403 protected function getContainerStat( $container, $bypassCache = false ) {
1404 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1406 if ( $bypassCache ) { // purge cache
1407 $this->containerStatCache
->clear( $container );
1408 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1409 $this->primeContainerCache( [ $container ] ); // check persistent cache
1411 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1412 $auth = $this->getAuthentication();
1417 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1419 'url' => $this->storageUrl( $auth, $container ),
1420 'headers' => $this->authTokenHeaders( $auth )
1423 if ( $rcode === 204 ) {
1425 'count' => $rhdrs['x-container-object-count'],
1426 'bytes' => $rhdrs['x-container-bytes-used']
1428 if ( $bypassCache ) {
1431 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1432 $this->setContainerCache( $container, $stat ); // update persistent cache
1434 } elseif ( $rcode === 404 ) {
1437 $this->onError( null, __METHOD__
,
1438 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1444 return $this->containerStatCache
->get( $container, 'stat' );
1448 * Create a Swift container
1450 * @param string $container Container name
1451 * @param array $params
1452 * @return StatusValue
1454 protected function createContainer( $container, array $params ) {
1455 $status = $this->newStatus();
1457 $auth = $this->getAuthentication();
1459 $status->fatal( 'backend-fail-connect', $this->name
);
1464 // @see SwiftFileBackend::setContainerAccess()
1465 if ( empty( $params['noAccess'] ) ) {
1466 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] ); // public
1468 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
] ); // private
1471 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] ); // sanity
1473 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1475 'url' => $this->storageUrl( $auth, $container ),
1476 'headers' => $this->authTokenHeaders( $auth ) +
[
1477 'x-container-read' => implode( ',', $readUsers ),
1478 'x-container-write' => implode( ',', $writeUsers )
1482 if ( $rcode === 201 ) { // new
1484 } elseif ( $rcode === 202 ) { // already there
1485 // this shouldn't really happen, but is OK
1487 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1494 * Delete a Swift container
1496 * @param string $container Container name
1497 * @param array $params
1498 * @return StatusValue
1500 protected function deleteContainer( $container, array $params ) {
1501 $status = $this->newStatus();
1503 $auth = $this->getAuthentication();
1505 $status->fatal( 'backend-fail-connect', $this->name
);
1510 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1511 'method' => 'DELETE',
1512 'url' => $this->storageUrl( $auth, $container ),
1513 'headers' => $this->authTokenHeaders( $auth )
1516 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1517 $this->containerStatCache
->clear( $container ); // purge
1518 } elseif ( $rcode === 404 ) { // not there
1519 // this shouldn't really happen, but is OK
1520 } elseif ( $rcode === 409 ) { // not empty
1521 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1523 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1530 * Get a list of objects under a container.
1531 * Either just the names or a list of stdClass objects with details can be returned.
1533 * @param string $fullCont
1534 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1536 * @param string|null $after
1537 * @param string|null $prefix
1538 * @param string|null $delim
1539 * @return StatusValue With the list as value
1541 private function objectListing(
1542 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1544 $status = $this->newStatus();
1546 $auth = $this->getAuthentication();
1548 $status->fatal( 'backend-fail-connect', $this->name
);
1553 $query = [ 'limit' => $limit ];
1554 if ( $type === 'info' ) {
1555 $query['format'] = 'json';
1557 if ( $after !== null ) {
1558 $query['marker'] = $after;
1560 if ( $prefix !== null ) {
1561 $query['prefix'] = $prefix;
1563 if ( $delim !== null ) {
1564 $query['delimiter'] = $delim;
1567 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1569 'url' => $this->storageUrl( $auth, $fullCont ),
1571 'headers' => $this->authTokenHeaders( $auth )
1574 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1575 if ( $rcode === 200 ) { // good
1576 if ( $type === 'info' ) {
1577 $status->value
= FormatJson
::decode( trim( $rbody ) );
1579 $status->value
= explode( "\n", trim( $rbody ) );
1581 } elseif ( $rcode === 204 ) {
1582 $status->value
= []; // empty container
1583 } elseif ( $rcode === 404 ) {
1584 $status->value
= []; // no container
1586 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1592 protected function doPrimeContainerCache( array $containerInfo ) {
1593 foreach ( $containerInfo as $container => $info ) {
1594 $this->containerStatCache
->set( $container, 'stat', $info );
1598 protected function doGetFileStatMulti( array $params ) {
1601 $auth = $this->getAuthentication();
1604 foreach ( $params['srcs'] as $path ) {
1605 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1606 if ( $srcRel === null ) {
1607 $stats[$path] = false;
1608 continue; // invalid storage path
1609 } elseif ( !$auth ) {
1610 $stats[$path] = null;
1614 // (a) Check the container
1615 $cstat = $this->getContainerStat( $srcCont );
1616 if ( $cstat === false ) {
1617 $stats[$path] = false;
1618 continue; // ok, nothing to do
1619 } elseif ( !is_array( $cstat ) ) {
1620 $stats[$path] = null;
1626 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1627 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1631 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1632 $reqs = $this->http
->runMulti( $reqs, $opts );
1634 foreach ( $params['srcs'] as $path ) {
1635 if ( array_key_exists( $path, $stats ) ) {
1636 continue; // some sort of failure above
1638 // (b) Check the file
1639 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1640 if ( $rcode === 200 ||
$rcode === 204 ) {
1641 // Update the object if it is missing some headers
1642 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1643 // Load the stat array from the headers
1644 $stat = $this->getStatFromHeaders( $rhdrs );
1645 if ( $this->isRGW
) {
1646 $stat['latest'] = true; // strong consistency
1648 } elseif ( $rcode === 404 ) {
1652 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1654 $stats[$path] = $stat;
1661 * @param array $rhdrs
1664 protected function getStatFromHeaders( array $rhdrs ) {
1665 // Fetch all of the custom metadata headers
1666 $metadata = $this->getMetadata( $rhdrs );
1667 // Fetch all of the custom raw HTTP headers
1668 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1671 // Convert various random Swift dates to TS_MW
1672 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1673 // Empty objects actually return no content-length header in Ceph
1674 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1675 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1676 // Note: manifiest ETags are not an MD5 of the file
1677 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1678 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1683 * @return array|null Credential map
1685 protected function getAuthentication() {
1686 if ( $this->authErrorTimestamp
!== null ) {
1687 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1688 return null; // failed last attempt; don't bother
1689 } else { // actually retry this time
1690 $this->authErrorTimestamp
= null;
1693 // Session keys expire after a while, so we renew them periodically
1694 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1695 // Authenticate with proxy and get a session key...
1696 if ( !$this->authCreds ||
$reAuth ) {
1697 $this->authSessionTimestamp
= 0;
1698 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1699 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1700 // Try to use the credential cache
1701 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1702 $this->authCreds
= $creds;
1703 // Skew the timestamp for worst case to avoid using stale credentials
1704 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1705 } else { // cache miss
1706 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1708 'url' => "{$this->swiftAuthUrl}/v1.0",
1710 'x-auth-user' => $this->swiftUser
,
1711 'x-auth-key' => $this->swiftKey
1715 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1716 $this->authCreds
= [
1717 'auth_token' => $rhdrs['x-auth-token'],
1718 'storage_url' => ( $this->swiftStorageUrl
!== null )
1719 ?
$this->swiftStorageUrl
1720 : $rhdrs['x-storage-url']
1723 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1724 $this->authSessionTimestamp
= time();
1725 } elseif ( $rcode === 401 ) {
1726 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1727 $this->authErrorTimestamp
= time();
1731 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1732 $this->authErrorTimestamp
= time();
1737 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1738 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1739 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1743 return $this->authCreds
;
1747 * @param array $creds From getAuthentication()
1748 * @param string $container
1749 * @param string $object
1752 protected function storageUrl( array $creds, $container = null, $object = null ) {
1753 $parts = [ $creds['storage_url'] ];
1754 if ( strlen( $container ) ) {
1755 $parts[] = rawurlencode( $container );
1757 if ( strlen( $object ) ) {
1758 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1761 return implode( '/', $parts );
1765 * @param array $creds From getAuthentication()
1768 protected function authTokenHeaders( array $creds ) {
1769 return [ 'x-auth-token' => $creds['auth_token'] ];
1773 * Get the cache key for a container
1775 * @param string $username
1778 private function getCredsCacheKey( $username ) {
1779 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1783 * Log an unexpected exception for this backend.
1784 * This also sets the StatusValue object to have a fatal error.
1786 * @param StatusValue|null $status
1787 * @param string $func
1788 * @param array $params
1789 * @param string $err Error string
1790 * @param int $code HTTP status
1791 * @param string $desc HTTP StatusValue description
1793 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1794 if ( $status instanceof StatusValue
) {
1795 $status->fatal( 'backend-fail-internal', $this->name
);
1797 if ( $code == 401 ) { // possibly a stale token
1798 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1800 $msg = "HTTP {code} ({desc}) in '{func}' (given '{params}')";
1805 'req_params' => FormatJson
::encode( $params ),
1809 $msgParams['err'] = $err;
1811 $this->logger
->error( $msg, $msgParams );
1816 * @see FileBackendStoreOpHandle
1818 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1819 /** @var array List of Requests for MultiHttpClient */
1825 * @param SwiftFileBackend $backend
1826 * @param Closure $callback Function that takes (HTTP request array, status)
1827 * @param array $httpOp MultiHttpClient op
1829 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1830 $this->backend
= $backend;
1831 $this->callback
= $callback;
1832 $this->httpOp
= $httpOp;
1837 * SwiftFileBackend helper class to page through listings.
1838 * Swift also has a listing limit of 10,000 objects for sanity.
1839 * Do not use this class from places outside SwiftFileBackend.
1841 * @ingroup FileBackend
1843 abstract class SwiftFileBackendList
implements Iterator
{
1844 /** @var array List of path or (path,stat array) entries */
1845 protected $bufferIter = [];
1847 /** @var string List items *after* this path */
1848 protected $bufferAfter = null;
1854 protected $params = [];
1856 /** @var SwiftFileBackend */
1859 /** @var string Container name */
1860 protected $container;
1862 /** @var string Storage directory */
1866 protected $suffixStart;
1868 const PAGE_SIZE
= 9000; // file listing buffer size
1871 * @param SwiftFileBackend $backend
1872 * @param string $fullCont Resolved container name
1873 * @param string $dir Resolved directory relative to container
1874 * @param array $params
1876 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1877 $this->backend
= $backend;
1878 $this->container
= $fullCont;
1880 if ( substr( $this->dir
, -1 ) === '/' ) {
1881 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1883 if ( $this->dir
== '' ) { // whole container
1884 $this->suffixStart
= 0;
1885 } else { // dir within container
1886 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1888 $this->params
= $params;
1892 * @see Iterator::key()
1895 public function key() {
1900 * @see Iterator::next()
1902 public function next() {
1903 // Advance to the next file in the page
1904 next( $this->bufferIter
);
1906 // Check if there are no files left in this page and
1907 // advance to the next page if this page was not empty.
1908 if ( !$this->valid() && count( $this->bufferIter
) ) {
1909 $this->bufferIter
= $this->pageFromList(
1910 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1911 ); // updates $this->bufferAfter
1916 * @see Iterator::rewind()
1918 public function rewind() {
1920 $this->bufferAfter
= null;
1921 $this->bufferIter
= $this->pageFromList(
1922 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1923 ); // updates $this->bufferAfter
1927 * @see Iterator::valid()
1930 public function valid() {
1931 if ( $this->bufferIter
=== null ) {
1932 return false; // some failure?
1934 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1939 * Get the given list portion (page)
1941 * @param string $container Resolved container name
1942 * @param string $dir Resolved path relative to container
1943 * @param string &$after
1945 * @param array $params
1946 * @return Traversable|array
1948 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1952 * Iterator for listing directories
1954 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1956 * @see Iterator::current()
1957 * @return string|bool String (relative path) or false
1959 public function current() {
1960 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1963 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1964 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1969 * Iterator for listing regular files
1971 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1973 * @see Iterator::current()
1974 * @return string|bool String (relative path) or false
1976 public function current() {
1977 list( $path, $stat ) = current( $this->bufferIter
);
1978 $relPath = substr( $path, $this->suffixStart
);
1979 if ( is_array( $stat ) ) {
1980 $storageDir = rtrim( $this->params
['dir'], '/' );
1981 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1987 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1988 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );