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
25 use Wikimedia\AtEase\AtEase
;
28 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
30 * StatusValue messages should avoid mentioning the Swift account name.
31 * Likewise, error suppression should be used to avoid path disclosure.
33 * @ingroup FileBackend
36 class SwiftFileBackend
extends FileBackendStore
{
37 /** @var MultiHttpClient */
39 /** @var int TTL in seconds */
41 /** @var string Authentication base URL (without version) */
42 protected $swiftAuthUrl;
43 /** @var string Override of storage base URL */
44 protected $swiftStorageUrl;
45 /** @var string Swift user (account:user) to authenticate as */
47 /** @var string Secret key for user */
49 /** @var string Shared secret value for making temp URLs */
50 protected $swiftTempUrlKey;
51 /** @var string S3 access key (RADOS Gateway) */
52 protected $rgwS3AccessKey;
53 /** @var string S3 authentication key (RADOS Gateway) */
54 protected $rgwS3SecretKey;
55 /** @var array Additional users (account:user) with read permissions on public containers */
57 /** @var array Additional users (account:user) with write permissions on public containers */
58 protected $writeUsers;
59 /** @var array Additional users (account:user) with read permissions on private containers */
60 protected $secureReadUsers;
61 /** @var array Additional users (account:user) with write permissions on private containers */
62 protected $secureWriteUsers;
67 /** @var MapCacheLRU Container stat cache */
68 protected $containerStatCache;
72 /** @var int UNIX timestamp */
73 protected $authSessionTimestamp = 0;
74 /** @var int UNIX timestamp */
75 protected $authErrorTimestamp = null;
77 /** @var bool Whether the server is an Ceph RGW */
78 protected $isRGW = false;
81 * @see FileBackendStore::__construct()
82 * @param array $config Params include:
83 * - swiftAuthUrl : Swift authentication server URL
84 * - swiftUser : Swift user used by MediaWiki (account:username)
85 * - swiftKey : Swift authentication key for the above user
86 * - swiftAuthTTL : Swift authentication TTL (seconds)
87 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
88 * Do not set this until it has been set in the backend.
89 * - swiftStorageUrl : Swift storage URL (overrides that of the authentication response).
90 * This is useful to set if a TLS proxy is in use.
91 * - shardViaHashLevels : Map of container names to sharding config with:
92 * - base : base of hash characters, 16 or 36
93 * - levels : the number of hash levels (and digits)
94 * - repeat : hash subdirectories are prefixed with all the
95 * parent hash directory names (e.g. "a/ab/abc")
96 * - cacheAuthInfo : Whether to cache authentication tokens in APC, etc.
97 * If those are not available, then the main cache will be used.
98 * This is probably insecure in shared hosting environments.
99 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
100 * Do not set this until it has been set in the backend.
101 * This is used for generating expiring pre-authenticated URLs.
102 * Only use this when using rgw and to work around
103 * http://tracker.newdream.net/issues/3454.
104 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
105 * Do not set this until it has been set in the backend.
106 * This is used for generating expiring pre-authenticated URLs.
107 * Only use this when using rgw and to work around
108 * http://tracker.newdream.net/issues/3454.
109 * - readUsers : Swift users with read access to public containers (account:username)
110 * - writeUsers : Swift users with write access to public containers (account:username)
111 * - secureReadUsers : Swift users with read access to private containers (account:username)
112 * - secureWriteUsers : Swift users with write access to private containers (account:username)
114 public function __construct( array $config ) {
115 parent
::__construct( $config );
117 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
118 $this->swiftUser
= $config['swiftUser'];
119 $this->swiftKey
= $config['swiftKey'];
121 $this->authTTL
= $config['swiftAuthTTL'] ??
15 * 60; // some sane number
122 $this->swiftTempUrlKey
= $config['swiftTempUrlKey'] ??
'';
123 $this->swiftStorageUrl
= $config['swiftStorageUrl'] ??
null;
124 $this->shardViaHashLevels
= $config['shardViaHashLevels'] ??
'';
125 $this->rgwS3AccessKey
= $config['rgwS3AccessKey'] ??
'';
126 $this->rgwS3SecretKey
= $config['rgwS3SecretKey'] ??
'';
127 // HTTP helper client
128 $this->http
= new MultiHttpClient( [] );
129 // Cache container information to mask latency
130 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
131 $this->memCache
= $config['wanCache'];
133 // Process cache for container info
134 $this->containerStatCache
= new MapCacheLRU( 300 );
135 // Cache auth token information to avoid RTTs
136 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
137 $this->srvCache
= $config['srvCache'];
139 $this->srvCache
= new EmptyBagOStuff();
141 $this->readUsers
= $config['readUsers'] ??
[];
142 $this->writeUsers
= $config['writeUsers'] ??
[];
143 $this->secureReadUsers
= $config['secureReadUsers'] ??
[];
144 $this->secureWriteUsers
= $config['secureWriteUsers'] ??
[];
147 public function getFeatures() {
149 self
::ATTR_UNICODE_PATHS |
155 protected function resolveContainerPath( $container, $relStoragePath ) {
156 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
157 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
158 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
159 return null; // too long for Swift
162 return $relStoragePath;
165 public function isPathUsableInternal( $storagePath ) {
166 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
167 if ( $rel === null ) {
168 return false; // invalid
171 return is_array( $this->getContainerStat( $container ) );
175 * Filter/normalize a header map to only include mutable "content-"/"x-content-" headers
177 * Mutable headers can be changed via HTTP POST even if the file content is the same
179 * @see https://docs.openstack.org/api-ref/object-store
180 * @param string[] $headers Map of (header => value) for a swift object
181 * @return string[] Map of (header => value) for Content-* headers mutable via POST
183 protected function extractMutableContentHeaders( array $headers ) {
184 $contentHeaders = [];
185 // Normalize casing, and strip out illegal headers
186 foreach ( $headers as $name => $value ) {
187 $name = strtolower( $name );
188 if ( !preg_match( '/^(x-)?content-(?!length$)/', $name ) ) {
189 // Only allow content-* and x-content-* headers (but not content-length)
191 } elseif ( $name === 'content-type' && !strlen( $value ) ) {
192 // This header can be set to a value but not unset for sanity
195 $contentHeaders[$name] = $value;
197 // By default, Swift has annoyingly low maximum header value limits
198 if ( isset( $contentHeaders['content-disposition'] ) ) {
200 // @note: assume FileBackend::makeContentDisposition() already used
201 foreach ( explode( ';', $contentHeaders['content-disposition'] ) as $part ) {
202 $part = trim( $part );
203 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
204 if ( strlen( $new ) <= 255 ) {
207 break; // too long; sigh
210 $contentHeaders['content-disposition'] = $disposition;
213 return $contentHeaders;
217 * @see https://docs.openstack.org/api-ref/object-store
218 * @param string[] $headers Map of (header => value) for a swift object
219 * @return string[] Map of (metadata header name => metadata value)
221 protected function extractMetadataHeaders( array $headers ) {
222 $metadataHeaders = [];
223 foreach ( $headers as $name => $value ) {
224 $name = strtolower( $name );
225 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
226 $metadataHeaders[$name] = $value;
230 return $metadataHeaders;
234 * @see https://docs.openstack.org/api-ref/object-store
235 * @param string[] $headers Map of (header => value) for a swift object
236 * @return string[] Map of (metadata key name => metadata value)
238 protected function getMetadataFromHeaders( array $headers ) {
239 $prefixLen = strlen( 'x-object-meta-' );
242 foreach ( $this->extractMetadataHeaders( $headers ) as $name => $value ) {
243 $metadata[substr( $name, $prefixLen )] = $value;
249 protected function doCreateInternal( array $params ) {
250 $status = $this->newStatus();
252 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
253 if ( $dstRel === null ) {
254 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
259 // Headers that are not strictly a function of the file content
260 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
261 // Make sure that the "content-type" header is set to something sensible
262 $mutableHeaders['content-type'] = $mutableHeaders['content-type']
263 ??
$this->getContentType( $params['dst'], $params['content'], null );
267 'url' => [ $dstCont, $dstRel ],
268 'headers' => array_merge(
271 'etag' => md5( $params['content'] ),
272 'content-length' => strlen( $params['content'] ),
273 'x-object-meta-sha1base36' =>
274 Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 )
277 'body' => $params['content']
280 $method = __METHOD__
;
281 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
282 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
283 if ( $rcode === 201 ||
$rcode === 202 ) {
285 } elseif ( $rcode === 412 ) {
286 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
288 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
291 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
294 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
295 if ( !empty( $params['async'] ) ) { // deferred
296 $status->value
= $opHandle;
297 } else { // actually write the object in Swift
298 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
304 protected function doStoreInternal( array $params ) {
305 $status = $this->newStatus();
307 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
308 if ( $dstRel === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
314 // Open a handle to the source file so that it can be streamed. The size and hash
315 // will be computed using the handle. In the off chance that the source file changes
316 // during this operation, the PUT will fail due to an ETag mismatch and be aborted.
317 AtEase
::suppressWarnings();
318 $srcHandle = fopen( $params['src'], 'rb' );
319 AtEase
::restoreWarnings();
320 if ( $srcHandle === false ) { // source doesn't exist?
321 $status->fatal( 'backend-fail-notexists', $params['src'] );
326 // Compute the MD5 and SHA-1 hashes in one pass
327 $srcSize = fstat( $srcHandle )['size'];
328 $md5Context = hash_init( 'md5' );
329 $sha1Context = hash_init( 'sha1' );
331 while ( !feof( $srcHandle ) ) {
332 $buffer = (string)fread( $srcHandle, 131072 ); // 128 KiB
333 hash_update( $md5Context, $buffer );
334 hash_update( $sha1Context, $buffer );
335 $hashDigestSize +
= strlen( $buffer );
337 // Reset the handle back to the beginning so that it can be streamed
338 rewind( $srcHandle );
340 if ( $hashDigestSize !== $srcSize ) {
341 $status->fatal( 'backend-fail-hash', $params['src'] );
346 // Headers that are not strictly a function of the file content
347 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
348 // Make sure that the "content-type" header is set to something sensible
349 $mutableHeaders['content-type'] = $mutableHeaders['content-type']
350 ??
$this->getContentType( $params['dst'], null, $params['src'] );
354 'url' => [ $dstCont, $dstRel ],
355 'headers' => array_merge(
358 'content-length' => $srcSize,
359 'etag' => hash_final( $md5Context ),
360 'x-object-meta-sha1base36' =>
361 Wikimedia\base_convert
( hash_final( $sha1Context ), 16, 36, 31 )
364 'body' => $srcHandle // resource
367 $method = __METHOD__
;
368 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
369 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
370 if ( $rcode === 201 ||
$rcode === 202 ) {
372 } elseif ( $rcode === 412 ) {
373 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
375 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
378 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
381 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
382 $opHandle->resourcesToClose
[] = $srcHandle;
384 if ( !empty( $params['async'] ) ) { // deferred
385 $status->value
= $opHandle;
386 } else { // actually write the object in Swift
387 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
393 protected function doCopyInternal( array $params ) {
394 $status = $this->newStatus();
396 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
397 if ( $srcRel === null ) {
398 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
403 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
404 if ( $dstRel === null ) {
405 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
412 'url' => [ $dstCont, $dstRel ],
413 'headers' => array_merge(
414 $this->extractMutableContentHeaders( $params['headers'] ??
[] ),
416 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
417 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
422 $method = __METHOD__
;
423 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
424 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
425 if ( $rcode === 201 ) {
427 } elseif ( $rcode === 404 ) {
428 if ( empty( $params['ignoreMissingSource'] ) ) {
429 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
432 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
435 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
438 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
439 if ( !empty( $params['async'] ) ) { // deferred
440 $status->value
= $opHandle;
441 } else { // actually write the object in Swift
442 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
448 protected function doMoveInternal( array $params ) {
449 $status = $this->newStatus();
451 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
452 if ( $srcRel === null ) {
453 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
458 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
459 if ( $dstRel === null ) {
460 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
467 'url' => [ $dstCont, $dstRel ],
468 'headers' => array_merge(
469 $this->extractMutableContentHeaders( $params['headers'] ??
[] ),
471 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
472 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
476 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
478 'method' => 'DELETE',
479 'url' => [ $srcCont, $srcRel ],
484 $method = __METHOD__
;
485 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
486 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
487 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
489 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
491 } elseif ( $rcode === 404 ) {
492 if ( empty( $params['ignoreMissingSource'] ) ) {
493 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
495 // Leave Status as OK but skip the DELETE request
496 return SwiftFileOpHandle
::CONTINUE_NO
;
499 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
502 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
505 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
506 if ( !empty( $params['async'] ) ) { // deferred
507 $status->value
= $opHandle;
508 } else { // actually move the object in Swift
509 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
515 protected function doDeleteInternal( array $params ) {
516 $status = $this->newStatus();
518 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
519 if ( $srcRel === null ) {
520 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
526 'method' => 'DELETE',
527 'url' => [ $srcCont, $srcRel ],
531 $method = __METHOD__
;
532 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
533 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
534 if ( $rcode === 204 ) {
536 } elseif ( $rcode === 404 ) {
537 if ( empty( $params['ignoreMissingSource'] ) ) {
538 $status->fatal( 'backend-fail-delete', $params['src'] );
541 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
544 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
547 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
548 if ( !empty( $params['async'] ) ) { // deferred
549 $status->value
= $opHandle;
550 } else { // actually delete the object in Swift
551 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
557 protected function doDescribeInternal( array $params ) {
558 $status = $this->newStatus();
560 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
561 if ( $srcRel === null ) {
562 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
567 // Fetch the old object headers/metadata...this should be in stat cache by now
568 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
569 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
570 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
573 $status->fatal( 'backend-fail-describe', $params['src'] );
578 // Swift object POST clears any prior headers, so merge the new and old headers here.
579 // Also, during, POST, libcurl adds "Content-Type: application/x-www-form-urlencoded"
580 // if "Content-Type" is not set, which would clobber the header value for the object.
581 $oldMetadataHeaders = [];
582 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
583 $oldMetadataHeaders["x-object-meta-$name"] = $value;
585 $newContentHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
586 $oldContentHeaders = $stat['xattr']['headers'];
590 'url' => [ $srcCont, $srcRel ],
591 'headers' => $oldMetadataHeaders +
$newContentHeaders +
$oldContentHeaders
594 $method = __METHOD__
;
595 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
596 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
597 if ( $rcode === 202 ) {
599 } elseif ( $rcode === 404 ) {
600 $status->fatal( 'backend-fail-describe', $params['src'] );
602 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
606 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
607 if ( !empty( $params['async'] ) ) { // deferred
608 $status->value
= $opHandle;
609 } else { // actually change the object in Swift
610 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
616 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
617 $status = $this->newStatus();
619 // (a) Check if container already exists
620 $stat = $this->getContainerStat( $fullCont );
621 if ( is_array( $stat ) ) {
622 return $status; // already there
623 } elseif ( $stat === self
::$RES_ERROR ) {
624 $status->fatal( 'backend-fail-internal', $this->name
);
625 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
630 // (b) Create container as needed with proper ACLs
631 if ( $stat === false ) {
632 $params['op'] = 'prepare';
633 $status->merge( $this->createContainer( $fullCont, $params ) );
639 protected function doSecureInternal( $fullCont, $dir, array $params ) {
640 $status = $this->newStatus();
641 if ( empty( $params['noAccess'] ) ) {
642 return $status; // nothing to do
645 $stat = $this->getContainerStat( $fullCont );
646 if ( is_array( $stat ) ) {
647 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
648 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
649 // Make container private to end-users...
650 $status->merge( $this->setContainerAccess(
655 } elseif ( $stat === false ) {
656 $status->fatal( 'backend-fail-usable', $params['dir'] );
658 $status->fatal( 'backend-fail-internal', $this->name
);
659 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
665 protected function doPublishInternal( $fullCont, $dir, array $params ) {
666 $status = $this->newStatus();
668 $stat = $this->getContainerStat( $fullCont );
669 if ( is_array( $stat ) ) {
670 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
671 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
673 // Make container public to end-users...
674 $status->merge( $this->setContainerAccess(
679 } elseif ( $stat === false ) {
680 $status->fatal( 'backend-fail-usable', $params['dir'] );
682 $status->fatal( 'backend-fail-internal', $this->name
);
683 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
689 protected function doCleanInternal( $fullCont, $dir, array $params ) {
690 $status = $this->newStatus();
692 // Only containers themselves can be removed, all else is virtual
694 return $status; // nothing to do
697 // (a) Check the container
698 $stat = $this->getContainerStat( $fullCont, true );
699 if ( $stat === false ) {
700 return $status; // ok, nothing to do
701 } elseif ( !is_array( $stat ) ) {
702 $status->fatal( 'backend-fail-internal', $this->name
);
703 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
708 // (b) Delete the container if empty
709 if ( $stat['count'] == 0 ) {
710 $params['op'] = 'clean';
711 $status->merge( $this->deleteContainer( $fullCont, $params ) );
717 protected function doGetFileStat( array $params ) {
718 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
719 unset( $params['src'] );
720 $stats = $this->doGetFileStatMulti( $params );
722 return reset( $stats );
726 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
727 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
728 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
731 * @param int $format Output format (TS_* constant)
733 * @throws FileBackendError
735 protected function convertSwiftDate( $ts, $format = TS_MW
) {
737 $timestamp = new MWTimestamp( $ts );
739 return $timestamp->getTimestamp( $format );
740 } catch ( Exception
$e ) {
741 throw new FileBackendError( $e->getMessage() );
746 * Fill in any missing object metadata and save it to Swift
748 * @param array $objHdrs Object response headers
749 * @param string $path Storage path to object
750 * @return array New headers
752 protected function addMissingHashMetadata( array $objHdrs, $path ) {
753 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
754 return $objHdrs; // nothing to do
757 /** @noinspection PhpUnusedLocalVariableInspection */
758 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
759 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
760 [ 'path' => $path ] );
762 $objHdrs['x-object-meta-sha1base36'] = false;
764 $auth = $this->getAuthentication();
766 return $objHdrs; // failed
769 // Find prior custom HTTP headers
770 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
771 // Find prior metadata headers
772 $postHeaders +
= $this->extractMetadataHeaders( $objHdrs );
774 $status = $this->newStatus();
775 /** @noinspection PhpUnusedLocalVariableInspection */
776 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
777 if ( $status->isOK() ) {
778 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
780 $hash = $tmpFile->getSha1Base36();
781 if ( $hash !== false ) {
782 $objHdrs['x-object-meta-sha1base36'] = $hash;
783 // Merge new SHA1 header into the old ones
784 $postHeaders['x-object-meta-sha1base36'] = $hash;
785 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
786 list( $rcode ) = $this->http
->run( [
788 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
789 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
791 if ( $rcode >= 200 && $rcode <= 299 ) {
792 $this->deleteFileCache( $path );
794 return $objHdrs; // success
800 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
801 [ 'path' => $path ] );
803 return $objHdrs; // failed
806 protected function doGetFileContentsMulti( array $params ) {
807 $auth = $this->getAuthentication();
809 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
810 // Blindly create tmp files and stream to them, catching any exception
811 // if the file does not exist. Do not waste time doing file stats here.
812 $reqs = []; // (path => op)
814 // Initial dummy values to preserve path order
815 $contents = array_fill_keys( $params['srcs'], self
::$RES_ERROR );
816 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
817 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
818 if ( $srcRel === null ||
!$auth ) {
819 continue; // invalid storage path or auth error
821 // Create a new temporary memory file...
822 $handle = fopen( 'php://temp', 'wb' );
826 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
827 'headers' => $this->authTokenHeaders( $auth )
828 +
$this->headersFromParams( $params ),
834 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
835 $reqs = $this->http
->runMulti( $reqs, $opts );
836 foreach ( $reqs as $path => $op ) {
837 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
838 if ( $rcode >= 200 && $rcode <= 299 ) {
839 rewind( $op['stream'] ); // start from the beginning
840 $content = (string)stream_get_contents( $op['stream'] );
841 $size = strlen( $content );
842 // Make sure that stream finished
843 if ( $size === (int)$rhdrs['content-length'] ) {
844 $contents[$path] = $content;
846 $contents[$path] = self
::$RES_ERROR;
847 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
848 $this->onError( null, __METHOD__
,
849 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
851 } elseif ( $rcode === 404 ) {
852 $contents[$path] = self
::$RES_ABSENT;
854 $contents[$path] = self
::$RES_ERROR;
855 $this->onError( null, __METHOD__
,
856 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
858 fclose( $op['stream'] ); // close open handle
864 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
865 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
866 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
867 if ( $status->isOK() ) {
868 return ( count( $status->value
) ) > 0;
871 return self
::$RES_ERROR;
875 * @see FileBackendStore::getDirectoryListInternal()
876 * @param string $fullCont
878 * @param array $params
879 * @return SwiftFileBackendDirList
881 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
882 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
886 * @see FileBackendStore::getFileListInternal()
887 * @param string $fullCont
889 * @param array $params
890 * @return SwiftFileBackendFileList
892 public function getFileListInternal( $fullCont, $dir, array $params ) {
893 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
897 * Do not call this function outside of SwiftFileBackendFileList
899 * @param string $fullCont Resolved container name
900 * @param string $dir Resolved storage directory with no trailing slash
901 * @param string|null &$after Resolved container relative path to list items after
902 * @param int $limit Max number of items to list
903 * @param array $params Parameters for getDirectoryList()
904 * @return array List of container relative resolved paths of directories directly under $dir
905 * @throws FileBackendError
907 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
909 if ( $after === INF
) {
910 return $dirs; // nothing more
913 /** @noinspection PhpUnusedLocalVariableInspection */
914 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
916 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
917 // Non-recursive: only list dirs right under $dir
918 if ( !empty( $params['topOnly'] ) ) {
919 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
920 if ( !$status->isOK() ) {
921 throw new FileBackendError( "Iterator page I/O error." );
923 $objects = $status->value
;
924 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
925 foreach ( $objects as $object ) { // files and directories
926 if ( substr( $object, -1 ) === '/' ) {
927 $dirs[] = $object; // directories end in '/'
931 // Recursive: list all dirs under $dir and its subdirs
932 $getParentDir = function ( $path ) {
933 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
936 // Get directory from last item of prior page
937 $lastDir = $getParentDir( $after ); // must be first page
938 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
940 if ( !$status->isOK() ) {
941 throw new FileBackendError( "Iterator page I/O error." );
944 $objects = $status->value
;
946 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
947 foreach ( $objects as $object ) { // files
948 $objectDir = $getParentDir( $object ); // directory of object
950 if ( $objectDir !== false && $objectDir !== $dir ) {
951 // Swift stores paths in UTF-8, using binary sorting.
952 // See function "create_container_table" in common/db.py.
953 // If a directory is not "greater" than the last one,
954 // then it was already listed by the calling iterator.
955 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
957 do { // add dir and all its parent dirs
958 $dirs[] = "{$pDir}/";
959 $pDir = $getParentDir( $pDir );
960 } while ( $pDir !== false // sanity
961 && strcmp( $pDir, $lastDir ) > 0 // not done already
962 && strlen( $pDir ) > strlen( $dir ) // within $dir
965 $lastDir = $objectDir;
969 // Page on the unfiltered directory listing (what is returned may be filtered)
970 if ( count( $objects ) < $limit ) {
971 $after = INF
; // avoid a second RTT
973 $after = end( $objects ); // update last item
980 * Do not call this function outside of SwiftFileBackendFileList
982 * @param string $fullCont Resolved container name
983 * @param string $dir Resolved storage directory with no trailing slash
984 * @param string|null &$after Resolved container relative path of file to list items after
985 * @param int $limit Max number of items to list
986 * @param array $params Parameters for getDirectoryList()
987 * @return array List of resolved container relative paths of files under $dir
988 * @throws FileBackendError
990 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
991 $files = []; // list of (path, stat array or null) entries
992 if ( $after === INF
) {
993 return $files; // nothing more
996 /** @noinspection PhpUnusedLocalVariableInspection */
997 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
999 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
1000 // $objects will contain a list of unfiltered names or stdClass items
1001 // Non-recursive: only list files right under $dir
1002 if ( !empty( $params['topOnly'] ) ) {
1003 if ( !empty( $params['adviseStat'] ) ) {
1004 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
1006 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
1009 // Recursive: list all files under $dir and its subdirs
1010 if ( !empty( $params['adviseStat'] ) ) {
1011 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
1013 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
1017 // Reformat this list into a list of (name, stat array or null) entries
1018 if ( !$status->isOK() ) {
1019 throw new FileBackendError( "Iterator page I/O error." );
1022 $objects = $status->value
;
1023 $files = $this->buildFileObjectListing( $objects );
1025 // Page on the unfiltered object listing (what is returned may be filtered)
1026 if ( count( $objects ) < $limit ) {
1027 $after = INF
; // avoid a second RTT
1029 $after = end( $objects ); // update last item
1030 $after = is_object( $after ) ?
$after->name
: $after;
1037 * Build a list of file objects, filtering out any directories
1038 * and extracting any stat info if provided in $objects
1040 * @param stdClass[]|string[] $objects List of stdClass items or object names
1041 * @return array List of (names,stat array or null) entries
1043 private function buildFileObjectListing( array $objects ) {
1045 foreach ( $objects as $object ) {
1046 if ( is_object( $object ) ) {
1047 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1048 continue; // virtual directory entry; ignore
1051 // Convert various random Swift dates to TS_MW
1052 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1053 'size' => (int)$object->bytes
,
1055 // Note: manifiest ETags are not an MD5 of the file
1056 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1057 'latest' => false // eventually consistent
1059 $names[] = [ $object->name
, $stat ];
1060 } elseif ( substr( $object, -1 ) !== '/' ) {
1061 // Omit directories, which end in '/' in listings
1062 $names[] = [ $object, null ];
1070 * Do not call this function outside of SwiftFileBackendFileList
1072 * @param string $path Storage path
1073 * @param array $val Stat value
1075 public function loadListingStatInternal( $path, array $val ) {
1076 $this->cheapCache
->setField( $path, 'stat', $val );
1079 protected function doGetFileXAttributes( array $params ) {
1080 $stat = $this->getFileStat( $params );
1081 // Stat entries filled by file listings don't include metadata/headers
1082 if ( is_array( $stat ) && !isset( $stat['xattr'] ) ) {
1083 $this->clearCache( [ $params['src'] ] );
1084 $stat = $this->getFileStat( $params );
1087 if ( is_array( $stat ) ) {
1088 return $stat['xattr'];
1091 return ( $stat === self
::$RES_ERROR ) ? self
::$RES_ERROR : self
::$RES_ABSENT;
1094 protected function doGetFileSha1base36( array $params ) {
1095 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1096 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1097 $params['requireSHA1'] = true;
1099 $stat = $this->getFileStat( $params );
1100 if ( is_array( $stat ) ) {
1101 return $stat['sha1'];
1104 return ( $stat === self
::$RES_ERROR ) ? self
::$RES_ERROR : self
::$RES_ABSENT;
1107 protected function doStreamFile( array $params ) {
1108 $status = $this->newStatus();
1110 $flags = !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
1112 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1113 if ( $srcRel === null ) {
1114 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1115 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1120 $auth = $this->getAuthentication();
1121 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1122 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1123 $status->fatal( 'backend-fail-stream', $params['src'] );
1128 // If "headers" is set, we only want to send them if the file is there.
1129 // Do not bother checking if the file exists if headers are not set though.
1130 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1131 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1132 $status->fatal( 'backend-fail-stream', $params['src'] );
1137 // Send the requested additional headers
1138 foreach ( $params['headers'] as $header ) {
1139 header( $header ); // aways send
1142 if ( empty( $params['allowOB'] ) ) {
1143 // Cancel output buffering and gzipping if set
1144 ( $this->obResetFunc
)();
1147 $handle = fopen( 'php://output', 'wb' );
1148 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1150 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1151 'headers' => $this->authTokenHeaders( $auth )
1152 +
$this->headersFromParams( $params ) +
$params['options'],
1153 'stream' => $handle,
1154 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1157 if ( $rcode >= 200 && $rcode <= 299 ) {
1159 } elseif ( $rcode === 404 ) {
1160 $status->fatal( 'backend-fail-stream', $params['src'] );
1161 // Per T43113, nasty things can happen if bad cache entries get
1162 // stuck in cache. It's also possible that this error can come up
1163 // with simple race conditions. Clear out the stat cache to be safe.
1164 $this->clearCache( [ $params['src'] ] );
1165 $this->deleteFileCache( $params['src'] );
1167 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1173 protected function doGetLocalCopyMulti( array $params ) {
1174 $auth = $this->getAuthentication();
1176 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1177 // Blindly create tmp files and stream to them, catching any exception
1178 // if the file does not exist. Do not waste time doing file stats here.
1179 $reqs = []; // (path => op)
1181 // Initial dummy values to preserve path order
1182 $tmpFiles = array_fill_keys( $params['srcs'], self
::$RES_ERROR );
1183 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1184 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1185 if ( $srcRel === null ||
!$auth ) {
1186 continue; // invalid storage path or auth error
1188 // Get source file extension
1189 $ext = FileBackend
::extensionFromPath( $path );
1190 // Create a new temporary file...
1191 $tmpFile = $this->tmpFileFactory
->newTempFSFile( 'localcopy_', $ext );
1192 $handle = $tmpFile ?
fopen( $tmpFile->getPath(), 'wb' ) : false;
1196 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1197 'headers' => $this->authTokenHeaders( $auth )
1198 +
$this->headersFromParams( $params ),
1199 'stream' => $handle,
1201 $tmpFiles[$path] = $tmpFile;
1205 // Ceph RADOS Gateway is in use (strong consistency) or X-Newest will be used
1206 $latest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1208 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1209 $reqs = $this->http
->runMulti( $reqs, $opts );
1210 foreach ( $reqs as $path => $op ) {
1211 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1212 fclose( $op['stream'] ); // close open handle
1213 if ( $rcode >= 200 && $rcode <= 299 ) {
1214 /** @var TempFSFile $tmpFile */
1215 $tmpFile = $tmpFiles[$path];
1216 // Make sure that the stream finished and fully wrote to disk
1217 $size = $tmpFile->getSize();
1218 if ( $size !== (int)$rhdrs['content-length'] ) {
1219 $tmpFiles[$path] = self
::$RES_ERROR;
1220 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1221 $this->onError( null, __METHOD__
,
1222 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1224 // Set the file stat process cache in passing
1225 $stat = $this->getStatFromHeaders( $rhdrs );
1226 $stat['latest'] = $latest;
1227 $this->cheapCache
->setField( $path, 'stat', $stat );
1228 } elseif ( $rcode === 404 ) {
1229 $tmpFiles[$path] = self
::$RES_ABSENT;
1230 $this->cheapCache
->setField(
1233 $latest ? self
::$ABSENT_LATEST : self
::$ABSENT_NORMAL
1236 $tmpFiles[$path] = self
::$RES_ERROR;
1237 $this->onError( null, __METHOD__
,
1238 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1245 public function getFileHttpUrl( array $params ) {
1246 if ( $this->swiftTempUrlKey
!= '' ||
1247 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1249 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1250 if ( $srcRel === null ) {
1251 return self
::TEMPURL_ERROR
; // invalid path
1254 $auth = $this->getAuthentication();
1256 return self
::TEMPURL_ERROR
;
1259 $ttl = $params['ttl'] ??
86400;
1260 $expires = time() +
$ttl;
1262 if ( $this->swiftTempUrlKey
!= '' ) {
1263 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1264 // Swift wants the signature based on the unencoded object name
1265 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1266 $signature = hash_hmac( 'sha1',
1267 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1268 $this->swiftTempUrlKey
1271 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1272 } else { // give S3 API URL for rgw
1273 // Path for signature starts with the bucket
1274 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1275 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1276 // Calculate the hash
1277 $signature = base64_encode( hash_hmac(
1279 "GET\n\n\n{$expires}\n{$spath}",
1280 $this->rgwS3SecretKey
,
1283 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1284 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1285 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1286 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1289 'Signature' => $signature,
1290 'Expires' => $expires,
1291 'AWSAccessKeyId' => $this->rgwS3AccessKey
1296 return self
::TEMPURL_ERROR
;
1299 protected function directoriesAreVirtual() {
1304 * Get headers to send to Swift when reading a file based
1305 * on a FileBackend params array, e.g. that of getLocalCopy().
1306 * $params is currently only checked for a 'latest' flag.
1308 * @param array $params
1311 protected function headersFromParams( array $params ) {
1313 if ( !empty( $params['latest'] ) ) {
1314 $hdrs['x-newest'] = 'true';
1320 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1321 /** @var SwiftFileOpHandle[] $fileOpHandles */
1322 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1324 /** @var StatusValue[] $statuses */
1327 $auth = $this->getAuthentication();
1329 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1330 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1336 // Split the HTTP requests into stages that can be done concurrently
1337 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1338 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1339 $reqs = $fileOpHandle->httpOp
;
1340 // Convert the 'url' parameter to an actual URL using $auth
1341 foreach ( $reqs as $stage => &$req ) {
1342 list( $container, $relPath ) = $req['url'];
1343 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1344 $req['headers'] = $req['headers'] ??
[];
1345 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1346 $httpReqsByStage[$stage][$index] = $req;
1348 $statuses[$index] = $this->newStatus();
1351 // Run all requests for the first stage, then the next, and so on
1352 $reqCount = count( $httpReqsByStage );
1353 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1354 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1355 foreach ( $httpReqs as $index => $httpReq ) {
1356 /** @var SwiftFileOpHandle $fileOpHandle */
1357 $fileOpHandle = $fileOpHandles[$index];
1358 // Run the callback for each request of this operation
1359 $status = $statuses[$index];
1360 ( $fileOpHandle->callback
)( $httpReq, $status );
1361 // On failure, abort all remaining requests for this operation. This is used
1362 // in "move" operations to abort the DELETE request if the PUT request fails.
1365 $fileOpHandle->state
=== $fileOpHandle::CONTINUE_NO
1367 $stages = count( $fileOpHandle->httpOp
);
1368 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1369 unset( $httpReqsByStage[$s][$index] );
1379 * Set read/write permissions for a Swift container.
1381 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1383 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1384 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1386 * @param string $container Resolved Swift container
1387 * @param array $readUsers List of the possible criteria for a request to have
1388 * access to read a container. Each item is one of the following formats:
1389 * - account:user : Grants access if the request is by the given user
1390 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1391 * matches the expression and the request is not for a listing.
1392 * Setting this to '*' effectively makes a container public.
1393 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1394 * matches the expression and the request is for a listing.
1395 * @param array $writeUsers A list of the possible criteria for a request to have
1396 * access to write to a container. Each item is of the following format:
1397 * - account:user : Grants access if the request is by the given user
1398 * @return StatusValue
1400 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1401 $status = $this->newStatus();
1402 $auth = $this->getAuthentication();
1405 $status->fatal( 'backend-fail-connect', $this->name
);
1410 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1412 'url' => $this->storageUrl( $auth, $container ),
1413 'headers' => $this->authTokenHeaders( $auth ) +
[
1414 'x-container-read' => implode( ',', $readUsers ),
1415 'x-container-write' => implode( ',', $writeUsers )
1419 if ( $rcode != 204 && $rcode !== 202 ) {
1420 $status->fatal( 'backend-fail-internal', $this->name
);
1421 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1422 [ 'rcode' => $rcode ] );
1429 * Get a Swift container stat array, possibly from process cache.
1430 * Use $reCache if the file count or byte count is needed.
1432 * @param string $container Container name
1433 * @param bool $bypassCache Bypass all caches and load from Swift
1434 * @return array|bool|null False on 404, null on failure
1436 protected function getContainerStat( $container, $bypassCache = false ) {
1437 /** @noinspection PhpUnusedLocalVariableInspection */
1438 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1440 if ( $bypassCache ) { // purge cache
1441 $this->containerStatCache
->clear( $container );
1442 } elseif ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1443 $this->primeContainerCache( [ $container ] ); // check persistent cache
1445 if ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1446 $auth = $this->getAuthentication();
1448 return self
::$RES_ERROR;
1451 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1453 'url' => $this->storageUrl( $auth, $container ),
1454 'headers' => $this->authTokenHeaders( $auth )
1457 if ( $rcode === 204 ) {
1459 'count' => $rhdrs['x-container-object-count'],
1460 'bytes' => $rhdrs['x-container-bytes-used']
1462 if ( $bypassCache ) {
1465 $this->containerStatCache
->setField( $container, 'stat', $stat ); // cache it
1466 $this->setContainerCache( $container, $stat ); // update persistent cache
1468 } elseif ( $rcode === 404 ) {
1469 return self
::$RES_ABSENT;
1471 $this->onError( null, __METHOD__
,
1472 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1474 return self
::$RES_ERROR;
1478 return $this->containerStatCache
->getField( $container, 'stat' );
1482 * Create a Swift container
1484 * @param string $container Container name
1485 * @param array $params
1486 * @return StatusValue
1488 protected function createContainer( $container, array $params ) {
1489 $status = $this->newStatus();
1491 $auth = $this->getAuthentication();
1493 $status->fatal( 'backend-fail-connect', $this->name
);
1498 // @see SwiftFileBackend::setContainerAccess()
1499 if ( empty( $params['noAccess'] ) ) {
1501 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] );
1502 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
1505 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
1506 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
1509 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1511 'url' => $this->storageUrl( $auth, $container ),
1512 'headers' => $this->authTokenHeaders( $auth ) +
[
1513 'x-container-read' => implode( ',', $readUsers ),
1514 'x-container-write' => implode( ',', $writeUsers )
1518 if ( $rcode === 201 ) { // new
1520 } elseif ( $rcode === 202 ) { // already there
1521 // this shouldn't really happen, but is OK
1523 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1530 * Delete a Swift container
1532 * @param string $container Container name
1533 * @param array $params
1534 * @return StatusValue
1536 protected function deleteContainer( $container, array $params ) {
1537 $status = $this->newStatus();
1539 $auth = $this->getAuthentication();
1541 $status->fatal( 'backend-fail-connect', $this->name
);
1546 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1547 'method' => 'DELETE',
1548 'url' => $this->storageUrl( $auth, $container ),
1549 'headers' => $this->authTokenHeaders( $auth )
1552 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1553 $this->containerStatCache
->clear( $container ); // purge
1554 } elseif ( $rcode === 404 ) { // not there
1555 // this shouldn't really happen, but is OK
1556 } elseif ( $rcode === 409 ) { // not empty
1557 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1559 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1566 * Get a list of objects under a container.
1567 * Either just the names or a list of stdClass objects with details can be returned.
1569 * @param string $fullCont
1570 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1572 * @param string|null $after
1573 * @param string|null $prefix
1574 * @param string|null $delim
1575 * @return StatusValue With the list as value
1577 private function objectListing(
1578 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1580 $status = $this->newStatus();
1582 $auth = $this->getAuthentication();
1584 $status->fatal( 'backend-fail-connect', $this->name
);
1589 $query = [ 'limit' => $limit ];
1590 if ( $type === 'info' ) {
1591 $query['format'] = 'json';
1593 if ( $after !== null ) {
1594 $query['marker'] = $after;
1596 if ( $prefix !== null ) {
1597 $query['prefix'] = $prefix;
1599 if ( $delim !== null ) {
1600 $query['delimiter'] = $delim;
1603 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1605 'url' => $this->storageUrl( $auth, $fullCont ),
1607 'headers' => $this->authTokenHeaders( $auth )
1610 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1611 if ( $rcode === 200 ) { // good
1612 if ( $type === 'info' ) {
1613 $status->value
= FormatJson
::decode( trim( $rbody ) );
1615 $status->value
= explode( "\n", trim( $rbody ) );
1617 } elseif ( $rcode === 204 ) {
1618 $status->value
= []; // empty container
1619 } elseif ( $rcode === 404 ) {
1620 $status->value
= []; // no container
1622 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1628 protected function doPrimeContainerCache( array $containerInfo ) {
1629 foreach ( $containerInfo as $container => $info ) {
1630 $this->containerStatCache
->setField( $container, 'stat', $info );
1634 protected function doGetFileStatMulti( array $params ) {
1637 $auth = $this->getAuthentication();
1639 $reqs = []; // (path => op)
1640 // (a) Check the containers of the paths...
1641 foreach ( $params['srcs'] as $path ) {
1642 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1643 if ( $srcRel === null ||
!$auth ) {
1644 $stats[$path] = self
::$RES_ERROR;
1645 continue; // invalid storage path or auth error
1648 $cstat = $this->getContainerStat( $srcCont );
1649 if ( $cstat === self
::$RES_ABSENT ) {
1650 $stats[$path] = self
::$RES_ABSENT;
1651 continue; // ok, nothing to do
1652 } elseif ( !is_array( $cstat ) ) {
1653 $stats[$path] = self
::$RES_ERROR;
1659 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1660 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1664 // (b) Check the files themselves...
1665 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1666 $reqs = $this->http
->runMulti( $reqs, $opts );
1667 foreach ( $reqs as $path => $op ) {
1668 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1669 if ( $rcode === 200 ||
$rcode === 204 ) {
1670 // Update the object if it is missing some headers
1671 if ( !empty( $params['requireSHA1'] ) ) {
1672 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1674 // Load the stat array from the headers
1675 $stat = $this->getStatFromHeaders( $rhdrs );
1676 if ( $this->isRGW
) {
1677 $stat['latest'] = true; // strong consistency
1679 } elseif ( $rcode === 404 ) {
1680 $stat = self
::$RES_ABSENT;
1682 $stat = self
::$RES_ERROR;
1683 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1685 $stats[$path] = $stat;
1692 * @param array $rhdrs
1695 protected function getStatFromHeaders( array $rhdrs ) {
1696 // Fetch all of the custom metadata headers
1697 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1698 // Fetch all of the custom raw HTTP headers
1699 $headers = $this->extractMutableContentHeaders( $rhdrs );
1702 // Convert various random Swift dates to TS_MW
1703 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1704 // Empty objects actually return no content-length header in Ceph
1705 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1706 'sha1' => $metadata['sha1base36'] ??
null,
1707 // Note: manifiest ETags are not an MD5 of the file
1708 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1709 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1714 * @return array|null Credential map
1716 protected function getAuthentication() {
1717 if ( $this->authErrorTimestamp
!== null ) {
1718 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1719 return null; // failed last attempt; don't bother
1720 } else { // actually retry this time
1721 $this->authErrorTimestamp
= null;
1724 // Session keys expire after a while, so we renew them periodically
1725 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1726 // Authenticate with proxy and get a session key...
1727 if ( !$this->authCreds ||
$reAuth ) {
1728 $this->authSessionTimestamp
= 0;
1729 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1730 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1731 // Try to use the credential cache
1732 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1733 $this->authCreds
= $creds;
1734 // Skew the timestamp for worst case to avoid using stale credentials
1735 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1736 } else { // cache miss
1737 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1739 'url' => "{$this->swiftAuthUrl}/v1.0",
1741 'x-auth-user' => $this->swiftUser
,
1742 'x-auth-key' => $this->swiftKey
1746 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1747 $this->authCreds
= [
1748 'auth_token' => $rhdrs['x-auth-token'],
1749 'storage_url' => $this->swiftStorageUrl ??
$rhdrs['x-storage-url']
1752 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1753 $this->authSessionTimestamp
= time();
1754 } elseif ( $rcode === 401 ) {
1755 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1756 $this->authErrorTimestamp
= time();
1760 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1761 $this->authErrorTimestamp
= time();
1766 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1767 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1768 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1772 return $this->authCreds
;
1776 * @param array $creds From getAuthentication()
1777 * @param string|null $container
1778 * @param string|null $object
1781 protected function storageUrl( array $creds, $container = null, $object = null ) {
1782 $parts = [ $creds['storage_url'] ];
1783 if ( strlen( $container ) ) {
1784 $parts[] = rawurlencode( $container );
1786 if ( strlen( $object ) ) {
1787 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1790 return implode( '/', $parts );
1794 * @param array $creds From getAuthentication()
1797 protected function authTokenHeaders( array $creds ) {
1798 return [ 'x-auth-token' => $creds['auth_token'] ];
1802 * Get the cache key for a container
1804 * @param string $username
1807 private function getCredsCacheKey( $username ) {
1808 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1812 * Log an unexpected exception for this backend.
1813 * This also sets the StatusValue object to have a fatal error.
1815 * @param StatusValue|null $status
1816 * @param string $func
1817 * @param array $params
1818 * @param string $err Error string
1819 * @param int $code HTTP status
1820 * @param string $desc HTTP StatusValue description
1822 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1823 if ( $status instanceof StatusValue
) {
1824 $status->fatal( 'backend-fail-internal', $this->name
);
1826 if ( $code == 401 ) { // possibly a stale token
1827 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1829 $msg = "HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1834 'req_params' => FormatJson
::encode( $params ),
1838 $msgParams['err'] = $err;
1840 $this->logger
->error( $msg, $msgParams );