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 namespace Wikimedia\FileBackend
;
30 use Psr\Log\LoggerInterface
;
31 use Shellbox\Command\BoxedCommand
;
34 use Wikimedia\AtEase\AtEase
;
35 use Wikimedia\FileBackend\FileIteration\SwiftFileBackendDirList
;
36 use Wikimedia\FileBackend\FileIteration\SwiftFileBackendFileList
;
37 use Wikimedia\FileBackend\FileOpHandle\SwiftFileOpHandle
;
38 use Wikimedia\Http\MultiHttpClient
;
39 use Wikimedia\ObjectCache\BagOStuff
;
40 use Wikimedia\ObjectCache\EmptyBagOStuff
;
41 use Wikimedia\ObjectCache\WANObjectCache
;
42 use Wikimedia\RequestTimeout\TimeoutException
;
43 use Wikimedia\Timestamp\ConvertibleTimestamp
;
46 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
48 * StatusValue messages should avoid mentioning the Swift account name.
49 * Likewise, error suppression should be used to avoid path disclosure.
51 * @ingroup FileBackend
54 class SwiftFileBackend
extends FileBackendStore
{
55 private const DEFAULT_HTTP_OPTIONS
= [ 'httpVersion' => 'v1.1' ];
56 private const AUTH_FAILURE_ERROR
= 'Could not connect due to prior authentication failure';
58 /** @var MultiHttpClient */
60 /** @var int TTL in seconds */
62 /** @var string Authentication base URL (without version) */
63 protected $swiftAuthUrl;
64 /** @var string Override of storage base URL */
65 protected $swiftStorageUrl;
66 /** @var string Swift user (account:user) to authenticate as */
68 /** @var string Secret key for user */
70 /** @var string Shared secret value for making temp URLs */
71 protected $swiftTempUrlKey;
73 protected $canShellboxGetTempUrl;
74 /** @var string|null */
75 protected $shellboxIpRange;
76 /** @var string S3 access key (RADOS Gateway) */
77 protected $rgwS3AccessKey;
78 /** @var string S3 authentication key (RADOS Gateway) */
79 protected $rgwS3SecretKey;
80 /** @var array Additional users (account:user) with read permissions on public containers */
82 /** @var array Additional users (account:user) with write permissions on public containers */
83 protected $writeUsers;
84 /** @var array Additional users (account:user) with read permissions on private containers */
85 protected $secureReadUsers;
86 /** @var array Additional users (account:user) with write permissions on private containers */
87 protected $secureWriteUsers;
92 /** @var MapCacheLRU Container stat cache */
93 protected $containerStatCache;
95 /** @var array|null */
97 /** @var int|null UNIX timestamp */
98 protected $authErrorTimestamp = null;
100 /** @var bool Whether the server is an Ceph RGW */
101 protected $isRGW = false;
104 * @see FileBackendStore::__construct()
105 * @param array $config Params include:
106 * - swiftAuthUrl : Swift authentication server URL
107 * - swiftUser : Swift user used by MediaWiki (account:username)
108 * - swiftKey : Swift authentication key for the above user
109 * - swiftAuthTTL : Swift authentication TTL (seconds)
110 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
111 * Do not set this until it has been set in the backend.
112 * - canShellboxGetTempUrl : Set this to true to generate a TempURL allowing Shellbox to
113 * directly fetch files from Swift. swiftTempUrlKey should be set.
114 * - shellboxIpRange : An IP range string to use when generating TempURLs for Shellbox.
115 * Specifying this will improve security by preventing exfiltrated
116 * TempURLs from being usable outside the server.
117 * - swiftStorageUrl : Swift storage URL (overrides that of the authentication response).
118 * This is useful to set if a TLS proxy is in use.
119 * - shardViaHashLevels : Map of container names to sharding config with:
120 * - base : base of hash characters, 16 or 36
121 * - levels : the number of hash levels (and digits)
122 * - repeat : hash subdirectories are prefixed with all the
123 * parent hash directory names (e.g. "a/ab/abc")
124 * - cacheAuthInfo : Whether to cache authentication tokens in APC, etc.
125 * If those are not available, then the main cache will be used.
126 * This is probably insecure in shared hosting environments.
127 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
128 * Do not set this until it has been set in the backend.
129 * This is used for generating expiring pre-authenticated URLs.
130 * Only use this when using rgw and to work around
131 * http://tracker.newdream.net/issues/3454.
132 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
133 * Do not set this until it has been set in the backend.
134 * This is used for generating expiring pre-authenticated URLs.
135 * Only use this when using rgw and to work around
136 * http://tracker.newdream.net/issues/3454.
137 * - readUsers : Swift users with read access to public containers (account:username)
138 * - writeUsers : Swift users with write access to public containers (account:username)
139 * - secureReadUsers : Swift users with read access to private containers (account:username)
140 * - secureWriteUsers : Swift users with write access to private containers (account:username)
141 * - connTimeout : The HTTP connect timeout to use when connecting to Swift, in
143 * - reqTimeout : The HTTP request timeout to use when communicating with Swift, in
146 public function __construct( array $config ) {
147 parent
::__construct( $config );
149 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
150 $this->swiftUser
= $config['swiftUser'];
151 $this->swiftKey
= $config['swiftKey'];
153 $this->authTTL
= $config['swiftAuthTTL'] ??
15 * 60; // some sensible number
154 $this->swiftTempUrlKey
= $config['swiftTempUrlKey'] ??
'';
155 $this->canShellboxGetTempUrl
= $config['canShellboxGetTempUrl'] ??
false;
156 $this->shellboxIpRange
= $config['shellboxIpRange'] ??
null;
157 $this->swiftStorageUrl
= $config['swiftStorageUrl'] ??
null;
158 $this->shardViaHashLevels
= $config['shardViaHashLevels'] ??
'';
159 $this->rgwS3AccessKey
= $config['rgwS3AccessKey'] ??
'';
160 $this->rgwS3SecretKey
= $config['rgwS3SecretKey'] ??
'';
162 // HTTP helper client
164 foreach ( [ 'connTimeout', 'reqTimeout' ] as $optionName ) {
165 if ( isset( $config[$optionName] ) ) {
166 $httpOptions[$optionName] = $config[$optionName];
169 $this->http
= new MultiHttpClient( $httpOptions );
170 $this->http
->setLogger( $this->logger
);
172 // Cache container information to mask latency
173 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
174 $this->memCache
= $config['wanCache'];
176 // Process cache for container info
177 $this->containerStatCache
= new MapCacheLRU( 300 );
178 // Cache auth token information to avoid RTTs
179 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
180 $this->srvCache
= $config['srvCache'];
182 $this->srvCache
= new EmptyBagOStuff();
184 $this->readUsers
= $config['readUsers'] ??
[];
185 $this->writeUsers
= $config['writeUsers'] ??
[];
186 $this->secureReadUsers
= $config['secureReadUsers'] ??
[];
187 $this->secureWriteUsers
= $config['secureWriteUsers'] ??
[];
188 // Per https://docs.openstack.org/swift/latest/overview_large_objects.html
189 // we need to split objects if they are larger than 5 GB. Support for
190 // splitting objects has not yet been implemented by this class
191 // so limit max file size to 5GiB.
192 $this->maxFileSize
= 5 * 1024 * 1024 * 1024;
195 public function setLogger( LoggerInterface
$logger ) {
196 parent
::setLogger( $logger );
197 $this->http
->setLogger( $logger );
200 public function getFeatures() {
202 self
::ATTR_UNICODE_PATHS |
208 protected function resolveContainerPath( $container, $relStoragePath ) {
209 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
210 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
211 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
212 return null; // too long for Swift
215 return $relStoragePath;
218 public function isPathUsableInternal( $storagePath ) {
219 [ $container, $rel ] = $this->resolveStoragePathReal( $storagePath );
220 if ( $rel === null ) {
221 return false; // invalid
224 return is_array( $this->getContainerStat( $container ) );
228 * Filter/normalize a header map to only include mutable "content-"/"x-content-" headers
230 * Mutable headers can be changed via HTTP POST even if the file content is the same
232 * @see https://docs.openstack.org/api-ref/object-store
233 * @param string[] $headers Map of (header => value) for a swift object
234 * @return string[] Map of (header => value) for Content-* headers mutable via POST
236 protected function extractMutableContentHeaders( array $headers ) {
237 $contentHeaders = [];
238 // Normalize casing, and strip out illegal headers
239 foreach ( $headers as $name => $value ) {
240 $name = strtolower( $name );
241 if ( $name === 'x-delete-at' && is_numeric( $value ) ) {
242 // Expects a Unix Epoch date
243 $contentHeaders[$name] = $value;
244 } elseif ( $name === 'x-delete-after' && is_numeric( $value ) ) {
245 // Expects number of minutes time to live.
246 $contentHeaders[$name] = $value;
247 } elseif ( preg_match( '/^(x-)?content-(?!length$)/', $name ) ) {
248 // Only allow content-* and x-content-* headers (but not content-length)
249 $contentHeaders[$name] = $value;
250 } elseif ( $name === 'content-type' && strlen( $value ) ) {
251 // This header can be set to a value but not unset
252 $contentHeaders[$name] = $value;
255 // By default, Swift has annoyingly low maximum header value limits
256 if ( isset( $contentHeaders['content-disposition'] ) ) {
258 // @note: assume FileBackend::makeContentDisposition() already used
259 $offset = $maxLength - strlen( $contentHeaders['content-disposition'] );
261 $pos = strrpos( $contentHeaders['content-disposition'], ';', $offset );
262 $contentHeaders['content-disposition'] = $pos === false
264 : trim( substr( $contentHeaders['content-disposition'], 0, $pos ) );
268 return $contentHeaders;
272 * @see https://docs.openstack.org/api-ref/object-store
273 * @param string[] $headers Map of (header => value) for a swift object
274 * @return string[] Map of (metadata header name => metadata value)
276 protected function extractMetadataHeaders( array $headers ) {
277 $metadataHeaders = [];
278 foreach ( $headers as $name => $value ) {
279 $name = strtolower( $name );
280 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
281 $metadataHeaders[$name] = $value;
285 return $metadataHeaders;
289 * @see https://docs.openstack.org/api-ref/object-store
290 * @param string[] $headers Map of (header => value) for a swift object
291 * @return string[] Map of (metadata key name => metadata value)
293 protected function getMetadataFromHeaders( array $headers ) {
294 $prefixLen = strlen( 'x-object-meta-' );
297 foreach ( $this->extractMetadataHeaders( $headers ) as $name => $value ) {
298 $metadata[substr( $name, $prefixLen )] = $value;
304 protected function doCreateInternal( array $params ) {
305 $status = $this->newStatus();
307 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
308 if ( $dstRel === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
314 // Headers that are not strictly a function of the file content
315 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
316 // Make sure that the "content-type" header is set to something sensible
317 $mutableHeaders['content-type']
318 ??
= $this->getContentType( $params['dst'], $params['content'], null );
322 'container' => $dstCont,
323 'relPath' => $dstRel,
324 'headers' => array_merge(
327 'etag' => md5( $params['content'] ),
328 'content-length' => strlen( $params['content'] ),
329 'x-object-meta-sha1base36' =>
330 \Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 )
333 'body' => $params['content']
336 $method = __METHOD__
;
337 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
338 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
339 if ( $rcode === 201 ||
$rcode === 202 ) {
341 } elseif ( $rcode === 412 ) {
342 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
344 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
347 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
350 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
351 if ( !empty( $params['async'] ) ) { // deferred
352 $status->value
= $opHandle;
353 } else { // actually write the object in Swift
354 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
360 protected function doStoreInternal( array $params ) {
361 $status = $this->newStatus();
363 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
364 if ( $dstRel === null ) {
365 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
370 // Open a handle to the source file so that it can be streamed. The size and hash
371 // will be computed using the handle. In the off chance that the source file changes
372 // during this operation, the PUT will fail due to an ETag mismatch and be aborted.
373 AtEase
::suppressWarnings();
374 $srcHandle = fopen( $params['src'], 'rb' );
375 AtEase
::restoreWarnings();
376 if ( $srcHandle === false ) { // source doesn't exist?
377 $status->fatal( 'backend-fail-notexists', $params['src'] );
382 // Compute the MD5 and SHA-1 hashes in one pass
383 $srcSize = fstat( $srcHandle )['size'];
384 $md5Context = hash_init( 'md5' );
385 $sha1Context = hash_init( 'sha1' );
387 while ( !feof( $srcHandle ) ) {
388 $buffer = (string)fread( $srcHandle, 131_072
); // 128 KiB
389 hash_update( $md5Context, $buffer );
390 hash_update( $sha1Context, $buffer );
391 $hashDigestSize +
= strlen( $buffer );
393 // Reset the handle back to the beginning so that it can be streamed
394 rewind( $srcHandle );
396 if ( $hashDigestSize !== $srcSize ) {
397 $status->fatal( 'backend-fail-hash', $params['src'] );
402 // Headers that are not strictly a function of the file content
403 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
404 // Make sure that the "content-type" header is set to something sensible
405 $mutableHeaders['content-type']
406 ??
= $this->getContentType( $params['dst'], null, $params['src'] );
410 'container' => $dstCont,
411 'relPath' => $dstRel,
412 'headers' => array_merge(
415 'content-length' => $srcSize,
416 'etag' => hash_final( $md5Context ),
417 'x-object-meta-sha1base36' =>
418 \Wikimedia\base_convert
( hash_final( $sha1Context ), 16, 36, 31 )
421 'body' => $srcHandle // resource
424 $method = __METHOD__
;
425 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
426 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
427 if ( $rcode === 201 ||
$rcode === 202 ) {
429 } elseif ( $rcode === 412 ) {
430 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
432 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
435 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
438 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
439 $opHandle->resourcesToClose
[] = $srcHandle;
441 if ( !empty( $params['async'] ) ) { // deferred
442 $status->value
= $opHandle;
443 } else { // actually write the object in Swift
444 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
450 protected function doCopyInternal( array $params ) {
451 $status = $this->newStatus();
453 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
454 if ( $srcRel === null ) {
455 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
460 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
461 if ( $dstRel === null ) {
462 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
469 'container' => $dstCont,
470 'relPath' => $dstRel,
471 'headers' => array_merge(
472 $this->extractMutableContentHeaders( $params['headers'] ??
[] ),
474 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
475 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
480 $method = __METHOD__
;
481 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
482 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
483 if ( $rcode === 201 ) {
485 } elseif ( $rcode === 404 ) {
486 if ( empty( $params['ignoreMissingSource'] ) ) {
487 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
490 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
493 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
496 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
497 if ( !empty( $params['async'] ) ) { // deferred
498 $status->value
= $opHandle;
499 } else { // actually write the object in Swift
500 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
506 protected function doMoveInternal( array $params ) {
507 $status = $this->newStatus();
509 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
510 if ( $srcRel === null ) {
511 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
516 [ $dstCont, $dstRel ] = $this->resolveStoragePathReal( $params['dst'] );
517 if ( $dstRel === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
525 'container' => $dstCont,
526 'relPath' => $dstRel,
527 'headers' => array_merge(
528 $this->extractMutableContentHeaders( $params['headers'] ??
[] ),
530 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
531 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
535 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
537 'method' => 'DELETE',
538 'container' => $srcCont,
539 'relPath' => $srcRel,
544 $method = __METHOD__
;
545 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
546 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
547 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
549 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
551 } elseif ( $rcode === 404 ) {
552 if ( empty( $params['ignoreMissingSource'] ) ) {
553 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
555 // Leave Status as OK but skip the DELETE request
556 return SwiftFileOpHandle
::CONTINUE_NO
;
559 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
562 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
565 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
566 if ( !empty( $params['async'] ) ) { // deferred
567 $status->value
= $opHandle;
568 } else { // actually move the object in Swift
569 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
575 protected function doDeleteInternal( array $params ) {
576 $status = $this->newStatus();
578 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
579 if ( $srcRel === null ) {
580 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
586 'method' => 'DELETE',
587 'container' => $srcCont,
588 'relPath' => $srcRel,
592 $method = __METHOD__
;
593 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
594 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
595 if ( $rcode === 204 ) {
597 } elseif ( $rcode === 404 ) {
598 if ( empty( $params['ignoreMissingSource'] ) ) {
599 $status->fatal( 'backend-fail-delete', $params['src'] );
602 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
605 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
608 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
609 if ( !empty( $params['async'] ) ) { // deferred
610 $status->value
= $opHandle;
611 } else { // actually delete the object in Swift
612 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
618 protected function doDescribeInternal( array $params ) {
619 $status = $this->newStatus();
621 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
622 if ( $srcRel === null ) {
623 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
628 // Fetch the old object headers/metadata...this should be in stat cache by now
629 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
630 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
631 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
634 $status->fatal( 'backend-fail-describe', $params['src'] );
639 // Swift object POST clears any prior headers, so merge the new and old headers here.
640 // Also, during, POST, libcurl adds "Content-Type: application/x-www-form-urlencoded"
641 // if "Content-Type" is not set, which would clobber the header value for the object.
642 $oldMetadataHeaders = [];
643 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
644 $oldMetadataHeaders["x-object-meta-$name"] = $value;
646 $newContentHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
647 $oldContentHeaders = $stat['xattr']['headers'];
651 'container' => $srcCont,
652 'relPath' => $srcRel,
653 'headers' => $oldMetadataHeaders +
$newContentHeaders +
$oldContentHeaders
656 $method = __METHOD__
;
657 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
658 [ $rcode, $rdesc, , $rbody, $rerr ] = $request['response'];
659 if ( $rcode === 202 ) {
661 } elseif ( $rcode === 404 ) {
662 $status->fatal( 'backend-fail-describe', $params['src'] );
664 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc, $rbody );
668 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
669 if ( !empty( $params['async'] ) ) { // deferred
670 $status->value
= $opHandle;
671 } else { // actually change the object in Swift
672 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
681 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
682 $status = $this->newStatus();
684 // (a) Check if container already exists
685 $stat = $this->getContainerStat( $fullCont );
686 if ( is_array( $stat ) ) {
687 return $status; // already there
688 } elseif ( $stat === self
::RES_ERROR
) {
689 $status->fatal( 'backend-fail-internal', $this->name
);
690 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
692 // (b) Create container as needed with proper ACLs
693 $params['op'] = 'prepare';
694 $status->merge( $this->createContainer( $fullCont, $params ) );
700 protected function doSecureInternal( $fullCont, $dir, array $params ) {
701 $status = $this->newStatus();
702 if ( empty( $params['noAccess'] ) ) {
703 return $status; // nothing to do
706 $stat = $this->getContainerStat( $fullCont );
707 if ( is_array( $stat ) ) {
708 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
709 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
710 // Make container private to end-users...
711 $status->merge( $this->setContainerAccess(
716 } elseif ( $stat === self
::RES_ABSENT
) {
717 $status->fatal( 'backend-fail-usable', $params['dir'] );
719 $status->fatal( 'backend-fail-internal', $this->name
);
720 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
726 protected function doPublishInternal( $fullCont, $dir, array $params ) {
727 $status = $this->newStatus();
728 if ( empty( $params['access'] ) ) {
729 return $status; // nothing to do
732 $stat = $this->getContainerStat( $fullCont );
733 if ( is_array( $stat ) ) {
734 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
735 if ( !empty( $params['listing'] ) ) {
736 array_push( $readUsers, '.rlistings' );
738 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
740 // Make container public to end-users...
741 $status->merge( $this->setContainerAccess(
746 } elseif ( $stat === self
::RES_ABSENT
) {
747 $status->fatal( 'backend-fail-usable', $params['dir'] );
749 $status->fatal( 'backend-fail-internal', $this->name
);
750 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
756 protected function doCleanInternal( $fullCont, $dir, array $params ) {
757 $status = $this->newStatus();
759 // Only containers themselves can be removed, all else is virtual
761 return $status; // nothing to do
764 // (a) Check the container
765 $stat = $this->getContainerStat( $fullCont, true );
766 if ( $stat === self
::RES_ABSENT
) {
767 return $status; // ok, nothing to do
768 } elseif ( $stat === self
::RES_ERROR
) {
769 $status->fatal( 'backend-fail-internal', $this->name
);
770 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
771 } elseif ( is_array( $stat ) && $stat['count'] == 0 ) {
772 // (b) Delete the container if empty
773 $params['op'] = 'clean';
774 $status->merge( $this->deleteContainer( $fullCont, $params ) );
780 protected function doGetFileStat( array $params ) {
781 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
782 unset( $params['src'] );
783 $stats = $this->doGetFileStatMulti( $params );
785 return reset( $stats );
789 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
790 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
791 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
794 * @param int $format Output format (TS_* constant)
796 * @throws FileBackendError
798 protected function convertSwiftDate( $ts, $format = TS_MW
) {
800 $timestamp = new ConvertibleTimestamp( $ts );
802 return $timestamp->getTimestamp( $format );
803 } catch ( TimeoutException
$e ) {
805 } catch ( Exception
$e ) {
806 throw new FileBackendError( $e->getMessage() );
811 * Fill in any missing object metadata and save it to Swift
813 * @param array $objHdrs Object response headers
814 * @param string $path Storage path to object
815 * @return array New headers
817 protected function addMissingHashMetadata( array $objHdrs, $path ) {
818 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
819 return $objHdrs; // nothing to do
822 /** @noinspection PhpUnusedLocalVariableInspection */
823 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
824 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
825 [ 'path' => $path ] );
827 $objHdrs['x-object-meta-sha1base36'] = false;
829 // Find prior custom HTTP headers
830 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
831 // Find prior metadata headers
832 $postHeaders +
= $this->extractMetadataHeaders( $objHdrs );
834 $status = $this->newStatus();
835 /** @noinspection PhpUnusedLocalVariableInspection */
836 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
837 if ( $status->isOK() ) {
838 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
840 $hash = $tmpFile->getSha1Base36();
841 if ( $hash !== false ) {
842 $objHdrs['x-object-meta-sha1base36'] = $hash;
843 // Merge new SHA1 header into the old ones
844 $postHeaders['x-object-meta-sha1base36'] = $hash;
845 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
846 [ $rcode ] = $this->requestWithAuth( [
848 'container' => $srcCont,
849 'relPath' => $srcRel,
850 'headers' => $postHeaders
852 if ( $rcode >= 200 && $rcode <= 299 ) {
853 $this->deleteFileCache( $path );
855 return $objHdrs; // success
861 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
862 [ 'path' => $path ] );
864 return $objHdrs; // failed
867 protected function doGetFileContentsMulti( array $params ) {
868 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
869 // Blindly create tmp files and stream to them, catching any exception
870 // if the file does not exist. Do not waste time doing file stats here.
871 $reqs = []; // (path => op)
873 // Initial dummy values to preserve path order
874 $contents = array_fill_keys( $params['srcs'], self
::RES_ERROR
);
875 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
876 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
877 if ( $srcRel === null ) {
878 continue; // invalid storage path
880 // Create a new temporary memory file...
881 $handle = fopen( 'php://temp', 'wb' );
885 'container' => $srcCont,
886 'relPath' => $srcRel,
887 'headers' => $this->headersFromParams( $params ),
893 $reqs = $this->requestMultiWithAuth(
895 [ 'maxConnsPerHost' => $params['concurrency'] ]
897 foreach ( $reqs as $path => $op ) {
898 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
899 if ( $rcode >= 200 && $rcode <= 299 ) {
900 rewind( $op['stream'] ); // start from the beginning
901 $content = (string)stream_get_contents( $op['stream'] );
902 $size = strlen( $content );
903 // Make sure that stream finished
904 if ( $size === (int)$rhdrs['content-length'] ) {
905 $contents[$path] = $content;
907 $contents[$path] = self
::RES_ERROR
;
908 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
909 $this->onError( null, __METHOD__
,
910 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
912 } elseif ( $rcode === 404 ) {
913 $contents[$path] = self
::RES_ABSENT
;
915 $contents[$path] = self
::RES_ERROR
;
916 $this->onError( null, __METHOD__
,
917 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc, $rbody );
919 fclose( $op['stream'] ); // close open handle
925 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
926 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
927 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
928 if ( $status->isOK() ) {
929 return ( count( $status->value
) ) > 0;
932 return self
::RES_ERROR
;
936 * @see FileBackendStore::getDirectoryListInternal()
937 * @param string $fullCont
939 * @param array $params
940 * @return SwiftFileBackendDirList
942 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
943 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
947 * @see FileBackendStore::getFileListInternal()
948 * @param string $fullCont
950 * @param array $params
951 * @return SwiftFileBackendFileList
953 public function getFileListInternal( $fullCont, $dir, array $params ) {
954 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
958 * Do not call this function outside of SwiftFileBackendFileList
960 * @param string $fullCont Resolved container name
961 * @param string $dir Resolved storage directory with no trailing slash
962 * @param string|null &$after Resolved container relative path used for continuation paging
963 * @param int $limit Max number of items to list
964 * @param array $params Parameters for {@link getDirectoryList()}
965 * @return string[] List of resolved container relative directories directly under $dir
966 * @throws FileBackendError
968 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
970 if ( $after === INF
) {
971 return $dirs; // nothing more
974 /** @noinspection PhpUnusedLocalVariableInspection */
975 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
977 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
978 // Non-recursive: only list dirs right under $dir
979 if ( !empty( $params['topOnly'] ) ) {
980 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
981 if ( !$status->isOK() ) {
982 throw new FileBackendError( "Iterator page I/O error." );
984 $objects = $status->value
;
985 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
986 foreach ( $objects as $object ) { // files and directories
987 if ( substr( $object, -1 ) === '/' ) {
988 $dirs[] = $object; // directories end in '/'
992 // Recursive: list all dirs under $dir and its subdirs
993 $getParentDir = static function ( $path ) {
994 return ( $path !== null && strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
997 // Get directory from last item of prior page
998 $lastDir = $getParentDir( $after ); // must be first page
999 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
1001 if ( !$status->isOK() ) {
1002 throw new FileBackendError( "Iterator page I/O error." );
1005 $objects = $status->value
;
1007 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
1008 foreach ( $objects as $object ) { // files
1009 $objectDir = $getParentDir( $object ); // directory of object
1011 if ( $objectDir !== false && $objectDir !== $dir ) {
1012 // Swift stores paths in UTF-8, using binary sorting.
1013 // See function "create_container_table" in common/db.py.
1014 // If a directory is not "greater" than the last one,
1015 // then it was already listed by the calling iterator.
1016 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1018 do { // add dir and all its parent dirs
1019 $dirs[] = "{$pDir}/";
1020 $pDir = $getParentDir( $pDir );
1021 } while ( $pDir !== false
1022 && strcmp( $pDir, $lastDir ) > 0 // not done already
1023 && strlen( $pDir ) > strlen( $dir ) // within $dir
1026 $lastDir = $objectDir;
1030 // Page on the unfiltered directory listing (what is returned may be filtered)
1031 if ( count( $objects ) < $limit ) {
1032 $after = INF
; // avoid a second RTT
1034 $after = end( $objects ); // update last item
1041 * Do not call this function outside of SwiftFileBackendFileList
1043 * @param string $fullCont Resolved container name
1044 * @param string $dir Resolved storage directory with no trailing slash
1045 * @param string|null &$after Resolved container relative path of file to list items after
1046 * @param int $limit Max number of items to list
1047 * @param array $params Parameters for {@link getFileList()}
1048 * @return array[] List of (name, stat map or null) tuples under $dir
1049 * @throws FileBackendError
1051 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1052 $files = []; // list of (path, stat map or null) entries
1053 if ( $after === INF
) {
1054 return $files; // nothing more
1057 /** @noinspection PhpUnusedLocalVariableInspection */
1058 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1060 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
1061 // $objects will contain a list of unfiltered names or stdClass items
1062 // Non-recursive: only list files right under $dir
1063 if ( !empty( $params['topOnly'] ) ) {
1064 if ( !empty( $params['adviseStat'] ) ) {
1065 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
1067 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
1070 // Recursive: list all files under $dir and its subdirs
1071 if ( !empty( $params['adviseStat'] ) ) {
1072 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
1074 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
1078 // Reformat this list into a list of (name, stat map or null) entries
1079 if ( !$status->isOK() ) {
1080 throw new FileBackendError( "Iterator page I/O error." );
1083 $objects = $status->value
;
1084 $files = $this->buildFileObjectListing( $objects );
1086 // Page on the unfiltered object listing (what is returned may be filtered)
1087 if ( count( $objects ) < $limit ) {
1088 $after = INF
; // avoid a second RTT
1090 $after = end( $objects ); // update last item
1091 $after = is_object( $after ) ?
$after->name
: $after;
1098 * Build a list of file objects, filtering out any directories
1099 * and extracting any stat info if provided in $objects
1101 * @param stdClass[]|string[] $objects List of stdClass items or object names
1102 * @return array[] List of (name, stat map or null) entries
1104 private function buildFileObjectListing( array $objects ) {
1106 foreach ( $objects as $object ) {
1107 if ( is_object( $object ) ) {
1108 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1109 continue; // virtual directory entry; ignore
1112 // Convert various random Swift dates to TS_MW
1113 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1114 'size' => (int)$object->bytes
,
1116 // Note: manifest ETags are not an MD5 of the file
1117 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1118 'latest' => false // eventually consistent
1120 $names[] = [ $object->name
, $stat ];
1121 } elseif ( substr( $object, -1 ) !== '/' ) {
1122 // Omit directories, which end in '/' in listings
1123 $names[] = [ $object, null ];
1131 * Do not call this function outside of SwiftFileBackendFileList
1133 * @param string $path Storage path
1134 * @param array $val Stat value
1136 public function loadListingStatInternal( $path, array $val ) {
1137 $this->cheapCache
->setField( $path, 'stat', $val );
1140 protected function doGetFileXAttributes( array $params ) {
1141 $stat = $this->getFileStat( $params );
1142 // Stat entries filled by file listings don't include metadata/headers
1143 if ( is_array( $stat ) && !isset( $stat['xattr'] ) ) {
1144 $this->clearCache( [ $params['src'] ] );
1145 $stat = $this->getFileStat( $params );
1148 if ( is_array( $stat ) ) {
1149 return $stat['xattr'];
1152 return $stat === self
::RES_ERROR ? self
::RES_ERROR
: self
::RES_ABSENT
;
1155 protected function doGetFileSha1base36( array $params ) {
1156 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1157 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1158 $params['requireSHA1'] = true;
1160 $stat = $this->getFileStat( $params );
1161 if ( is_array( $stat ) ) {
1162 return $stat['sha1'];
1165 return $stat === self
::RES_ERROR ? self
::RES_ERROR
: self
::RES_ABSENT
;
1168 protected function doStreamFile( array $params ) {
1169 $status = $this->newStatus();
1171 $flags = !empty( $params['headless'] ) ? HTTPFileStreamer
::STREAM_HEADLESS
: 0;
1173 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
1174 if ( $srcRel === null ) {
1175 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1176 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1181 if ( !is_array( $this->getContainerStat( $srcCont ) ) ) {
1182 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1183 $status->fatal( 'backend-fail-stream', $params['src'] );
1188 // If "headers" is set, we only want to send them if the file is there.
1189 // Do not bother checking if the file exists if headers are not set though.
1190 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1191 HTTPFileStreamer
::send404Message( $params['src'], $flags );
1192 $status->fatal( 'backend-fail-stream', $params['src'] );
1197 // Send the requested additional headers
1198 if ( empty( $params['headless'] ) ) {
1199 foreach ( $params['headers'] as $header ) {
1200 $this->header( $header );
1204 if ( empty( $params['allowOB'] ) ) {
1205 // Cancel output buffering and gzipping if set
1206 $this->resetOutputBuffer();
1209 $handle = fopen( 'php://output', 'wb' );
1210 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1212 'container' => $srcCont,
1213 'relPath' => $srcRel,
1214 'headers' => $this->headersFromParams( $params ) +
$params['options'],
1215 'stream' => $handle,
1216 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1219 if ( $rcode >= 200 && $rcode <= 299 ) {
1221 } elseif ( $rcode === 404 ) {
1222 $status->fatal( 'backend-fail-stream', $params['src'] );
1223 // Per T43113, nasty things can happen if bad cache entries get
1224 // stuck in cache. It's also possible that this error can come up
1225 // with simple race conditions. Clear out the stat cache to be safe.
1226 $this->clearCache( [ $params['src'] ] );
1227 $this->deleteFileCache( $params['src'] );
1229 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc, $rbody );
1235 protected function doGetLocalCopyMulti( array $params ) {
1236 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1237 // Blindly create tmp files and stream to them, catching any exception
1238 // if the file does not exist. Do not waste time doing file stats here.
1239 $reqs = []; // (path => op)
1241 // Initial dummy values to preserve path order
1242 $tmpFiles = array_fill_keys( $params['srcs'], self
::RES_ERROR
);
1243 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1244 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
1245 if ( $srcRel === null ) {
1246 continue; // invalid storage path
1248 // Get source file extension
1249 $ext = FileBackend
::extensionFromPath( $path );
1250 // Create a new temporary file...
1251 $tmpFile = $this->tmpFileFactory
->newTempFSFile( 'localcopy_', $ext );
1252 $handle = $tmpFile ?
fopen( $tmpFile->getPath(), 'wb' ) : false;
1256 'container' => $srcCont,
1257 'relPath' => $srcRel,
1258 'headers' => $this->headersFromParams( $params ),
1259 'stream' => $handle,
1261 $tmpFiles[$path] = $tmpFile;
1265 // Ceph RADOS Gateway is in use (strong consistency) or X-Newest will be used
1266 $latest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1268 $reqs = $this->requestMultiWithAuth(
1270 [ 'maxConnsPerHost' => $params['concurrency'] ]
1272 foreach ( $reqs as $path => $op ) {
1273 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
1274 fclose( $op['stream'] ); // close open handle
1275 if ( $rcode >= 200 && $rcode <= 299 ) {
1276 /** @var TempFSFile $tmpFile */
1277 $tmpFile = $tmpFiles[$path];
1278 // Make sure that the stream finished and fully wrote to disk
1279 $size = $tmpFile->getSize();
1280 if ( $size !== (int)$rhdrs['content-length'] ) {
1281 $tmpFiles[$path] = self
::RES_ERROR
;
1282 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1283 $this->onError( null, __METHOD__
,
1284 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1286 // Set the file stat process cache in passing
1287 $stat = $this->getStatFromHeaders( $rhdrs );
1288 $stat['latest'] = $latest;
1289 $this->cheapCache
->setField( $path, 'stat', $stat );
1290 } elseif ( $rcode === 404 ) {
1291 $tmpFiles[$path] = self
::RES_ABSENT
;
1292 $this->cheapCache
->setField(
1295 $latest ? self
::ABSENT_LATEST
: self
::ABSENT_NORMAL
1298 $tmpFiles[$path] = self
::RES_ERROR
;
1299 $this->onError( null, __METHOD__
,
1300 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc, $rbody );
1307 public function addShellboxInputFile( BoxedCommand
$command, string $boxedName,
1310 if ( $this->canShellboxGetTempUrl
) {
1311 $urlParams = [ 'src' => $params['src'] ];
1312 if ( $this->shellboxIpRange
!== null ) {
1313 $urlParams['ipRange'] = $this->shellboxIpRange
;
1315 $url = $this->getFileHttpUrl( $urlParams );
1317 $command->inputFileFromUrl( $boxedName, $url );
1318 return $this->newStatus();
1321 return parent
::addShellboxInputFile( $command, $boxedName, $params );
1324 public function getFileHttpUrl( array $params ) {
1325 if ( $this->swiftTempUrlKey
== '' &&
1326 ( $this->rgwS3AccessKey
== '' ||
$this->rgwS3SecretKey
!= '' )
1328 $this->logger
->debug( "Can't get Swift file URL: no key available" );
1329 return self
::TEMPURL_ERROR
;
1332 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $params['src'] );
1333 if ( $srcRel === null ) {
1334 $this->logger
->debug( "Can't get Swift file URL: can't resolve path" );
1335 return self
::TEMPURL_ERROR
; // invalid path
1338 $auth = $this->getAuthentication();
1340 $this->logger
->debug( "Can't get Swift file URL: authentication failed" );
1341 return self
::TEMPURL_ERROR
;
1344 $method = $params['method'] ??
'GET';
1345 $ttl = $params['ttl'] ??
86400;
1346 $expires = time() +
$ttl;
1348 if ( $this->swiftTempUrlKey
!= '' ) {
1349 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1350 // Swift wants the signature based on the unencoded object name
1351 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1355 "{$contPath}/{$srcRel}"
1358 'temp_url_expires' => $expires,
1360 if ( isset( $params['ipRange'] ) ) {
1361 array_unshift( $messageParts, "ip={$params['ipRange']}" );
1362 $query['temp_url_ip_range'] = $params['ipRange'];
1365 $signature = hash_hmac( 'sha1',
1366 implode( "\n", $messageParts ),
1367 $this->swiftTempUrlKey
1369 $query = [ 'temp_url_sig' => $signature ] +
$query;
1371 return $url . '?' . http_build_query( $query );
1372 } else { // give S3 API URL for rgw
1373 // Path for signature starts with the bucket
1374 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1375 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1376 // Calculate the hash
1377 $signature = base64_encode( hash_hmac(
1379 "{$method}\n\n\n{$expires}\n{$spath}",
1380 $this->rgwS3SecretKey
,
1383 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1384 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1385 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1386 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1389 'Signature' => $signature,
1390 'Expires' => $expires,
1391 'AWSAccessKeyId' => $this->rgwS3AccessKey
1396 protected function directoriesAreVirtual() {
1401 * Get headers to send to Swift when reading a file based
1402 * on a FileBackend params array, e.g. that of getLocalCopy().
1403 * $params is currently only checked for a 'latest' flag.
1405 * @param array $params
1408 protected function headersFromParams( array $params ) {
1410 if ( !empty( $params['latest'] ) ) {
1411 $hdrs['x-newest'] = 'true';
1417 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1418 /** @var SwiftFileOpHandle[] $fileOpHandles */
1419 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1421 /** @var StatusValue[] $statuses */
1424 // Split the HTTP requests into stages that can be done concurrently
1425 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1426 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1427 $reqs = $fileOpHandle->httpOp
;
1428 foreach ( $reqs as $stage => $req ) {
1429 $httpReqsByStage[$stage][$index] = $req;
1431 $statuses[$index] = $this->newStatus();
1434 // Run all requests for the first stage, then the next, and so on
1435 $reqCount = count( $httpReqsByStage );
1436 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1437 $httpReqs = $this->requestMultiWithAuth( $httpReqsByStage[$stage] );
1438 foreach ( $httpReqs as $index => $httpReq ) {
1439 /** @var SwiftFileOpHandle $fileOpHandle */
1440 $fileOpHandle = $fileOpHandles[$index];
1441 // Run the callback for each request of this operation
1442 $status = $statuses[$index];
1443 ( $fileOpHandle->callback
)( $httpReq, $status );
1444 // On failure, abort all remaining requests for this operation. This is used
1445 // in "move" operations to abort the DELETE request if the PUT request fails.
1448 $fileOpHandle->state
=== $fileOpHandle::CONTINUE_NO
1450 $stages = count( $fileOpHandle->httpOp
);
1451 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1452 unset( $httpReqsByStage[$s][$index] );
1462 * Set read/write permissions for a Swift container.
1464 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1466 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1467 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1469 * @param string $container Resolved Swift container
1470 * @param array $readUsers List of the possible criteria for a request to have
1471 * access to read a container. Each item is one of the following formats:
1472 * - account:user : Grants access if the request is by the given user
1473 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1474 * matches the expression and the request is not for a listing.
1475 * Setting this to '*' effectively makes a container public.
1476 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1477 * matches the expression and the request is for a listing.
1478 * @param array $writeUsers A list of the possible criteria for a request to have
1479 * access to write to a container. Each item is of the following format:
1480 * - account:user : Grants access if the request is by the given user
1481 * @return StatusValue Good status without value for success, fatal otherwise.
1483 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1484 $status = $this->newStatus();
1486 [ $rcode, , , , ] = $this->requestWithAuth( [
1488 'container' => $container,
1490 'x-container-read' => implode( ',', $readUsers ),
1491 'x-container-write' => implode( ',', $writeUsers )
1495 if ( $rcode != 204 && $rcode !== 202 ) {
1496 $status->fatal( 'backend-fail-internal', $this->name
);
1497 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1498 [ 'rcode' => $rcode ] );
1505 * Get a Swift container stat map, possibly from process cache.
1506 * Use $reCache if the file count or byte count is needed.
1508 * @param string $container Container name
1509 * @param bool $bypassCache Bypass all caches and load from Swift
1510 * @return array|false|null False on 404, null on failure
1512 protected function getContainerStat( $container, $bypassCache = false ) {
1513 /** @noinspection PhpUnusedLocalVariableInspection */
1514 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1516 if ( $bypassCache ) { // purge cache
1517 $this->containerStatCache
->clear( $container );
1518 } elseif ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1519 $this->primeContainerCache( [ $container ] ); // check persistent cache
1521 if ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1522 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $this->requestWithAuth( [
1524 'container' => $container
1527 if ( $rcode === 204 ) {
1529 'count' => $rhdrs['x-container-object-count'],
1530 'bytes' => $rhdrs['x-container-bytes-used']
1532 if ( $bypassCache ) {
1535 $this->containerStatCache
->setField( $container, 'stat', $stat ); // cache it
1536 $this->setContainerCache( $container, $stat ); // update persistent cache
1538 } elseif ( $rcode === 404 ) {
1539 return self
::RES_ABSENT
;
1541 $this->onError( null, __METHOD__
,
1542 [ 'cont' => $container ], $rerr, $rcode, $rdesc, $rbody );
1544 return self
::RES_ERROR
;
1548 return $this->containerStatCache
->getField( $container, 'stat' );
1552 * Create a Swift container
1554 * @param string $container Container name
1555 * @param array $params
1556 * @return StatusValue Good status without value for success, fatal otherwise.
1558 protected function createContainer( $container, array $params ) {
1559 $status = $this->newStatus();
1561 // @see SwiftFileBackend::setContainerAccess()
1562 if ( empty( $params['noAccess'] ) ) {
1564 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] );
1565 if ( empty( $params['noListing'] ) ) {
1566 array_push( $readUsers, '.rlistings' );
1568 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
1571 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
1572 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
1575 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1577 'container' => $container,
1579 'x-container-read' => implode( ',', $readUsers ),
1580 'x-container-write' => implode( ',', $writeUsers )
1584 if ( $rcode === 201 ) { // new
1586 } elseif ( $rcode === 202 ) { // already there
1587 // this shouldn't really happen, but is OK
1589 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc, $rbody );
1596 * Delete a Swift container
1598 * @param string $container Container name
1599 * @param array $params
1600 * @return StatusValue
1602 protected function deleteContainer( $container, array $params ) {
1603 $status = $this->newStatus();
1605 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1606 'method' => 'DELETE',
1607 'container' => $container
1610 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1611 $this->containerStatCache
->clear( $container ); // purge
1612 } elseif ( $rcode === 404 ) { // not there
1613 // this shouldn't really happen, but is OK
1614 } elseif ( $rcode === 409 ) { // not empty
1615 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1617 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc, $rbody );
1624 * Get a list of objects under a container.
1625 * Either just the names or a list of stdClass objects with details can be returned.
1627 * @param string $fullCont
1628 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1630 * @param string|null $after
1631 * @param string|null $prefix
1632 * @param string|null $delim
1633 * @return StatusValue With the list as value
1635 private function objectListing(
1636 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1638 $status = $this->newStatus();
1640 $query = [ 'limit' => $limit ];
1641 if ( $type === 'info' ) {
1642 $query['format'] = 'json';
1644 if ( $after !== null ) {
1645 $query['marker'] = $after;
1647 if ( $prefix !== null ) {
1648 $query['prefix'] = $prefix;
1650 if ( $delim !== null ) {
1651 $query['delimiter'] = $delim;
1654 [ $rcode, $rdesc, , $rbody, $rerr ] = $this->requestWithAuth( [
1656 'container' => $fullCont,
1660 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1661 if ( $rcode === 200 ) { // good
1662 if ( $type === 'info' ) {
1663 $status->value
= json_decode( trim( $rbody ) );
1665 $status->value
= explode( "\n", trim( $rbody ) );
1667 } elseif ( $rcode === 204 ) {
1668 $status->value
= []; // empty container
1669 } elseif ( $rcode === 404 ) {
1670 $status->value
= []; // no container
1672 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc, $rbody );
1678 protected function doPrimeContainerCache( array $containerInfo ) {
1679 foreach ( $containerInfo as $container => $info ) {
1680 $this->containerStatCache
->setField( $container, 'stat', $info );
1684 protected function doGetFileStatMulti( array $params ) {
1687 $reqs = []; // (path => op)
1688 // (a) Check the containers of the paths...
1689 foreach ( $params['srcs'] as $path ) {
1690 [ $srcCont, $srcRel ] = $this->resolveStoragePathReal( $path );
1691 if ( $srcRel === null ) {
1692 // invalid storage path
1693 $stats[$path] = self
::RES_ERROR
;
1697 $cstat = $this->getContainerStat( $srcCont );
1698 if ( $cstat === self
::RES_ABSENT
) {
1699 $stats[$path] = self
::RES_ABSENT
;
1700 continue; // ok, nothing to do
1701 } elseif ( $cstat === self
::RES_ERROR
) {
1702 $stats[$path] = self
::RES_ERROR
;
1708 'container' => $srcCont,
1709 'relPath' => $srcRel,
1710 'headers' => $this->headersFromParams( $params )
1714 // (b) Check the files themselves...
1715 $reqs = $this->requestMultiWithAuth(
1717 [ 'maxConnsPerHost' => $params['concurrency'] ]
1719 foreach ( $reqs as $path => $op ) {
1720 [ $rcode, $rdesc, $rhdrs, $rbody, $rerr ] = $op['response'];
1721 if ( $rcode === 200 ||
$rcode === 204 ) {
1722 // Update the object if it is missing some headers
1723 if ( !empty( $params['requireSHA1'] ) ) {
1724 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1726 // Load the stat map from the headers
1727 $stat = $this->getStatFromHeaders( $rhdrs );
1728 if ( $this->isRGW
) {
1729 $stat['latest'] = true; // strong consistency
1731 } elseif ( $rcode === 404 ) {
1732 $stat = self
::RES_ABSENT
;
1734 $stat = self
::RES_ERROR
;
1735 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc, $rbody );
1737 $stats[$path] = $stat;
1744 * @param array $rhdrs
1747 protected function getStatFromHeaders( array $rhdrs ) {
1748 // Fetch all of the custom metadata headers
1749 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1750 // Fetch all of the custom raw HTTP headers
1751 $headers = $this->extractMutableContentHeaders( $rhdrs );
1754 // Convert various random Swift dates to TS_MW
1755 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1756 // Empty objects actually return no content-length header in Ceph
1757 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1758 'sha1' => $metadata['sha1base36'] ??
null,
1759 // Note: manifest ETags are not an MD5 of the file
1760 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1761 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1766 * Get the cached auth token.
1768 * @return array|null Credential map
1770 protected function getAuthentication() {
1771 if ( $this->authErrorTimestamp
!== null ) {
1772 $interval = time() - $this->authErrorTimestamp
;
1773 if ( $interval < 60 ) {
1774 $this->logger
->debug(
1775 'rejecting request since auth failure occurred {interval} seconds ago',
1776 [ 'interval' => $interval ]
1779 } else { // actually retry this time
1780 $this->authErrorTimestamp
= null;
1783 // Authenticate with proxy and get a session key...
1784 if ( !$this->authCreds
) {
1785 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1786 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1787 // Try to use the credential cache
1788 if ( isset( $creds['auth_token'] )
1789 && isset( $creds['storage_url'] )
1790 && isset( $creds['expiry_time'] )
1791 && $creds['expiry_time'] > time()
1793 $this->setAuthCreds( $creds );
1794 } else { // cache miss
1795 $this->refreshAuthentication();
1799 return $this->authCreds
;
1803 * Update the auth credentials
1805 * @param array|null $creds
1807 private function setAuthCreds( ?
array $creds ) {
1808 $this->logger
->debug( 'Using auth token with expiry_time={expiry_time}',
1810 'expiry_time' => isset( $creds['expiry_time'] )
1811 ?
gmdate( 'c', $creds['expiry_time'] ) : 'null'
1814 $this->authCreds
= $creds;
1815 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1816 if ( $creds && str_ends_with( $creds['storage_url'], '/v1' ) ) {
1817 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1822 * Fetch the auth token from the server, without caching.
1824 * @return array|null Credential map
1826 private function refreshAuthentication() {
1827 [ $rcode, , $rhdrs, $rbody, ] = $this->http
->run( [
1829 'url' => "{$this->swiftAuthUrl}/v1.0",
1831 'x-auth-user' => $this->swiftUser
,
1832 'x-auth-key' => $this->swiftKey
1834 ], self
::DEFAULT_HTTP_OPTIONS
);
1836 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1837 if ( isset( $rhdrs['x-auth-token-expires'] ) ) {
1838 $ttl = intval( $rhdrs['x-auth-token-expires'] );
1840 $ttl = $this->authTTL
;
1842 $expiryTime = time() +
$ttl;
1844 'auth_token' => $rhdrs['x-auth-token'],
1845 'storage_url' => $this->swiftStorageUrl ??
$rhdrs['x-storage-url'],
1846 'expiry_time' => $expiryTime,
1848 $this->srvCache
->set( $this->getCredsCacheKey( $this->swiftUser
), $creds, $expiryTime );
1849 } elseif ( $rcode === 401 ) {
1850 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1851 $this->authErrorTimestamp
= time();
1854 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode, $rbody );
1855 $this->authErrorTimestamp
= time();
1858 $this->setAuthCreds( $creds );
1863 * @param array $creds From getAuthentication()
1864 * @param string|null $container
1865 * @param string|null $object
1868 protected function storageUrl( array $creds, $container = null, $object = null ) {
1869 $parts = [ $creds['storage_url'] ];
1870 if ( strlen( $container ??
'' ) ) {
1871 $parts[] = rawurlencode( $container );
1873 if ( strlen( $object ??
'' ) ) {
1874 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1877 return implode( '/', $parts );
1881 * @param array $creds From getAuthentication()
1884 protected function authTokenHeaders( array $creds ) {
1885 return [ 'x-auth-token' => $creds['auth_token'] ];
1889 * Get the cache key for a container
1891 * @param string $username
1894 private function getCredsCacheKey( $username ) {
1895 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1899 * Perform an authenticated HTTP request
1901 * @param array $req The request data, including:
1902 * - container: The name of the container (required)
1903 * - relPath: The relative path under the container. If this is omitted,
1904 * the request will refer to the container itself.
1905 * - headers: An array of request headers to send, in addition to the
1907 * - Other keys to be passed through to MultiHttpClient::run()
1908 * @param array $options Options to pass through to MultiHttpClient, in
1909 * addition to the default options DEFAULT_HTTP_OPTIONS
1910 * @return array The response array from MultiHttpClient::run()
1912 private function requestWithAuth( array $req, array $options = [] ) {
1913 return $this->requestMultiWithAuth( [ $req ], $options )[0]['response'];
1917 * Perform a batch of authenticated HTTP requests
1919 * @param array $reqs An array of request data arrays. See self::requestWithAuth()
1920 * @param array $options Options to pass through to MultiHttpClient, in
1921 * addition to the default options DEFAULT_HTTP_OPTIONS
1922 * @return array The request array with responses populated, as returned by
1923 * MultiHttpClient::runMulti()
1925 private function requestMultiWithAuth( array $reqs, $options = [] ) {
1926 $remainingTries = 2;
1927 $auth = $this->getAuthentication();
1930 foreach ( $reqs as &$req ) {
1931 if ( !isset( $req['response'] ) ) {
1932 $req['response'] = $this->getAuthFailureResponse();
1937 foreach ( $reqs as &$req ) {
1938 '@phan-var array $req'; // Not array[]
1939 if ( isset( $req['response'] ) ) {
1940 // Request was attempted before
1941 // Retry only if it gave a 401 response code
1942 if ( $req['response']['code'] !== 401 ) {
1946 $req['headers'] = $this->authTokenHeaders( $auth ) +
( $req['headers'] ??
[] );
1947 $req['url'] = $this->storageUrl( $auth, $req['container'], $req['relPath'] ??
null );
1950 $reqs = $this->http
->runMulti( $reqs, $options + self
::DEFAULT_HTTP_OPTIONS
);
1951 if ( --$remainingTries > 0 ) {
1952 // Retry if any request failed with 401 "not authorized"
1953 foreach ( $reqs as $req ) {
1954 if ( $req['response']['code'] === 401 ) {
1955 $auth = $this->refreshAuthentication();
1966 * Get a synthetic response to return from requestWithAuth() or requestMultiWithAuth()
1967 * if the request could not be issued due to failure of a prior authentication request.
1968 * This failure should not be logged as an HTTP error since the original failure would
1973 private function getAuthFailureResponse() {
1983 'error' => self
::AUTH_FAILURE_ERROR
,
1984 4 => self
::AUTH_FAILURE_ERROR
1989 * Determine whether an HTTP response was generated by getAuthFailureResponse()
1992 * @param string $error
1995 private function isAuthFailureResponse( $code, $error ) {
1996 return $code === 0 && $error === self
::AUTH_FAILURE_ERROR
;
2000 * Log an unexpected exception for this backend.
2001 * This also sets the StatusValue object to have a fatal error.
2003 * @param StatusValue|null $status To add fatal errors to
2004 * @param string $func
2005 * @param array $params
2006 * @param string $err Error string
2007 * @param int $code HTTP status
2008 * @param string $desc HTTP StatusValue description
2009 * @param string $body HTTP body
2011 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '', $body = '' ) {
2012 if ( $this->isAuthFailureResponse( $code, $err ) ) {
2013 if ( $status instanceof StatusValue
) {
2014 $status->fatal( 'backend-fail-connect', $this->name
);
2019 if ( $status instanceof StatusValue
) {
2020 $status->fatal( 'backend-fail-internal', $this->name
);
2022 $msg = "HTTP {code} ({desc}) in '{func}'";
2027 'req_params' => $params,
2031 $msgParams['err'] = $err;
2033 if ( $code == 502 ) {
2034 $msg .= ' ({truncatedBody})';
2035 $msgParams['truncatedBody'] = substr( strip_tags( $body ), 0, 100 );
2037 $this->logger
->error( $msg, $msgParams );
2041 /** @deprecated class alias since 1.43 */
2042 class_alias( SwiftFileBackend
::class, 'SwiftFileBackend' );