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() {
148 return ( FileBackend
::ATTR_UNICODE_PATHS |
149 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
152 protected function resolveContainerPath( $container, $relStoragePath ) {
153 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
154 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
155 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
156 return null; // too long for Swift
159 return $relStoragePath;
162 public function isPathUsableInternal( $storagePath ) {
163 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
164 if ( $rel === null ) {
165 return false; // invalid
168 return is_array( $this->getContainerStat( $container ) );
172 * Sanitize and filter the custom headers from a $params array.
173 * Only allows certain "standard" Content- and X-Content- headers.
175 * @param array $params
176 * @return array Sanitized value of 'headers' field in $params
178 protected function sanitizeHdrsStrict( array $params ) {
179 if ( !isset( $params['headers'] ) ) {
183 $headers = $this->getCustomHeaders( $params['headers'] );
184 unset( $headers[ 'content-type' ] );
190 * Sanitize and filter the custom headers from a $params array.
191 * Only allows certain "standard" Content- and X-Content- headers.
193 * When POSTing data, libcurl adds Content-Type: application/x-www-form-urlencoded
194 * if Content-Type is not set, which overwrites the stored Content-Type header
195 * in Swift - therefore for POSTing data do not strip the Content-Type header (the
196 * previously-stored header that has been already read back from swift is sent)
198 * @param array $params
199 * @return array Sanitized value of 'headers' field in $params
201 protected function sanitizeHdrs( array $params ) {
202 return isset( $params['headers'] )
203 ?
$this->getCustomHeaders( $params['headers'] )
208 * @param array $rawHeaders
209 * @return array Custom non-metadata HTTP headers
211 protected function getCustomHeaders( array $rawHeaders ) {
214 // Normalize casing, and strip out illegal headers
215 foreach ( $rawHeaders as $name => $value ) {
216 $name = strtolower( $name );
217 if ( preg_match( '/^content-length$/', $name ) ) {
218 continue; // blacklisted
219 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
220 $headers[$name] = $value; // allowed
221 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
222 $headers[$name] = $value; // allowed
225 // By default, Swift has annoyingly low maximum header value limits
226 if ( isset( $headers['content-disposition'] ) ) {
228 // @note: assume FileBackend::makeContentDisposition() already used
229 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
230 $part = trim( $part );
231 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
232 if ( strlen( $new ) <= 255 ) {
235 break; // too long; sigh
238 $headers['content-disposition'] = $disposition;
245 * @param array $rawHeaders
246 * @return array Custom metadata headers
248 protected function getMetadataHeaders( array $rawHeaders ) {
250 foreach ( $rawHeaders as $name => $value ) {
251 $name = strtolower( $name );
252 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
253 $headers[$name] = $value;
261 * @param array $rawHeaders
262 * @return array Custom metadata headers with prefix removed
264 protected function getMetadata( array $rawHeaders ) {
266 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
267 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
273 protected function doCreateInternal( array $params ) {
274 $status = $this->newStatus();
276 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
277 if ( $dstRel === null ) {
278 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
283 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
284 $contentType = $params['headers']['content-type']
285 ??
$this->getContentType( $params['dst'], $params['content'], null );
289 'url' => [ $dstCont, $dstRel ],
291 'content-length' => strlen( $params['content'] ),
292 'etag' => md5( $params['content'] ),
293 'content-type' => $contentType,
294 'x-object-meta-sha1base36' => $sha1Hash
295 ] +
$this->sanitizeHdrsStrict( $params ),
296 'body' => $params['content']
299 $method = __METHOD__
;
300 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
301 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
302 if ( $rcode === 201 ||
$rcode === 202 ) {
304 } elseif ( $rcode === 412 ) {
305 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
307 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
311 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
312 if ( !empty( $params['async'] ) ) { // deferred
313 $status->value
= $opHandle;
314 } else { // actually write the object in Swift
315 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
321 protected function doStoreInternal( array $params ) {
322 $status = $this->newStatus();
324 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
325 if ( $dstRel === null ) {
326 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
331 AtEase
::suppressWarnings();
332 $sha1Hash = sha1_file( $params['src'] );
333 AtEase
::restoreWarnings();
334 if ( $sha1Hash === false ) { // source doesn't exist?
335 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
339 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
340 $contentType = $params['headers']['content-type']
341 ??
$this->getContentType( $params['dst'], null, $params['src'] );
343 $handle = fopen( $params['src'], 'rb' );
344 if ( $handle === false ) { // source doesn't exist?
345 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
352 'url' => [ $dstCont, $dstRel ],
354 'content-length' => filesize( $params['src'] ),
355 'etag' => md5_file( $params['src'] ),
356 'content-type' => $contentType,
357 'x-object-meta-sha1base36' => $sha1Hash
358 ] +
$this->sanitizeHdrsStrict( $params ),
359 'body' => $handle // resource
362 $method = __METHOD__
;
363 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
364 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
365 if ( $rcode === 201 ||
$rcode === 202 ) {
367 } elseif ( $rcode === 412 ) {
368 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
370 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
374 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
375 $opHandle->resourcesToClose
[] = $handle;
377 if ( !empty( $params['async'] ) ) { // deferred
378 $status->value
= $opHandle;
379 } else { // actually write the object in Swift
380 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
386 protected function doCopyInternal( array $params ) {
387 $status = $this->newStatus();
389 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
390 if ( $srcRel === null ) {
391 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
396 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
397 if ( $dstRel === null ) {
398 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
405 'url' => [ $dstCont, $dstRel ],
407 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
408 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
409 ] +
$this->sanitizeHdrsStrict( $params ), // extra headers merged into object
412 $method = __METHOD__
;
413 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
414 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
415 if ( $rcode === 201 ) {
417 } elseif ( $rcode === 404 ) {
418 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
420 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
424 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
425 if ( !empty( $params['async'] ) ) { // deferred
426 $status->value
= $opHandle;
427 } else { // actually write the object in Swift
428 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
434 protected function doMoveInternal( array $params ) {
435 $status = $this->newStatus();
437 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
438 if ( $srcRel === null ) {
439 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
444 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
445 if ( $dstRel === null ) {
446 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
454 'url' => [ $dstCont, $dstRel ],
456 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
457 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
458 ] +
$this->sanitizeHdrsStrict( $params ) // extra headers merged into object
461 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
463 'method' => 'DELETE',
464 'url' => [ $srcCont, $srcRel ],
469 $method = __METHOD__
;
470 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
471 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
472 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
474 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
476 } elseif ( $rcode === 404 ) {
477 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
479 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
483 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
484 if ( !empty( $params['async'] ) ) { // deferred
485 $status->value
= $opHandle;
486 } else { // actually move the object in Swift
487 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
493 protected function doDeleteInternal( array $params ) {
494 $status = $this->newStatus();
496 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
497 if ( $srcRel === null ) {
498 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
504 'method' => 'DELETE',
505 'url' => [ $srcCont, $srcRel ],
509 $method = __METHOD__
;
510 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
511 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
512 if ( $rcode === 204 ) {
514 } elseif ( $rcode === 404 ) {
515 if ( empty( $params['ignoreMissingSource'] ) ) {
516 $status->fatal( 'backend-fail-delete', $params['src'] );
519 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
523 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
524 if ( !empty( $params['async'] ) ) { // deferred
525 $status->value
= $opHandle;
526 } else { // actually delete the object in Swift
527 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
533 protected function doDescribeInternal( array $params ) {
534 $status = $this->newStatus();
536 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
537 if ( $srcRel === null ) {
538 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
543 // Fetch the old object headers/metadata...this should be in stat cache by now
544 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
545 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
546 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
549 $status->fatal( 'backend-fail-describe', $params['src'] );
554 // POST clears prior headers, so we need to merge the changes in to the old ones
556 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
557 $metaHdrs["x-object-meta-$name"] = $value;
559 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
563 'url' => [ $srcCont, $srcRel ],
564 'headers' => $metaHdrs +
$customHdrs
567 $method = __METHOD__
;
568 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
569 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
570 if ( $rcode === 202 ) {
572 } elseif ( $rcode === 404 ) {
573 $status->fatal( 'backend-fail-describe', $params['src'] );
575 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
579 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
580 if ( !empty( $params['async'] ) ) { // deferred
581 $status->value
= $opHandle;
582 } else { // actually change the object in Swift
583 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
589 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
590 $status = $this->newStatus();
592 // (a) Check if container already exists
593 $stat = $this->getContainerStat( $fullCont );
594 if ( is_array( $stat ) ) {
595 return $status; // already there
596 } elseif ( $stat === self
::UNKNOWN
) {
597 $status->fatal( 'backend-fail-internal', $this->name
);
598 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
603 // (b) Create container as needed with proper ACLs
604 if ( $stat === false ) {
605 $params['op'] = 'prepare';
606 $status->merge( $this->createContainer( $fullCont, $params ) );
612 protected function doSecureInternal( $fullCont, $dir, array $params ) {
613 $status = $this->newStatus();
614 if ( empty( $params['noAccess'] ) ) {
615 return $status; // nothing to do
618 $stat = $this->getContainerStat( $fullCont );
619 if ( is_array( $stat ) ) {
620 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
621 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
622 // Make container private to end-users...
623 $status->merge( $this->setContainerAccess(
628 } elseif ( $stat === false ) {
629 $status->fatal( 'backend-fail-usable', $params['dir'] );
631 $status->fatal( 'backend-fail-internal', $this->name
);
632 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
638 protected function doPublishInternal( $fullCont, $dir, array $params ) {
639 $status = $this->newStatus();
641 $stat = $this->getContainerStat( $fullCont );
642 if ( is_array( $stat ) ) {
643 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
644 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
646 // Make container public to end-users...
647 $status->merge( $this->setContainerAccess(
652 } elseif ( $stat === false ) {
653 $status->fatal( 'backend-fail-usable', $params['dir'] );
655 $status->fatal( 'backend-fail-internal', $this->name
);
656 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
662 protected function doCleanInternal( $fullCont, $dir, array $params ) {
663 $status = $this->newStatus();
665 // Only containers themselves can be removed, all else is virtual
667 return $status; // nothing to do
670 // (a) Check the container
671 $stat = $this->getContainerStat( $fullCont, true );
672 if ( $stat === false ) {
673 return $status; // ok, nothing to do
674 } elseif ( !is_array( $stat ) ) {
675 $status->fatal( 'backend-fail-internal', $this->name
);
676 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
681 // (b) Delete the container if empty
682 if ( $stat['count'] == 0 ) {
683 $params['op'] = 'clean';
684 $status->merge( $this->deleteContainer( $fullCont, $params ) );
690 protected function doGetFileStat( array $params ) {
691 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
692 unset( $params['src'] );
693 $stats = $this->doGetFileStatMulti( $params );
695 return reset( $stats );
699 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
700 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
701 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
704 * @param int $format Output format (TS_* constant)
706 * @throws FileBackendError
708 protected function convertSwiftDate( $ts, $format = TS_MW
) {
710 $timestamp = new MWTimestamp( $ts );
712 return $timestamp->getTimestamp( $format );
713 } catch ( Exception
$e ) {
714 throw new FileBackendError( $e->getMessage() );
719 * Fill in any missing object metadata and save it to Swift
721 * @param array $objHdrs Object response headers
722 * @param string $path Storage path to object
723 * @return array New headers
725 protected function addMissingHashMetadata( array $objHdrs, $path ) {
726 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
727 return $objHdrs; // nothing to do
730 /** @noinspection PhpUnusedLocalVariableInspection */
731 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
732 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
733 [ 'path' => $path ] );
735 $objHdrs['x-object-meta-sha1base36'] = false;
737 $auth = $this->getAuthentication();
739 return $objHdrs; // failed
742 // Find prior custom HTTP headers
743 $postHeaders = $this->getCustomHeaders( $objHdrs );
744 // Find prior metadata headers
745 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
747 $status = $this->newStatus();
748 /** @noinspection PhpUnusedLocalVariableInspection */
749 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
750 if ( $status->isOK() ) {
751 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
753 $hash = $tmpFile->getSha1Base36();
754 if ( $hash !== false ) {
755 $objHdrs['x-object-meta-sha1base36'] = $hash;
756 // Merge new SHA1 header into the old ones
757 $postHeaders['x-object-meta-sha1base36'] = $hash;
758 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
759 list( $rcode ) = $this->http
->run( [
761 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
762 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
764 if ( $rcode >= 200 && $rcode <= 299 ) {
765 $this->deleteFileCache( $path );
767 return $objHdrs; // success
773 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
774 [ 'path' => $path ] );
776 return $objHdrs; // failed
779 protected function doGetFileContentsMulti( array $params ) {
782 $auth = $this->getAuthentication();
784 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
785 // Blindly create tmp files and stream to them, catching any exception
786 // if the file does not exist. Do not waste time doing file stats here.
787 $reqs = []; // (path => op)
789 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
790 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
791 if ( $srcRel === null ||
!$auth ) {
792 $contents[$path] = false;
795 // Create a new temporary memory file...
796 $handle = fopen( 'php://temp', 'wb' );
800 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
801 'headers' => $this->authTokenHeaders( $auth )
802 +
$this->headersFromParams( $params ),
806 $contents[$path] = false;
809 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
810 $reqs = $this->http
->runMulti( $reqs, $opts );
811 foreach ( $reqs as $path => $op ) {
812 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
813 if ( $rcode >= 200 && $rcode <= 299 ) {
814 rewind( $op['stream'] ); // start from the beginning
815 $contents[$path] = stream_get_contents( $op['stream'] );
816 } elseif ( $rcode === 404 ) {
817 $contents[$path] = false;
819 $this->onError( null, __METHOD__
,
820 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
822 fclose( $op['stream'] ); // close open handle
828 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
829 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
830 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
831 if ( $status->isOK() ) {
832 return ( count( $status->value
) ) > 0;
835 return self
::UNKNOWN
; // error
839 * @see FileBackendStore::getDirectoryListInternal()
840 * @param string $fullCont
842 * @param array $params
843 * @return SwiftFileBackendDirList
845 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
846 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
850 * @see FileBackendStore::getFileListInternal()
851 * @param string $fullCont
853 * @param array $params
854 * @return SwiftFileBackendFileList
856 public function getFileListInternal( $fullCont, $dir, array $params ) {
857 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
861 * Do not call this function outside of SwiftFileBackendFileList
863 * @param string $fullCont Resolved container name
864 * @param string $dir Resolved storage directory with no trailing slash
865 * @param string|null &$after Resolved container relative path to list items after
866 * @param int $limit Max number of items to list
867 * @param array $params Parameters for getDirectoryList()
868 * @return array List of container relative resolved paths of directories directly under $dir
869 * @throws FileBackendError
871 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
873 if ( $after === INF
) {
874 return $dirs; // nothing more
877 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
879 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
880 // Non-recursive: only list dirs right under $dir
881 if ( !empty( $params['topOnly'] ) ) {
882 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
883 if ( !$status->isOK() ) {
884 throw new FileBackendError( "Iterator page I/O error." );
886 $objects = $status->value
;
887 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
888 foreach ( $objects as $object ) { // files and directories
889 if ( substr( $object, -1 ) === '/' ) {
890 $dirs[] = $object; // directories end in '/'
894 // Recursive: list all dirs under $dir and its subdirs
895 $getParentDir = function ( $path ) {
896 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
899 // Get directory from last item of prior page
900 $lastDir = $getParentDir( $after ); // must be first page
901 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
903 if ( !$status->isOK() ) {
904 throw new FileBackendError( "Iterator page I/O error." );
907 $objects = $status->value
;
909 // @phan-suppress-next-line PhanTypeSuspiciousNonTraversableForeach
910 foreach ( $objects as $object ) { // files
911 $objectDir = $getParentDir( $object ); // directory of object
913 if ( $objectDir !== false && $objectDir !== $dir ) {
914 // Swift stores paths in UTF-8, using binary sorting.
915 // See function "create_container_table" in common/db.py.
916 // If a directory is not "greater" than the last one,
917 // then it was already listed by the calling iterator.
918 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
920 do { // add dir and all its parent dirs
921 $dirs[] = "{$pDir}/";
922 $pDir = $getParentDir( $pDir );
923 } while ( $pDir !== false // sanity
924 && strcmp( $pDir, $lastDir ) > 0 // not done already
925 && strlen( $pDir ) > strlen( $dir ) // within $dir
928 $lastDir = $objectDir;
932 // Page on the unfiltered directory listing (what is returned may be filtered)
933 if ( count( $objects ) < $limit ) {
934 $after = INF
; // avoid a second RTT
936 $after = end( $objects ); // update last item
943 * Do not call this function outside of SwiftFileBackendFileList
945 * @param string $fullCont Resolved container name
946 * @param string $dir Resolved storage directory with no trailing slash
947 * @param string|null &$after Resolved container relative path of file to list items after
948 * @param int $limit Max number of items to list
949 * @param array $params Parameters for getDirectoryList()
950 * @return array List of resolved container relative paths of files under $dir
951 * @throws FileBackendError
953 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
954 $files = []; // list of (path, stat array or null) entries
955 if ( $after === INF
) {
956 return $files; // nothing more
959 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
961 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
962 // $objects will contain a list of unfiltered names or CF_Object items
963 // Non-recursive: only list files right under $dir
964 if ( !empty( $params['topOnly'] ) ) {
965 if ( !empty( $params['adviseStat'] ) ) {
966 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
968 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
971 // Recursive: list all files under $dir and its subdirs
972 if ( !empty( $params['adviseStat'] ) ) {
973 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
975 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
979 // Reformat this list into a list of (name, stat array or null) entries
980 if ( !$status->isOK() ) {
981 throw new FileBackendError( "Iterator page I/O error." );
984 $objects = $status->value
;
985 $files = $this->buildFileObjectListing( $params, $dir, $objects );
987 // Page on the unfiltered object listing (what is returned may be filtered)
988 if ( count( $objects ) < $limit ) {
989 $after = INF
; // avoid a second RTT
991 $after = end( $objects ); // update last item
992 $after = is_object( $after ) ?
$after->name
: $after;
999 * Build a list of file objects, filtering out any directories
1000 * and extracting any stat info if provided in $objects (for CF_Objects)
1002 * @param array $params Parameters for getDirectoryList()
1003 * @param string $dir Resolved container directory path
1004 * @param array $objects List of CF_Object items or object names
1005 * @return array List of (names,stat array or null) entries
1007 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1009 foreach ( $objects as $object ) {
1010 if ( is_object( $object ) ) {
1011 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1012 continue; // virtual directory entry; ignore
1015 // Convert various random Swift dates to TS_MW
1016 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1017 'size' => (int)$object->bytes
,
1019 // Note: manifiest ETags are not an MD5 of the file
1020 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1021 'latest' => false // eventually consistent
1023 $names[] = [ $object->name
, $stat ];
1024 } elseif ( substr( $object, -1 ) !== '/' ) {
1025 // Omit directories, which end in '/' in listings
1026 $names[] = [ $object, null ];
1034 * Do not call this function outside of SwiftFileBackendFileList
1036 * @param string $path Storage path
1037 * @param array $val Stat value
1039 public function loadListingStatInternal( $path, array $val ) {
1040 $this->cheapCache
->setField( $path, 'stat', $val );
1043 protected function doGetFileXAttributes( array $params ) {
1044 $stat = $this->getFileStat( $params );
1046 if ( !isset( $stat['xattr'] ) ) {
1047 // Stat entries filled by file listings don't include metadata/headers
1048 $this->clearCache( [ $params['src'] ] );
1049 $stat = $this->getFileStat( $params );
1052 return $stat['xattr'];
1058 protected function doGetFileSha1base36( array $params ) {
1059 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1060 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1061 $params['requireSHA1'] = true;
1063 $stat = $this->getFileStat( $params );
1065 return $stat['sha1'];
1071 protected function doStreamFile( array $params ) {
1072 $status = $this->newStatus();
1074 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1076 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1077 if ( $srcRel === null ) {
1078 StreamFile
::send404Message( $params['src'], $flags );
1079 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1084 $auth = $this->getAuthentication();
1085 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1086 StreamFile
::send404Message( $params['src'], $flags );
1087 $status->fatal( 'backend-fail-stream', $params['src'] );
1092 // If "headers" is set, we only want to send them if the file is there.
1093 // Do not bother checking if the file exists if headers are not set though.
1094 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1095 StreamFile
::send404Message( $params['src'], $flags );
1096 $status->fatal( 'backend-fail-stream', $params['src'] );
1101 // Send the requested additional headers
1102 foreach ( $params['headers'] as $header ) {
1103 header( $header ); // aways send
1106 if ( empty( $params['allowOB'] ) ) {
1107 // Cancel output buffering and gzipping if set
1108 ( $this->obResetFunc
)();
1111 $handle = fopen( 'php://output', 'wb' );
1112 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1114 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1115 'headers' => $this->authTokenHeaders( $auth )
1116 +
$this->headersFromParams( $params ) +
$params['options'],
1117 'stream' => $handle,
1118 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1121 if ( $rcode >= 200 && $rcode <= 299 ) {
1123 } elseif ( $rcode === 404 ) {
1124 $status->fatal( 'backend-fail-stream', $params['src'] );
1125 // Per T43113, nasty things can happen if bad cache entries get
1126 // stuck in cache. It's also possible that this error can come up
1127 // with simple race conditions. Clear out the stat cache to be safe.
1128 $this->clearCache( [ $params['src'] ] );
1129 $this->deleteFileCache( $params['src'] );
1131 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1137 protected function doGetLocalCopyMulti( array $params ) {
1138 /** @var TempFSFile[] $tmpFiles */
1141 $auth = $this->getAuthentication();
1143 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1144 // Blindly create tmp files and stream to them, catching any exception
1145 // if the file does not exist. Do not waste time doing file stats here.
1146 $reqs = []; // (path => op)
1148 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1149 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1150 if ( $srcRel === null ||
!$auth ) {
1151 $tmpFiles[$path] = null;
1154 // Get source file extension
1155 $ext = FileBackend
::extensionFromPath( $path );
1156 // Create a new temporary file...
1157 $tmpFile = $this->tmpFileFactory
->newTempFSFile( 'localcopy_', $ext );
1159 $handle = fopen( $tmpFile->getPath(), 'wb' );
1163 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1164 'headers' => $this->authTokenHeaders( $auth )
1165 +
$this->headersFromParams( $params ),
1166 'stream' => $handle,
1172 $tmpFiles[$path] = $tmpFile;
1175 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1176 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1177 $reqs = $this->http
->runMulti( $reqs, $opts );
1178 foreach ( $reqs as $path => $op ) {
1179 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1180 fclose( $op['stream'] ); // close open handle
1181 if ( $rcode >= 200 && $rcode <= 299 ) {
1182 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1183 // Double check that the disk is not full/broken
1184 if ( $size != $rhdrs['content-length'] ) {
1185 $tmpFiles[$path] = null;
1186 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1187 $this->onError( null, __METHOD__
,
1188 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1190 // Set the file stat process cache in passing
1191 $stat = $this->getStatFromHeaders( $rhdrs );
1192 $stat['latest'] = $isLatest;
1193 $this->cheapCache
->setField( $path, 'stat', $stat );
1194 } elseif ( $rcode === 404 ) {
1195 $tmpFiles[$path] = false;
1197 $tmpFiles[$path] = null;
1198 $this->onError( null, __METHOD__
,
1199 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1206 public function getFileHttpUrl( array $params ) {
1207 if ( $this->swiftTempUrlKey
!= '' ||
1208 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1210 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1211 if ( $srcRel === null ) {
1212 return null; // invalid path
1215 $auth = $this->getAuthentication();
1220 $ttl = $params['ttl'] ??
86400;
1221 $expires = time() +
$ttl;
1223 if ( $this->swiftTempUrlKey
!= '' ) {
1224 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1225 // Swift wants the signature based on the unencoded object name
1226 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1227 $signature = hash_hmac( 'sha1',
1228 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1229 $this->swiftTempUrlKey
1232 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1233 } else { // give S3 API URL for rgw
1234 // Path for signature starts with the bucket
1235 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1236 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1237 // Calculate the hash
1238 $signature = base64_encode( hash_hmac(
1240 "GET\n\n\n{$expires}\n{$spath}",
1241 $this->rgwS3SecretKey
,
1244 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1245 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1246 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1247 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1250 'Signature' => $signature,
1251 'Expires' => $expires,
1252 'AWSAccessKeyId' => $this->rgwS3AccessKey
1260 protected function directoriesAreVirtual() {
1265 * Get headers to send to Swift when reading a file based
1266 * on a FileBackend params array, e.g. that of getLocalCopy().
1267 * $params is currently only checked for a 'latest' flag.
1269 * @param array $params
1272 protected function headersFromParams( array $params ) {
1274 if ( !empty( $params['latest'] ) ) {
1275 $hdrs['x-newest'] = 'true';
1282 * @param FileBackendStoreOpHandle[] $fileOpHandles
1284 * @return StatusValue[]
1286 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1287 /** @var StatusValue[] $statuses */
1290 $auth = $this->getAuthentication();
1292 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1293 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1299 // Split the HTTP requests into stages that can be done concurrently
1300 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1301 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1302 /** @var SwiftFileOpHandle $fileOpHandle */
1303 $reqs = $fileOpHandle->httpOp
;
1304 // Convert the 'url' parameter to an actual URL using $auth
1305 foreach ( $reqs as $stage => &$req ) {
1306 list( $container, $relPath ) = $req['url'];
1307 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1308 $req['headers'] = $req['headers'] ??
[];
1309 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1310 $httpReqsByStage[$stage][$index] = $req;
1312 $statuses[$index] = $this->newStatus();
1315 // Run all requests for the first stage, then the next, and so on
1316 $reqCount = count( $httpReqsByStage );
1317 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1318 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1319 foreach ( $httpReqs as $index => $httpReq ) {
1320 // Run the callback for each request of this operation
1321 $callback = $fileOpHandles[$index]->callback
;
1322 $callback( $httpReq, $statuses[$index] );
1323 // On failure, abort all remaining requests for this operation
1324 // (e.g. abort the DELETE request if the COPY request fails for a move)
1325 if ( !$statuses[$index]->isOK() ) {
1326 $stages = count( $fileOpHandles[$index]->httpOp
);
1327 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1328 unset( $httpReqsByStage[$s][$index] );
1338 * Set read/write permissions for a Swift container.
1340 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1342 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1343 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1345 * @param string $container Resolved Swift container
1346 * @param array $readUsers List of the possible criteria for a request to have
1347 * access to read a container. Each item is one of the following formats:
1348 * - account:user : Grants access if the request is by the given user
1349 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1350 * matches the expression and the request is not for a listing.
1351 * Setting this to '*' effectively makes a container public.
1352 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1353 * matches the expression and the request is for a listing.
1354 * @param array $writeUsers A list of the possible criteria for a request to have
1355 * access to write to a container. Each item is of the following format:
1356 * - account:user : Grants access if the request is by the given user
1357 * @return StatusValue
1359 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1360 $status = $this->newStatus();
1361 $auth = $this->getAuthentication();
1364 $status->fatal( 'backend-fail-connect', $this->name
);
1369 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1371 'url' => $this->storageUrl( $auth, $container ),
1372 'headers' => $this->authTokenHeaders( $auth ) +
[
1373 'x-container-read' => implode( ',', $readUsers ),
1374 'x-container-write' => implode( ',', $writeUsers )
1378 if ( $rcode != 204 && $rcode !== 202 ) {
1379 $status->fatal( 'backend-fail-internal', $this->name
);
1380 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1381 [ 'rcode' => $rcode ] );
1388 * Get a Swift container stat array, possibly from process cache.
1389 * Use $reCache if the file count or byte count is needed.
1391 * @param string $container Container name
1392 * @param bool $bypassCache Bypass all caches and load from Swift
1393 * @return array|bool|null False on 404, null on failure
1395 protected function getContainerStat( $container, $bypassCache = false ) {
1396 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1398 if ( $bypassCache ) { // purge cache
1399 $this->containerStatCache
->clear( $container );
1400 } elseif ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1401 $this->primeContainerCache( [ $container ] ); // check persistent cache
1403 if ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1404 $auth = $this->getAuthentication();
1406 return self
::UNKNOWN
;
1409 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1411 'url' => $this->storageUrl( $auth, $container ),
1412 'headers' => $this->authTokenHeaders( $auth )
1415 if ( $rcode === 204 ) {
1417 'count' => $rhdrs['x-container-object-count'],
1418 'bytes' => $rhdrs['x-container-bytes-used']
1420 if ( $bypassCache ) {
1423 $this->containerStatCache
->setField( $container, 'stat', $stat ); // cache it
1424 $this->setContainerCache( $container, $stat ); // update persistent cache
1426 } elseif ( $rcode === 404 ) {
1429 $this->onError( null, __METHOD__
,
1430 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1432 return self
::UNKNOWN
;
1436 return $this->containerStatCache
->getField( $container, 'stat' );
1440 * Create a Swift container
1442 * @param string $container Container name
1443 * @param array $params
1444 * @return StatusValue
1446 protected function createContainer( $container, array $params ) {
1447 $status = $this->newStatus();
1449 $auth = $this->getAuthentication();
1451 $status->fatal( 'backend-fail-connect', $this->name
);
1456 // @see SwiftFileBackend::setContainerAccess()
1457 if ( empty( $params['noAccess'] ) ) {
1459 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] );
1460 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
1463 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
1464 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
1467 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1469 'url' => $this->storageUrl( $auth, $container ),
1470 'headers' => $this->authTokenHeaders( $auth ) +
[
1471 'x-container-read' => implode( ',', $readUsers ),
1472 'x-container-write' => implode( ',', $writeUsers )
1476 if ( $rcode === 201 ) { // new
1478 } elseif ( $rcode === 202 ) { // already there
1479 // this shouldn't really happen, but is OK
1481 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1488 * Delete a Swift container
1490 * @param string $container Container name
1491 * @param array $params
1492 * @return StatusValue
1494 protected function deleteContainer( $container, array $params ) {
1495 $status = $this->newStatus();
1497 $auth = $this->getAuthentication();
1499 $status->fatal( 'backend-fail-connect', $this->name
);
1504 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1505 'method' => 'DELETE',
1506 'url' => $this->storageUrl( $auth, $container ),
1507 'headers' => $this->authTokenHeaders( $auth )
1510 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1511 $this->containerStatCache
->clear( $container ); // purge
1512 } elseif ( $rcode === 404 ) { // not there
1513 // this shouldn't really happen, but is OK
1514 } elseif ( $rcode === 409 ) { // not empty
1515 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1517 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1524 * Get a list of objects under a container.
1525 * Either just the names or a list of stdClass objects with details can be returned.
1527 * @param string $fullCont
1528 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1530 * @param string|null $after
1531 * @param string|null $prefix
1532 * @param string|null $delim
1533 * @return StatusValue With the list as value
1535 private function objectListing(
1536 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1538 $status = $this->newStatus();
1540 $auth = $this->getAuthentication();
1542 $status->fatal( 'backend-fail-connect', $this->name
);
1547 $query = [ 'limit' => $limit ];
1548 if ( $type === 'info' ) {
1549 $query['format'] = 'json';
1551 if ( $after !== null ) {
1552 $query['marker'] = $after;
1554 if ( $prefix !== null ) {
1555 $query['prefix'] = $prefix;
1557 if ( $delim !== null ) {
1558 $query['delimiter'] = $delim;
1561 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1563 'url' => $this->storageUrl( $auth, $fullCont ),
1565 'headers' => $this->authTokenHeaders( $auth )
1568 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1569 if ( $rcode === 200 ) { // good
1570 if ( $type === 'info' ) {
1571 $status->value
= FormatJson
::decode( trim( $rbody ) );
1573 $status->value
= explode( "\n", trim( $rbody ) );
1575 } elseif ( $rcode === 204 ) {
1576 $status->value
= []; // empty container
1577 } elseif ( $rcode === 404 ) {
1578 $status->value
= []; // no container
1580 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1586 protected function doPrimeContainerCache( array $containerInfo ) {
1587 foreach ( $containerInfo as $container => $info ) {
1588 $this->containerStatCache
->setField( $container, 'stat', $info );
1592 protected function doGetFileStatMulti( array $params ) {
1595 $auth = $this->getAuthentication();
1598 foreach ( $params['srcs'] as $path ) {
1599 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1600 if ( $srcRel === null ) {
1601 $stats[$path] = false;
1602 continue; // invalid storage path
1603 } elseif ( !$auth ) {
1604 $stats[$path] = self
::UNKNOWN
;
1608 // (a) Check the container
1609 $cstat = $this->getContainerStat( $srcCont );
1610 if ( $cstat === false ) {
1611 $stats[$path] = false;
1612 continue; // ok, nothing to do
1613 } elseif ( !is_array( $cstat ) ) {
1614 $stats[$path] = self
::UNKNOWN
;
1620 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1621 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1625 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1626 $reqs = $this->http
->runMulti( $reqs, $opts );
1628 foreach ( $params['srcs'] as $path ) {
1629 if ( array_key_exists( $path, $stats ) ) {
1630 continue; // some sort of failure above
1632 // (b) Check the file
1633 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1634 if ( $rcode === 200 ||
$rcode === 204 ) {
1635 // Update the object if it is missing some headers
1636 if ( !empty( $params['requireSHA1'] ) ) {
1637 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1639 // Load the stat array from the headers
1640 $stat = $this->getStatFromHeaders( $rhdrs );
1641 if ( $this->isRGW
) {
1642 $stat['latest'] = true; // strong consistency
1644 } elseif ( $rcode === 404 ) {
1647 $stat = self
::UNKNOWN
;
1648 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1650 $stats[$path] = $stat;
1657 * @param array $rhdrs
1660 protected function getStatFromHeaders( array $rhdrs ) {
1661 // Fetch all of the custom metadata headers
1662 $metadata = $this->getMetadata( $rhdrs );
1663 // Fetch all of the custom raw HTTP headers
1664 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1667 // Convert various random Swift dates to TS_MW
1668 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1669 // Empty objects actually return no content-length header in Ceph
1670 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1671 'sha1' => $metadata['sha1base36'] ??
null,
1672 // Note: manifiest ETags are not an MD5 of the file
1673 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1674 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1679 * @return array|null Credential map
1681 protected function getAuthentication() {
1682 if ( $this->authErrorTimestamp
!== null ) {
1683 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1684 return null; // failed last attempt; don't bother
1685 } else { // actually retry this time
1686 $this->authErrorTimestamp
= null;
1689 // Session keys expire after a while, so we renew them periodically
1690 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1691 // Authenticate with proxy and get a session key...
1692 if ( !$this->authCreds ||
$reAuth ) {
1693 $this->authSessionTimestamp
= 0;
1694 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1695 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1696 // Try to use the credential cache
1697 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1698 $this->authCreds
= $creds;
1699 // Skew the timestamp for worst case to avoid using stale credentials
1700 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1701 } else { // cache miss
1702 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1704 'url' => "{$this->swiftAuthUrl}/v1.0",
1706 'x-auth-user' => $this->swiftUser
,
1707 'x-auth-key' => $this->swiftKey
1711 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1712 $this->authCreds
= [
1713 'auth_token' => $rhdrs['x-auth-token'],
1714 'storage_url' => $this->swiftStorageUrl ??
$rhdrs['x-storage-url']
1717 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1718 $this->authSessionTimestamp
= time();
1719 } elseif ( $rcode === 401 ) {
1720 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1721 $this->authErrorTimestamp
= time();
1725 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1726 $this->authErrorTimestamp
= time();
1731 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1732 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1733 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1737 return $this->authCreds
;
1741 * @param array $creds From getAuthentication()
1742 * @param string|null $container
1743 * @param string|null $object
1746 protected function storageUrl( array $creds, $container = null, $object = null ) {
1747 $parts = [ $creds['storage_url'] ];
1748 if ( strlen( $container ) ) {
1749 $parts[] = rawurlencode( $container );
1751 if ( strlen( $object ) ) {
1752 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1755 return implode( '/', $parts );
1759 * @param array $creds From getAuthentication()
1762 protected function authTokenHeaders( array $creds ) {
1763 return [ 'x-auth-token' => $creds['auth_token'] ];
1767 * Get the cache key for a container
1769 * @param string $username
1772 private function getCredsCacheKey( $username ) {
1773 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1777 * Log an unexpected exception for this backend.
1778 * This also sets the StatusValue object to have a fatal error.
1780 * @param StatusValue|null $status
1781 * @param string $func
1782 * @param array $params
1783 * @param string $err Error string
1784 * @param int $code HTTP status
1785 * @param string $desc HTTP StatusValue description
1787 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1788 if ( $status instanceof StatusValue
) {
1789 $status->fatal( 'backend-fail-internal', $this->name
);
1791 if ( $code == 401 ) { // possibly a stale token
1792 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1794 $msg = "HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1799 'req_params' => FormatJson
::encode( $params ),
1803 $msgParams['err'] = $err;
1805 $this->logger
->error( $msg, $msgParams );