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 * Sanitize and filter the custom headers from a $params array.
176 * Only allows certain "standard" Content- and X-Content- headers.
178 * @param array $params
179 * @return array Sanitized value of 'headers' field in $params
181 protected function sanitizeHdrsStrict( array $params ) {
182 if ( !isset( $params['headers'] ) ) {
186 $headers = $this->getCustomHeaders( $params['headers'] );
187 unset( $headers[ 'content-type' ] );
193 * Sanitize and filter the custom headers from a $params array.
194 * Only allows certain "standard" Content- and X-Content- headers.
196 * When POSTing data, libcurl adds Content-Type: application/x-www-form-urlencoded
197 * if Content-Type is not set, which overwrites the stored Content-Type header
198 * in Swift - therefore for POSTing data do not strip the Content-Type header (the
199 * previously-stored header that has been already read back from swift is sent)
201 * @param array $params
202 * @return array Sanitized value of 'headers' field in $params
204 protected function sanitizeHdrs( array $params ) {
205 return isset( $params['headers'] )
206 ?
$this->getCustomHeaders( $params['headers'] )
211 * @param array $rawHeaders
212 * @return array Custom non-metadata HTTP headers
214 protected function getCustomHeaders( array $rawHeaders ) {
217 // Normalize casing, and strip out illegal headers
218 foreach ( $rawHeaders as $name => $value ) {
219 $name = strtolower( $name );
220 if ( preg_match( '/^content-length$/', $name ) ) {
221 continue; // blacklisted
222 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
223 $headers[$name] = $value; // allowed
224 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
225 $headers[$name] = $value; // allowed
228 // By default, Swift has annoyingly low maximum header value limits
229 if ( isset( $headers['content-disposition'] ) ) {
231 // @note: assume FileBackend::makeContentDisposition() already used
232 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
233 $part = trim( $part );
234 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
235 if ( strlen( $new ) <= 255 ) {
238 break; // too long; sigh
241 $headers['content-disposition'] = $disposition;
248 * @param array $rawHeaders
249 * @return array Custom metadata headers
251 protected function getMetadataHeaders( array $rawHeaders ) {
253 foreach ( $rawHeaders as $name => $value ) {
254 $name = strtolower( $name );
255 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
256 $headers[$name] = $value;
264 * @param array $rawHeaders
265 * @return array Custom metadata headers with prefix removed
267 protected function getMetadata( array $rawHeaders ) {
269 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
270 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
276 protected function doCreateInternal( array $params ) {
277 $status = $this->newStatus();
279 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
280 if ( $dstRel === null ) {
281 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
286 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
287 $contentType = $params['headers']['content-type']
288 ??
$this->getContentType( $params['dst'], $params['content'], null );
292 'url' => [ $dstCont, $dstRel ],
294 'content-length' => strlen( $params['content'] ),
295 'etag' => md5( $params['content'] ),
296 'content-type' => $contentType,
297 'x-object-meta-sha1base36' => $sha1Hash
298 ] +
$this->sanitizeHdrsStrict( $params ),
299 'body' => $params['content']
302 $method = __METHOD__
;
303 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
304 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
305 if ( $rcode === 201 ||
$rcode === 202 ) {
307 } elseif ( $rcode === 412 ) {
308 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
310 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
314 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
315 if ( !empty( $params['async'] ) ) { // deferred
316 $status->value
= $opHandle;
317 } else { // actually write the object in Swift
318 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
324 protected function doStoreInternal( array $params ) {
325 $status = $this->newStatus();
327 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
328 if ( $dstRel === null ) {
329 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
334 AtEase
::suppressWarnings();
335 $sha1Hash = sha1_file( $params['src'] );
336 AtEase
::restoreWarnings();
337 if ( $sha1Hash === false ) { // source doesn't exist?
338 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
342 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
343 $contentType = $params['headers']['content-type']
344 ??
$this->getContentType( $params['dst'], null, $params['src'] );
346 $handle = fopen( $params['src'], 'rb' );
347 if ( $handle === false ) { // source doesn't exist?
348 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
355 'url' => [ $dstCont, $dstRel ],
357 'content-length' => filesize( $params['src'] ),
358 'etag' => md5_file( $params['src'] ),
359 'content-type' => $contentType,
360 'x-object-meta-sha1base36' => $sha1Hash
361 ] +
$this->sanitizeHdrsStrict( $params ),
362 'body' => $handle // resource
365 $method = __METHOD__
;
366 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
367 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
368 if ( $rcode === 201 ||
$rcode === 202 ) {
370 } elseif ( $rcode === 412 ) {
371 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
373 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
377 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
378 $opHandle->resourcesToClose
[] = $handle;
380 if ( !empty( $params['async'] ) ) { // deferred
381 $status->value
= $opHandle;
382 } else { // actually write the object in Swift
383 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
389 protected function doCopyInternal( array $params ) {
390 $status = $this->newStatus();
392 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
393 if ( $srcRel === null ) {
394 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
399 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
400 if ( $dstRel === null ) {
401 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
408 'url' => [ $dstCont, $dstRel ],
410 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
411 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
412 ] +
$this->sanitizeHdrsStrict( $params ), // extra headers merged into object
415 $method = __METHOD__
;
416 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
417 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
418 if ( $rcode === 201 ) {
420 } elseif ( $rcode === 404 ) {
421 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
423 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
427 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
428 if ( !empty( $params['async'] ) ) { // deferred
429 $status->value
= $opHandle;
430 } else { // actually write the object in Swift
431 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
437 protected function doMoveInternal( array $params ) {
438 $status = $this->newStatus();
440 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
441 if ( $srcRel === null ) {
442 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
447 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
448 if ( $dstRel === null ) {
449 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
457 'url' => [ $dstCont, $dstRel ],
459 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
460 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
461 ] +
$this->sanitizeHdrsStrict( $params ) // extra headers merged into object
464 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
466 'method' => 'DELETE',
467 'url' => [ $srcCont, $srcRel ],
472 $method = __METHOD__
;
473 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
474 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
475 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
477 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
479 } elseif ( $rcode === 404 ) {
480 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
482 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
486 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
487 if ( !empty( $params['async'] ) ) { // deferred
488 $status->value
= $opHandle;
489 } else { // actually move the object in Swift
490 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
496 protected function doDeleteInternal( array $params ) {
497 $status = $this->newStatus();
499 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
500 if ( $srcRel === null ) {
501 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
507 'method' => 'DELETE',
508 'url' => [ $srcCont, $srcRel ],
512 $method = __METHOD__
;
513 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
514 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
515 if ( $rcode === 204 ) {
517 } elseif ( $rcode === 404 ) {
518 if ( empty( $params['ignoreMissingSource'] ) ) {
519 $status->fatal( 'backend-fail-delete', $params['src'] );
522 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
526 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
527 if ( !empty( $params['async'] ) ) { // deferred
528 $status->value
= $opHandle;
529 } else { // actually delete the object in Swift
530 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
536 protected function doDescribeInternal( array $params ) {
537 $status = $this->newStatus();
539 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
540 if ( $srcRel === null ) {
541 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
546 // Fetch the old object headers/metadata...this should be in stat cache by now
547 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
548 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
549 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
552 $status->fatal( 'backend-fail-describe', $params['src'] );
557 // POST clears prior headers, so we need to merge the changes in to the old ones
559 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
560 $metaHdrs["x-object-meta-$name"] = $value;
562 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
566 'url' => [ $srcCont, $srcRel ],
567 'headers' => $metaHdrs +
$customHdrs
570 $method = __METHOD__
;
571 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
572 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
573 if ( $rcode === 202 ) {
575 } elseif ( $rcode === 404 ) {
576 $status->fatal( 'backend-fail-describe', $params['src'] );
578 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
582 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
583 if ( !empty( $params['async'] ) ) { // deferred
584 $status->value
= $opHandle;
585 } else { // actually change the object in Swift
586 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
592 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
593 $status = $this->newStatus();
595 // (a) Check if container already exists
596 $stat = $this->getContainerStat( $fullCont );
597 if ( is_array( $stat ) ) {
598 return $status; // already there
599 } elseif ( $stat === self
::$RES_ERROR ) {
600 $status->fatal( 'backend-fail-internal', $this->name
);
601 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
606 // (b) Create container as needed with proper ACLs
607 if ( $stat === false ) {
608 $params['op'] = 'prepare';
609 $status->merge( $this->createContainer( $fullCont, $params ) );
615 protected function doSecureInternal( $fullCont, $dir, array $params ) {
616 $status = $this->newStatus();
617 if ( empty( $params['noAccess'] ) ) {
618 return $status; // nothing to do
621 $stat = $this->getContainerStat( $fullCont );
622 if ( is_array( $stat ) ) {
623 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
624 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
625 // Make container private to end-users...
626 $status->merge( $this->setContainerAccess(
631 } elseif ( $stat === false ) {
632 $status->fatal( 'backend-fail-usable', $params['dir'] );
634 $status->fatal( 'backend-fail-internal', $this->name
);
635 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
641 protected function doPublishInternal( $fullCont, $dir, array $params ) {
642 $status = $this->newStatus();
644 $stat = $this->getContainerStat( $fullCont );
645 if ( is_array( $stat ) ) {
646 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
647 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
649 // Make container public to end-users...
650 $status->merge( $this->setContainerAccess(
655 } elseif ( $stat === false ) {
656 $status->fatal( 'backend-fail-usable', $params['dir'] );
658 $status->fatal( 'backend-fail-internal', $this->name
);
659 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
665 protected function doCleanInternal( $fullCont, $dir, array $params ) {
666 $status = $this->newStatus();
668 // Only containers themselves can be removed, all else is virtual
670 return $status; // nothing to do
673 // (a) Check the container
674 $stat = $this->getContainerStat( $fullCont, true );
675 if ( $stat === false ) {
676 return $status; // ok, nothing to do
677 } elseif ( !is_array( $stat ) ) {
678 $status->fatal( 'backend-fail-internal', $this->name
);
679 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
684 // (b) Delete the container if empty
685 if ( $stat['count'] == 0 ) {
686 $params['op'] = 'clean';
687 $status->merge( $this->deleteContainer( $fullCont, $params ) );
693 protected function doGetFileStat( array $params ) {
694 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
695 unset( $params['src'] );
696 $stats = $this->doGetFileStatMulti( $params );
698 return reset( $stats );
702 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
703 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
704 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
707 * @param int $format Output format (TS_* constant)
709 * @throws FileBackendError
711 protected function convertSwiftDate( $ts, $format = TS_MW
) {
713 $timestamp = new MWTimestamp( $ts );
715 return $timestamp->getTimestamp( $format );
716 } catch ( Exception
$e ) {
717 throw new FileBackendError( $e->getMessage() );
722 * Fill in any missing object metadata and save it to Swift
724 * @param array $objHdrs Object response headers
725 * @param string $path Storage path to object
726 * @return array New headers
728 protected function addMissingHashMetadata( array $objHdrs, $path ) {
729 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
730 return $objHdrs; // nothing to do
733 /** @noinspection PhpUnusedLocalVariableInspection */
734 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
735 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
736 [ 'path' => $path ] );
738 $objHdrs['x-object-meta-sha1base36'] = false;
740 $auth = $this->getAuthentication();
742 return $objHdrs; // failed
745 // Find prior custom HTTP headers
746 $postHeaders = $this->getCustomHeaders( $objHdrs );
747 // Find prior metadata headers
748 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
750 $status = $this->newStatus();
751 /** @noinspection PhpUnusedLocalVariableInspection */
752 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
753 if ( $status->isOK() ) {
754 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
756 $hash = $tmpFile->getSha1Base36();
757 if ( $hash !== false ) {
758 $objHdrs['x-object-meta-sha1base36'] = $hash;
759 // Merge new SHA1 header into the old ones
760 $postHeaders['x-object-meta-sha1base36'] = $hash;
761 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
762 list( $rcode ) = $this->http
->run( [
764 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
765 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
767 if ( $rcode >= 200 && $rcode <= 299 ) {
768 $this->deleteFileCache( $path );
770 return $objHdrs; // success
776 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
777 [ 'path' => $path ] );
779 return $objHdrs; // failed
782 protected function doGetFileContentsMulti( array $params ) {
783 $auth = $this->getAuthentication();
785 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
786 // Blindly create tmp files and stream to them, catching any exception
787 // if the file does not exist. Do not waste time doing file stats here.
788 $reqs = []; // (path => op)
790 // Initial dummy values to preserve path order
791 $contents = array_fill_keys( $params['srcs'], self
::$RES_ERROR );
792 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
793 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
794 if ( $srcRel === null ||
!$auth ) {
795 continue; // invalid storage path or auth error
797 // Create a new temporary memory file...
798 $handle = fopen( 'php://temp', 'wb' );
802 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
803 'headers' => $this->authTokenHeaders( $auth )
804 +
$this->headersFromParams( $params ),
810 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
811 $reqs = $this->http
->runMulti( $reqs, $opts );
812 foreach ( $reqs as $path => $op ) {
813 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
814 if ( $rcode >= 200 && $rcode <= 299 ) {
815 rewind( $op['stream'] ); // start from the beginning
816 $content = (string)stream_get_contents( $op['stream'] );
817 $size = strlen( $content );
818 // Make sure that stream finished
819 if ( $size === (int)$rhdrs['content-length'] ) {
820 $contents[$path] = $content;
822 $contents[$path] = self
::$RES_ERROR;
823 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
824 $this->onError( null, __METHOD__
,
825 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
827 } elseif ( $rcode === 404 ) {
828 $contents[$path] = self
::$RES_ABSENT;
830 $contents[$path] = self
::$RES_ERROR;
831 $this->onError( null, __METHOD__
,
832 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
834 fclose( $op['stream'] ); // close open handle
840 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
841 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
842 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
843 if ( $status->isOK() ) {
844 return ( count( $status->value
) ) > 0;
847 return self
::$RES_ERROR;
851 * @see FileBackendStore::getDirectoryListInternal()
852 * @param string $fullCont
854 * @param array $params
855 * @return SwiftFileBackendDirList
857 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
858 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
862 * @see FileBackendStore::getFileListInternal()
863 * @param string $fullCont
865 * @param array $params
866 * @return SwiftFileBackendFileList
868 public function getFileListInternal( $fullCont, $dir, array $params ) {
869 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
873 * Do not call this function outside of SwiftFileBackendFileList
875 * @param string $fullCont Resolved container name
876 * @param string $dir Resolved storage directory with no trailing slash
877 * @param string|null &$after Resolved container relative path to list items after
878 * @param int $limit Max number of items to list
879 * @param array $params Parameters for getDirectoryList()
880 * @return array List of container relative resolved paths of directories directly under $dir
881 * @throws FileBackendError
883 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
885 if ( $after === INF
) {
886 return $dirs; // nothing more
889 /** @noinspection PhpUnusedLocalVariableInspection */
890 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
892 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
893 // Non-recursive: only list dirs right under $dir
894 if ( !empty( $params['topOnly'] ) ) {
895 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
896 if ( !$status->isOK() ) {
897 throw new FileBackendError( "Iterator page I/O error." );
899 $objects = $status->value
;
900 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
901 foreach ( $objects as $object ) { // files and directories
902 if ( substr( $object, -1 ) === '/' ) {
903 $dirs[] = $object; // directories end in '/'
907 // Recursive: list all dirs under $dir and its subdirs
908 $getParentDir = function ( $path ) {
909 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
912 // Get directory from last item of prior page
913 $lastDir = $getParentDir( $after ); // must be first page
914 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
916 if ( !$status->isOK() ) {
917 throw new FileBackendError( "Iterator page I/O error." );
920 $objects = $status->value
;
922 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
923 foreach ( $objects as $object ) { // files
924 $objectDir = $getParentDir( $object ); // directory of object
926 if ( $objectDir !== false && $objectDir !== $dir ) {
927 // Swift stores paths in UTF-8, using binary sorting.
928 // See function "create_container_table" in common/db.py.
929 // If a directory is not "greater" than the last one,
930 // then it was already listed by the calling iterator.
931 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
933 do { // add dir and all its parent dirs
934 $dirs[] = "{$pDir}/";
935 $pDir = $getParentDir( $pDir );
936 } while ( $pDir !== false // sanity
937 && strcmp( $pDir, $lastDir ) > 0 // not done already
938 && strlen( $pDir ) > strlen( $dir ) // within $dir
941 $lastDir = $objectDir;
945 // Page on the unfiltered directory listing (what is returned may be filtered)
946 if ( count( $objects ) < $limit ) {
947 $after = INF
; // avoid a second RTT
949 $after = end( $objects ); // update last item
956 * Do not call this function outside of SwiftFileBackendFileList
958 * @param string $fullCont Resolved container name
959 * @param string $dir Resolved storage directory with no trailing slash
960 * @param string|null &$after Resolved container relative path of file to list items after
961 * @param int $limit Max number of items to list
962 * @param array $params Parameters for getDirectoryList()
963 * @return array List of resolved container relative paths of files under $dir
964 * @throws FileBackendError
966 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
967 $files = []; // list of (path, stat array or null) entries
968 if ( $after === INF
) {
969 return $files; // nothing more
972 /** @noinspection PhpUnusedLocalVariableInspection */
973 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
975 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
976 // $objects will contain a list of unfiltered names or stdClass items
977 // Non-recursive: only list files right under $dir
978 if ( !empty( $params['topOnly'] ) ) {
979 if ( !empty( $params['adviseStat'] ) ) {
980 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
982 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
985 // Recursive: list all files under $dir and its subdirs
986 if ( !empty( $params['adviseStat'] ) ) {
987 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
989 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
993 // Reformat this list into a list of (name, stat array or null) entries
994 if ( !$status->isOK() ) {
995 throw new FileBackendError( "Iterator page I/O error." );
998 $objects = $status->value
;
999 $files = $this->buildFileObjectListing( $objects );
1001 // Page on the unfiltered object listing (what is returned may be filtered)
1002 if ( count( $objects ) < $limit ) {
1003 $after = INF
; // avoid a second RTT
1005 $after = end( $objects ); // update last item
1006 $after = is_object( $after ) ?
$after->name
: $after;
1013 * Build a list of file objects, filtering out any directories
1014 * and extracting any stat info if provided in $objects
1016 * @param stdClass[]|string[] $objects List of stdClass items or object names
1017 * @return array List of (names,stat array or null) entries
1019 private function buildFileObjectListing( array $objects ) {
1021 foreach ( $objects as $object ) {
1022 if ( is_object( $object ) ) {
1023 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1024 continue; // virtual directory entry; ignore
1027 // Convert various random Swift dates to TS_MW
1028 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1029 'size' => (int)$object->bytes
,
1031 // Note: manifiest ETags are not an MD5 of the file
1032 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1033 'latest' => false // eventually consistent
1035 $names[] = [ $object->name
, $stat ];
1036 } elseif ( substr( $object, -1 ) !== '/' ) {
1037 // Omit directories, which end in '/' in listings
1038 $names[] = [ $object, null ];
1046 * Do not call this function outside of SwiftFileBackendFileList
1048 * @param string $path Storage path
1049 * @param array $val Stat value
1051 public function loadListingStatInternal( $path, array $val ) {
1052 $this->cheapCache
->setField( $path, 'stat', $val );
1055 protected function doGetFileXAttributes( array $params ) {
1056 $stat = $this->getFileStat( $params );
1057 // Stat entries filled by file listings don't include metadata/headers
1058 if ( is_array( $stat ) && !isset( $stat['xattr'] ) ) {
1059 $this->clearCache( [ $params['src'] ] );
1060 $stat = $this->getFileStat( $params );
1063 if ( is_array( $stat ) ) {
1064 return $stat['xattr'];
1067 return ( $stat === self
::$RES_ERROR ) ? self
::$RES_ERROR : self
::$RES_ABSENT;
1070 protected function doGetFileSha1base36( array $params ) {
1071 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1072 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1073 $params['requireSHA1'] = true;
1075 $stat = $this->getFileStat( $params );
1076 if ( is_array( $stat ) ) {
1077 return $stat['sha1'];
1080 return ( $stat === self
::$RES_ERROR ) ? self
::$RES_ERROR : self
::$RES_ABSENT;
1083 protected function doStreamFile( array $params ) {
1084 $status = $this->newStatus();
1086 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1088 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1089 if ( $srcRel === null ) {
1090 StreamFile
::send404Message( $params['src'], $flags );
1091 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1096 $auth = $this->getAuthentication();
1097 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1098 StreamFile
::send404Message( $params['src'], $flags );
1099 $status->fatal( 'backend-fail-stream', $params['src'] );
1104 // If "headers" is set, we only want to send them if the file is there.
1105 // Do not bother checking if the file exists if headers are not set though.
1106 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1107 StreamFile
::send404Message( $params['src'], $flags );
1108 $status->fatal( 'backend-fail-stream', $params['src'] );
1113 // Send the requested additional headers
1114 foreach ( $params['headers'] as $header ) {
1115 header( $header ); // aways send
1118 if ( empty( $params['allowOB'] ) ) {
1119 // Cancel output buffering and gzipping if set
1120 ( $this->obResetFunc
)();
1123 $handle = fopen( 'php://output', 'wb' );
1124 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1126 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1127 'headers' => $this->authTokenHeaders( $auth )
1128 +
$this->headersFromParams( $params ) +
$params['options'],
1129 'stream' => $handle,
1130 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1133 if ( $rcode >= 200 && $rcode <= 299 ) {
1135 } elseif ( $rcode === 404 ) {
1136 $status->fatal( 'backend-fail-stream', $params['src'] );
1137 // Per T43113, nasty things can happen if bad cache entries get
1138 // stuck in cache. It's also possible that this error can come up
1139 // with simple race conditions. Clear out the stat cache to be safe.
1140 $this->clearCache( [ $params['src'] ] );
1141 $this->deleteFileCache( $params['src'] );
1143 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1149 protected function doGetLocalCopyMulti( array $params ) {
1150 $auth = $this->getAuthentication();
1152 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1153 // Blindly create tmp files and stream to them, catching any exception
1154 // if the file does not exist. Do not waste time doing file stats here.
1155 $reqs = []; // (path => op)
1157 // Initial dummy values to preserve path order
1158 $tmpFiles = array_fill_keys( $params['srcs'], self
::$RES_ERROR );
1159 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1160 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1161 if ( $srcRel === null ||
!$auth ) {
1162 continue; // invalid storage path or auth error
1164 // Get source file extension
1165 $ext = FileBackend
::extensionFromPath( $path );
1166 // Create a new temporary file...
1167 $tmpFile = $this->tmpFileFactory
->newTempFSFile( 'localcopy_', $ext );
1168 $handle = $tmpFile ?
fopen( $tmpFile->getPath(), 'wb' ) : false;
1172 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1173 'headers' => $this->authTokenHeaders( $auth )
1174 +
$this->headersFromParams( $params ),
1175 'stream' => $handle,
1177 $tmpFiles[$path] = $tmpFile;
1181 // Ceph RADOS Gateway is in use (strong consistency) or X-Newest will be used
1182 $latest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1184 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1185 $reqs = $this->http
->runMulti( $reqs, $opts );
1186 foreach ( $reqs as $path => $op ) {
1187 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1188 fclose( $op['stream'] ); // close open handle
1189 if ( $rcode >= 200 && $rcode <= 299 ) {
1190 /** @var TempFSFile $tmpFile */
1191 $tmpFile = $tmpFiles[$path];
1192 // Make sure that the stream finished and fully wrote to disk
1193 $size = $tmpFile->getSize();
1194 if ( $size !== (int)$rhdrs['content-length'] ) {
1195 $tmpFiles[$path] = self
::$RES_ERROR;
1196 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1197 $this->onError( null, __METHOD__
,
1198 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1200 // Set the file stat process cache in passing
1201 $stat = $this->getStatFromHeaders( $rhdrs );
1202 $stat['latest'] = $latest;
1203 $this->cheapCache
->setField( $path, 'stat', $stat );
1204 } elseif ( $rcode === 404 ) {
1205 $tmpFiles[$path] = self
::$RES_ABSENT;
1206 $this->cheapCache
->setField(
1209 $latest ? self
::$ABSENT_LATEST : self
::$ABSENT_NORMAL
1212 $tmpFiles[$path] = self
::$RES_ERROR;
1213 $this->onError( null, __METHOD__
,
1214 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1221 public function getFileHttpUrl( array $params ) {
1222 if ( $this->swiftTempUrlKey
!= '' ||
1223 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1225 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1226 if ( $srcRel === null ) {
1227 return self
::TEMPURL_ERROR
; // invalid path
1230 $auth = $this->getAuthentication();
1232 return self
::TEMPURL_ERROR
;
1235 $ttl = $params['ttl'] ??
86400;
1236 $expires = time() +
$ttl;
1238 if ( $this->swiftTempUrlKey
!= '' ) {
1239 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1240 // Swift wants the signature based on the unencoded object name
1241 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1242 $signature = hash_hmac( 'sha1',
1243 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1244 $this->swiftTempUrlKey
1247 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1248 } else { // give S3 API URL for rgw
1249 // Path for signature starts with the bucket
1250 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1251 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1252 // Calculate the hash
1253 $signature = base64_encode( hash_hmac(
1255 "GET\n\n\n{$expires}\n{$spath}",
1256 $this->rgwS3SecretKey
,
1259 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1260 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1261 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1262 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1265 'Signature' => $signature,
1266 'Expires' => $expires,
1267 'AWSAccessKeyId' => $this->rgwS3AccessKey
1272 return self
::TEMPURL_ERROR
;
1275 protected function directoriesAreVirtual() {
1280 * Get headers to send to Swift when reading a file based
1281 * on a FileBackend params array, e.g. that of getLocalCopy().
1282 * $params is currently only checked for a 'latest' flag.
1284 * @param array $params
1287 protected function headersFromParams( array $params ) {
1289 if ( !empty( $params['latest'] ) ) {
1290 $hdrs['x-newest'] = 'true';
1297 * @param FileBackendStoreOpHandle[] $fileOpHandles
1299 * @return StatusValue[]
1301 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1302 /** @var SwiftFileOpHandle[] $fileOpHandles */
1303 '@phan-var SwiftFileOpHandle[] $fileOpHandles';
1305 /** @var StatusValue[] $statuses */
1308 $auth = $this->getAuthentication();
1310 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1311 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1317 // Split the HTTP requests into stages that can be done concurrently
1318 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1319 foreach ( $fileOpHandles as $index => $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 // Run the callback for each request of this operation
1338 $callback = $fileOpHandles[$index]->callback
;
1339 $callback( $httpReq, $statuses[$index] );
1340 // On failure, abort all remaining requests for this operation
1341 // (e.g. abort the DELETE request if the COPY request fails for a move)
1342 if ( !$statuses[$index]->isOK() ) {
1343 $stages = count( $fileOpHandles[$index]->httpOp
);
1344 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1345 unset( $httpReqsByStage[$s][$index] );
1355 * Set read/write permissions for a Swift container.
1357 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1359 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1360 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1362 * @param string $container Resolved Swift container
1363 * @param array $readUsers List of the possible criteria for a request to have
1364 * access to read a container. Each item is one of the following formats:
1365 * - account:user : Grants access if the request is by the given user
1366 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1367 * matches the expression and the request is not for a listing.
1368 * Setting this to '*' effectively makes a container public.
1369 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1370 * matches the expression and the request is for a listing.
1371 * @param array $writeUsers A list of the possible criteria for a request to have
1372 * access to write to a container. Each item is of the following format:
1373 * - account:user : Grants access if the request is by the given user
1374 * @return StatusValue
1376 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1377 $status = $this->newStatus();
1378 $auth = $this->getAuthentication();
1381 $status->fatal( 'backend-fail-connect', $this->name
);
1386 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1388 'url' => $this->storageUrl( $auth, $container ),
1389 'headers' => $this->authTokenHeaders( $auth ) +
[
1390 'x-container-read' => implode( ',', $readUsers ),
1391 'x-container-write' => implode( ',', $writeUsers )
1395 if ( $rcode != 204 && $rcode !== 202 ) {
1396 $status->fatal( 'backend-fail-internal', $this->name
);
1397 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1398 [ 'rcode' => $rcode ] );
1405 * Get a Swift container stat array, possibly from process cache.
1406 * Use $reCache if the file count or byte count is needed.
1408 * @param string $container Container name
1409 * @param bool $bypassCache Bypass all caches and load from Swift
1410 * @return array|bool|null False on 404, null on failure
1412 protected function getContainerStat( $container, $bypassCache = false ) {
1413 /** @noinspection PhpUnusedLocalVariableInspection */
1414 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1416 if ( $bypassCache ) { // purge cache
1417 $this->containerStatCache
->clear( $container );
1418 } elseif ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1419 $this->primeContainerCache( [ $container ] ); // check persistent cache
1421 if ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1422 $auth = $this->getAuthentication();
1424 return self
::$RES_ERROR;
1427 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1429 'url' => $this->storageUrl( $auth, $container ),
1430 'headers' => $this->authTokenHeaders( $auth )
1433 if ( $rcode === 204 ) {
1435 'count' => $rhdrs['x-container-object-count'],
1436 'bytes' => $rhdrs['x-container-bytes-used']
1438 if ( $bypassCache ) {
1441 $this->containerStatCache
->setField( $container, 'stat', $stat ); // cache it
1442 $this->setContainerCache( $container, $stat ); // update persistent cache
1444 } elseif ( $rcode === 404 ) {
1445 return self
::$RES_ABSENT;
1447 $this->onError( null, __METHOD__
,
1448 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1450 return self
::$RES_ERROR;
1454 return $this->containerStatCache
->getField( $container, 'stat' );
1458 * Create a Swift container
1460 * @param string $container Container name
1461 * @param array $params
1462 * @return StatusValue
1464 protected function createContainer( $container, array $params ) {
1465 $status = $this->newStatus();
1467 $auth = $this->getAuthentication();
1469 $status->fatal( 'backend-fail-connect', $this->name
);
1474 // @see SwiftFileBackend::setContainerAccess()
1475 if ( empty( $params['noAccess'] ) ) {
1477 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] );
1478 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
1481 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
1482 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
1485 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1487 'url' => $this->storageUrl( $auth, $container ),
1488 'headers' => $this->authTokenHeaders( $auth ) +
[
1489 'x-container-read' => implode( ',', $readUsers ),
1490 'x-container-write' => implode( ',', $writeUsers )
1494 if ( $rcode === 201 ) { // new
1496 } elseif ( $rcode === 202 ) { // already there
1497 // this shouldn't really happen, but is OK
1499 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1506 * Delete a Swift container
1508 * @param string $container Container name
1509 * @param array $params
1510 * @return StatusValue
1512 protected function deleteContainer( $container, array $params ) {
1513 $status = $this->newStatus();
1515 $auth = $this->getAuthentication();
1517 $status->fatal( 'backend-fail-connect', $this->name
);
1522 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1523 'method' => 'DELETE',
1524 'url' => $this->storageUrl( $auth, $container ),
1525 'headers' => $this->authTokenHeaders( $auth )
1528 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1529 $this->containerStatCache
->clear( $container ); // purge
1530 } elseif ( $rcode === 404 ) { // not there
1531 // this shouldn't really happen, but is OK
1532 } elseif ( $rcode === 409 ) { // not empty
1533 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1535 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1542 * Get a list of objects under a container.
1543 * Either just the names or a list of stdClass objects with details can be returned.
1545 * @param string $fullCont
1546 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1548 * @param string|null $after
1549 * @param string|null $prefix
1550 * @param string|null $delim
1551 * @return StatusValue With the list as value
1553 private function objectListing(
1554 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1556 $status = $this->newStatus();
1558 $auth = $this->getAuthentication();
1560 $status->fatal( 'backend-fail-connect', $this->name
);
1565 $query = [ 'limit' => $limit ];
1566 if ( $type === 'info' ) {
1567 $query['format'] = 'json';
1569 if ( $after !== null ) {
1570 $query['marker'] = $after;
1572 if ( $prefix !== null ) {
1573 $query['prefix'] = $prefix;
1575 if ( $delim !== null ) {
1576 $query['delimiter'] = $delim;
1579 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1581 'url' => $this->storageUrl( $auth, $fullCont ),
1583 'headers' => $this->authTokenHeaders( $auth )
1586 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1587 if ( $rcode === 200 ) { // good
1588 if ( $type === 'info' ) {
1589 $status->value
= FormatJson
::decode( trim( $rbody ) );
1591 $status->value
= explode( "\n", trim( $rbody ) );
1593 } elseif ( $rcode === 204 ) {
1594 $status->value
= []; // empty container
1595 } elseif ( $rcode === 404 ) {
1596 $status->value
= []; // no container
1598 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1604 protected function doPrimeContainerCache( array $containerInfo ) {
1605 foreach ( $containerInfo as $container => $info ) {
1606 $this->containerStatCache
->setField( $container, 'stat', $info );
1610 protected function doGetFileStatMulti( array $params ) {
1613 $auth = $this->getAuthentication();
1615 $reqs = []; // (path => op)
1616 // (a) Check the containers of the paths...
1617 foreach ( $params['srcs'] as $path ) {
1618 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1619 if ( $srcRel === null ||
!$auth ) {
1620 $stats[$path] = self
::$RES_ERROR;
1621 continue; // invalid storage path or auth error
1624 $cstat = $this->getContainerStat( $srcCont );
1625 if ( $cstat === self
::$RES_ABSENT ) {
1626 $stats[$path] = self
::$RES_ABSENT;
1627 continue; // ok, nothing to do
1628 } elseif ( !is_array( $cstat ) ) {
1629 $stats[$path] = self
::$RES_ERROR;
1635 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1636 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1640 // (b) Check the files themselves...
1641 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1642 $reqs = $this->http
->runMulti( $reqs, $opts );
1643 foreach ( $reqs as $path => $op ) {
1644 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1645 if ( $rcode === 200 ||
$rcode === 204 ) {
1646 // Update the object if it is missing some headers
1647 if ( !empty( $params['requireSHA1'] ) ) {
1648 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1650 // Load the stat array from the headers
1651 $stat = $this->getStatFromHeaders( $rhdrs );
1652 if ( $this->isRGW
) {
1653 $stat['latest'] = true; // strong consistency
1655 } elseif ( $rcode === 404 ) {
1656 $stat = self
::$RES_ABSENT;
1658 $stat = self
::$RES_ERROR;
1659 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1661 $stats[$path] = $stat;
1668 * @param array $rhdrs
1671 protected function getStatFromHeaders( array $rhdrs ) {
1672 // Fetch all of the custom metadata headers
1673 $metadata = $this->getMetadata( $rhdrs );
1674 // Fetch all of the custom raw HTTP headers
1675 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1678 // Convert various random Swift dates to TS_MW
1679 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1680 // Empty objects actually return no content-length header in Ceph
1681 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1682 'sha1' => $metadata['sha1base36'] ??
null,
1683 // Note: manifiest ETags are not an MD5 of the file
1684 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1685 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1690 * @return array|null Credential map
1692 protected function getAuthentication() {
1693 if ( $this->authErrorTimestamp
!== null ) {
1694 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1695 return null; // failed last attempt; don't bother
1696 } else { // actually retry this time
1697 $this->authErrorTimestamp
= null;
1700 // Session keys expire after a while, so we renew them periodically
1701 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1702 // Authenticate with proxy and get a session key...
1703 if ( !$this->authCreds ||
$reAuth ) {
1704 $this->authSessionTimestamp
= 0;
1705 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1706 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1707 // Try to use the credential cache
1708 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1709 $this->authCreds
= $creds;
1710 // Skew the timestamp for worst case to avoid using stale credentials
1711 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1712 } else { // cache miss
1713 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1715 'url' => "{$this->swiftAuthUrl}/v1.0",
1717 'x-auth-user' => $this->swiftUser
,
1718 'x-auth-key' => $this->swiftKey
1722 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1723 $this->authCreds
= [
1724 'auth_token' => $rhdrs['x-auth-token'],
1725 'storage_url' => $this->swiftStorageUrl ??
$rhdrs['x-storage-url']
1728 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1729 $this->authSessionTimestamp
= time();
1730 } elseif ( $rcode === 401 ) {
1731 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1732 $this->authErrorTimestamp
= time();
1736 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1737 $this->authErrorTimestamp
= time();
1742 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1743 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1744 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1748 return $this->authCreds
;
1752 * @param array $creds From getAuthentication()
1753 * @param string|null $container
1754 * @param string|null $object
1757 protected function storageUrl( array $creds, $container = null, $object = null ) {
1758 $parts = [ $creds['storage_url'] ];
1759 if ( strlen( $container ) ) {
1760 $parts[] = rawurlencode( $container );
1762 if ( strlen( $object ) ) {
1763 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1766 return implode( '/', $parts );
1770 * @param array $creds From getAuthentication()
1773 protected function authTokenHeaders( array $creds ) {
1774 return [ 'x-auth-token' => $creds['auth_token'] ];
1778 * Get the cache key for a container
1780 * @param string $username
1783 private function getCredsCacheKey( $username ) {
1784 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1788 * Log an unexpected exception for this backend.
1789 * This also sets the StatusValue object to have a fatal error.
1791 * @param StatusValue|null $status
1792 * @param string $func
1793 * @param array $params
1794 * @param string $err Error string
1795 * @param int $code HTTP status
1796 * @param string $desc HTTP StatusValue description
1798 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1799 if ( $status instanceof StatusValue
) {
1800 $status->fatal( 'backend-fail-internal', $this->name
);
1802 if ( $code == 401 ) { // possibly a stale token
1803 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1805 $msg = "HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1810 'req_params' => FormatJson
::encode( $params ),
1814 $msgParams['err'] = $err;
1816 $this->logger
->error( $msg, $msgParams );