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
26 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
28 * StatusValue messages should avoid mentioning the Swift account name.
29 * Likewise, error suppression should be used to avoid path disclosure.
31 * @ingroup FileBackend
34 class SwiftFileBackend
extends FileBackendStore
{
35 /** @var MultiHttpClient */
37 /** @var int TTL in seconds */
39 /** @var string Authentication base URL (without version) */
40 protected $swiftAuthUrl;
41 /** @var string Override of storage base URL */
42 protected $swiftStorageUrl;
43 /** @var string Swift user (account:user) to authenticate as */
45 /** @var string Secret key for user */
47 /** @var string Shared secret value for making temp URLs */
48 protected $swiftTempUrlKey;
49 /** @var string S3 access key (RADOS Gateway) */
50 protected $rgwS3AccessKey;
51 /** @var string S3 authentication key (RADOS Gateway) */
52 protected $rgwS3SecretKey;
53 /** @var array Additional users (account:user) with read permissions on public containers */
55 /** @var array Additional users (account:user) with write permissions on public containers */
56 protected $writeUsers;
57 /** @var array Additional users (account:user) with read permissions on private containers */
58 protected $secureReadUsers;
59 /** @var array Additional users (account:user) with write permissions on private containers */
60 protected $secureWriteUsers;
65 /** @var ProcessCacheLRU Container stat cache */
66 protected $containerStatCache;
70 /** @var int UNIX timestamp */
71 protected $authSessionTimestamp = 0;
72 /** @var int UNIX timestamp */
73 protected $authErrorTimestamp = null;
75 /** @var bool Whether the server is an Ceph RGW */
76 protected $isRGW = false;
79 * @see FileBackendStore::__construct()
80 * @param array $config Params include:
81 * - swiftAuthUrl : Swift authentication server URL
82 * - swiftUser : Swift user used by MediaWiki (account:username)
83 * - swiftKey : Swift authentication key for the above user
84 * - swiftAuthTTL : Swift authentication TTL (seconds)
85 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
86 * Do not set this until it has been set in the backend.
87 * - swiftStorageUrl : Swift storage URL (overrides that of the authentication response).
88 * This is useful to set if a TLS proxy is in use.
89 * - shardViaHashLevels : Map of container names to sharding config with:
90 * - base : base of hash characters, 16 or 36
91 * - levels : the number of hash levels (and digits)
92 * - repeat : hash subdirectories are prefixed with all the
93 * parent hash directory names (e.g. "a/ab/abc")
94 * - cacheAuthInfo : Whether to cache authentication tokens in APC, etc.
95 * If those are not available, then the main cache will be used.
96 * This is probably insecure in shared hosting environments.
97 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
98 * Do not set this until it has been set in the backend.
99 * This is used for generating expiring pre-authenticated URLs.
100 * Only use this when using rgw and to work around
101 * http://tracker.newdream.net/issues/3454.
102 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
103 * Do not set this until it has been set in the backend.
104 * This is used for generating expiring pre-authenticated URLs.
105 * Only use this when using rgw and to work around
106 * http://tracker.newdream.net/issues/3454.
107 * - readUsers : Swift users with read access to public containers (account:username)
108 * - writeUsers : Swift users with write access to public containers (account:username)
109 * - secureReadUsers : Swift users with read access to private containers (account:username)
110 * - secureWriteUsers : Swift users with write access to private containers (account:username)
112 public function __construct( array $config ) {
113 parent
::__construct( $config );
115 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
116 $this->swiftUser
= $config['swiftUser'];
117 $this->swiftKey
= $config['swiftKey'];
119 $this->authTTL
= $config['swiftAuthTTL'] ??
15 * 60; // some sane number
120 $this->swiftTempUrlKey
= $config['swiftTempUrlKey'] ??
'';
121 $this->swiftStorageUrl
= $config['swiftStorageUrl'] ??
null;
122 $this->shardViaHashLevels
= $config['shardViaHashLevels'] ??
'';
123 $this->rgwS3AccessKey
= $config['rgwS3AccessKey'] ??
'';
124 $this->rgwS3SecretKey
= $config['rgwS3SecretKey'] ??
'';
125 // HTTP helper client
126 $this->http
= new MultiHttpClient( [] );
127 // Cache container information to mask latency
128 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
129 $this->memCache
= $config['wanCache'];
131 // Process cache for container info
132 $this->containerStatCache
= new ProcessCacheLRU( 300 );
133 // Cache auth token information to avoid RTTs
134 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
135 $this->srvCache
= $config['srvCache'];
137 $this->srvCache
= new EmptyBagOStuff();
139 $this->readUsers
= $config['readUsers'] ??
[];
140 $this->writeUsers
= $config['writeUsers'] ??
[];
141 $this->secureReadUsers
= $config['secureReadUsers'] ??
[];
142 $this->secureWriteUsers
= $config['secureWriteUsers'] ??
[];
145 public function getFeatures() {
146 return ( FileBackend
::ATTR_UNICODE_PATHS |
147 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
150 protected function resolveContainerPath( $container, $relStoragePath ) {
151 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
152 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
153 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
154 return null; // too long for Swift
157 return $relStoragePath;
160 public function isPathUsableInternal( $storagePath ) {
161 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
162 if ( $rel === null ) {
163 return false; // invalid
166 return is_array( $this->getContainerStat( $container ) );
170 * Sanitize and filter the custom headers from a $params array.
171 * Only allows certain "standard" Content- and X-Content- headers.
173 * @param array $params
174 * @return array Sanitized value of 'headers' field in $params
176 protected function sanitizeHdrsStrict( array $params ) {
177 if ( !isset( $params['headers'] ) ) {
181 $headers = $this->getCustomHeaders( $params['headers'] );
182 unset( $headers[ 'content-type' ] );
188 * Sanitize and filter the custom headers from a $params array.
189 * Only allows certain "standard" Content- and X-Content- headers.
191 * When POSTing data, libcurl adds Content-Type: application/x-www-form-urlencoded
192 * if Content-Type is not set, which overwrites the stored Content-Type header
193 * in Swift - therefore for POSTing data do not strip the Content-Type header (the
194 * previously-stored header that has been already read back from swift is sent)
196 * @param array $params
197 * @return array Sanitized value of 'headers' field in $params
199 protected function sanitizeHdrs( array $params ) {
200 return isset( $params['headers'] )
201 ?
$this->getCustomHeaders( $params['headers'] )
206 * @param array $rawHeaders
207 * @return array Custom non-metadata HTTP headers
209 protected function getCustomHeaders( array $rawHeaders ) {
212 // Normalize casing, and strip out illegal headers
213 foreach ( $rawHeaders as $name => $value ) {
214 $name = strtolower( $name );
215 if ( preg_match( '/^content-length$/', $name ) ) {
216 continue; // blacklisted
217 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
218 $headers[$name] = $value; // allowed
219 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
220 $headers[$name] = $value; // allowed
223 // By default, Swift has annoyingly low maximum header value limits
224 if ( isset( $headers['content-disposition'] ) ) {
226 // @note: assume FileBackend::makeContentDisposition() already used
227 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
228 $part = trim( $part );
229 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
230 if ( strlen( $new ) <= 255 ) {
233 break; // too long; sigh
236 $headers['content-disposition'] = $disposition;
243 * @param array $rawHeaders
244 * @return array Custom metadata headers
246 protected function getMetadataHeaders( array $rawHeaders ) {
248 foreach ( $rawHeaders as $name => $value ) {
249 $name = strtolower( $name );
250 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
251 $headers[$name] = $value;
259 * @param array $rawHeaders
260 * @return array Custom metadata headers with prefix removed
262 protected function getMetadata( array $rawHeaders ) {
264 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
265 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
271 protected function doCreateInternal( array $params ) {
272 $status = $this->newStatus();
274 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
275 if ( $dstRel === null ) {
276 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
281 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
282 $contentType = $params['headers']['content-type']
283 ??
$this->getContentType( $params['dst'], $params['content'], null );
287 'url' => [ $dstCont, $dstRel ],
289 'content-length' => strlen( $params['content'] ),
290 'etag' => md5( $params['content'] ),
291 'content-type' => $contentType,
292 'x-object-meta-sha1base36' => $sha1Hash
293 ] +
$this->sanitizeHdrsStrict( $params ),
294 'body' => $params['content']
297 $method = __METHOD__
;
298 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
299 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
300 if ( $rcode === 201 ) {
302 } elseif ( $rcode === 412 ) {
303 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
305 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
309 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
310 if ( !empty( $params['async'] ) ) { // deferred
311 $status->value
= $opHandle;
312 } else { // actually write the object in Swift
313 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
319 protected function doStoreInternal( array $params ) {
320 $status = $this->newStatus();
322 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
323 if ( $dstRel === null ) {
324 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
329 Wikimedia\
suppressWarnings();
330 $sha1Hash = sha1_file( $params['src'] );
331 Wikimedia\restoreWarnings
();
332 if ( $sha1Hash === false ) { // source doesn't exist?
333 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
337 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
338 $contentType = $params['headers']['content-type']
339 ??
$this->getContentType( $params['dst'], null, $params['src'] );
341 $handle = fopen( $params['src'], 'rb' );
342 if ( $handle === false ) { // source doesn't exist?
343 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
350 'url' => [ $dstCont, $dstRel ],
352 'content-length' => filesize( $params['src'] ),
353 'etag' => md5_file( $params['src'] ),
354 'content-type' => $contentType,
355 'x-object-meta-sha1base36' => $sha1Hash
356 ] +
$this->sanitizeHdrsStrict( $params ),
357 'body' => $handle // resource
360 $method = __METHOD__
;
361 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
362 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
363 if ( $rcode === 201 ) {
365 } elseif ( $rcode === 412 ) {
366 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
368 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
372 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
373 $opHandle->resourcesToClose
[] = $handle;
375 if ( !empty( $params['async'] ) ) { // deferred
376 $status->value
= $opHandle;
377 } else { // actually write the object in Swift
378 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
384 protected function doCopyInternal( array $params ) {
385 $status = $this->newStatus();
387 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
388 if ( $srcRel === null ) {
389 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
394 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
395 if ( $dstRel === null ) {
396 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
403 'url' => [ $dstCont, $dstRel ],
405 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
406 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
407 ] +
$this->sanitizeHdrsStrict( $params ), // extra headers merged into object
410 $method = __METHOD__
;
411 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
412 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
413 if ( $rcode === 201 ) {
415 } elseif ( $rcode === 404 ) {
416 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
418 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
422 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
423 if ( !empty( $params['async'] ) ) { // deferred
424 $status->value
= $opHandle;
425 } else { // actually write the object in Swift
426 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
432 protected function doMoveInternal( array $params ) {
433 $status = $this->newStatus();
435 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
436 if ( $srcRel === null ) {
437 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
442 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
443 if ( $dstRel === null ) {
444 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
452 'url' => [ $dstCont, $dstRel ],
454 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
455 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
456 ] +
$this->sanitizeHdrsStrict( $params ) // extra headers merged into object
459 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
461 'method' => 'DELETE',
462 'url' => [ $srcCont, $srcRel ],
467 $method = __METHOD__
;
468 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
469 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
470 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
472 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
474 } elseif ( $rcode === 404 ) {
475 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
477 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
481 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
482 if ( !empty( $params['async'] ) ) { // deferred
483 $status->value
= $opHandle;
484 } else { // actually move the object in Swift
485 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
491 protected function doDeleteInternal( array $params ) {
492 $status = $this->newStatus();
494 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
495 if ( $srcRel === null ) {
496 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
502 'method' => 'DELETE',
503 'url' => [ $srcCont, $srcRel ],
507 $method = __METHOD__
;
508 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
509 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
510 if ( $rcode === 204 ) {
512 } elseif ( $rcode === 404 ) {
513 if ( empty( $params['ignoreMissingSource'] ) ) {
514 $status->fatal( 'backend-fail-delete', $params['src'] );
517 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
521 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
522 if ( !empty( $params['async'] ) ) { // deferred
523 $status->value
= $opHandle;
524 } else { // actually delete the object in Swift
525 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
531 protected function doDescribeInternal( array $params ) {
532 $status = $this->newStatus();
534 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
535 if ( $srcRel === null ) {
536 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
541 // Fetch the old object headers/metadata...this should be in stat cache by now
542 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
543 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
544 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
547 $status->fatal( 'backend-fail-describe', $params['src'] );
552 // POST clears prior headers, so we need to merge the changes in to the old ones
554 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
555 $metaHdrs["x-object-meta-$name"] = $value;
557 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
561 'url' => [ $srcCont, $srcRel ],
562 'headers' => $metaHdrs +
$customHdrs
565 $method = __METHOD__
;
566 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
567 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
568 if ( $rcode === 202 ) {
570 } elseif ( $rcode === 404 ) {
571 $status->fatal( 'backend-fail-describe', $params['src'] );
573 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
577 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
578 if ( !empty( $params['async'] ) ) { // deferred
579 $status->value
= $opHandle;
580 } else { // actually change the object in Swift
581 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
587 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
588 $status = $this->newStatus();
590 // (a) Check if container already exists
591 $stat = $this->getContainerStat( $fullCont );
592 if ( is_array( $stat ) ) {
593 return $status; // already there
594 } elseif ( $stat === null ) {
595 $status->fatal( 'backend-fail-internal', $this->name
);
596 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
601 // (b) Create container as needed with proper ACLs
602 if ( $stat === false ) {
603 $params['op'] = 'prepare';
604 $status->merge( $this->createContainer( $fullCont, $params ) );
610 protected function doSecureInternal( $fullCont, $dir, array $params ) {
611 $status = $this->newStatus();
612 if ( empty( $params['noAccess'] ) ) {
613 return $status; // nothing to do
616 $stat = $this->getContainerStat( $fullCont );
617 if ( is_array( $stat ) ) {
618 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
619 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
620 // Make container private to end-users...
621 $status->merge( $this->setContainerAccess(
626 } elseif ( $stat === false ) {
627 $status->fatal( 'backend-fail-usable', $params['dir'] );
629 $status->fatal( 'backend-fail-internal', $this->name
);
630 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
636 protected function doPublishInternal( $fullCont, $dir, array $params ) {
637 $status = $this->newStatus();
639 $stat = $this->getContainerStat( $fullCont );
640 if ( is_array( $stat ) ) {
641 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
642 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
644 // Make container public to end-users...
645 $status->merge( $this->setContainerAccess(
650 } elseif ( $stat === false ) {
651 $status->fatal( 'backend-fail-usable', $params['dir'] );
653 $status->fatal( 'backend-fail-internal', $this->name
);
654 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
660 protected function doCleanInternal( $fullCont, $dir, array $params ) {
661 $status = $this->newStatus();
663 // Only containers themselves can be removed, all else is virtual
665 return $status; // nothing to do
668 // (a) Check the container
669 $stat = $this->getContainerStat( $fullCont, true );
670 if ( $stat === false ) {
671 return $status; // ok, nothing to do
672 } elseif ( !is_array( $stat ) ) {
673 $status->fatal( 'backend-fail-internal', $this->name
);
674 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
679 // (b) Delete the container if empty
680 if ( $stat['count'] == 0 ) {
681 $params['op'] = 'clean';
682 $status->merge( $this->deleteContainer( $fullCont, $params ) );
688 protected function doGetFileStat( array $params ) {
689 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
690 unset( $params['src'] );
691 $stats = $this->doGetFileStatMulti( $params );
693 return reset( $stats );
697 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
698 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
699 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
702 * @param int $format Output format (TS_* constant)
704 * @throws FileBackendError
706 protected function convertSwiftDate( $ts, $format = TS_MW
) {
708 $timestamp = new MWTimestamp( $ts );
710 return $timestamp->getTimestamp( $format );
711 } catch ( Exception
$e ) {
712 throw new FileBackendError( $e->getMessage() );
717 * Fill in any missing object metadata and save it to Swift
719 * @param array $objHdrs Object response headers
720 * @param string $path Storage path to object
721 * @return array New headers
723 protected function addMissingMetadata( array $objHdrs, $path ) {
724 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
725 return $objHdrs; // nothing to do
728 /** @noinspection PhpUnusedLocalVariableInspection */
729 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
730 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
731 [ 'path' => $path ] );
733 $objHdrs['x-object-meta-sha1base36'] = false;
735 $auth = $this->getAuthentication();
737 return $objHdrs; // failed
740 // Find prior custom HTTP headers
741 $postHeaders = $this->getCustomHeaders( $objHdrs );
742 // Find prior metadata headers
743 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
745 $status = $this->newStatus();
746 /** @noinspection PhpUnusedLocalVariableInspection */
747 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
748 if ( $status->isOK() ) {
749 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
751 $hash = $tmpFile->getSha1Base36();
752 if ( $hash !== false ) {
753 $objHdrs['x-object-meta-sha1base36'] = $hash;
754 // Merge new SHA1 header into the old ones
755 $postHeaders['x-object-meta-sha1base36'] = $hash;
756 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
757 list( $rcode ) = $this->http
->run( [
759 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
760 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
762 if ( $rcode >= 200 && $rcode <= 299 ) {
763 $this->deleteFileCache( $path );
765 return $objHdrs; // success
771 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
772 [ 'path' => $path ] );
774 return $objHdrs; // failed
777 protected function doGetFileContentsMulti( array $params ) {
780 $auth = $this->getAuthentication();
782 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
783 // Blindly create tmp files and stream to them, catching any exception if the file does
784 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
785 $reqs = []; // (path => op)
787 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
788 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
789 if ( $srcRel === null ||
!$auth ) {
790 $contents[$path] = false;
793 // Create a new temporary memory file...
794 $handle = fopen( 'php://temp', 'wb' );
798 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
799 'headers' => $this->authTokenHeaders( $auth )
800 +
$this->headersFromParams( $params ),
804 $contents[$path] = false;
807 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
808 $reqs = $this->http
->runMulti( $reqs, $opts );
809 foreach ( $reqs as $path => $op ) {
810 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
811 if ( $rcode >= 200 && $rcode <= 299 ) {
812 rewind( $op['stream'] ); // start from the beginning
813 $contents[$path] = stream_get_contents( $op['stream'] );
814 } elseif ( $rcode === 404 ) {
815 $contents[$path] = false;
817 $this->onError( null, __METHOD__
,
818 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
820 fclose( $op['stream'] ); // close open handle
826 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
827 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
828 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
829 if ( $status->isOK() ) {
830 return ( count( $status->value
) ) > 0;
833 return null; // error
837 * @see FileBackendStore::getDirectoryListInternal()
838 * @param string $fullCont
840 * @param array $params
841 * @return SwiftFileBackendDirList
843 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
844 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
848 * @see FileBackendStore::getFileListInternal()
849 * @param string $fullCont
851 * @param array $params
852 * @return SwiftFileBackendFileList
854 public function getFileListInternal( $fullCont, $dir, array $params ) {
855 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
859 * Do not call this function outside of SwiftFileBackendFileList
861 * @param string $fullCont Resolved container name
862 * @param string $dir Resolved storage directory with no trailing slash
863 * @param string|null &$after Resolved container relative path to list items after
864 * @param int $limit Max number of items to list
865 * @param array $params Parameters for getDirectoryList()
866 * @return array List of container relative resolved paths of directories directly under $dir
867 * @throws FileBackendError
869 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
871 if ( $after === INF
) {
872 return $dirs; // nothing more
875 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
877 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
878 // Non-recursive: only list dirs right under $dir
879 if ( !empty( $params['topOnly'] ) ) {
880 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
881 if ( !$status->isOK() ) {
882 throw new FileBackendError( "Iterator page I/O error." );
884 $objects = $status->value
;
885 foreach ( $objects as $object ) { // files and directories
886 if ( substr( $object, -1 ) === '/' ) {
887 $dirs[] = $object; // directories end in '/'
891 // Recursive: list all dirs under $dir and its subdirs
892 $getParentDir = function ( $path ) {
893 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
896 // Get directory from last item of prior page
897 $lastDir = $getParentDir( $after ); // must be first page
898 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
900 if ( !$status->isOK() ) {
901 throw new FileBackendError( "Iterator page I/O error." );
904 $objects = $status->value
;
906 foreach ( $objects as $object ) { // files
907 $objectDir = $getParentDir( $object ); // directory of object
909 if ( $objectDir !== false && $objectDir !== $dir ) {
910 // Swift stores paths in UTF-8, using binary sorting.
911 // See function "create_container_table" in common/db.py.
912 // If a directory is not "greater" than the last one,
913 // then it was already listed by the calling iterator.
914 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
916 do { // add dir and all its parent dirs
917 $dirs[] = "{$pDir}/";
918 $pDir = $getParentDir( $pDir );
919 } while ( $pDir !== false // sanity
920 && strcmp( $pDir, $lastDir ) > 0 // not done already
921 && strlen( $pDir ) > strlen( $dir ) // within $dir
924 $lastDir = $objectDir;
928 // Page on the unfiltered directory listing (what is returned may be filtered)
929 if ( count( $objects ) < $limit ) {
930 $after = INF
; // avoid a second RTT
932 $after = end( $objects ); // update last item
939 * Do not call this function outside of SwiftFileBackendFileList
941 * @param string $fullCont Resolved container name
942 * @param string $dir Resolved storage directory with no trailing slash
943 * @param string|null &$after Resolved container relative path of file to list items after
944 * @param int $limit Max number of items to list
945 * @param array $params Parameters for getDirectoryList()
946 * @return array List of resolved container relative paths of files under $dir
947 * @throws FileBackendError
949 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
950 $files = []; // list of (path, stat array or null) entries
951 if ( $after === INF
) {
952 return $files; // nothing more
955 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
957 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
958 // $objects will contain a list of unfiltered names or CF_Object items
959 // Non-recursive: only list files right under $dir
960 if ( !empty( $params['topOnly'] ) ) {
961 if ( !empty( $params['adviseStat'] ) ) {
962 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
964 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
967 // Recursive: list all files under $dir and its subdirs
968 if ( !empty( $params['adviseStat'] ) ) {
969 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
971 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
975 // Reformat this list into a list of (name, stat array or null) entries
976 if ( !$status->isOK() ) {
977 throw new FileBackendError( "Iterator page I/O error." );
980 $objects = $status->value
;
981 $files = $this->buildFileObjectListing( $params, $dir, $objects );
983 // Page on the unfiltered object listing (what is returned may be filtered)
984 if ( count( $objects ) < $limit ) {
985 $after = INF
; // avoid a second RTT
987 $after = end( $objects ); // update last item
988 $after = is_object( $after ) ?
$after->name
: $after;
995 * Build a list of file objects, filtering out any directories
996 * and extracting any stat info if provided in $objects (for CF_Objects)
998 * @param array $params Parameters for getDirectoryList()
999 * @param string $dir Resolved container directory path
1000 * @param array $objects List of CF_Object items or object names
1001 * @return array List of (names,stat array or null) entries
1003 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1005 foreach ( $objects as $object ) {
1006 if ( is_object( $object ) ) {
1007 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1008 continue; // virtual directory entry; ignore
1011 // Convert various random Swift dates to TS_MW
1012 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1013 'size' => (int)$object->bytes
,
1015 // Note: manifiest ETags are not an MD5 of the file
1016 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1017 'latest' => false // eventually consistent
1019 $names[] = [ $object->name
, $stat ];
1020 } elseif ( substr( $object, -1 ) !== '/' ) {
1021 // Omit directories, which end in '/' in listings
1022 $names[] = [ $object, null ];
1030 * Do not call this function outside of SwiftFileBackendFileList
1032 * @param string $path Storage path
1033 * @param array $val Stat value
1035 public function loadListingStatInternal( $path, array $val ) {
1036 $this->cheapCache
->set( $path, 'stat', $val );
1039 protected function doGetFileXAttributes( array $params ) {
1040 $stat = $this->getFileStat( $params );
1042 if ( !isset( $stat['xattr'] ) ) {
1043 // Stat entries filled by file listings don't include metadata/headers
1044 $this->clearCache( [ $params['src'] ] );
1045 $stat = $this->getFileStat( $params );
1048 return $stat['xattr'];
1054 protected function doGetFileSha1base36( array $params ) {
1055 $stat = $this->getFileStat( $params );
1057 if ( !isset( $stat['sha1'] ) ) {
1058 // Stat entries filled by file listings don't include SHA1
1059 $this->clearCache( [ $params['src'] ] );
1060 $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 if the file does
1143 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
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 = TempFSFile
::factory( 'localcopy_', $ext, $this->tmpDirectory
);
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
->set( $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
->has( $container, 'stat' ) ) {
1399 $this->primeContainerCache( [ $container ] ); // check persistent cache
1401 if ( !$this->containerStatCache
->has( $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
->set( $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
->get( $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
->set( $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 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1635 // Load the stat array from the headers
1636 $stat = $this->getStatFromHeaders( $rhdrs );
1637 if ( $this->isRGW
) {
1638 $stat['latest'] = true; // strong consistency
1640 } elseif ( $rcode === 404 ) {
1644 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1646 $stats[$path] = $stat;
1653 * @param array $rhdrs
1656 protected function getStatFromHeaders( array $rhdrs ) {
1657 // Fetch all of the custom metadata headers
1658 $metadata = $this->getMetadata( $rhdrs );
1659 // Fetch all of the custom raw HTTP headers
1660 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1663 // Convert various random Swift dates to TS_MW
1664 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1665 // Empty objects actually return no content-length header in Ceph
1666 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1667 'sha1' => $metadata['sha1base36'] ??
null,
1668 // Note: manifiest ETags are not an MD5 of the file
1669 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1670 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1675 * @return array|null Credential map
1677 protected function getAuthentication() {
1678 if ( $this->authErrorTimestamp
!== null ) {
1679 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1680 return null; // failed last attempt; don't bother
1681 } else { // actually retry this time
1682 $this->authErrorTimestamp
= null;
1685 // Session keys expire after a while, so we renew them periodically
1686 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1687 // Authenticate with proxy and get a session key...
1688 if ( !$this->authCreds ||
$reAuth ) {
1689 $this->authSessionTimestamp
= 0;
1690 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1691 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1692 // Try to use the credential cache
1693 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1694 $this->authCreds
= $creds;
1695 // Skew the timestamp for worst case to avoid using stale credentials
1696 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1697 } else { // cache miss
1698 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1700 'url' => "{$this->swiftAuthUrl}/v1.0",
1702 'x-auth-user' => $this->swiftUser
,
1703 'x-auth-key' => $this->swiftKey
1707 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1708 $this->authCreds
= [
1709 'auth_token' => $rhdrs['x-auth-token'],
1710 'storage_url' => ( $this->swiftStorageUrl
!== null )
1711 ?
$this->swiftStorageUrl
1712 : $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 $container
1741 * @param string $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 );
1808 * @see FileBackendStoreOpHandle
1810 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1811 /** @var array List of Requests for MultiHttpClient */
1817 * @param SwiftFileBackend $backend
1818 * @param Closure $callback Function that takes (HTTP request array, status)
1819 * @param array $httpOp MultiHttpClient op
1821 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1822 $this->backend
= $backend;
1823 $this->callback
= $callback;
1824 $this->httpOp
= $httpOp;
1829 * SwiftFileBackend helper class to page through listings.
1830 * Swift also has a listing limit of 10,000 objects for sanity.
1831 * Do not use this class from places outside SwiftFileBackend.
1833 * @ingroup FileBackend
1835 abstract class SwiftFileBackendList
implements Iterator
{
1836 /** @var array List of path or (path,stat array) entries */
1837 protected $bufferIter = [];
1839 /** @var string List items *after* this path */
1840 protected $bufferAfter = null;
1846 protected $params = [];
1848 /** @var SwiftFileBackend */
1851 /** @var string Container name */
1852 protected $container;
1854 /** @var string Storage directory */
1858 protected $suffixStart;
1860 const PAGE_SIZE
= 9000; // file listing buffer size
1863 * @param SwiftFileBackend $backend
1864 * @param string $fullCont Resolved container name
1865 * @param string $dir Resolved directory relative to container
1866 * @param array $params
1868 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1869 $this->backend
= $backend;
1870 $this->container
= $fullCont;
1872 if ( substr( $this->dir
, -1 ) === '/' ) {
1873 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1875 if ( $this->dir
== '' ) { // whole container
1876 $this->suffixStart
= 0;
1877 } else { // dir within container
1878 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1880 $this->params
= $params;
1884 * @see Iterator::key()
1887 public function key() {
1892 * @see Iterator::next()
1894 public function next() {
1895 // Advance to the next file in the page
1896 next( $this->bufferIter
);
1898 // Check if there are no files left in this page and
1899 // advance to the next page if this page was not empty.
1900 if ( !$this->valid() && count( $this->bufferIter
) ) {
1901 $this->bufferIter
= $this->pageFromList(
1902 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1903 ); // updates $this->bufferAfter
1908 * @see Iterator::rewind()
1910 public function rewind() {
1912 $this->bufferAfter
= null;
1913 $this->bufferIter
= $this->pageFromList(
1914 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1915 ); // updates $this->bufferAfter
1919 * @see Iterator::valid()
1922 public function valid() {
1923 if ( $this->bufferIter
=== null ) {
1924 return false; // some failure?
1926 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1931 * Get the given list portion (page)
1933 * @param string $container Resolved container name
1934 * @param string $dir Resolved path relative to container
1935 * @param string &$after
1937 * @param array $params
1938 * @return Traversable|array
1940 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1944 * Iterator for listing directories
1946 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1948 * @see Iterator::current()
1949 * @return string|bool String (relative path) or false
1951 public function current() {
1952 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1955 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1956 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1961 * Iterator for listing regular files
1963 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1965 * @see Iterator::current()
1966 * @return string|bool String (relative path) or false
1968 public function current() {
1969 list( $path, $stat ) = current( $this->bufferIter
);
1970 $relPath = substr( $path, $this->suffixStart
);
1971 if ( is_array( $stat ) ) {
1972 $storageDir = rtrim( $this->params
['dir'], '/' );
1973 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1979 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1980 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );