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) to open read permissions for */
55 /** @var array Additional users (account:user) to open write permissions for */
56 protected $writeUsers;
61 /** @var ProcessCacheLRU Container stat cache */
62 protected $containerStatCache;
66 /** @var int UNIX timestamp */
67 protected $authSessionTimestamp = 0;
68 /** @var int UNIX timestamp */
69 protected $authErrorTimestamp = null;
71 /** @var bool Whether the server is an Ceph RGW */
72 protected $isRGW = false;
75 * @see FileBackendStore::__construct()
76 * @param array $config Params include:
77 * - swiftAuthUrl : Swift authentication server URL
78 * - swiftUser : Swift user used by MediaWiki (account:username)
79 * - swiftKey : Swift authentication key for the above user
80 * - swiftAuthTTL : Swift authentication TTL (seconds)
81 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
82 * Do not set this until it has been set in the backend.
83 * - swiftStorageUrl : Swift storage URL (overrides that of the authentication response).
84 * This is useful to set if a TLS proxy is in use.
85 * - shardViaHashLevels : Map of container names to sharding config with:
86 * - base : base of hash characters, 16 or 36
87 * - levels : the number of hash levels (and digits)
88 * - repeat : hash subdirectories are prefixed with all the
89 * parent hash directory names (e.g. "a/ab/abc")
90 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
91 * If those are not available, then the main cache will be used.
92 * This is probably insecure in shared hosting environments.
93 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
94 * Do not set this until it has been set in the backend.
95 * This is used for generating expiring pre-authenticated URLs.
96 * Only use this when using rgw and to work around
97 * http://tracker.newdream.net/issues/3454.
98 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
99 * Do not set this until it has been set in the backend.
100 * This is used for generating expiring pre-authenticated URLs.
101 * Only use this when using rgw and to work around
102 * http://tracker.newdream.net/issues/3454.
103 * - readUsers : Swift users that should have read access (account:username)
104 * - writeUsers : Swift users that should have write access (account:username)
106 public function __construct( array $config ) {
107 parent
::__construct( $config );
109 $this->swiftAuthUrl
= $config['swiftAuthUrl'];
110 $this->swiftUser
= $config['swiftUser'];
111 $this->swiftKey
= $config['swiftKey'];
113 $this->authTTL
= isset( $config['swiftAuthTTL'] )
114 ?
$config['swiftAuthTTL']
115 : 15 * 60; // some sane number
116 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
117 ?
$config['swiftTempUrlKey']
119 $this->swiftStorageUrl
= isset( $config['swiftStorageUrl'] )
120 ?
$config['swiftStorageUrl']
122 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
123 ?
$config['shardViaHashLevels']
125 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
126 ?
$config['rgwS3AccessKey']
128 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
129 ?
$config['rgwS3SecretKey']
131 // HTTP helper client
132 $this->http
= new MultiHttpClient( [] );
133 // Cache container information to mask latency
134 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
135 $this->memCache
= $config['wanCache'];
137 // Process cache for container info
138 $this->containerStatCache
= new ProcessCacheLRU( 300 );
139 // Cache auth token information to avoid RTTs
140 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
141 $this->srvCache
= $config['srvCache'];
143 $this->srvCache
= new EmptyBagOStuff();
145 $this->readUsers
= isset( $config['readUsers'] )
146 ?
$config['readUsers']
148 $this->writeUsers
= isset( $config['writeUsers'] )
149 ?
$config['writeUsers']
153 public function getFeatures() {
154 return ( FileBackend
::ATTR_UNICODE_PATHS |
155 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
158 protected function resolveContainerPath( $container, $relStoragePath ) {
159 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
160 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
161 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
162 return null; // too long for Swift
165 return $relStoragePath;
168 public function isPathUsableInternal( $storagePath ) {
169 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
170 if ( $rel === null ) {
171 return false; // invalid
174 return is_array( $this->getContainerStat( $container ) );
178 * Sanitize and filter the custom headers from a $params array.
179 * Only allows certain "standard" Content- and X-Content- headers.
181 * @param array $params
182 * @return array Sanitized value of 'headers' field in $params
184 protected function sanitizeHdrs( array $params ) {
185 return isset( $params['headers'] )
186 ?
$this->getCustomHeaders( $params['headers'] )
191 * @param array $rawHeaders
192 * @return array Custom non-metadata HTTP headers
194 protected function getCustomHeaders( array $rawHeaders ) {
197 // Normalize casing, and strip out illegal headers
198 foreach ( $rawHeaders as $name => $value ) {
199 $name = strtolower( $name );
200 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
201 continue; // blacklisted
202 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
203 $headers[$name] = $value; // allowed
204 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
205 $headers[$name] = $value; // allowed
208 // By default, Swift has annoyingly low maximum header value limits
209 if ( isset( $headers['content-disposition'] ) ) {
211 // @note: assume FileBackend::makeContentDisposition() already used
212 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
213 $part = trim( $part );
214 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
215 if ( strlen( $new ) <= 255 ) {
218 break; // too long; sigh
221 $headers['content-disposition'] = $disposition;
228 * @param array $rawHeaders
229 * @return array Custom metadata headers
231 protected function getMetadataHeaders( array $rawHeaders ) {
233 foreach ( $rawHeaders as $name => $value ) {
234 $name = strtolower( $name );
235 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
236 $headers[$name] = $value;
244 * @param array $rawHeaders
245 * @return array Custom metadata headers with prefix removed
247 protected function getMetadata( array $rawHeaders ) {
249 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
250 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
256 protected function doCreateInternal( array $params ) {
257 $status = $this->newStatus();
259 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
260 if ( $dstRel === null ) {
261 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
266 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
267 $contentType = isset( $params['headers']['content-type'] )
268 ?
$params['headers']['content-type']
269 : $this->getContentType( $params['dst'], $params['content'], null );
273 'url' => [ $dstCont, $dstRel ],
275 'content-length' => strlen( $params['content'] ),
276 'etag' => md5( $params['content'] ),
277 'content-type' => $contentType,
278 'x-object-meta-sha1base36' => $sha1Hash
279 ] +
$this->sanitizeHdrs( $params ),
280 'body' => $params['content']
283 $method = __METHOD__
;
284 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
285 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
286 if ( $rcode === 201 ) {
288 } elseif ( $rcode === 412 ) {
289 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
291 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
295 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
296 if ( !empty( $params['async'] ) ) { // deferred
297 $status->value
= $opHandle;
298 } else { // actually write the object in Swift
299 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
305 protected function doStoreInternal( array $params ) {
306 $status = $this->newStatus();
308 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
309 if ( $dstRel === null ) {
310 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
315 MediaWiki\
suppressWarnings();
316 $sha1Hash = sha1_file( $params['src'] );
317 MediaWiki\restoreWarnings
();
318 if ( $sha1Hash === false ) { // source doesn't exist?
319 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
323 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
324 $contentType = isset( $params['headers']['content-type'] )
325 ?
$params['headers']['content-type']
326 : $this->getContentType( $params['dst'], null, $params['src'] );
328 $handle = fopen( $params['src'], 'rb' );
329 if ( $handle === false ) { // source doesn't exist?
330 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
337 'url' => [ $dstCont, $dstRel ],
339 'content-length' => filesize( $params['src'] ),
340 'etag' => md5_file( $params['src'] ),
341 'content-type' => $contentType,
342 'x-object-meta-sha1base36' => $sha1Hash
343 ] +
$this->sanitizeHdrs( $params ),
344 'body' => $handle // resource
347 $method = __METHOD__
;
348 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
349 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
350 if ( $rcode === 201 ) {
352 } elseif ( $rcode === 412 ) {
353 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
355 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
359 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
360 $opHandle->resourcesToClose
[] = $handle;
362 if ( !empty( $params['async'] ) ) { // deferred
363 $status->value
= $opHandle;
364 } else { // actually write the object in Swift
365 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
371 protected function doCopyInternal( array $params ) {
372 $status = $this->newStatus();
374 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
375 if ( $srcRel === null ) {
376 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
381 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
382 if ( $dstRel === null ) {
383 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
390 'url' => [ $dstCont, $dstRel ],
392 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
393 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
394 ] +
$this->sanitizeHdrs( $params ), // extra headers merged into object
397 $method = __METHOD__
;
398 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
399 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
400 if ( $rcode === 201 ) {
402 } elseif ( $rcode === 404 ) {
403 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
405 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
409 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
410 if ( !empty( $params['async'] ) ) { // deferred
411 $status->value
= $opHandle;
412 } else { // actually write the object in Swift
413 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
419 protected function doMoveInternal( array $params ) {
420 $status = $this->newStatus();
422 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
423 if ( $srcRel === null ) {
424 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
429 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
430 if ( $dstRel === null ) {
431 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
439 'url' => [ $dstCont, $dstRel ],
441 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
442 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
443 ] +
$this->sanitizeHdrs( $params ) // extra headers merged into object
446 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
448 'method' => 'DELETE',
449 'url' => [ $srcCont, $srcRel ],
454 $method = __METHOD__
;
455 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
456 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
457 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
459 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
461 } elseif ( $rcode === 404 ) {
462 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
464 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
468 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
469 if ( !empty( $params['async'] ) ) { // deferred
470 $status->value
= $opHandle;
471 } else { // actually move the object in Swift
472 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
478 protected function doDeleteInternal( array $params ) {
479 $status = $this->newStatus();
481 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
482 if ( $srcRel === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
489 'method' => 'DELETE',
490 'url' => [ $srcCont, $srcRel ],
494 $method = __METHOD__
;
495 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
496 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
497 if ( $rcode === 204 ) {
499 } elseif ( $rcode === 404 ) {
500 if ( empty( $params['ignoreMissingSource'] ) ) {
501 $status->fatal( 'backend-fail-delete', $params['src'] );
504 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
508 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
509 if ( !empty( $params['async'] ) ) { // deferred
510 $status->value
= $opHandle;
511 } else { // actually delete the object in Swift
512 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
518 protected function doDescribeInternal( array $params ) {
519 $status = $this->newStatus();
521 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
522 if ( $srcRel === null ) {
523 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
528 // Fetch the old object headers/metadata...this should be in stat cache by now
529 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
530 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
531 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
534 $status->fatal( 'backend-fail-describe', $params['src'] );
539 // POST clears prior headers, so we need to merge the changes in to the old ones
541 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
542 $metaHdrs["x-object-meta-$name"] = $value;
544 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
548 'url' => [ $srcCont, $srcRel ],
549 'headers' => $metaHdrs +
$customHdrs
552 $method = __METHOD__
;
553 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
554 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
555 if ( $rcode === 202 ) {
557 } elseif ( $rcode === 404 ) {
558 $status->fatal( 'backend-fail-describe', $params['src'] );
560 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
564 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
565 if ( !empty( $params['async'] ) ) { // deferred
566 $status->value
= $opHandle;
567 } else { // actually change the object in Swift
568 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
574 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
575 $status = $this->newStatus();
577 // (a) Check if container already exists
578 $stat = $this->getContainerStat( $fullCont );
579 if ( is_array( $stat ) ) {
580 return $status; // already there
581 } elseif ( $stat === null ) {
582 $status->fatal( 'backend-fail-internal', $this->name
);
583 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
588 // (b) Create container as needed with proper ACLs
589 if ( $stat === false ) {
590 $params['op'] = 'prepare';
591 $status->merge( $this->createContainer( $fullCont, $params ) );
597 protected function doSecureInternal( $fullCont, $dir, array $params ) {
598 $status = $this->newStatus();
599 if ( empty( $params['noAccess'] ) ) {
600 return $status; // nothing to do
603 $stat = $this->getContainerStat( $fullCont );
604 if ( is_array( $stat ) ) {
605 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
] );
606 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
607 // Make container private to end-users...
608 $status->merge( $this->setContainerAccess(
613 } elseif ( $stat === false ) {
614 $status->fatal( 'backend-fail-usable', $params['dir'] );
616 $status->fatal( 'backend-fail-internal', $this->name
);
617 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
623 protected function doPublishInternal( $fullCont, $dir, array $params ) {
624 $status = $this->newStatus();
626 $stat = $this->getContainerStat( $fullCont );
627 if ( is_array( $stat ) ) {
628 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
629 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
631 // Make container public to end-users...
632 $status->merge( $this->setContainerAccess(
637 } elseif ( $stat === false ) {
638 $status->fatal( 'backend-fail-usable', $params['dir'] );
640 $status->fatal( 'backend-fail-internal', $this->name
);
641 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
647 protected function doCleanInternal( $fullCont, $dir, array $params ) {
648 $status = $this->newStatus();
650 // Only containers themselves can be removed, all else is virtual
652 return $status; // nothing to do
655 // (a) Check the container
656 $stat = $this->getContainerStat( $fullCont, true );
657 if ( $stat === false ) {
658 return $status; // ok, nothing to do
659 } elseif ( !is_array( $stat ) ) {
660 $status->fatal( 'backend-fail-internal', $this->name
);
661 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
666 // (b) Delete the container if empty
667 if ( $stat['count'] == 0 ) {
668 $params['op'] = 'clean';
669 $status->merge( $this->deleteContainer( $fullCont, $params ) );
675 protected function doGetFileStat( array $params ) {
676 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
677 unset( $params['src'] );
678 $stats = $this->doGetFileStatMulti( $params );
680 return reset( $stats );
684 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
685 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
686 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
689 * @param int $format Output format (TS_* constant)
691 * @throws FileBackendError
693 protected function convertSwiftDate( $ts, $format = TS_MW
) {
695 $timestamp = new MWTimestamp( $ts );
697 return $timestamp->getTimestamp( $format );
698 } catch ( Exception
$e ) {
699 throw new FileBackendError( $e->getMessage() );
704 * Fill in any missing object metadata and save it to Swift
706 * @param array $objHdrs Object response headers
707 * @param string $path Storage path to object
708 * @return array New headers
710 protected function addMissingMetadata( array $objHdrs, $path ) {
711 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
712 return $objHdrs; // nothing to do
715 /** @noinspection PhpUnusedLocalVariableInspection */
716 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
717 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
718 [ 'path' => $path ] );
720 $objHdrs['x-object-meta-sha1base36'] = false;
722 $auth = $this->getAuthentication();
724 return $objHdrs; // failed
727 // Find prior custom HTTP headers
728 $postHeaders = $this->getCustomHeaders( $objHdrs );
729 // Find prior metadata headers
730 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
732 $status = $this->newStatus();
733 /** @noinspection PhpUnusedLocalVariableInspection */
734 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
735 if ( $status->isOK() ) {
736 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
738 $hash = $tmpFile->getSha1Base36();
739 if ( $hash !== false ) {
740 $objHdrs['x-object-meta-sha1base36'] = $hash;
741 // Merge new SHA1 header into the old ones
742 $postHeaders['x-object-meta-sha1base36'] = $hash;
743 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
744 list( $rcode ) = $this->http
->run( [
746 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
747 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
749 if ( $rcode >= 200 && $rcode <= 299 ) {
750 $this->deleteFileCache( $path );
752 return $objHdrs; // success
758 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
759 [ 'path' => $path ] );
761 return $objHdrs; // failed
764 protected function doGetFileContentsMulti( array $params ) {
767 $auth = $this->getAuthentication();
769 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
770 // Blindly create tmp files and stream to them, catching any exception if the file does
771 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
772 $reqs = []; // (path => op)
774 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
775 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
776 if ( $srcRel === null ||
!$auth ) {
777 $contents[$path] = false;
780 // Create a new temporary memory file...
781 $handle = fopen( 'php://temp', 'wb' );
785 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
786 'headers' => $this->authTokenHeaders( $auth )
787 +
$this->headersFromParams( $params ),
791 $contents[$path] = false;
794 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
795 $reqs = $this->http
->runMulti( $reqs, $opts );
796 foreach ( $reqs as $path => $op ) {
797 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
798 if ( $rcode >= 200 && $rcode <= 299 ) {
799 rewind( $op['stream'] ); // start from the beginning
800 $contents[$path] = stream_get_contents( $op['stream'] );
801 } elseif ( $rcode === 404 ) {
802 $contents[$path] = false;
804 $this->onError( null, __METHOD__
,
805 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
807 fclose( $op['stream'] ); // close open handle
813 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
814 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
815 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
816 if ( $status->isOK() ) {
817 return ( count( $status->value
) ) > 0;
820 return null; // error
824 * @see FileBackendStore::getDirectoryListInternal()
825 * @param string $fullCont
827 * @param array $params
828 * @return SwiftFileBackendDirList
830 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
831 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
835 * @see FileBackendStore::getFileListInternal()
836 * @param string $fullCont
838 * @param array $params
839 * @return SwiftFileBackendFileList
841 public function getFileListInternal( $fullCont, $dir, array $params ) {
842 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
846 * Do not call this function outside of SwiftFileBackendFileList
848 * @param string $fullCont Resolved container name
849 * @param string $dir Resolved storage directory with no trailing slash
850 * @param string|null &$after Resolved container relative path to list items after
851 * @param int $limit Max number of items to list
852 * @param array $params Parameters for getDirectoryList()
853 * @return array List of container relative resolved paths of directories directly under $dir
854 * @throws FileBackendError
856 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
858 if ( $after === INF
) {
859 return $dirs; // nothing more
862 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
864 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
865 // Non-recursive: only list dirs right under $dir
866 if ( !empty( $params['topOnly'] ) ) {
867 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
868 if ( !$status->isOK() ) {
869 throw new FileBackendError( "Iterator page I/O error." );
871 $objects = $status->value
;
872 foreach ( $objects as $object ) { // files and directories
873 if ( substr( $object, -1 ) === '/' ) {
874 $dirs[] = $object; // directories end in '/'
878 // Recursive: list all dirs under $dir and its subdirs
879 $getParentDir = function ( $path ) {
880 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
883 // Get directory from last item of prior page
884 $lastDir = $getParentDir( $after ); // must be first page
885 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
887 if ( !$status->isOK() ) {
888 throw new FileBackendError( "Iterator page I/O error." );
891 $objects = $status->value
;
893 foreach ( $objects as $object ) { // files
894 $objectDir = $getParentDir( $object ); // directory of object
896 if ( $objectDir !== false && $objectDir !== $dir ) {
897 // Swift stores paths in UTF-8, using binary sorting.
898 // See function "create_container_table" in common/db.py.
899 // If a directory is not "greater" than the last one,
900 // then it was already listed by the calling iterator.
901 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
903 do { // add dir and all its parent dirs
904 $dirs[] = "{$pDir}/";
905 $pDir = $getParentDir( $pDir );
906 } while ( $pDir !== false // sanity
907 && strcmp( $pDir, $lastDir ) > 0 // not done already
908 && strlen( $pDir ) > strlen( $dir ) // within $dir
911 $lastDir = $objectDir;
915 // Page on the unfiltered directory listing (what is returned may be filtered)
916 if ( count( $objects ) < $limit ) {
917 $after = INF
; // avoid a second RTT
919 $after = end( $objects ); // update last item
926 * Do not call this function outside of SwiftFileBackendFileList
928 * @param string $fullCont Resolved container name
929 * @param string $dir Resolved storage directory with no trailing slash
930 * @param string|null &$after Resolved container relative path of file to list items after
931 * @param int $limit Max number of items to list
932 * @param array $params Parameters for getDirectoryList()
933 * @return array List of resolved container relative paths of files under $dir
934 * @throws FileBackendError
936 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
937 $files = []; // list of (path, stat array or null) entries
938 if ( $after === INF
) {
939 return $files; // nothing more
942 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
944 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
945 // $objects will contain a list of unfiltered names or CF_Object items
946 // Non-recursive: only list files right under $dir
947 if ( !empty( $params['topOnly'] ) ) {
948 if ( !empty( $params['adviseStat'] ) ) {
949 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
951 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
954 // Recursive: list all files under $dir and its subdirs
955 if ( !empty( $params['adviseStat'] ) ) {
956 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
958 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
962 // Reformat this list into a list of (name, stat array or null) entries
963 if ( !$status->isOK() ) {
964 throw new FileBackendError( "Iterator page I/O error." );
967 $objects = $status->value
;
968 $files = $this->buildFileObjectListing( $params, $dir, $objects );
970 // Page on the unfiltered object listing (what is returned may be filtered)
971 if ( count( $objects ) < $limit ) {
972 $after = INF
; // avoid a second RTT
974 $after = end( $objects ); // update last item
975 $after = is_object( $after ) ?
$after->name
: $after;
982 * Build a list of file objects, filtering out any directories
983 * and extracting any stat info if provided in $objects (for CF_Objects)
985 * @param array $params Parameters for getDirectoryList()
986 * @param string $dir Resolved container directory path
987 * @param array $objects List of CF_Object items or object names
988 * @return array List of (names,stat array or null) entries
990 private function buildFileObjectListing( array $params, $dir, array $objects ) {
992 foreach ( $objects as $object ) {
993 if ( is_object( $object ) ) {
994 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
995 continue; // virtual directory entry; ignore
998 // Convert various random Swift dates to TS_MW
999 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1000 'size' => (int)$object->bytes
,
1002 // Note: manifiest ETags are not an MD5 of the file
1003 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1004 'latest' => false // eventually consistent
1006 $names[] = [ $object->name
, $stat ];
1007 } elseif ( substr( $object, -1 ) !== '/' ) {
1008 // Omit directories, which end in '/' in listings
1009 $names[] = [ $object, null ];
1017 * Do not call this function outside of SwiftFileBackendFileList
1019 * @param string $path Storage path
1020 * @param array $val Stat value
1022 public function loadListingStatInternal( $path, array $val ) {
1023 $this->cheapCache
->set( $path, 'stat', $val );
1026 protected function doGetFileXAttributes( array $params ) {
1027 $stat = $this->getFileStat( $params );
1029 if ( !isset( $stat['xattr'] ) ) {
1030 // Stat entries filled by file listings don't include metadata/headers
1031 $this->clearCache( [ $params['src'] ] );
1032 $stat = $this->getFileStat( $params );
1035 return $stat['xattr'];
1041 protected function doGetFileSha1base36( array $params ) {
1042 $stat = $this->getFileStat( $params );
1044 if ( !isset( $stat['sha1'] ) ) {
1045 // Stat entries filled by file listings don't include SHA1
1046 $this->clearCache( [ $params['src'] ] );
1047 $stat = $this->getFileStat( $params );
1050 return $stat['sha1'];
1056 protected function doStreamFile( array $params ) {
1057 $status = $this->newStatus();
1059 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1061 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1062 if ( $srcRel === null ) {
1063 StreamFile
::send404Message( $params['src'], $flags );
1064 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1069 $auth = $this->getAuthentication();
1070 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1071 StreamFile
::send404Message( $params['src'], $flags );
1072 $status->fatal( 'backend-fail-stream', $params['src'] );
1077 // If "headers" is set, we only want to send them if the file is there.
1078 // Do not bother checking if the file exists if headers are not set though.
1079 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1080 StreamFile
::send404Message( $params['src'], $flags );
1081 $status->fatal( 'backend-fail-stream', $params['src'] );
1086 // Send the requested additional headers
1087 foreach ( $params['headers'] as $header ) {
1088 header( $header ); // aways send
1091 if ( empty( $params['allowOB'] ) ) {
1092 // Cancel output buffering and gzipping if set
1093 call_user_func( $this->obResetFunc
);
1096 $handle = fopen( 'php://output', 'wb' );
1097 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1099 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1100 'headers' => $this->authTokenHeaders( $auth )
1101 +
$this->headersFromParams( $params ) +
$params['options'],
1102 'stream' => $handle,
1103 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1106 if ( $rcode >= 200 && $rcode <= 299 ) {
1108 } elseif ( $rcode === 404 ) {
1109 $status->fatal( 'backend-fail-stream', $params['src'] );
1110 // Per T43113, nasty things can happen if bad cache entries get
1111 // stuck in cache. It's also possible that this error can come up
1112 // with simple race conditions. Clear out the stat cache to be safe.
1113 $this->clearCache( [ $params['src'] ] );
1114 $this->deleteFileCache( $params['src'] );
1116 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1122 protected function doGetLocalCopyMulti( array $params ) {
1123 /** @var TempFSFile[] $tmpFiles */
1126 $auth = $this->getAuthentication();
1128 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1129 // Blindly create tmp files and stream to them, catching any exception if the file does
1130 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1131 $reqs = []; // (path => op)
1133 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1134 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1135 if ( $srcRel === null ||
!$auth ) {
1136 $tmpFiles[$path] = null;
1139 // Get source file extension
1140 $ext = FileBackend
::extensionFromPath( $path );
1141 // Create a new temporary file...
1142 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext, $this->tmpDirectory
);
1144 $handle = fopen( $tmpFile->getPath(), 'wb' );
1148 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1149 'headers' => $this->authTokenHeaders( $auth )
1150 +
$this->headersFromParams( $params ),
1151 'stream' => $handle,
1157 $tmpFiles[$path] = $tmpFile;
1160 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1161 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1162 $reqs = $this->http
->runMulti( $reqs, $opts );
1163 foreach ( $reqs as $path => $op ) {
1164 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1165 fclose( $op['stream'] ); // close open handle
1166 if ( $rcode >= 200 && $rcode <= 299 ) {
1167 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1168 // Double check that the disk is not full/broken
1169 if ( $size != $rhdrs['content-length'] ) {
1170 $tmpFiles[$path] = null;
1171 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1172 $this->onError( null, __METHOD__
,
1173 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1175 // Set the file stat process cache in passing
1176 $stat = $this->getStatFromHeaders( $rhdrs );
1177 $stat['latest'] = $isLatest;
1178 $this->cheapCache
->set( $path, 'stat', $stat );
1179 } elseif ( $rcode === 404 ) {
1180 $tmpFiles[$path] = false;
1182 $tmpFiles[$path] = null;
1183 $this->onError( null, __METHOD__
,
1184 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1191 public function getFileHttpUrl( array $params ) {
1192 if ( $this->swiftTempUrlKey
!= '' ||
1193 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1195 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1196 if ( $srcRel === null ) {
1197 return null; // invalid path
1200 $auth = $this->getAuthentication();
1205 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1206 $expires = time() +
$ttl;
1208 if ( $this->swiftTempUrlKey
!= '' ) {
1209 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1210 // Swift wants the signature based on the unencoded object name
1211 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1212 $signature = hash_hmac( 'sha1',
1213 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1214 $this->swiftTempUrlKey
1217 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1218 } else { // give S3 API URL for rgw
1219 // Path for signature starts with the bucket
1220 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1221 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1222 // Calculate the hash
1223 $signature = base64_encode( hash_hmac(
1225 "GET\n\n\n{$expires}\n{$spath}",
1226 $this->rgwS3SecretKey
,
1229 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1230 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1231 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1232 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1235 'Signature' => $signature,
1236 'Expires' => $expires,
1237 'AWSAccessKeyId' => $this->rgwS3AccessKey
1245 protected function directoriesAreVirtual() {
1250 * Get headers to send to Swift when reading a file based
1251 * on a FileBackend params array, e.g. that of getLocalCopy().
1252 * $params is currently only checked for a 'latest' flag.
1254 * @param array $params
1257 protected function headersFromParams( array $params ) {
1259 if ( !empty( $params['latest'] ) ) {
1260 $hdrs['x-newest'] = 'true';
1267 * @param FileBackendStoreOpHandle[] $fileOpHandles
1269 * @return StatusValue[]
1271 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1272 /** @var StatusValue[] $statuses */
1275 $auth = $this->getAuthentication();
1277 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1278 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1284 // Split the HTTP requests into stages that can be done concurrently
1285 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1286 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1287 /** @var SwiftFileOpHandle $fileOpHandle */
1288 $reqs = $fileOpHandle->httpOp
;
1289 // Convert the 'url' parameter to an actual URL using $auth
1290 foreach ( $reqs as $stage => &$req ) {
1291 list( $container, $relPath ) = $req['url'];
1292 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1293 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : [];
1294 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1295 $httpReqsByStage[$stage][$index] = $req;
1297 $statuses[$index] = $this->newStatus();
1300 // Run all requests for the first stage, then the next, and so on
1301 $reqCount = count( $httpReqsByStage );
1302 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1303 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1304 foreach ( $httpReqs as $index => $httpReq ) {
1305 // Run the callback for each request of this operation
1306 $callback = $fileOpHandles[$index]->callback
;
1307 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1308 // On failure, abort all remaining requests for this operation
1309 // (e.g. abort the DELETE request if the COPY request fails for a move)
1310 if ( !$statuses[$index]->isOK() ) {
1311 $stages = count( $fileOpHandles[$index]->httpOp
);
1312 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1313 unset( $httpReqsByStage[$s][$index] );
1323 * Set read/write permissions for a Swift container.
1325 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1327 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1328 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1330 * @param string $container Resolved Swift container
1331 * @param array $readUsers List of the possible criteria for a request to have
1332 * access to read a container. Each item is one of the following formats:
1333 * - account:user : Grants access if the request is by the given user
1334 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1335 * matches the expression and the request is not for a listing.
1336 * Setting this to '*' effectively makes a container public.
1337 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1338 * matches the expression and the request is for a listing.
1339 * @param array $writeUsers A list of the possible criteria for a request to have
1340 * access to write to a container. Each item is of the following format:
1341 * - account:user : Grants access if the request is by the given user
1342 * @return StatusValue
1344 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1345 $status = $this->newStatus();
1346 $auth = $this->getAuthentication();
1349 $status->fatal( 'backend-fail-connect', $this->name
);
1354 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1356 'url' => $this->storageUrl( $auth, $container ),
1357 'headers' => $this->authTokenHeaders( $auth ) +
[
1358 'x-container-read' => implode( ',', $readUsers ),
1359 'x-container-write' => implode( ',', $writeUsers )
1363 if ( $rcode != 204 && $rcode !== 202 ) {
1364 $status->fatal( 'backend-fail-internal', $this->name
);
1365 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1366 [ 'rcode' => $rcode ] );
1373 * Get a Swift container stat array, possibly from process cache.
1374 * Use $reCache if the file count or byte count is needed.
1376 * @param string $container Container name
1377 * @param bool $bypassCache Bypass all caches and load from Swift
1378 * @return array|bool|null False on 404, null on failure
1380 protected function getContainerStat( $container, $bypassCache = false ) {
1381 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1383 if ( $bypassCache ) { // purge cache
1384 $this->containerStatCache
->clear( $container );
1385 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1386 $this->primeContainerCache( [ $container ] ); // check persistent cache
1388 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1389 $auth = $this->getAuthentication();
1394 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1396 'url' => $this->storageUrl( $auth, $container ),
1397 'headers' => $this->authTokenHeaders( $auth )
1400 if ( $rcode === 204 ) {
1402 'count' => $rhdrs['x-container-object-count'],
1403 'bytes' => $rhdrs['x-container-bytes-used']
1405 if ( $bypassCache ) {
1408 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1409 $this->setContainerCache( $container, $stat ); // update persistent cache
1411 } elseif ( $rcode === 404 ) {
1414 $this->onError( null, __METHOD__
,
1415 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1421 return $this->containerStatCache
->get( $container, 'stat' );
1425 * Create a Swift container
1427 * @param string $container Container name
1428 * @param array $params
1429 * @return StatusValue
1431 protected function createContainer( $container, array $params ) {
1432 $status = $this->newStatus();
1434 $auth = $this->getAuthentication();
1436 $status->fatal( 'backend-fail-connect', $this->name
);
1441 // @see SwiftFileBackend::setContainerAccess()
1442 if ( empty( $params['noAccess'] ) ) {
1443 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] ); // public
1445 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
] ); // private
1448 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] ); // sanity
1450 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1452 'url' => $this->storageUrl( $auth, $container ),
1453 'headers' => $this->authTokenHeaders( $auth ) +
[
1454 'x-container-read' => implode( ',', $readUsers ),
1455 'x-container-write' => implode( ',', $writeUsers )
1459 if ( $rcode === 201 ) { // new
1461 } elseif ( $rcode === 202 ) { // already there
1462 // this shouldn't really happen, but is OK
1464 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1471 * Delete a Swift container
1473 * @param string $container Container name
1474 * @param array $params
1475 * @return StatusValue
1477 protected function deleteContainer( $container, array $params ) {
1478 $status = $this->newStatus();
1480 $auth = $this->getAuthentication();
1482 $status->fatal( 'backend-fail-connect', $this->name
);
1487 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1488 'method' => 'DELETE',
1489 'url' => $this->storageUrl( $auth, $container ),
1490 'headers' => $this->authTokenHeaders( $auth )
1493 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1494 $this->containerStatCache
->clear( $container ); // purge
1495 } elseif ( $rcode === 404 ) { // not there
1496 // this shouldn't really happen, but is OK
1497 } elseif ( $rcode === 409 ) { // not empty
1498 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1500 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1507 * Get a list of objects under a container.
1508 * Either just the names or a list of stdClass objects with details can be returned.
1510 * @param string $fullCont
1511 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1513 * @param string|null $after
1514 * @param string|null $prefix
1515 * @param string|null $delim
1516 * @return StatusValue With the list as value
1518 private function objectListing(
1519 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1521 $status = $this->newStatus();
1523 $auth = $this->getAuthentication();
1525 $status->fatal( 'backend-fail-connect', $this->name
);
1530 $query = [ 'limit' => $limit ];
1531 if ( $type === 'info' ) {
1532 $query['format'] = 'json';
1534 if ( $after !== null ) {
1535 $query['marker'] = $after;
1537 if ( $prefix !== null ) {
1538 $query['prefix'] = $prefix;
1540 if ( $delim !== null ) {
1541 $query['delimiter'] = $delim;
1544 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1546 'url' => $this->storageUrl( $auth, $fullCont ),
1548 'headers' => $this->authTokenHeaders( $auth )
1551 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1552 if ( $rcode === 200 ) { // good
1553 if ( $type === 'info' ) {
1554 $status->value
= FormatJson
::decode( trim( $rbody ) );
1556 $status->value
= explode( "\n", trim( $rbody ) );
1558 } elseif ( $rcode === 204 ) {
1559 $status->value
= []; // empty container
1560 } elseif ( $rcode === 404 ) {
1561 $status->value
= []; // no container
1563 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1569 protected function doPrimeContainerCache( array $containerInfo ) {
1570 foreach ( $containerInfo as $container => $info ) {
1571 $this->containerStatCache
->set( $container, 'stat', $info );
1575 protected function doGetFileStatMulti( array $params ) {
1578 $auth = $this->getAuthentication();
1581 foreach ( $params['srcs'] as $path ) {
1582 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1583 if ( $srcRel === null ) {
1584 $stats[$path] = false;
1585 continue; // invalid storage path
1586 } elseif ( !$auth ) {
1587 $stats[$path] = null;
1591 // (a) Check the container
1592 $cstat = $this->getContainerStat( $srcCont );
1593 if ( $cstat === false ) {
1594 $stats[$path] = false;
1595 continue; // ok, nothing to do
1596 } elseif ( !is_array( $cstat ) ) {
1597 $stats[$path] = null;
1603 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1604 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1608 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1609 $reqs = $this->http
->runMulti( $reqs, $opts );
1611 foreach ( $params['srcs'] as $path ) {
1612 if ( array_key_exists( $path, $stats ) ) {
1613 continue; // some sort of failure above
1615 // (b) Check the file
1616 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1617 if ( $rcode === 200 ||
$rcode === 204 ) {
1618 // Update the object if it is missing some headers
1619 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1620 // Load the stat array from the headers
1621 $stat = $this->getStatFromHeaders( $rhdrs );
1622 if ( $this->isRGW
) {
1623 $stat['latest'] = true; // strong consistency
1625 } elseif ( $rcode === 404 ) {
1629 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1631 $stats[$path] = $stat;
1638 * @param array $rhdrs
1641 protected function getStatFromHeaders( array $rhdrs ) {
1642 // Fetch all of the custom metadata headers
1643 $metadata = $this->getMetadata( $rhdrs );
1644 // Fetch all of the custom raw HTTP headers
1645 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1648 // Convert various random Swift dates to TS_MW
1649 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1650 // Empty objects actually return no content-length header in Ceph
1651 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1652 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1653 // Note: manifiest ETags are not an MD5 of the file
1654 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1655 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1660 * @return array|null Credential map
1662 protected function getAuthentication() {
1663 if ( $this->authErrorTimestamp
!== null ) {
1664 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1665 return null; // failed last attempt; don't bother
1666 } else { // actually retry this time
1667 $this->authErrorTimestamp
= null;
1670 // Session keys expire after a while, so we renew them periodically
1671 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1672 // Authenticate with proxy and get a session key...
1673 if ( !$this->authCreds ||
$reAuth ) {
1674 $this->authSessionTimestamp
= 0;
1675 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1676 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1677 // Try to use the credential cache
1678 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1679 $this->authCreds
= $creds;
1680 // Skew the timestamp for worst case to avoid using stale credentials
1681 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1682 } else { // cache miss
1683 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1685 'url' => "{$this->swiftAuthUrl}/v1.0",
1687 'x-auth-user' => $this->swiftUser
,
1688 'x-auth-key' => $this->swiftKey
1692 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1693 $this->authCreds
= [
1694 'auth_token' => $rhdrs['x-auth-token'],
1695 'storage_url' => ( $this->swiftStorageUrl
!== null )
1696 ?
$this->swiftStorageUrl
1697 : $rhdrs['x-storage-url']
1700 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1701 $this->authSessionTimestamp
= time();
1702 } elseif ( $rcode === 401 ) {
1703 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1704 $this->authErrorTimestamp
= time();
1708 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1709 $this->authErrorTimestamp
= time();
1714 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1715 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1716 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1720 return $this->authCreds
;
1724 * @param array $creds From getAuthentication()
1725 * @param string $container
1726 * @param string $object
1729 protected function storageUrl( array $creds, $container = null, $object = null ) {
1730 $parts = [ $creds['storage_url'] ];
1731 if ( strlen( $container ) ) {
1732 $parts[] = rawurlencode( $container );
1734 if ( strlen( $object ) ) {
1735 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1738 return implode( '/', $parts );
1742 * @param array $creds From getAuthentication()
1745 protected function authTokenHeaders( array $creds ) {
1746 return [ 'x-auth-token' => $creds['auth_token'] ];
1750 * Get the cache key for a container
1752 * @param string $username
1755 private function getCredsCacheKey( $username ) {
1756 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1760 * Log an unexpected exception for this backend.
1761 * This also sets the StatusValue object to have a fatal error.
1763 * @param StatusValue|null $status
1764 * @param string $func
1765 * @param array $params
1766 * @param string $err Error string
1767 * @param int $code HTTP status
1768 * @param string $desc HTTP StatusValue description
1770 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1771 if ( $status instanceof StatusValue
) {
1772 $status->fatal( 'backend-fail-internal', $this->name
);
1774 if ( $code == 401 ) { // possibly a stale token
1775 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1777 $msg = "HTTP {code} ({desc}) in '{func}' (given '{params}')";
1782 'req_params' => FormatJson
::encode( $params ),
1786 $msgParams['err'] = $err;
1788 $this->logger
->error( $msg, $msgParams );
1793 * @see FileBackendStoreOpHandle
1795 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1796 /** @var array List of Requests for MultiHttpClient */
1802 * @param SwiftFileBackend $backend
1803 * @param Closure $callback Function that takes (HTTP request array, status)
1804 * @param array $httpOp MultiHttpClient op
1806 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1807 $this->backend
= $backend;
1808 $this->callback
= $callback;
1809 $this->httpOp
= $httpOp;
1814 * SwiftFileBackend helper class to page through listings.
1815 * Swift also has a listing limit of 10,000 objects for sanity.
1816 * Do not use this class from places outside SwiftFileBackend.
1818 * @ingroup FileBackend
1820 abstract class SwiftFileBackendList
implements Iterator
{
1821 /** @var array List of path or (path,stat array) entries */
1822 protected $bufferIter = [];
1824 /** @var string List items *after* this path */
1825 protected $bufferAfter = null;
1831 protected $params = [];
1833 /** @var SwiftFileBackend */
1836 /** @var string Container name */
1837 protected $container;
1839 /** @var string Storage directory */
1843 protected $suffixStart;
1845 const PAGE_SIZE
= 9000; // file listing buffer size
1848 * @param SwiftFileBackend $backend
1849 * @param string $fullCont Resolved container name
1850 * @param string $dir Resolved directory relative to container
1851 * @param array $params
1853 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1854 $this->backend
= $backend;
1855 $this->container
= $fullCont;
1857 if ( substr( $this->dir
, -1 ) === '/' ) {
1858 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1860 if ( $this->dir
== '' ) { // whole container
1861 $this->suffixStart
= 0;
1862 } else { // dir within container
1863 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1865 $this->params
= $params;
1869 * @see Iterator::key()
1872 public function key() {
1877 * @see Iterator::next()
1879 public function next() {
1880 // Advance to the next file in the page
1881 next( $this->bufferIter
);
1883 // Check if there are no files left in this page and
1884 // advance to the next page if this page was not empty.
1885 if ( !$this->valid() && count( $this->bufferIter
) ) {
1886 $this->bufferIter
= $this->pageFromList(
1887 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1888 ); // updates $this->bufferAfter
1893 * @see Iterator::rewind()
1895 public function rewind() {
1897 $this->bufferAfter
= null;
1898 $this->bufferIter
= $this->pageFromList(
1899 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1900 ); // updates $this->bufferAfter
1904 * @see Iterator::valid()
1907 public function valid() {
1908 if ( $this->bufferIter
=== null ) {
1909 return false; // some failure?
1911 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1916 * Get the given list portion (page)
1918 * @param string $container Resolved container name
1919 * @param string $dir Resolved path relative to container
1920 * @param string &$after
1922 * @param array $params
1923 * @return Traversable|array
1925 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1929 * Iterator for listing directories
1931 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1933 * @see Iterator::current()
1934 * @return string|bool String (relative path) or false
1936 public function current() {
1937 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1940 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1941 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1946 * Iterator for listing regular files
1948 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1950 * @see Iterator::current()
1951 * @return string|bool String (relative path) or false
1953 public function current() {
1954 list( $path, $stat ) = current( $this->bufferIter
);
1955 $relPath = substr( $path, $this->suffixStart
);
1956 if ( is_array( $stat ) ) {
1957 $storageDir = rtrim( $this->params
['dir'], '/' );
1958 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1964 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1965 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );