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 === null ) {
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 null; // 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 foreach ( $objects as $object ) { // files and directories
888 if ( substr( $object, -1 ) === '/' ) {
889 $dirs[] = $object; // directories end in '/'
893 // Recursive: list all dirs under $dir and its subdirs
894 $getParentDir = function ( $path ) {
895 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
898 // Get directory from last item of prior page
899 $lastDir = $getParentDir( $after ); // must be first page
900 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
902 if ( !$status->isOK() ) {
903 throw new FileBackendError( "Iterator page I/O error." );
906 $objects = $status->value
;
908 foreach ( $objects as $object ) { // files
909 $objectDir = $getParentDir( $object ); // directory of object
911 if ( $objectDir !== false && $objectDir !== $dir ) {
912 // Swift stores paths in UTF-8, using binary sorting.
913 // See function "create_container_table" in common/db.py.
914 // If a directory is not "greater" than the last one,
915 // then it was already listed by the calling iterator.
916 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
918 do { // add dir and all its parent dirs
919 $dirs[] = "{$pDir}/";
920 $pDir = $getParentDir( $pDir );
921 } while ( $pDir !== false // sanity
922 && strcmp( $pDir, $lastDir ) > 0 // not done already
923 && strlen( $pDir ) > strlen( $dir ) // within $dir
926 $lastDir = $objectDir;
930 // Page on the unfiltered directory listing (what is returned may be filtered)
931 if ( count( $objects ) < $limit ) {
932 $after = INF
; // avoid a second RTT
934 $after = end( $objects ); // update last item
941 * Do not call this function outside of SwiftFileBackendFileList
943 * @param string $fullCont Resolved container name
944 * @param string $dir Resolved storage directory with no trailing slash
945 * @param string|null &$after Resolved container relative path of file to list items after
946 * @param int $limit Max number of items to list
947 * @param array $params Parameters for getDirectoryList()
948 * @return array List of resolved container relative paths of files under $dir
949 * @throws FileBackendError
951 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
952 $files = []; // list of (path, stat array or null) entries
953 if ( $after === INF
) {
954 return $files; // nothing more
957 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
959 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
960 // $objects will contain a list of unfiltered names or CF_Object items
961 // Non-recursive: only list files right under $dir
962 if ( !empty( $params['topOnly'] ) ) {
963 if ( !empty( $params['adviseStat'] ) ) {
964 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
966 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
969 // Recursive: list all files under $dir and its subdirs
970 if ( !empty( $params['adviseStat'] ) ) {
971 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
973 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
977 // Reformat this list into a list of (name, stat array or null) entries
978 if ( !$status->isOK() ) {
979 throw new FileBackendError( "Iterator page I/O error." );
982 $objects = $status->value
;
983 $files = $this->buildFileObjectListing( $params, $dir, $objects );
985 // Page on the unfiltered object listing (what is returned may be filtered)
986 if ( count( $objects ) < $limit ) {
987 $after = INF
; // avoid a second RTT
989 $after = end( $objects ); // update last item
990 $after = is_object( $after ) ?
$after->name
: $after;
997 * Build a list of file objects, filtering out any directories
998 * and extracting any stat info if provided in $objects (for CF_Objects)
1000 * @param array $params Parameters for getDirectoryList()
1001 * @param string $dir Resolved container directory path
1002 * @param array $objects List of CF_Object items or object names
1003 * @return array List of (names,stat array or null) entries
1005 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1007 foreach ( $objects as $object ) {
1008 if ( is_object( $object ) ) {
1009 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1010 continue; // virtual directory entry; ignore
1013 // Convert various random Swift dates to TS_MW
1014 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1015 'size' => (int)$object->bytes
,
1017 // Note: manifiest ETags are not an MD5 of the file
1018 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1019 'latest' => false // eventually consistent
1021 $names[] = [ $object->name
, $stat ];
1022 } elseif ( substr( $object, -1 ) !== '/' ) {
1023 // Omit directories, which end in '/' in listings
1024 $names[] = [ $object, null ];
1032 * Do not call this function outside of SwiftFileBackendFileList
1034 * @param string $path Storage path
1035 * @param array $val Stat value
1037 public function loadListingStatInternal( $path, array $val ) {
1038 $this->cheapCache
->setField( $path, 'stat', $val );
1041 protected function doGetFileXAttributes( array $params ) {
1042 $stat = $this->getFileStat( $params );
1044 if ( !isset( $stat['xattr'] ) ) {
1045 // Stat entries filled by file listings don't include metadata/headers
1046 $this->clearCache( [ $params['src'] ] );
1047 $stat = $this->getFileStat( $params );
1050 return $stat['xattr'];
1056 protected function doGetFileSha1base36( array $params ) {
1057 // Avoid using stat entries from file listings, which never include the SHA-1 hash.
1058 // Also, recompute the hash if it's not part of the metadata headers for some reason.
1059 $params['requireSHA1'] = true;
1061 $stat = $this->getFileStat( $params );
1063 return $stat['sha1'];
1069 protected function doStreamFile( array $params ) {
1070 $status = $this->newStatus();
1072 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1074 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1075 if ( $srcRel === null ) {
1076 StreamFile
::send404Message( $params['src'], $flags );
1077 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1082 $auth = $this->getAuthentication();
1083 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1084 StreamFile
::send404Message( $params['src'], $flags );
1085 $status->fatal( 'backend-fail-stream', $params['src'] );
1090 // If "headers" is set, we only want to send them if the file is there.
1091 // Do not bother checking if the file exists if headers are not set though.
1092 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1093 StreamFile
::send404Message( $params['src'], $flags );
1094 $status->fatal( 'backend-fail-stream', $params['src'] );
1099 // Send the requested additional headers
1100 foreach ( $params['headers'] as $header ) {
1101 header( $header ); // aways send
1104 if ( empty( $params['allowOB'] ) ) {
1105 // Cancel output buffering and gzipping if set
1106 ( $this->obResetFunc
)();
1109 $handle = fopen( 'php://output', 'wb' );
1110 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1112 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1113 'headers' => $this->authTokenHeaders( $auth )
1114 +
$this->headersFromParams( $params ) +
$params['options'],
1115 'stream' => $handle,
1116 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1119 if ( $rcode >= 200 && $rcode <= 299 ) {
1121 } elseif ( $rcode === 404 ) {
1122 $status->fatal( 'backend-fail-stream', $params['src'] );
1123 // Per T43113, nasty things can happen if bad cache entries get
1124 // stuck in cache. It's also possible that this error can come up
1125 // with simple race conditions. Clear out the stat cache to be safe.
1126 $this->clearCache( [ $params['src'] ] );
1127 $this->deleteFileCache( $params['src'] );
1129 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1135 protected function doGetLocalCopyMulti( array $params ) {
1136 /** @var TempFSFile[] $tmpFiles */
1139 $auth = $this->getAuthentication();
1141 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1142 // Blindly create tmp files and stream to them, catching any exception
1143 // if the file does not exist. Do not waste time doing file stats here.
1144 $reqs = []; // (path => op)
1146 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1147 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1148 if ( $srcRel === null ||
!$auth ) {
1149 $tmpFiles[$path] = null;
1152 // Get source file extension
1153 $ext = FileBackend
::extensionFromPath( $path );
1154 // Create a new temporary file...
1155 $tmpFile = $this->tmpFileFactory
->newTempFSFile( 'localcopy_', $ext );
1157 $handle = fopen( $tmpFile->getPath(), 'wb' );
1161 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1162 'headers' => $this->authTokenHeaders( $auth )
1163 +
$this->headersFromParams( $params ),
1164 'stream' => $handle,
1170 $tmpFiles[$path] = $tmpFile;
1173 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1174 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1175 $reqs = $this->http
->runMulti( $reqs, $opts );
1176 foreach ( $reqs as $path => $op ) {
1177 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1178 fclose( $op['stream'] ); // close open handle
1179 if ( $rcode >= 200 && $rcode <= 299 ) {
1180 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1181 // Double check that the disk is not full/broken
1182 if ( $size != $rhdrs['content-length'] ) {
1183 $tmpFiles[$path] = null;
1184 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1185 $this->onError( null, __METHOD__
,
1186 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1188 // Set the file stat process cache in passing
1189 $stat = $this->getStatFromHeaders( $rhdrs );
1190 $stat['latest'] = $isLatest;
1191 $this->cheapCache
->setField( $path, 'stat', $stat );
1192 } elseif ( $rcode === 404 ) {
1193 $tmpFiles[$path] = false;
1195 $tmpFiles[$path] = null;
1196 $this->onError( null, __METHOD__
,
1197 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1204 public function getFileHttpUrl( array $params ) {
1205 if ( $this->swiftTempUrlKey
!= '' ||
1206 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1208 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1209 if ( $srcRel === null ) {
1210 return null; // invalid path
1213 $auth = $this->getAuthentication();
1218 $ttl = $params['ttl'] ??
86400;
1219 $expires = time() +
$ttl;
1221 if ( $this->swiftTempUrlKey
!= '' ) {
1222 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1223 // Swift wants the signature based on the unencoded object name
1224 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1225 $signature = hash_hmac( 'sha1',
1226 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1227 $this->swiftTempUrlKey
1230 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1231 } else { // give S3 API URL for rgw
1232 // Path for signature starts with the bucket
1233 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1234 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1235 // Calculate the hash
1236 $signature = base64_encode( hash_hmac(
1238 "GET\n\n\n{$expires}\n{$spath}",
1239 $this->rgwS3SecretKey
,
1242 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1243 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1244 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1245 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1248 'Signature' => $signature,
1249 'Expires' => $expires,
1250 'AWSAccessKeyId' => $this->rgwS3AccessKey
1258 protected function directoriesAreVirtual() {
1263 * Get headers to send to Swift when reading a file based
1264 * on a FileBackend params array, e.g. that of getLocalCopy().
1265 * $params is currently only checked for a 'latest' flag.
1267 * @param array $params
1270 protected function headersFromParams( array $params ) {
1272 if ( !empty( $params['latest'] ) ) {
1273 $hdrs['x-newest'] = 'true';
1280 * @param FileBackendStoreOpHandle[] $fileOpHandles
1282 * @return StatusValue[]
1284 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1285 /** @var StatusValue[] $statuses */
1288 $auth = $this->getAuthentication();
1290 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1291 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1297 // Split the HTTP requests into stages that can be done concurrently
1298 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1299 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1300 /** @var SwiftFileOpHandle $fileOpHandle */
1301 $reqs = $fileOpHandle->httpOp
;
1302 // Convert the 'url' parameter to an actual URL using $auth
1303 foreach ( $reqs as $stage => &$req ) {
1304 list( $container, $relPath ) = $req['url'];
1305 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1306 $req['headers'] = $req['headers'] ??
[];
1307 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1308 $httpReqsByStage[$stage][$index] = $req;
1310 $statuses[$index] = $this->newStatus();
1313 // Run all requests for the first stage, then the next, and so on
1314 $reqCount = count( $httpReqsByStage );
1315 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1316 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1317 foreach ( $httpReqs as $index => $httpReq ) {
1318 // Run the callback for each request of this operation
1319 $callback = $fileOpHandles[$index]->callback
;
1320 $callback( $httpReq, $statuses[$index] );
1321 // On failure, abort all remaining requests for this operation
1322 // (e.g. abort the DELETE request if the COPY request fails for a move)
1323 if ( !$statuses[$index]->isOK() ) {
1324 $stages = count( $fileOpHandles[$index]->httpOp
);
1325 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1326 unset( $httpReqsByStage[$s][$index] );
1336 * Set read/write permissions for a Swift container.
1338 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1340 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1341 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1343 * @param string $container Resolved Swift container
1344 * @param array $readUsers List of the possible criteria for a request to have
1345 * access to read a container. Each item is one of the following formats:
1346 * - account:user : Grants access if the request is by the given user
1347 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1348 * matches the expression and the request is not for a listing.
1349 * Setting this to '*' effectively makes a container public.
1350 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1351 * matches the expression and the request is for a listing.
1352 * @param array $writeUsers A list of the possible criteria for a request to have
1353 * access to write to a container. Each item is of the following format:
1354 * - account:user : Grants access if the request is by the given user
1355 * @return StatusValue
1357 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1358 $status = $this->newStatus();
1359 $auth = $this->getAuthentication();
1362 $status->fatal( 'backend-fail-connect', $this->name
);
1367 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1369 'url' => $this->storageUrl( $auth, $container ),
1370 'headers' => $this->authTokenHeaders( $auth ) +
[
1371 'x-container-read' => implode( ',', $readUsers ),
1372 'x-container-write' => implode( ',', $writeUsers )
1376 if ( $rcode != 204 && $rcode !== 202 ) {
1377 $status->fatal( 'backend-fail-internal', $this->name
);
1378 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1379 [ 'rcode' => $rcode ] );
1386 * Get a Swift container stat array, possibly from process cache.
1387 * Use $reCache if the file count or byte count is needed.
1389 * @param string $container Container name
1390 * @param bool $bypassCache Bypass all caches and load from Swift
1391 * @return array|bool|null False on 404, null on failure
1393 protected function getContainerStat( $container, $bypassCache = false ) {
1394 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1396 if ( $bypassCache ) { // purge cache
1397 $this->containerStatCache
->clear( $container );
1398 } elseif ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1399 $this->primeContainerCache( [ $container ] ); // check persistent cache
1401 if ( !$this->containerStatCache
->hasField( $container, 'stat' ) ) {
1402 $auth = $this->getAuthentication();
1407 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1409 'url' => $this->storageUrl( $auth, $container ),
1410 'headers' => $this->authTokenHeaders( $auth )
1413 if ( $rcode === 204 ) {
1415 'count' => $rhdrs['x-container-object-count'],
1416 'bytes' => $rhdrs['x-container-bytes-used']
1418 if ( $bypassCache ) {
1421 $this->containerStatCache
->setField( $container, 'stat', $stat ); // cache it
1422 $this->setContainerCache( $container, $stat ); // update persistent cache
1424 } elseif ( $rcode === 404 ) {
1427 $this->onError( null, __METHOD__
,
1428 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1434 return $this->containerStatCache
->getField( $container, 'stat' );
1438 * Create a Swift container
1440 * @param string $container Container name
1441 * @param array $params
1442 * @return StatusValue
1444 protected function createContainer( $container, array $params ) {
1445 $status = $this->newStatus();
1447 $auth = $this->getAuthentication();
1449 $status->fatal( 'backend-fail-connect', $this->name
);
1454 // @see SwiftFileBackend::setContainerAccess()
1455 if ( empty( $params['noAccess'] ) ) {
1457 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] );
1458 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
1461 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
1462 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
1465 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1467 'url' => $this->storageUrl( $auth, $container ),
1468 'headers' => $this->authTokenHeaders( $auth ) +
[
1469 'x-container-read' => implode( ',', $readUsers ),
1470 'x-container-write' => implode( ',', $writeUsers )
1474 if ( $rcode === 201 ) { // new
1476 } elseif ( $rcode === 202 ) { // already there
1477 // this shouldn't really happen, but is OK
1479 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1486 * Delete a Swift container
1488 * @param string $container Container name
1489 * @param array $params
1490 * @return StatusValue
1492 protected function deleteContainer( $container, array $params ) {
1493 $status = $this->newStatus();
1495 $auth = $this->getAuthentication();
1497 $status->fatal( 'backend-fail-connect', $this->name
);
1502 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1503 'method' => 'DELETE',
1504 'url' => $this->storageUrl( $auth, $container ),
1505 'headers' => $this->authTokenHeaders( $auth )
1508 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1509 $this->containerStatCache
->clear( $container ); // purge
1510 } elseif ( $rcode === 404 ) { // not there
1511 // this shouldn't really happen, but is OK
1512 } elseif ( $rcode === 409 ) { // not empty
1513 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1515 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1522 * Get a list of objects under a container.
1523 * Either just the names or a list of stdClass objects with details can be returned.
1525 * @param string $fullCont
1526 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1528 * @param string|null $after
1529 * @param string|null $prefix
1530 * @param string|null $delim
1531 * @return StatusValue With the list as value
1533 private function objectListing(
1534 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1536 $status = $this->newStatus();
1538 $auth = $this->getAuthentication();
1540 $status->fatal( 'backend-fail-connect', $this->name
);
1545 $query = [ 'limit' => $limit ];
1546 if ( $type === 'info' ) {
1547 $query['format'] = 'json';
1549 if ( $after !== null ) {
1550 $query['marker'] = $after;
1552 if ( $prefix !== null ) {
1553 $query['prefix'] = $prefix;
1555 if ( $delim !== null ) {
1556 $query['delimiter'] = $delim;
1559 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1561 'url' => $this->storageUrl( $auth, $fullCont ),
1563 'headers' => $this->authTokenHeaders( $auth )
1566 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1567 if ( $rcode === 200 ) { // good
1568 if ( $type === 'info' ) {
1569 $status->value
= FormatJson
::decode( trim( $rbody ) );
1571 $status->value
= explode( "\n", trim( $rbody ) );
1573 } elseif ( $rcode === 204 ) {
1574 $status->value
= []; // empty container
1575 } elseif ( $rcode === 404 ) {
1576 $status->value
= []; // no container
1578 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1584 protected function doPrimeContainerCache( array $containerInfo ) {
1585 foreach ( $containerInfo as $container => $info ) {
1586 $this->containerStatCache
->setField( $container, 'stat', $info );
1590 protected function doGetFileStatMulti( array $params ) {
1593 $auth = $this->getAuthentication();
1596 foreach ( $params['srcs'] as $path ) {
1597 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1598 if ( $srcRel === null ) {
1599 $stats[$path] = false;
1600 continue; // invalid storage path
1601 } elseif ( !$auth ) {
1602 $stats[$path] = null;
1606 // (a) Check the container
1607 $cstat = $this->getContainerStat( $srcCont );
1608 if ( $cstat === false ) {
1609 $stats[$path] = false;
1610 continue; // ok, nothing to do
1611 } elseif ( !is_array( $cstat ) ) {
1612 $stats[$path] = null;
1618 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1619 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1623 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1624 $reqs = $this->http
->runMulti( $reqs, $opts );
1626 foreach ( $params['srcs'] as $path ) {
1627 if ( array_key_exists( $path, $stats ) ) {
1628 continue; // some sort of failure above
1630 // (b) Check the file
1631 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1632 if ( $rcode === 200 ||
$rcode === 204 ) {
1633 // Update the object if it is missing some headers
1634 if ( !empty( $params['requireSHA1'] ) ) {
1635 $rhdrs = $this->addMissingHashMetadata( $rhdrs, $path );
1637 // Load the stat array from the headers
1638 $stat = $this->getStatFromHeaders( $rhdrs );
1639 if ( $this->isRGW
) {
1640 $stat['latest'] = true; // strong consistency
1642 } elseif ( $rcode === 404 ) {
1646 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1648 $stats[$path] = $stat;
1655 * @param array $rhdrs
1658 protected function getStatFromHeaders( array $rhdrs ) {
1659 // Fetch all of the custom metadata headers
1660 $metadata = $this->getMetadata( $rhdrs );
1661 // Fetch all of the custom raw HTTP headers
1662 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1665 // Convert various random Swift dates to TS_MW
1666 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1667 // Empty objects actually return no content-length header in Ceph
1668 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1669 'sha1' => $metadata['sha1base36'] ??
null,
1670 // Note: manifiest ETags are not an MD5 of the file
1671 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1672 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1677 * @return array|null Credential map
1679 protected function getAuthentication() {
1680 if ( $this->authErrorTimestamp
!== null ) {
1681 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1682 return null; // failed last attempt; don't bother
1683 } else { // actually retry this time
1684 $this->authErrorTimestamp
= null;
1687 // Session keys expire after a while, so we renew them periodically
1688 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1689 // Authenticate with proxy and get a session key...
1690 if ( !$this->authCreds ||
$reAuth ) {
1691 $this->authSessionTimestamp
= 0;
1692 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1693 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1694 // Try to use the credential cache
1695 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1696 $this->authCreds
= $creds;
1697 // Skew the timestamp for worst case to avoid using stale credentials
1698 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1699 } else { // cache miss
1700 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1702 'url' => "{$this->swiftAuthUrl}/v1.0",
1704 'x-auth-user' => $this->swiftUser
,
1705 'x-auth-key' => $this->swiftKey
1709 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1710 $this->authCreds
= [
1711 'auth_token' => $rhdrs['x-auth-token'],
1712 'storage_url' => $this->swiftStorageUrl ??
$rhdrs['x-storage-url']
1715 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1716 $this->authSessionTimestamp
= time();
1717 } elseif ( $rcode === 401 ) {
1718 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1719 $this->authErrorTimestamp
= time();
1723 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1724 $this->authErrorTimestamp
= time();
1729 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1730 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1731 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1735 return $this->authCreds
;
1739 * @param array $creds From getAuthentication()
1740 * @param string|null $container
1741 * @param string|null $object
1744 protected function storageUrl( array $creds, $container = null, $object = null ) {
1745 $parts = [ $creds['storage_url'] ];
1746 if ( strlen( $container ) ) {
1747 $parts[] = rawurlencode( $container );
1749 if ( strlen( $object ) ) {
1750 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1753 return implode( '/', $parts );
1757 * @param array $creds From getAuthentication()
1760 protected function authTokenHeaders( array $creds ) {
1761 return [ 'x-auth-token' => $creds['auth_token'] ];
1765 * Get the cache key for a container
1767 * @param string $username
1770 private function getCredsCacheKey( $username ) {
1771 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1775 * Log an unexpected exception for this backend.
1776 * This also sets the StatusValue object to have a fatal error.
1778 * @param StatusValue|null $status
1779 * @param string $func
1780 * @param array $params
1781 * @param string $err Error string
1782 * @param int $code HTTP status
1783 * @param string $desc HTTP StatusValue description
1785 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1786 if ( $status instanceof StatusValue
) {
1787 $status->fatal( 'backend-fail-internal', $this->name
);
1789 if ( $code == 401 ) { // possibly a stale token
1790 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1792 $msg = "HTTP {code} ({desc}) in '{func}' (given '{req_params}')";
1797 'req_params' => FormatJson
::encode( $params ),
1801 $msgParams['err'] = $err;
1803 $this->logger
->error( $msg, $msgParams );