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 'content-length' => strlen( $params['content'] ),
272 'etag' => md5( $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 AtEase
::suppressWarnings();
315 $sha1Base16 = sha1_file( $params['src'] );
316 AtEase
::restoreWarnings();
317 if ( $sha1Base16 === false ) { // source doesn't exist?
318 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
323 $handle = fopen( $params['src'], 'rb' );
324 if ( $handle === false ) { // source doesn't exist?
325 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
330 // Headers that are not strictly a function of the file content
331 $mutableHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
332 // Make sure that the "content-type" header is set to something sensible
333 $mutableHeaders['content-type'] = $mutableHeaders['content-type']
334 ??
$this->getContentType( $params['dst'], null, $params['src'] );
338 'url' => [ $dstCont, $dstRel ],
339 'headers' => array_merge(
342 'content-length' => fstat( $handle )['size'],
343 'etag' => md5_file( $params['src'] ),
344 'x-object-meta-sha1base36' => Wikimedia\base_convert
( $sha1Base16, 16, 36, 31 )
347 'body' => $handle // resource
350 $method = __METHOD__
;
351 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
352 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
353 if ( $rcode === 201 ||
$rcode === 202 ) {
355 } elseif ( $rcode === 412 ) {
356 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
358 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
361 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
364 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
365 $opHandle->resourcesToClose
[] = $handle;
367 if ( !empty( $params['async'] ) ) { // deferred
368 $status->value
= $opHandle;
369 } else { // actually write the object in Swift
370 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
376 protected function doCopyInternal( array $params ) {
377 $status = $this->newStatus();
379 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
380 if ( $srcRel === null ) {
381 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
386 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
387 if ( $dstRel === null ) {
388 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
395 'url' => [ $dstCont, $dstRel ],
396 'headers' => array_merge(
397 $this->extractMutableContentHeaders( $params['headers'] ??
[] ),
399 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
400 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
405 $method = __METHOD__
;
406 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
407 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
408 if ( $rcode === 201 ) {
410 } elseif ( $rcode === 404 ) {
411 if ( empty( $params['ignoreMissingSource'] ) ) {
412 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
415 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
418 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
421 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
422 if ( !empty( $params['async'] ) ) { // deferred
423 $status->value
= $opHandle;
424 } else { // actually write the object in Swift
425 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
431 protected function doMoveInternal( array $params ) {
432 $status = $this->newStatus();
434 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
435 if ( $srcRel === null ) {
436 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
441 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
442 if ( $dstRel === null ) {
443 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
450 'url' => [ $dstCont, $dstRel ],
451 'headers' => array_merge(
452 $this->extractMutableContentHeaders( $params['headers'] ??
[] ),
454 'x-copy-from' => '/' . rawurlencode( $srcCont ) . '/' .
455 str_replace( "%2F", "/", rawurlencode( $srcRel ) )
459 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
461 'method' => 'DELETE',
462 'url' => [ $srcCont, $srcRel ],
467 $method = __METHOD__
;
468 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
469 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
470 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
472 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
474 } elseif ( $rcode === 404 ) {
475 if ( empty( $params['ignoreMissingSource'] ) ) {
476 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
478 // Leave Status as OK but skip the DELETE request
479 return SwiftFileOpHandle
::CONTINUE_NO
;
482 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
485 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
488 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
489 if ( !empty( $params['async'] ) ) { // deferred
490 $status->value
= $opHandle;
491 } else { // actually move the object in Swift
492 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
498 protected function doDeleteInternal( array $params ) {
499 $status = $this->newStatus();
501 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
502 if ( $srcRel === null ) {
503 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
509 'method' => 'DELETE',
510 'url' => [ $srcCont, $srcRel ],
514 $method = __METHOD__
;
515 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
516 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
517 if ( $rcode === 204 ) {
519 } elseif ( $rcode === 404 ) {
520 if ( empty( $params['ignoreMissingSource'] ) ) {
521 $status->fatal( 'backend-fail-delete', $params['src'] );
524 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
527 return SwiftFileOpHandle
::CONTINUE_IF_OK
;
530 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
531 if ( !empty( $params['async'] ) ) { // deferred
532 $status->value
= $opHandle;
533 } else { // actually delete the object in Swift
534 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
540 protected function doDescribeInternal( array $params ) {
541 $status = $this->newStatus();
543 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
544 if ( $srcRel === null ) {
545 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
550 // Fetch the old object headers/metadata...this should be in stat cache by now
551 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
552 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
553 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
556 $status->fatal( 'backend-fail-describe', $params['src'] );
561 // Swift object POST clears any prior headers, so merge the new and old headers here.
562 // Also, during, POST, libcurl adds "Content-Type: application/x-www-form-urlencoded"
563 // if "Content-Type" is not set, which would clobber the header value for the object.
564 $oldMetadataHeaders = [];
565 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
566 $oldMetadataHeaders["x-object-meta-$name"] = $value;
568 $newContentHeaders = $this->extractMutableContentHeaders( $params['headers'] ??
[] );
569 $oldContentHeaders = $stat['xattr']['headers'];
573 'url' => [ $srcCont, $srcRel ],
574 'headers' => $oldMetadataHeaders +
$newContentHeaders +
$oldContentHeaders
577 $method = __METHOD__
;
578 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
579 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
580 if ( $rcode === 202 ) {
582 } elseif ( $rcode === 404 ) {
583 $status->fatal( 'backend-fail-describe', $params['src'] );
585 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
589 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
590 if ( !empty( $params['async'] ) ) { // deferred
591 $status->value
= $opHandle;
592 } else { // actually change the object in Swift
593 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
599 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
600 $status = $this->newStatus();
602 // (a) Check if container already exists
603 $stat = $this->getContainerStat( $fullCont );
604 if ( is_array( $stat ) ) {
605 return $status; // already there
606 } elseif ( $stat === self
::$RES_ERROR ) {
607 $status->fatal( 'backend-fail-internal', $this->name
);
608 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
613 // (b) Create container as needed with proper ACLs
614 if ( $stat === false ) {
615 $params['op'] = 'prepare';
616 $status->merge( $this->createContainer( $fullCont, $params ) );
622 protected function doSecureInternal( $fullCont, $dir, array $params ) {
623 $status = $this->newStatus();
624 if ( empty( $params['noAccess'] ) ) {
625 return $status; // nothing to do
628 $stat = $this->getContainerStat( $fullCont );
629 if ( is_array( $stat ) ) {
630 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
631 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
632 // Make container private to end-users...
633 $status->merge( $this->setContainerAccess(
638 } elseif ( $stat === false ) {
639 $status->fatal( 'backend-fail-usable', $params['dir'] );
641 $status->fatal( 'backend-fail-internal', $this->name
);
642 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
648 protected function doPublishInternal( $fullCont, $dir, array $params ) {
649 $status = $this->newStatus();
651 $stat = $this->getContainerStat( $fullCont );
652 if ( is_array( $stat ) ) {
653 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
654 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
656 // Make container public to end-users...
657 $status->merge( $this->setContainerAccess(
662 } elseif ( $stat === false ) {
663 $status->fatal( 'backend-fail-usable', $params['dir'] );
665 $status->fatal( 'backend-fail-internal', $this->name
);
666 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
672 protected function doCleanInternal( $fullCont, $dir, array $params ) {
673 $status = $this->newStatus();
675 // Only containers themselves can be removed, all else is virtual
677 return $status; // nothing to do
680 // (a) Check the container
681 $stat = $this->getContainerStat( $fullCont, true );
682 if ( $stat === false ) {
683 return $status; // ok, nothing to do
684 } elseif ( !is_array( $stat ) ) {
685 $status->fatal( 'backend-fail-internal', $this->name
);
686 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
691 // (b) Delete the container if empty
692 if ( $stat['count'] == 0 ) {
693 $params['op'] = 'clean';
694 $status->merge( $this->deleteContainer( $fullCont, $params ) );
700 protected function doGetFileStat( array $params ) {
701 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
702 unset( $params['src'] );
703 $stats = $this->doGetFileStatMulti( $params );
705 return reset( $stats );
709 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
710 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
711 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
714 * @param int $format Output format (TS_* constant)
716 * @throws FileBackendError
718 protected function convertSwiftDate( $ts, $format = TS_MW
) {
720 $timestamp = new MWTimestamp( $ts );
722 return $timestamp->getTimestamp( $format );
723 } catch ( Exception
$e ) {
724 throw new FileBackendError( $e->getMessage() );
729 * Fill in any missing object metadata and save it to Swift
731 * @param array $objHdrs Object response headers
732 * @param string $path Storage path to object
733 * @return array New headers
735 protected function addMissingHashMetadata( array $objHdrs, $path ) {
736 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
737 return $objHdrs; // nothing to do
740 /** @noinspection PhpUnusedLocalVariableInspection */
741 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
742 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
743 [ 'path' => $path ] );
745 $objHdrs['x-object-meta-sha1base36'] = false;
747 $auth = $this->getAuthentication();
749 return $objHdrs; // failed
752 // Find prior custom HTTP headers
753 $postHeaders = $this->extractMutableContentHeaders( $objHdrs );
754 // Find prior metadata headers
755 $postHeaders +
= $this->extractMetadataHeaders( $objHdrs );
757 $status = $this->newStatus();
758 /** @noinspection PhpUnusedLocalVariableInspection */
759 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
760 if ( $status->isOK() ) {
761 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
763 $hash = $tmpFile->getSha1Base36();
764 if ( $hash !== false ) {
765 $objHdrs['x-object-meta-sha1base36'] = $hash;
766 // Merge new SHA1 header into the old ones
767 $postHeaders['x-object-meta-sha1base36'] = $hash;
768 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
769 list( $rcode ) = $this->http
->run( [
771 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
772 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
774 if ( $rcode >= 200 && $rcode <= 299 ) {
775 $this->deleteFileCache( $path );
777 return $objHdrs; // success
783 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
784 [ 'path' => $path ] );
786 return $objHdrs; // failed
789 protected function doGetFileContentsMulti( array $params ) {
790 $auth = $this->getAuthentication();
792 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
793 // Blindly create tmp files and stream to them, catching any exception
794 // if the file does not exist. Do not waste time doing file stats here.
795 $reqs = []; // (path => op)
797 // Initial dummy values to preserve path order
798 $contents = array_fill_keys( $params['srcs'], self
::$RES_ERROR );
799 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
800 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
801 if ( $srcRel === null ||
!$auth ) {
802 continue; // invalid storage path or auth error
804 // Create a new temporary memory file...
805 $handle = fopen( 'php://temp', 'wb' );
809 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
810 'headers' => $this->authTokenHeaders( $auth )
811 +
$this->headersFromParams( $params ),
817 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
818 $reqs = $this->http
->runMulti( $reqs, $opts );
819 foreach ( $reqs as $path => $op ) {
820 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
821 if ( $rcode >= 200 && $rcode <= 299 ) {
822 rewind( $op['stream'] ); // start from the beginning
823 $content = (string)stream_get_contents( $op['stream'] );
824 $size = strlen( $content );
825 // Make sure that stream finished
826 if ( $size === (int)$rhdrs['content-length'] ) {
827 $contents[$path] = $content;
829 $contents[$path] = self
::$RES_ERROR;
830 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
831 $this->onError( null, __METHOD__
,
832 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
834 } elseif ( $rcode === 404 ) {
835 $contents[$path] = self
::$RES_ABSENT;
837 $contents[$path] = self
::$RES_ERROR;
838 $this->onError( null, __METHOD__
,
839 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
841 fclose( $op['stream'] ); // close open handle
847 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
848 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
849 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
850 if ( $status->isOK() ) {
851 return ( count( $status->value
) ) > 0;
854 return self
::$RES_ERROR;
858 * @see FileBackendStore::getDirectoryListInternal()
859 * @param string $fullCont
861 * @param array $params
862 * @return SwiftFileBackendDirList
864 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
865 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
869 * @see FileBackendStore::getFileListInternal()
870 * @param string $fullCont
872 * @param array $params
873 * @return SwiftFileBackendFileList
875 public function getFileListInternal( $fullCont, $dir, array $params ) {
876 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
880 * Do not call this function outside of SwiftFileBackendFileList
882 * @param string $fullCont Resolved container name
883 * @param string $dir Resolved storage directory with no trailing slash
884 * @param string|null &$after Resolved container relative path to list items after
885 * @param int $limit Max number of items to list
886 * @param array $params Parameters for getDirectoryList()
887 * @return array List of container relative resolved paths of directories directly under $dir
888 * @throws FileBackendError
890 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
892 if ( $after === INF
) {
893 return $dirs; // nothing more
896 /** @noinspection PhpUnusedLocalVariableInspection */
897 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
899 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
900 // Non-recursive: only list dirs right under $dir
901 if ( !empty( $params['topOnly'] ) ) {
902 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
903 if ( !$status->isOK() ) {
904 throw new FileBackendError( "Iterator page I/O error." );
906 $objects = $status->value
;
907 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
908 foreach ( $objects as $object ) { // files and directories
909 if ( substr( $object, -1 ) === '/' ) {
910 $dirs[] = $object; // directories end in '/'
914 // Recursive: list all dirs under $dir and its subdirs
915 $getParentDir = function ( $path ) {
916 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
919 // Get directory from last item of prior page
920 $lastDir = $getParentDir( $after ); // must be first page
921 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
923 if ( !$status->isOK() ) {
924 throw new FileBackendError( "Iterator page I/O error." );
927 $objects = $status->value
;
929 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
930 foreach ( $objects as $object ) { // files
931 $objectDir = $getParentDir( $object ); // directory of object
933 if ( $objectDir !== false && $objectDir !== $dir ) {
934 // Swift stores paths in UTF-8, using binary sorting.
935 // See function "create_container_table" in common/db.py.
936 // If a directory is not "greater" than the last one,
937 // then it was already listed by the calling iterator.
938 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
940 do { // add dir and all its parent dirs
941 $dirs[] = "{$pDir}/";
942 $pDir = $getParentDir( $pDir );
943 } while ( $pDir !== false // sanity
944 && strcmp( $pDir, $lastDir ) > 0 // not done already
945 && strlen( $pDir ) > strlen( $dir ) // within $dir
948 $lastDir = $objectDir;
952 // Page on the unfiltered directory listing (what is returned may be filtered)
953 if ( count( $objects ) < $limit ) {
954 $after = INF
; // avoid a second RTT
956 $after = end( $objects ); // update last item
963 * Do not call this function outside of SwiftFileBackendFileList
965 * @param string $fullCont Resolved container name
966 * @param string $dir Resolved storage directory with no trailing slash
967 * @param string|null &$after Resolved container relative path of file to list items after
968 * @param int $limit Max number of items to list
969 * @param array $params Parameters for getDirectoryList()
970 * @return array List of resolved container relative paths of files under $dir
971 * @throws FileBackendError
973 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
974 $files = []; // list of (path, stat array or null) entries
975 if ( $after === INF
) {
976 return $files; // nothing more
979 /** @noinspection PhpUnusedLocalVariableInspection */
980 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
982 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
983 // $objects will contain a list of unfiltered names or stdClass items
984 // Non-recursive: only list files right under $dir
985 if ( !empty( $params['topOnly'] ) ) {
986 if ( !empty( $params['adviseStat'] ) ) {
987 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
989 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
992 // Recursive: list all files under $dir and its subdirs
993 if ( !empty( $params['adviseStat'] ) ) {
994 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
996 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
1000 // Reformat this list into a list of (name, stat array or null) entries
1001 if ( !$status->isOK() ) {
1002 throw new FileBackendError( "Iterator page I/O error." );
1005 $objects = $status->value
;
1006 $files = $this->buildFileObjectListing( $objects );
1008 // Page on the unfiltered object listing (what is returned may be filtered)
1009 if ( count( $objects ) < $limit ) {
1010 $after = INF
; // avoid a second RTT
1012 $after = end( $objects ); // update last item
1013 $after = is_object( $after ) ?
$after->name
: $after;
1020 * Build a list of file objects, filtering out any directories
1021 * and extracting any stat info if provided in $objects
1023 * @param stdClass[]|string[] $objects List of stdClass items or object names
1024 * @return array List of (names,stat array or null) entries
1026 private function buildFileObjectListing( array $objects ) {
1028 foreach ( $objects as $object ) {
1029 if ( is_object( $object ) ) {
1030 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1031 continue; // virtual directory entry; ignore
1034 // Convert various random Swift dates to TS_MW
1035 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1036 'size' => (int)$object->bytes
,
1038 // Note: manifiest ETags are not an MD5 of the file
1039 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1040 'latest' => false // eventually consistent
1042 $names[] = [ $object->name
, $stat ];
1043 } elseif ( substr( $object, -1 ) !== '/' ) {
1044 // Omit directories, which end in '/' in listings
1045 $names[] = [ $object, null ];
1053 * Do not call this function outside of SwiftFileBackendFileList
1055 * @param string $path Storage path
1056 * @param array $val Stat value
1058 public function loadListingStatInternal( $path, array $val ) {
1059 $this->cheapCache
->setField( $path, 'stat', $val );
1062 protected function doGetFileXAttributes( array $params ) {
1063 $stat = $this->getFileStat( $params );
1064 // Stat entries filled by file listings don't include metadata/headers
1065 if ( is_array( $stat ) && !isset( $stat['xattr'] ) ) {
1066 $this->clearCache( [ $params['src'] ] );
1067 $stat = $this->getFileStat( $params );
1070 if ( is_array( $stat ) ) {
1071 return $stat['xattr'];
1074 return ( $stat === self
::$RES_ERROR ) ? self
::$RES_ERROR : self
::$RES_ABSENT;
1077 protected function doGetFileSha1base36( array $params ) {
1078 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1079 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1080 $params['requireSHA1'] = true;
1082 $stat = $this->getFileStat( $params );
1083 if ( is_array( $stat ) ) {
1084 return $stat['sha1'];
1087 return ( $stat === self
::$RES_ERROR ) ? self
::$RES_ERROR : self
::$RES_ABSENT;
1090 protected function doStreamFile( array $params ) {
1091 $status = $this->newStatus();
1093 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1095 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1096 if ( $srcRel === null ) {
1097 StreamFile
::send404Message( $params['src'], $flags );
1098 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1103 $auth = $this->getAuthentication();
1104 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1105 StreamFile
::send404Message( $params['src'], $flags );
1106 $status->fatal( 'backend-fail-stream', $params['src'] );
1111 // If "headers" is set, we only want to send them if the file is there.
1112 // Do not bother checking if the file exists if headers are not set though.
1113 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1114 StreamFile
::send404Message( $params['src'], $flags );
1115 $status->fatal( 'backend-fail-stream', $params['src'] );
1120 // Send the requested additional headers
1121 foreach ( $params['headers'] as $header ) {
1122 header( $header ); // aways send
1125 if ( empty( $params['allowOB'] ) ) {
1126 // Cancel output buffering and gzipping if set
1127 ( $this->obResetFunc
)();
1130 $handle = fopen( 'php://output', 'wb' );
1131 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1133 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1134 'headers' => $this->authTokenHeaders( $auth )
1135 +
$this->headersFromParams( $params ) +
$params['options'],
1136 'stream' => $handle,
1137 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1140 if ( $rcode >= 200 && $rcode <= 299 ) {
1142 } elseif ( $rcode === 404 ) {
1143 $status->fatal( 'backend-fail-stream', $params['src'] );
1144 // Per T43113, nasty things can happen if bad cache entries get
1145 // stuck in cache. It's also possible that this error can come up
1146 // with simple race conditions. Clear out the stat cache to be safe.
1147 $this->clearCache( [ $params['src'] ] );
1148 $this->deleteFileCache( $params['src'] );
1150 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1156 protected function doGetLocalCopyMulti( array $params ) {
1157 $auth = $this->getAuthentication();
1159 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1160 // Blindly create tmp files and stream to them, catching any exception
1161 // if the file does not exist. Do not waste time doing file stats here.
1162 $reqs = []; // (path => op)
1164 // Initial dummy values to preserve path order
1165 $tmpFiles = array_fill_keys( $params['srcs'], self
::$RES_ERROR );
1166 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1167 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1168 if ( $srcRel === null ||
!$auth ) {
1169 continue; // invalid storage path or auth error
1171 // Get source file extension
1172 $ext = FileBackend
::extensionFromPath( $path );
1173 // Create a new temporary file...
1174 $tmpFile = $this->tmpFileFactory
->newTempFSFile( 'localcopy_', $ext );
1175 $handle = $tmpFile ?
fopen( $tmpFile->getPath(), 'wb' ) : false;
1179 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1180 'headers' => $this->authTokenHeaders( $auth )
1181 +
$this->headersFromParams( $params ),
1182 'stream' => $handle,
1184 $tmpFiles[$path] = $tmpFile;
1188 // Ceph RADOS Gateway is in use (strong consistency) or X-Newest will be used
1189 $latest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1191 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1192 $reqs = $this->http
->runMulti( $reqs, $opts );
1193 foreach ( $reqs as $path => $op ) {
1194 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1195 fclose( $op['stream'] ); // close open handle
1196 if ( $rcode >= 200 && $rcode <= 299 ) {
1197 /** @var TempFSFile $tmpFile */
1198 $tmpFile = $tmpFiles[$path];
1199 // Make sure that the stream finished and fully wrote to disk
1200 $size = $tmpFile->getSize();
1201 if ( $size !== (int)$rhdrs['content-length'] ) {
1202 $tmpFiles[$path] = self
::$RES_ERROR;
1203 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1204 $this->onError( null, __METHOD__
,
1205 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1207 // Set the file stat process cache in passing
1208 $stat = $this->getStatFromHeaders( $rhdrs );
1209 $stat['latest'] = $latest;
1210 $this->cheapCache
->setField( $path, 'stat', $stat );
1211 } elseif ( $rcode === 404 ) {
1212 $tmpFiles[$path] = self
::$RES_ABSENT;
1213 $this->cheapCache
->setField(
1216 $latest ? self
::$ABSENT_LATEST : self
::$ABSENT_NORMAL
1219 $tmpFiles[$path] = self
::$RES_ERROR;
1220 $this->onError( null, __METHOD__
,
1221 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1228 public function getFileHttpUrl( array $params ) {
1229 if ( $this->swiftTempUrlKey
!= '' ||
1230 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1232 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1233 if ( $srcRel === null ) {
1234 return self
::TEMPURL_ERROR
; // invalid path
1237 $auth = $this->getAuthentication();
1239 return self
::TEMPURL_ERROR
;
1242 $ttl = $params['ttl'] ??
86400;
1243 $expires = time() +
$ttl;
1245 if ( $this->swiftTempUrlKey
!= '' ) {
1246 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1247 // Swift wants the signature based on the unencoded object name
1248 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1249 $signature = hash_hmac( 'sha1',
1250 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1251 $this->swiftTempUrlKey
1254 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1255 } else { // give S3 API URL for rgw
1256 // Path for signature starts with the bucket
1257 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1258 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1259 // Calculate the hash
1260 $signature = base64_encode( hash_hmac(
1262 "GET\n\n\n{$expires}\n{$spath}",
1263 $this->rgwS3SecretKey
,
1266 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1267 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1268 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1269 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1272 'Signature' => $signature,
1273 'Expires' => $expires,
1274 'AWSAccessKeyId' => $this->rgwS3AccessKey
1279 return self
::TEMPURL_ERROR
;
1282 protected function directoriesAreVirtual() {
1287 * Get headers to send to Swift when reading a file based
1288 * on a FileBackend params array, e.g. that of getLocalCopy().
1289 * $params is currently only checked for a 'latest' flag.
1291 * @param array $params
1294 protected function headersFromParams( array $params ) {
1296 if ( !empty( $params['latest'] ) ) {
1297 $hdrs['x-newest'] = 'true';
1303 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1304 /** @var StatusValue[] $statuses */
1307 $auth = $this->getAuthentication();
1309 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1310 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1316 // Split the HTTP requests into stages that can be done concurrently
1317 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1318 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1319 /** @var SwiftFileOpHandle $fileOpHandle */
1320 $reqs = $fileOpHandle->httpOp
;
1321 // Convert the 'url' parameter to an actual URL using $auth
1322 foreach ( $reqs as $stage => &$req ) {
1323 list( $container, $relPath ) = $req['url'];
1324 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1325 $req['headers'] = $req['headers'] ??
[];
1326 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1327 $httpReqsByStage[$stage][$index] = $req;
1329 $statuses[$index] = $this->newStatus();
1332 // Run all requests for the first stage, then the next, and so on
1333 $reqCount = count( $httpReqsByStage );
1334 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1335 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1336 foreach ( $httpReqs as $index => $httpReq ) {
1337 /** @var SwiftFileOpHandle $fileOpHandle */
1338 $fileOpHandle = $fileOpHandles[$index];
1339 // Run the callback for each request of this operation
1340 $status = $statuses[$index];
1341 ( $fileOpHandle->callback
)( $httpReq, $status );
1342 // On failure, abort all remaining requests for this operation. This is used
1343 // in "move" operations to abort the DELETE request if the PUT request fails.
1346 $fileOpHandle->state
=== $fileOpHandle::CONTINUE_NO
1348 $stages = count( $fileOpHandle->httpOp
);
1349 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1350 unset( $httpReqsByStage[$s][$index] );
1360 * Set read/write permissions for a Swift container.
1362 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1364 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1365 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1367 * @param string $container Resolved Swift container
1368 * @param array $readUsers List of the possible criteria for a request to have
1369 * access to read a container. Each item is one of the following formats:
1370 * - account:user : Grants access if the request is by the given user
1371 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1372 * matches the expression and the request is not for a listing.
1373 * Setting this to '*' effectively makes a container public.
1374 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1375 * matches the expression and the request is for a listing.
1376 * @param array $writeUsers A list of the possible criteria for a request to have
1377 * access to write to a container. Each item is of the following format:
1378 * - account:user : Grants access if the request is by the given user
1379 * @return StatusValue
1381 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1382 $status = $this->newStatus();
1383 $auth = $this->getAuthentication();
1386 $status->fatal( 'backend-fail-connect', $this->name
);
1391 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1393 'url' => $this->storageUrl( $auth, $container ),
1394 'headers' => $this->authTokenHeaders( $auth ) +
[
1395 'x-container-read' => implode( ',', $readUsers ),
1396 'x-container-write' => implode( ',', $writeUsers )
1400 if ( $rcode != 204 && $rcode !== 202 ) {
1401 $status->fatal( 'backend-fail-internal', $this->name
);
1402 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1403 [ 'rcode' => $rcode ] );
1410 * Get a Swift container stat array, possibly from process cache.
1411 * Use $reCache if the file count or byte count is needed.
1413 * @param string $container Container name
1414 * @param bool $bypassCache Bypass all caches and load from Swift
1415 * @return array|bool|null False on 404, null on failure
1417 protected function getContainerStat( $container, $bypassCache = false ) {
1418 /** @noinspection PhpUnusedLocalVariableInspection */
1419 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1421 if ( $bypassCache ) { // purge cache
1422 $this->containerStatCache
->clear( $container );
1423 } elseif ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1424 $this->primeContainerCache( [ $container ] ); // check persistent cache
1426 if ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1427 $auth = $this->getAuthentication();
1429 return self
::$RES_ERROR;
1432 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1434 'url' => $this->storageUrl( $auth, $container ),
1435 'headers' => $this->authTokenHeaders( $auth )
1438 if ( $rcode === 204 ) {
1440 'count' => $rhdrs['x-container-object-count'],
1441 'bytes' => $rhdrs['x-container-bytes-used']
1443 if ( $bypassCache ) {
1446 $this->containerStatCache
->setField( $container, 'stat', $stat ); // cache it
1447 $this->setContainerCache( $container, $stat ); // update persistent cache
1449 } elseif ( $rcode === 404 ) {
1450 return self
::$RES_ABSENT;
1452 $this->onError( null, __METHOD__
,
1453 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1455 return self
::$RES_ERROR;
1459 return $this->containerStatCache
->getField( $container, 'stat' );
1463 * Create a Swift container
1465 * @param string $container Container name
1466 * @param array $params
1467 * @return StatusValue
1469 protected function createContainer( $container, array $params ) {
1470 $status = $this->newStatus();
1472 $auth = $this->getAuthentication();
1474 $status->fatal( 'backend-fail-connect', $this->name
);
1479 // @see SwiftFileBackend::setContainerAccess()
1480 if ( empty( $params['noAccess'] ) ) {
1482 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] );
1483 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
1486 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
1487 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
1490 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1492 'url' => $this->storageUrl( $auth, $container ),
1493 'headers' => $this->authTokenHeaders( $auth ) +
[
1494 'x-container-read' => implode( ',', $readUsers ),
1495 'x-container-write' => implode( ',', $writeUsers )
1499 if ( $rcode === 201 ) { // new
1501 } elseif ( $rcode === 202 ) { // already there
1502 // this shouldn't really happen, but is OK
1504 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1511 * Delete a Swift container
1513 * @param string $container Container name
1514 * @param array $params
1515 * @return StatusValue
1517 protected function deleteContainer( $container, array $params ) {
1518 $status = $this->newStatus();
1520 $auth = $this->getAuthentication();
1522 $status->fatal( 'backend-fail-connect', $this->name
);
1527 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1528 'method' => 'DELETE',
1529 'url' => $this->storageUrl( $auth, $container ),
1530 'headers' => $this->authTokenHeaders( $auth )
1533 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1534 $this->containerStatCache
->clear( $container ); // purge
1535 } elseif ( $rcode === 404 ) { // not there
1536 // this shouldn't really happen, but is OK
1537 } elseif ( $rcode === 409 ) { // not empty
1538 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1540 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1547 * Get a list of objects under a container.
1548 * Either just the names or a list of stdClass objects with details can be returned.
1550 * @param string $fullCont
1551 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1553 * @param string|null $after
1554 * @param string|null $prefix
1555 * @param string|null $delim
1556 * @return StatusValue With the list as value
1558 private function objectListing(
1559 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1561 $status = $this->newStatus();
1563 $auth = $this->getAuthentication();
1565 $status->fatal( 'backend-fail-connect', $this->name
);
1570 $query = [ 'limit' => $limit ];
1571 if ( $type === 'info' ) {
1572 $query['format'] = 'json';
1574 if ( $after !== null ) {
1575 $query['marker'] = $after;
1577 if ( $prefix !== null ) {
1578 $query['prefix'] = $prefix;
1580 if ( $delim !== null ) {
1581 $query['delimiter'] = $delim;
1584 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1586 'url' => $this->storageUrl( $auth, $fullCont ),
1588 'headers' => $this->authTokenHeaders( $auth )
1591 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1592 if ( $rcode === 200 ) { // good
1593 if ( $type === 'info' ) {
1594 $status->value
= FormatJson
::decode( trim( $rbody ) );
1596 $status->value
= explode( "\n", trim( $rbody ) );
1598 } elseif ( $rcode === 204 ) {
1599 $status->value
= []; // empty container
1600 } elseif ( $rcode === 404 ) {
1601 $status->value
= []; // no container
1603 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1609 protected function doPrimeContainerCache( array $containerInfo ) {
1610 foreach ( $containerInfo as $container => $info ) {
1611 $this->containerStatCache
->setField( $container, 'stat', $info );
1615 protected function doGetFileStatMulti( array $params ) {
1618 $auth = $this->getAuthentication();
1620 $reqs = []; // (path => op)
1621 // (a) Check the containers of the paths...
1622 foreach ( $params['srcs'] as $path ) {
1623 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1624 if ( $srcRel === null ||
!$auth ) {
1625 $stats[$path] = self
::$RES_ERROR;
1626 continue; // invalid storage path or auth error
1629 $cstat = $this->getContainerStat( $srcCont );
1630 if ( $cstat === self
::$RES_ABSENT ) {
1631 $stats[$path] = self
::$RES_ABSENT;
1632 continue; // ok, nothing to do
1633 } elseif ( !is_array( $cstat ) ) {
1634 $stats[$path] = self
::$RES_ERROR;
1640 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1641 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1645 // (b) Check the files themselves...
1646 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1647 $reqs = $this->http
->runMulti( $reqs, $opts );
1648 foreach ( $reqs as $path => $op ) {
1649 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1650 if ( $rcode === 200 ||
$rcode === 204 ) {
1651 // Update the object if it is missing some headers
1652 if ( !empty( $params['requireSHA1'] ) ) {
1653 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1655 // Load the stat array from the headers
1656 $stat = $this->getStatFromHeaders( $rhdrs );
1657 if ( $this->isRGW
) {
1658 $stat['latest'] = true; // strong consistency
1660 } elseif ( $rcode === 404 ) {
1661 $stat = self
::$RES_ABSENT;
1663 $stat = self
::$RES_ERROR;
1664 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1666 $stats[$path] = $stat;
1673 * @param array $rhdrs
1676 protected function getStatFromHeaders( array $rhdrs ) {
1677 // Fetch all of the custom metadata headers
1678 $metadata = $this->getMetadataFromHeaders( $rhdrs );
1679 // Fetch all of the custom raw HTTP headers
1680 $headers = $this->extractMutableContentHeaders( $rhdrs );
1683 // Convert various random Swift dates to TS_MW
1684 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1685 // Empty objects actually return no content-length header in Ceph
1686 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1687 'sha1' => $metadata['sha1base36'] ??
null,
1688 // Note: manifiest ETags are not an MD5 of the file
1689 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1690 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1695 * @return array|null Credential map
1697 protected function getAuthentication() {
1698 if ( $this->authErrorTimestamp
!== null ) {
1699 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1700 return null; // failed last attempt; don't bother
1701 } else { // actually retry this time
1702 $this->authErrorTimestamp
= null;
1705 // Session keys expire after a while, so we renew them periodically
1706 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1707 // Authenticate with proxy and get a session key...
1708 if ( !$this->authCreds ||
$reAuth ) {
1709 $this->authSessionTimestamp
= 0;
1710 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1711 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1712 // Try to use the credential cache
1713 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1714 $this->authCreds
= $creds;
1715 // Skew the timestamp for worst case to avoid using stale credentials
1716 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1717 } else { // cache miss
1718 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1720 'url' => "{$this->swiftAuthUrl}/v1.0",
1722 'x-auth-user' => $this->swiftUser
,
1723 'x-auth-key' => $this->swiftKey
1727 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1728 $this->authCreds
= [
1729 'auth_token' => $rhdrs['x-auth-token'],
1730 'storage_url' => $this->swiftStorageUrl ??
$rhdrs['x-storage-url']
1733 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1734 $this->authSessionTimestamp
= time();
1735 } elseif ( $rcode === 401 ) {
1736 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1737 $this->authErrorTimestamp
= time();
1741 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1742 $this->authErrorTimestamp
= time();
1747 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1748 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1749 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1753 return $this->authCreds
;
1757 * @param array $creds From getAuthentication()
1758 * @param string|null $container
1759 * @param string|null $object
1762 protected function storageUrl( array $creds, $container = null, $object = null ) {
1763 $parts = [ $creds['storage_url'] ];
1764 if ( strlen( $container ) ) {
1765 $parts[] = rawurlencode( $container );
1767 if ( strlen( $object ) ) {
1768 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1771 return implode( '/', $parts );
1775 * @param array $creds From getAuthentication()
1778 protected function authTokenHeaders( array $creds ) {
1779 return [ 'x-auth-token' => $creds['auth_token'] ];
1783 * Get the cache key for a container
1785 * @param string $username
1788 private function getCredsCacheKey( $username ) {
1789 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1793 * Log an unexpected exception for this backend.
1794 * This also sets the StatusValue object to have a fatal error.
1796 * @param StatusValue|null $status
1797 * @param string $func
1798 * @param array $params
1799 * @param string $err Error string
1800 * @param int $code HTTP status
1801 * @param string $desc HTTP StatusValue description
1803 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1804 if ( $status instanceof StatusValue
) {
1805 $status->fatal( 'backend-fail-internal', $this->name
);
1807 if ( $code == 401 ) { // possibly a stale token
1808 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1810 $msg = "HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1815 'req_params' => FormatJson
::encode( $params ),
1819 $msgParams['err'] = $err;
1821 $this->logger
->error( $msg, $msgParams );