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
= isset( $config['swiftAuthTTL'] )
120 ?
$config['swiftAuthTTL']
121 : 15 * 60; // some sane number
122 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
123 ?
$config['swiftTempUrlKey']
125 $this->swiftStorageUrl
= isset( $config['swiftStorageUrl'] )
126 ?
$config['swiftStorageUrl']
128 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
129 ?
$config['shardViaHashLevels']
131 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
132 ?
$config['rgwS3AccessKey']
134 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
135 ?
$config['rgwS3SecretKey']
137 // HTTP helper client
138 $this->http
= new MultiHttpClient( [] );
139 // Cache container information to mask latency
140 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache
) {
141 $this->memCache
= $config['wanCache'];
143 // Process cache for container info
144 $this->containerStatCache
= new ProcessCacheLRU( 300 );
145 // Cache auth token information to avoid RTTs
146 if ( !empty( $config['cacheAuthInfo'] ) && isset( $config['srvCache'] ) ) {
147 $this->srvCache
= $config['srvCache'];
149 $this->srvCache
= new EmptyBagOStuff();
151 $this->readUsers
= isset( $config['readUsers'] )
152 ?
$config['readUsers']
154 $this->writeUsers
= isset( $config['writeUsers'] )
155 ?
$config['writeUsers']
157 $this->secureReadUsers
= isset( $config['secureReadUsers'] )
158 ?
$config['secureReadUsers']
160 $this->secureWriteUsers
= isset( $config['secureWriteUsers'] )
161 ?
$config['secureWriteUsers']
165 public function getFeatures() {
166 return ( FileBackend
::ATTR_UNICODE_PATHS |
167 FileBackend
::ATTR_HEADERS | FileBackend
::ATTR_METADATA
);
170 protected function resolveContainerPath( $container, $relStoragePath ) {
171 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) {
172 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
173 } elseif ( strlen( rawurlencode( $relStoragePath ) ) > 1024 ) {
174 return null; // too long for Swift
177 return $relStoragePath;
180 public function isPathUsableInternal( $storagePath ) {
181 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
182 if ( $rel === null ) {
183 return false; // invalid
186 return is_array( $this->getContainerStat( $container ) );
190 * Sanitize and filter the custom headers from a $params array.
191 * Only allows certain "standard" Content- and X-Content- headers.
193 * @param array $params
194 * @return array Sanitized value of 'headers' field in $params
196 protected function sanitizeHdrsStrict( array $params ) {
197 if ( !isset( $params['headers'] ) ) {
201 $headers = $this->getCustomHeaders( $params['headers'] );
202 unset( $headers[ 'content-type' ] );
208 * Sanitize and filter the custom headers from a $params array.
209 * Only allows certain "standard" Content- and X-Content- headers.
211 * When POSTing data, libcurl adds Content-Type: application/x-www-form-urlencoded
212 * if Content-Type is not set, which overwrites the stored Content-Type header
213 * in Swift - therefore for POSTing data do not strip the Content-Type header (the
214 * previously-stored header that has been already read back from swift is sent)
216 * @param array $params
217 * @return array Sanitized value of 'headers' field in $params
219 protected function sanitizeHdrs( array $params ) {
220 return isset( $params['headers'] )
221 ?
$this->getCustomHeaders( $params['headers'] )
226 * @param array $rawHeaders
227 * @return array Custom non-metadata HTTP headers
229 protected function getCustomHeaders( array $rawHeaders ) {
232 // Normalize casing, and strip out illegal headers
233 foreach ( $rawHeaders as $name => $value ) {
234 $name = strtolower( $name );
235 if ( preg_match( '/^content-length$/', $name ) ) {
236 continue; // blacklisted
237 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
238 $headers[$name] = $value; // allowed
239 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
240 $headers[$name] = $value; // allowed
243 // By default, Swift has annoyingly low maximum header value limits
244 if ( isset( $headers['content-disposition'] ) ) {
246 // @note: assume FileBackend::makeContentDisposition() already used
247 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
248 $part = trim( $part );
249 $new = ( $disposition === '' ) ?
$part : "{$disposition};{$part}";
250 if ( strlen( $new ) <= 255 ) {
253 break; // too long; sigh
256 $headers['content-disposition'] = $disposition;
263 * @param array $rawHeaders
264 * @return array Custom metadata headers
266 protected function getMetadataHeaders( array $rawHeaders ) {
268 foreach ( $rawHeaders as $name => $value ) {
269 $name = strtolower( $name );
270 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
271 $headers[$name] = $value;
279 * @param array $rawHeaders
280 * @return array Custom metadata headers with prefix removed
282 protected function getMetadata( array $rawHeaders ) {
284 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
285 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
291 protected function doCreateInternal( array $params ) {
292 $status = $this->newStatus();
294 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
295 if ( $dstRel === null ) {
296 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
301 $sha1Hash = Wikimedia\base_convert
( sha1( $params['content'] ), 16, 36, 31 );
302 $contentType = isset( $params['headers']['content-type'] )
303 ?
$params['headers']['content-type']
304 : $this->getContentType( $params['dst'], $params['content'], null );
308 'url' => [ $dstCont, $dstRel ],
310 'content-length' => strlen( $params['content'] ),
311 'etag' => md5( $params['content'] ),
312 'content-type' => $contentType,
313 'x-object-meta-sha1base36' => $sha1Hash
314 ] +
$this->sanitizeHdrsStrict( $params ),
315 'body' => $params['content']
318 $method = __METHOD__
;
319 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
320 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
321 if ( $rcode === 201 ) {
323 } elseif ( $rcode === 412 ) {
324 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
326 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
330 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
331 if ( !empty( $params['async'] ) ) { // deferred
332 $status->value
= $opHandle;
333 } else { // actually write the object in Swift
334 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
340 protected function doStoreInternal( array $params ) {
341 $status = $this->newStatus();
343 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
344 if ( $dstRel === null ) {
345 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
350 Wikimedia\
suppressWarnings();
351 $sha1Hash = sha1_file( $params['src'] );
352 Wikimedia\restoreWarnings
();
353 if ( $sha1Hash === false ) { // source doesn't exist?
354 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
358 $sha1Hash = Wikimedia\base_convert
( $sha1Hash, 16, 36, 31 );
359 $contentType = isset( $params['headers']['content-type'] )
360 ?
$params['headers']['content-type']
361 : $this->getContentType( $params['dst'], null, $params['src'] );
363 $handle = fopen( $params['src'], 'rb' );
364 if ( $handle === false ) { // source doesn't exist?
365 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
372 'url' => [ $dstCont, $dstRel ],
374 'content-length' => filesize( $params['src'] ),
375 'etag' => md5_file( $params['src'] ),
376 'content-type' => $contentType,
377 'x-object-meta-sha1base36' => $sha1Hash
378 ] +
$this->sanitizeHdrsStrict( $params ),
379 'body' => $handle // resource
382 $method = __METHOD__
;
383 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
384 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
385 if ( $rcode === 201 ) {
387 } elseif ( $rcode === 412 ) {
388 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
390 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
394 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
395 $opHandle->resourcesToClose
[] = $handle;
397 if ( !empty( $params['async'] ) ) { // deferred
398 $status->value
= $opHandle;
399 } else { // actually write the object in Swift
400 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
406 protected function doCopyInternal( array $params ) {
407 $status = $this->newStatus();
409 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
410 if ( $srcRel === null ) {
411 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
416 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
417 if ( $dstRel === null ) {
418 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
425 'url' => [ $dstCont, $dstRel ],
427 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
428 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
429 ] +
$this->sanitizeHdrsStrict( $params ), // extra headers merged into object
432 $method = __METHOD__
;
433 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
434 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
435 if ( $rcode === 201 ) {
437 } elseif ( $rcode === 404 ) {
438 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
440 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
444 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
445 if ( !empty( $params['async'] ) ) { // deferred
446 $status->value
= $opHandle;
447 } else { // actually write the object in Swift
448 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
454 protected function doMoveInternal( array $params ) {
455 $status = $this->newStatus();
457 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
458 if ( $srcRel === null ) {
459 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
464 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
465 if ( $dstRel === null ) {
466 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
474 'url' => [ $dstCont, $dstRel ],
476 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
477 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
478 ] +
$this->sanitizeHdrsStrict( $params ) // extra headers merged into object
481 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
483 'method' => 'DELETE',
484 'url' => [ $srcCont, $srcRel ],
489 $method = __METHOD__
;
490 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
491 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
492 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
494 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
496 } elseif ( $rcode === 404 ) {
497 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
499 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
503 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
504 if ( !empty( $params['async'] ) ) { // deferred
505 $status->value
= $opHandle;
506 } else { // actually move the object in Swift
507 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
513 protected function doDeleteInternal( array $params ) {
514 $status = $this->newStatus();
516 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
517 if ( $srcRel === null ) {
518 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
524 'method' => 'DELETE',
525 'url' => [ $srcCont, $srcRel ],
529 $method = __METHOD__
;
530 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
531 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
532 if ( $rcode === 204 ) {
534 } elseif ( $rcode === 404 ) {
535 if ( empty( $params['ignoreMissingSource'] ) ) {
536 $status->fatal( 'backend-fail-delete', $params['src'] );
539 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
543 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
544 if ( !empty( $params['async'] ) ) { // deferred
545 $status->value
= $opHandle;
546 } else { // actually delete the object in Swift
547 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
553 protected function doDescribeInternal( array $params ) {
554 $status = $this->newStatus();
556 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
557 if ( $srcRel === null ) {
558 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
563 // Fetch the old object headers/metadata...this should be in stat cache by now
564 $stat = $this->getFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
565 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
566 $stat = $this->doGetFileStat( [ 'src' => $params['src'], 'latest' => 1 ] );
569 $status->fatal( 'backend-fail-describe', $params['src'] );
574 // POST clears prior headers, so we need to merge the changes in to the old ones
576 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
577 $metaHdrs["x-object-meta-$name"] = $value;
579 $customHdrs = $this->sanitizeHdrs( $params ) +
$stat['xattr']['headers'];
583 'url' => [ $srcCont, $srcRel ],
584 'headers' => $metaHdrs +
$customHdrs
587 $method = __METHOD__
;
588 $handler = function ( array $request, StatusValue
$status ) use ( $method, $params ) {
589 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
590 if ( $rcode === 202 ) {
592 } elseif ( $rcode === 404 ) {
593 $status->fatal( 'backend-fail-describe', $params['src'] );
595 $this->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
599 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
600 if ( !empty( $params['async'] ) ) { // deferred
601 $status->value
= $opHandle;
602 } else { // actually change the object in Swift
603 $status->merge( current( $this->executeOpHandlesInternal( [ $opHandle ] ) ) );
609 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
610 $status = $this->newStatus();
612 // (a) Check if container already exists
613 $stat = $this->getContainerStat( $fullCont );
614 if ( is_array( $stat ) ) {
615 return $status; // already there
616 } elseif ( $stat === null ) {
617 $status->fatal( 'backend-fail-internal', $this->name
);
618 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
623 // (b) Create container as needed with proper ACLs
624 if ( $stat === false ) {
625 $params['op'] = 'prepare';
626 $status->merge( $this->createContainer( $fullCont, $params ) );
632 protected function doSecureInternal( $fullCont, $dir, array $params ) {
633 $status = $this->newStatus();
634 if ( empty( $params['noAccess'] ) ) {
635 return $status; // nothing to do
638 $stat = $this->getContainerStat( $fullCont );
639 if ( is_array( $stat ) ) {
640 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
641 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
642 // Make container private to end-users...
643 $status->merge( $this->setContainerAccess(
648 } elseif ( $stat === false ) {
649 $status->fatal( 'backend-fail-usable', $params['dir'] );
651 $status->fatal( 'backend-fail-internal', $this->name
);
652 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
658 protected function doPublishInternal( $fullCont, $dir, array $params ) {
659 $status = $this->newStatus();
661 $stat = $this->getContainerStat( $fullCont );
662 if ( is_array( $stat ) ) {
663 $readUsers = array_merge( $this->readUsers
, [ $this->swiftUser
, '.r:*' ] );
664 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
666 // Make container public to end-users...
667 $status->merge( $this->setContainerAccess(
672 } elseif ( $stat === false ) {
673 $status->fatal( 'backend-fail-usable', $params['dir'] );
675 $status->fatal( 'backend-fail-internal', $this->name
);
676 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
682 protected function doCleanInternal( $fullCont, $dir, array $params ) {
683 $status = $this->newStatus();
685 // Only containers themselves can be removed, all else is virtual
687 return $status; // nothing to do
690 // (a) Check the container
691 $stat = $this->getContainerStat( $fullCont, true );
692 if ( $stat === false ) {
693 return $status; // ok, nothing to do
694 } elseif ( !is_array( $stat ) ) {
695 $status->fatal( 'backend-fail-internal', $this->name
);
696 $this->logger
->error( __METHOD__
. ': cannot get container stat' );
701 // (b) Delete the container if empty
702 if ( $stat['count'] == 0 ) {
703 $params['op'] = 'clean';
704 $status->merge( $this->deleteContainer( $fullCont, $params ) );
710 protected function doGetFileStat( array $params ) {
711 $params = [ 'srcs' => [ $params['src'] ], 'concurrency' => 1 ] +
$params;
712 unset( $params['src'] );
713 $stats = $this->doGetFileStatMulti( $params );
715 return reset( $stats );
719 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
720 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
721 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
724 * @param int $format Output format (TS_* constant)
726 * @throws FileBackendError
728 protected function convertSwiftDate( $ts, $format = TS_MW
) {
730 $timestamp = new MWTimestamp( $ts );
732 return $timestamp->getTimestamp( $format );
733 } catch ( Exception
$e ) {
734 throw new FileBackendError( $e->getMessage() );
739 * Fill in any missing object metadata and save it to Swift
741 * @param array $objHdrs Object response headers
742 * @param string $path Storage path to object
743 * @return array New headers
745 protected function addMissingMetadata( array $objHdrs, $path ) {
746 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
747 return $objHdrs; // nothing to do
750 /** @noinspection PhpUnusedLocalVariableInspection */
751 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
752 $this->logger
->error( __METHOD__
. ": {path} was not stored with SHA-1 metadata.",
753 [ 'path' => $path ] );
755 $objHdrs['x-object-meta-sha1base36'] = false;
757 $auth = $this->getAuthentication();
759 return $objHdrs; // failed
762 // Find prior custom HTTP headers
763 $postHeaders = $this->getCustomHeaders( $objHdrs );
764 // Find prior metadata headers
765 $postHeaders +
= $this->getMetadataHeaders( $objHdrs );
767 $status = $this->newStatus();
768 /** @noinspection PhpUnusedLocalVariableInspection */
769 $scopeLockS = $this->getScopedFileLocks( [ $path ], LockManager
::LOCK_UW
, $status );
770 if ( $status->isOK() ) {
771 $tmpFile = $this->getLocalCopy( [ 'src' => $path, 'latest' => 1 ] );
773 $hash = $tmpFile->getSha1Base36();
774 if ( $hash !== false ) {
775 $objHdrs['x-object-meta-sha1base36'] = $hash;
776 // Merge new SHA1 header into the old ones
777 $postHeaders['x-object-meta-sha1base36'] = $hash;
778 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
779 list( $rcode ) = $this->http
->run( [
781 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
782 'headers' => $this->authTokenHeaders( $auth ) +
$postHeaders
784 if ( $rcode >= 200 && $rcode <= 299 ) {
785 $this->deleteFileCache( $path );
787 return $objHdrs; // success
793 $this->logger
->error( __METHOD__
. ': unable to set SHA-1 metadata for {path}',
794 [ 'path' => $path ] );
796 return $objHdrs; // failed
799 protected function doGetFileContentsMulti( array $params ) {
802 $auth = $this->getAuthentication();
804 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
805 // Blindly create tmp files and stream to them, catching any exception if the file does
806 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
807 $reqs = []; // (path => op)
809 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
810 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
811 if ( $srcRel === null ||
!$auth ) {
812 $contents[$path] = false;
815 // Create a new temporary memory file...
816 $handle = fopen( 'php://temp', 'wb' );
820 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
821 'headers' => $this->authTokenHeaders( $auth )
822 +
$this->headersFromParams( $params ),
826 $contents[$path] = false;
829 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
830 $reqs = $this->http
->runMulti( $reqs, $opts );
831 foreach ( $reqs as $path => $op ) {
832 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
833 if ( $rcode >= 200 && $rcode <= 299 ) {
834 rewind( $op['stream'] ); // start from the beginning
835 $contents[$path] = stream_get_contents( $op['stream'] );
836 } elseif ( $rcode === 404 ) {
837 $contents[$path] = false;
839 $this->onError( null, __METHOD__
,
840 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
842 fclose( $op['stream'] ); // close open handle
848 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
849 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
850 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
851 if ( $status->isOK() ) {
852 return ( count( $status->value
) ) > 0;
855 return null; // error
859 * @see FileBackendStore::getDirectoryListInternal()
860 * @param string $fullCont
862 * @param array $params
863 * @return SwiftFileBackendDirList
865 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
866 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
870 * @see FileBackendStore::getFileListInternal()
871 * @param string $fullCont
873 * @param array $params
874 * @return SwiftFileBackendFileList
876 public function getFileListInternal( $fullCont, $dir, array $params ) {
877 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
881 * Do not call this function outside of SwiftFileBackendFileList
883 * @param string $fullCont Resolved container name
884 * @param string $dir Resolved storage directory with no trailing slash
885 * @param string|null &$after Resolved container relative path to list items after
886 * @param int $limit Max number of items to list
887 * @param array $params Parameters for getDirectoryList()
888 * @return array List of container relative resolved paths of directories directly under $dir
889 * @throws FileBackendError
891 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
893 if ( $after === INF
) {
894 return $dirs; // nothing more
897 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
899 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
900 // Non-recursive: only list dirs right under $dir
901 if ( !empty( $params['topOnly'] ) ) {
902 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
903 if ( !$status->isOK() ) {
904 throw new FileBackendError( "Iterator page I/O error." );
906 $objects = $status->value
;
907 foreach ( $objects as $object ) { // files and directories
908 if ( substr( $object, -1 ) === '/' ) {
909 $dirs[] = $object; // directories end in '/'
913 // Recursive: list all dirs under $dir and its subdirs
914 $getParentDir = function ( $path ) {
915 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
918 // Get directory from last item of prior page
919 $lastDir = $getParentDir( $after ); // must be first page
920 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
922 if ( !$status->isOK() ) {
923 throw new FileBackendError( "Iterator page I/O error." );
926 $objects = $status->value
;
928 foreach ( $objects as $object ) { // files
929 $objectDir = $getParentDir( $object ); // directory of object
931 if ( $objectDir !== false && $objectDir !== $dir ) {
932 // Swift stores paths in UTF-8, using binary sorting.
933 // See function "create_container_table" in common/db.py.
934 // If a directory is not "greater" than the last one,
935 // then it was already listed by the calling iterator.
936 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
938 do { // add dir and all its parent dirs
939 $dirs[] = "{$pDir}/";
940 $pDir = $getParentDir( $pDir );
941 } while ( $pDir !== false // sanity
942 && strcmp( $pDir, $lastDir ) > 0 // not done already
943 && strlen( $pDir ) > strlen( $dir ) // within $dir
946 $lastDir = $objectDir;
950 // Page on the unfiltered directory listing (what is returned may be filtered)
951 if ( count( $objects ) < $limit ) {
952 $after = INF
; // avoid a second RTT
954 $after = end( $objects ); // update last item
961 * Do not call this function outside of SwiftFileBackendFileList
963 * @param string $fullCont Resolved container name
964 * @param string $dir Resolved storage directory with no trailing slash
965 * @param string|null &$after Resolved container relative path of file to list items after
966 * @param int $limit Max number of items to list
967 * @param array $params Parameters for getDirectoryList()
968 * @return array List of resolved container relative paths of files under $dir
969 * @throws FileBackendError
971 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
972 $files = []; // list of (path, stat array or null) entries
973 if ( $after === INF
) {
974 return $files; // nothing more
977 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
979 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
980 // $objects will contain a list of unfiltered names or CF_Object items
981 // Non-recursive: only list files right under $dir
982 if ( !empty( $params['topOnly'] ) ) {
983 if ( !empty( $params['adviseStat'] ) ) {
984 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
986 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
989 // Recursive: list all files under $dir and its subdirs
990 if ( !empty( $params['adviseStat'] ) ) {
991 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
993 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
997 // Reformat this list into a list of (name, stat array or null) entries
998 if ( !$status->isOK() ) {
999 throw new FileBackendError( "Iterator page I/O error." );
1002 $objects = $status->value
;
1003 $files = $this->buildFileObjectListing( $params, $dir, $objects );
1005 // Page on the unfiltered object listing (what is returned may be filtered)
1006 if ( count( $objects ) < $limit ) {
1007 $after = INF
; // avoid a second RTT
1009 $after = end( $objects ); // update last item
1010 $after = is_object( $after ) ?
$after->name
: $after;
1017 * Build a list of file objects, filtering out any directories
1018 * and extracting any stat info if provided in $objects (for CF_Objects)
1020 * @param array $params Parameters for getDirectoryList()
1021 * @param string $dir Resolved container directory path
1022 * @param array $objects List of CF_Object items or object names
1023 * @return array List of (names,stat array or null) entries
1025 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1027 foreach ( $objects as $object ) {
1028 if ( is_object( $object ) ) {
1029 if ( isset( $object->subdir
) ||
!isset( $object->name
) ) {
1030 continue; // virtual directory entry; ignore
1033 // Convert various random Swift dates to TS_MW
1034 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1035 'size' => (int)$object->bytes
,
1037 // Note: manifiest ETags are not an MD5 of the file
1038 'md5' => ctype_xdigit( $object->hash
) ?
$object->hash
: null,
1039 'latest' => false // eventually consistent
1041 $names[] = [ $object->name
, $stat ];
1042 } elseif ( substr( $object, -1 ) !== '/' ) {
1043 // Omit directories, which end in '/' in listings
1044 $names[] = [ $object, null ];
1052 * Do not call this function outside of SwiftFileBackendFileList
1054 * @param string $path Storage path
1055 * @param array $val Stat value
1057 public function loadListingStatInternal( $path, array $val ) {
1058 $this->cheapCache
->set( $path, 'stat', $val );
1061 protected function doGetFileXAttributes( array $params ) {
1062 $stat = $this->getFileStat( $params );
1064 if ( !isset( $stat['xattr'] ) ) {
1065 // Stat entries filled by file listings don't include metadata/headers
1066 $this->clearCache( [ $params['src'] ] );
1067 $stat = $this->getFileStat( $params );
1070 return $stat['xattr'];
1076 protected function doGetFileSha1base36( array $params ) {
1077 $stat = $this->getFileStat( $params );
1079 if ( !isset( $stat['sha1'] ) ) {
1080 // Stat entries filled by file listings don't include SHA1
1081 $this->clearCache( [ $params['src'] ] );
1082 $stat = $this->getFileStat( $params );
1085 return $stat['sha1'];
1091 protected function doStreamFile( array $params ) {
1092 $status = $this->newStatus();
1094 $flags = !empty( $params['headless'] ) ? StreamFile
::STREAM_HEADLESS
: 0;
1096 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1097 if ( $srcRel === null ) {
1098 StreamFile
::send404Message( $params['src'], $flags );
1099 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1104 $auth = $this->getAuthentication();
1105 if ( !$auth ||
!is_array( $this->getContainerStat( $srcCont ) ) ) {
1106 StreamFile
::send404Message( $params['src'], $flags );
1107 $status->fatal( 'backend-fail-stream', $params['src'] );
1112 // If "headers" is set, we only want to send them if the file is there.
1113 // Do not bother checking if the file exists if headers are not set though.
1114 if ( $params['headers'] && !$this->fileExists( $params ) ) {
1115 StreamFile
::send404Message( $params['src'], $flags );
1116 $status->fatal( 'backend-fail-stream', $params['src'] );
1121 // Send the requested additional headers
1122 foreach ( $params['headers'] as $header ) {
1123 header( $header ); // aways send
1126 if ( empty( $params['allowOB'] ) ) {
1127 // Cancel output buffering and gzipping if set
1128 call_user_func( $this->obResetFunc
);
1131 $handle = fopen( 'php://output', 'wb' );
1132 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1134 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1135 'headers' => $this->authTokenHeaders( $auth )
1136 +
$this->headersFromParams( $params ) +
$params['options'],
1137 'stream' => $handle,
1138 'flags' => [ 'relayResponseHeaders' => empty( $params['headless'] ) ]
1141 if ( $rcode >= 200 && $rcode <= 299 ) {
1143 } elseif ( $rcode === 404 ) {
1144 $status->fatal( 'backend-fail-stream', $params['src'] );
1145 // Per T43113, nasty things can happen if bad cache entries get
1146 // stuck in cache. It's also possible that this error can come up
1147 // with simple race conditions. Clear out the stat cache to be safe.
1148 $this->clearCache( [ $params['src'] ] );
1149 $this->deleteFileCache( $params['src'] );
1151 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1157 protected function doGetLocalCopyMulti( array $params ) {
1158 /** @var TempFSFile[] $tmpFiles */
1161 $auth = $this->getAuthentication();
1163 $ep = array_diff_key( $params, [ 'srcs' => 1 ] ); // for error logging
1164 // Blindly create tmp files and stream to them, catching any exception if the file does
1165 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1166 $reqs = []; // (path => op)
1168 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1169 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1170 if ( $srcRel === null ||
!$auth ) {
1171 $tmpFiles[$path] = null;
1174 // Get source file extension
1175 $ext = FileBackend
::extensionFromPath( $path );
1176 // Create a new temporary file...
1177 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext, $this->tmpDirectory
);
1179 $handle = fopen( $tmpFile->getPath(), 'wb' );
1183 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1184 'headers' => $this->authTokenHeaders( $auth )
1185 +
$this->headersFromParams( $params ),
1186 'stream' => $handle,
1192 $tmpFiles[$path] = $tmpFile;
1195 $isLatest = ( $this->isRGW ||
!empty( $params['latest'] ) );
1196 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1197 $reqs = $this->http
->runMulti( $reqs, $opts );
1198 foreach ( $reqs as $path => $op ) {
1199 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1200 fclose( $op['stream'] ); // close open handle
1201 if ( $rcode >= 200 && $rcode <= 299 ) {
1202 $size = $tmpFiles[$path] ?
$tmpFiles[$path]->getSize() : 0;
1203 // Double check that the disk is not full/broken
1204 if ( $size != $rhdrs['content-length'] ) {
1205 $tmpFiles[$path] = null;
1206 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1207 $this->onError( null, __METHOD__
,
1208 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1210 // Set the file stat process cache in passing
1211 $stat = $this->getStatFromHeaders( $rhdrs );
1212 $stat['latest'] = $isLatest;
1213 $this->cheapCache
->set( $path, 'stat', $stat );
1214 } elseif ( $rcode === 404 ) {
1215 $tmpFiles[$path] = false;
1217 $tmpFiles[$path] = null;
1218 $this->onError( null, __METHOD__
,
1219 [ 'src' => $path ] +
$ep, $rerr, $rcode, $rdesc );
1226 public function getFileHttpUrl( array $params ) {
1227 if ( $this->swiftTempUrlKey
!= '' ||
1228 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1230 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1231 if ( $srcRel === null ) {
1232 return null; // invalid path
1235 $auth = $this->getAuthentication();
1240 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1241 $expires = time() +
$ttl;
1243 if ( $this->swiftTempUrlKey
!= '' ) {
1244 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1245 // Swift wants the signature based on the unencoded object name
1246 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH
);
1247 $signature = hash_hmac( 'sha1',
1248 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1249 $this->swiftTempUrlKey
1252 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1253 } else { // give S3 API URL for rgw
1254 // Path for signature starts with the bucket
1255 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1256 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1257 // Calculate the hash
1258 $signature = base64_encode( hash_hmac(
1260 "GET\n\n\n{$expires}\n{$spath}",
1261 $this->rgwS3SecretKey
,
1264 // See https://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1265 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1266 // Note: S3 API is the rgw default; remove the /swift/ URL bit.
1267 return str_replace( '/swift/v1', '', $this->storageUrl( $auth ) . $spath ) .
1270 'Signature' => $signature,
1271 'Expires' => $expires,
1272 'AWSAccessKeyId' => $this->rgwS3AccessKey
1280 protected function directoriesAreVirtual() {
1285 * Get headers to send to Swift when reading a file based
1286 * on a FileBackend params array, e.g. that of getLocalCopy().
1287 * $params is currently only checked for a 'latest' flag.
1289 * @param array $params
1292 protected function headersFromParams( array $params ) {
1294 if ( !empty( $params['latest'] ) ) {
1295 $hdrs['x-newest'] = 'true';
1302 * @param FileBackendStoreOpHandle[] $fileOpHandles
1304 * @return StatusValue[]
1306 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1307 /** @var StatusValue[] $statuses */
1310 $auth = $this->getAuthentication();
1312 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1313 $statuses[$index] = $this->newStatus( 'backend-fail-connect', $this->name
);
1319 // Split the HTTP requests into stages that can be done concurrently
1320 $httpReqsByStage = []; // map of (stage => index => HTTP request)
1321 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1322 /** @var SwiftFileOpHandle $fileOpHandle */
1323 $reqs = $fileOpHandle->httpOp
;
1324 // Convert the 'url' parameter to an actual URL using $auth
1325 foreach ( $reqs as $stage => &$req ) {
1326 list( $container, $relPath ) = $req['url'];
1327 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1328 $req['headers'] = isset( $req['headers'] ) ?
$req['headers'] : [];
1329 $req['headers'] = $this->authTokenHeaders( $auth ) +
$req['headers'];
1330 $httpReqsByStage[$stage][$index] = $req;
1332 $statuses[$index] = $this->newStatus();
1335 // Run all requests for the first stage, then the next, and so on
1336 $reqCount = count( $httpReqsByStage );
1337 for ( $stage = 0; $stage < $reqCount; ++
$stage ) {
1338 $httpReqs = $this->http
->runMulti( $httpReqsByStage[$stage] );
1339 foreach ( $httpReqs as $index => $httpReq ) {
1340 // Run the callback for each request of this operation
1341 $callback = $fileOpHandles[$index]->callback
;
1342 call_user_func_array( $callback, [ $httpReq, $statuses[$index] ] );
1343 // On failure, abort all remaining requests for this operation
1344 // (e.g. abort the DELETE request if the COPY request fails for a move)
1345 if ( !$statuses[$index]->isOK() ) {
1346 $stages = count( $fileOpHandles[$index]->httpOp
);
1347 for ( $s = ( $stage +
1 ); $s < $stages; ++
$s ) {
1348 unset( $httpReqsByStage[$s][$index] );
1358 * Set read/write permissions for a Swift container.
1360 * @see http://docs.openstack.org/developer/swift/misc.html#acls
1362 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1363 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1365 * @param string $container Resolved Swift container
1366 * @param array $readUsers List of the possible criteria for a request to have
1367 * access to read a container. Each item is one of the following formats:
1368 * - account:user : Grants access if the request is by the given user
1369 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1370 * matches the expression and the request is not for a listing.
1371 * Setting this to '*' effectively makes a container public.
1372 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1373 * matches the expression and the request is for a listing.
1374 * @param array $writeUsers A list of the possible criteria for a request to have
1375 * access to write to a container. Each item is of the following format:
1376 * - account:user : Grants access if the request is by the given user
1377 * @return StatusValue
1379 protected function setContainerAccess( $container, array $readUsers, array $writeUsers ) {
1380 $status = $this->newStatus();
1381 $auth = $this->getAuthentication();
1384 $status->fatal( 'backend-fail-connect', $this->name
);
1389 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1391 'url' => $this->storageUrl( $auth, $container ),
1392 'headers' => $this->authTokenHeaders( $auth ) +
[
1393 'x-container-read' => implode( ',', $readUsers ),
1394 'x-container-write' => implode( ',', $writeUsers )
1398 if ( $rcode != 204 && $rcode !== 202 ) {
1399 $status->fatal( 'backend-fail-internal', $this->name
);
1400 $this->logger
->error( __METHOD__
. ': unexpected rcode value ({rcode})',
1401 [ 'rcode' => $rcode ] );
1408 * Get a Swift container stat array, possibly from process cache.
1409 * Use $reCache if the file count or byte count is needed.
1411 * @param string $container Container name
1412 * @param bool $bypassCache Bypass all caches and load from Swift
1413 * @return array|bool|null False on 404, null on failure
1415 protected function getContainerStat( $container, $bypassCache = false ) {
1416 $ps = $this->scopedProfileSection( __METHOD__
. "-{$this->name}" );
1418 if ( $bypassCache ) { // purge cache
1419 $this->containerStatCache
->clear( $container );
1420 } elseif ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1421 $this->primeContainerCache( [ $container ] ); // check persistent cache
1423 if ( !$this->containerStatCache
->has( $container, 'stat' ) ) {
1424 $auth = $this->getAuthentication();
1429 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1431 'url' => $this->storageUrl( $auth, $container ),
1432 'headers' => $this->authTokenHeaders( $auth )
1435 if ( $rcode === 204 ) {
1437 'count' => $rhdrs['x-container-object-count'],
1438 'bytes' => $rhdrs['x-container-bytes-used']
1440 if ( $bypassCache ) {
1443 $this->containerStatCache
->set( $container, 'stat', $stat ); // cache it
1444 $this->setContainerCache( $container, $stat ); // update persistent cache
1446 } elseif ( $rcode === 404 ) {
1449 $this->onError( null, __METHOD__
,
1450 [ 'cont' => $container ], $rerr, $rcode, $rdesc );
1456 return $this->containerStatCache
->get( $container, 'stat' );
1460 * Create a Swift container
1462 * @param string $container Container name
1463 * @param array $params
1464 * @return StatusValue
1466 protected function createContainer( $container, array $params ) {
1467 $status = $this->newStatus();
1469 $auth = $this->getAuthentication();
1471 $status->fatal( 'backend-fail-connect', $this->name
);
1476 // @see SwiftFileBackend::setContainerAccess()
1477 if ( empty( $params['noAccess'] ) ) {
1479 $readUsers = array_merge( $this->readUsers
, [ '.r:*', $this->swiftUser
] );
1480 $writeUsers = array_merge( $this->writeUsers
, [ $this->swiftUser
] );
1483 $readUsers = array_merge( $this->secureReadUsers
, [ $this->swiftUser
] );
1484 $writeUsers = array_merge( $this->secureWriteUsers
, [ $this->swiftUser
] );
1487 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1489 'url' => $this->storageUrl( $auth, $container ),
1490 'headers' => $this->authTokenHeaders( $auth ) +
[
1491 'x-container-read' => implode( ',', $readUsers ),
1492 'x-container-write' => implode( ',', $writeUsers )
1496 if ( $rcode === 201 ) { // new
1498 } elseif ( $rcode === 202 ) { // already there
1499 // this shouldn't really happen, but is OK
1501 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1508 * Delete a Swift container
1510 * @param string $container Container name
1511 * @param array $params
1512 * @return StatusValue
1514 protected function deleteContainer( $container, array $params ) {
1515 $status = $this->newStatus();
1517 $auth = $this->getAuthentication();
1519 $status->fatal( 'backend-fail-connect', $this->name
);
1524 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1525 'method' => 'DELETE',
1526 'url' => $this->storageUrl( $auth, $container ),
1527 'headers' => $this->authTokenHeaders( $auth )
1530 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1531 $this->containerStatCache
->clear( $container ); // purge
1532 } elseif ( $rcode === 404 ) { // not there
1533 // this shouldn't really happen, but is OK
1534 } elseif ( $rcode === 409 ) { // not empty
1535 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc ); // race?
1537 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1544 * Get a list of objects under a container.
1545 * Either just the names or a list of stdClass objects with details can be returned.
1547 * @param string $fullCont
1548 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1550 * @param string|null $after
1551 * @param string|null $prefix
1552 * @param string|null $delim
1553 * @return StatusValue With the list as value
1555 private function objectListing(
1556 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1558 $status = $this->newStatus();
1560 $auth = $this->getAuthentication();
1562 $status->fatal( 'backend-fail-connect', $this->name
);
1567 $query = [ 'limit' => $limit ];
1568 if ( $type === 'info' ) {
1569 $query['format'] = 'json';
1571 if ( $after !== null ) {
1572 $query['marker'] = $after;
1574 if ( $prefix !== null ) {
1575 $query['prefix'] = $prefix;
1577 if ( $delim !== null ) {
1578 $query['delimiter'] = $delim;
1581 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1583 'url' => $this->storageUrl( $auth, $fullCont ),
1585 'headers' => $this->authTokenHeaders( $auth )
1588 $params = [ 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim ];
1589 if ( $rcode === 200 ) { // good
1590 if ( $type === 'info' ) {
1591 $status->value
= FormatJson
::decode( trim( $rbody ) );
1593 $status->value
= explode( "\n", trim( $rbody ) );
1595 } elseif ( $rcode === 204 ) {
1596 $status->value
= []; // empty container
1597 } elseif ( $rcode === 404 ) {
1598 $status->value
= []; // no container
1600 $this->onError( $status, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1606 protected function doPrimeContainerCache( array $containerInfo ) {
1607 foreach ( $containerInfo as $container => $info ) {
1608 $this->containerStatCache
->set( $container, 'stat', $info );
1612 protected function doGetFileStatMulti( array $params ) {
1615 $auth = $this->getAuthentication();
1618 foreach ( $params['srcs'] as $path ) {
1619 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1620 if ( $srcRel === null ) {
1621 $stats[$path] = false;
1622 continue; // invalid storage path
1623 } elseif ( !$auth ) {
1624 $stats[$path] = null;
1628 // (a) Check the container
1629 $cstat = $this->getContainerStat( $srcCont );
1630 if ( $cstat === false ) {
1631 $stats[$path] = false;
1632 continue; // ok, nothing to do
1633 } elseif ( !is_array( $cstat ) ) {
1634 $stats[$path] = null;
1640 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1641 'headers' => $this->authTokenHeaders( $auth ) +
$this->headersFromParams( $params )
1645 $opts = [ 'maxConnsPerHost' => $params['concurrency'] ];
1646 $reqs = $this->http
->runMulti( $reqs, $opts );
1648 foreach ( $params['srcs'] as $path ) {
1649 if ( array_key_exists( $path, $stats ) ) {
1650 continue; // some sort of failure above
1652 // (b) Check the file
1653 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1654 if ( $rcode === 200 ||
$rcode === 204 ) {
1655 // Update the object if it is missing some headers
1656 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1657 // Load the stat array from the headers
1658 $stat = $this->getStatFromHeaders( $rhdrs );
1659 if ( $this->isRGW
) {
1660 $stat['latest'] = true; // strong consistency
1662 } elseif ( $rcode === 404 ) {
1666 $this->onError( null, __METHOD__
, $params, $rerr, $rcode, $rdesc );
1668 $stats[$path] = $stat;
1675 * @param array $rhdrs
1678 protected function getStatFromHeaders( array $rhdrs ) {
1679 // Fetch all of the custom metadata headers
1680 $metadata = $this->getMetadata( $rhdrs );
1681 // Fetch all of the custom raw HTTP headers
1682 $headers = $this->sanitizeHdrs( [ 'headers' => $rhdrs ] );
1685 // Convert various random Swift dates to TS_MW
1686 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW
),
1687 // Empty objects actually return no content-length header in Ceph
1688 'size' => isset( $rhdrs['content-length'] ) ?
(int)$rhdrs['content-length'] : 0,
1689 'sha1' => isset( $metadata['sha1base36'] ) ?
$metadata['sha1base36'] : null,
1690 // Note: manifiest ETags are not an MD5 of the file
1691 'md5' => ctype_xdigit( $rhdrs['etag'] ) ?
$rhdrs['etag'] : null,
1692 'xattr' => [ 'metadata' => $metadata, 'headers' => $headers ]
1697 * @return array|null Credential map
1699 protected function getAuthentication() {
1700 if ( $this->authErrorTimestamp
!== null ) {
1701 if ( ( time() - $this->authErrorTimestamp
) < 60 ) {
1702 return null; // failed last attempt; don't bother
1703 } else { // actually retry this time
1704 $this->authErrorTimestamp
= null;
1707 // Session keys expire after a while, so we renew them periodically
1708 $reAuth = ( ( time() - $this->authSessionTimestamp
) > $this->authTTL
);
1709 // Authenticate with proxy and get a session key...
1710 if ( !$this->authCreds ||
$reAuth ) {
1711 $this->authSessionTimestamp
= 0;
1712 $cacheKey = $this->getCredsCacheKey( $this->swiftUser
);
1713 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1714 // Try to use the credential cache
1715 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1716 $this->authCreds
= $creds;
1717 // Skew the timestamp for worst case to avoid using stale credentials
1718 $this->authSessionTimestamp
= time() - ceil( $this->authTTL
/ 2 );
1719 } else { // cache miss
1720 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http
->run( [
1722 'url' => "{$this->swiftAuthUrl}/v1.0",
1724 'x-auth-user' => $this->swiftUser
,
1725 'x-auth-key' => $this->swiftKey
1729 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1730 $this->authCreds
= [
1731 'auth_token' => $rhdrs['x-auth-token'],
1732 'storage_url' => ( $this->swiftStorageUrl
!== null )
1733 ?
$this->swiftStorageUrl
1734 : $rhdrs['x-storage-url']
1737 $this->srvCache
->set( $cacheKey, $this->authCreds
, ceil( $this->authTTL
/ 2 ) );
1738 $this->authSessionTimestamp
= time();
1739 } elseif ( $rcode === 401 ) {
1740 $this->onError( null, __METHOD__
, [], "Authentication failed.", $rcode );
1741 $this->authErrorTimestamp
= time();
1745 $this->onError( null, __METHOD__
, [], "HTTP return code: $rcode", $rcode );
1746 $this->authErrorTimestamp
= time();
1751 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1752 if ( substr( $this->authCreds
['storage_url'], -3 ) === '/v1' ) {
1753 $this->isRGW
= true; // take advantage of strong consistency in Ceph
1757 return $this->authCreds
;
1761 * @param array $creds From getAuthentication()
1762 * @param string $container
1763 * @param string $object
1766 protected function storageUrl( array $creds, $container = null, $object = null ) {
1767 $parts = [ $creds['storage_url'] ];
1768 if ( strlen( $container ) ) {
1769 $parts[] = rawurlencode( $container );
1771 if ( strlen( $object ) ) {
1772 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1775 return implode( '/', $parts );
1779 * @param array $creds From getAuthentication()
1782 protected function authTokenHeaders( array $creds ) {
1783 return [ 'x-auth-token' => $creds['auth_token'] ];
1787 * Get the cache key for a container
1789 * @param string $username
1792 private function getCredsCacheKey( $username ) {
1793 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl
);
1797 * Log an unexpected exception for this backend.
1798 * This also sets the StatusValue object to have a fatal error.
1800 * @param StatusValue|null $status
1801 * @param string $func
1802 * @param array $params
1803 * @param string $err Error string
1804 * @param int $code HTTP status
1805 * @param string $desc HTTP StatusValue description
1807 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1808 if ( $status instanceof StatusValue
) {
1809 $status->fatal( 'backend-fail-internal', $this->name
);
1811 if ( $code == 401 ) { // possibly a stale token
1812 $this->srvCache
->delete( $this->getCredsCacheKey( $this->swiftUser
) );
1814 $msg = "HTTP {code} ({desc}) in '{func}' (given '{params}')";
1819 'req_params' => FormatJson
::encode( $params ),
1823 $msgParams['err'] = $err;
1825 $this->logger
->error( $msg, $msgParams );
1830 * @see FileBackendStoreOpHandle
1832 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1833 /** @var array List of Requests for MultiHttpClient */
1839 * @param SwiftFileBackend $backend
1840 * @param Closure $callback Function that takes (HTTP request array, status)
1841 * @param array $httpOp MultiHttpClient op
1843 public function __construct( SwiftFileBackend
$backend, Closure
$callback, array $httpOp ) {
1844 $this->backend
= $backend;
1845 $this->callback
= $callback;
1846 $this->httpOp
= $httpOp;
1851 * SwiftFileBackend helper class to page through listings.
1852 * Swift also has a listing limit of 10,000 objects for sanity.
1853 * Do not use this class from places outside SwiftFileBackend.
1855 * @ingroup FileBackend
1857 abstract class SwiftFileBackendList
implements Iterator
{
1858 /** @var array List of path or (path,stat array) entries */
1859 protected $bufferIter = [];
1861 /** @var string List items *after* this path */
1862 protected $bufferAfter = null;
1868 protected $params = [];
1870 /** @var SwiftFileBackend */
1873 /** @var string Container name */
1874 protected $container;
1876 /** @var string Storage directory */
1880 protected $suffixStart;
1882 const PAGE_SIZE
= 9000; // file listing buffer size
1885 * @param SwiftFileBackend $backend
1886 * @param string $fullCont Resolved container name
1887 * @param string $dir Resolved directory relative to container
1888 * @param array $params
1890 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1891 $this->backend
= $backend;
1892 $this->container
= $fullCont;
1894 if ( substr( $this->dir
, -1 ) === '/' ) {
1895 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1897 if ( $this->dir
== '' ) { // whole container
1898 $this->suffixStart
= 0;
1899 } else { // dir within container
1900 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1902 $this->params
= $params;
1906 * @see Iterator::key()
1909 public function key() {
1914 * @see Iterator::next()
1916 public function next() {
1917 // Advance to the next file in the page
1918 next( $this->bufferIter
);
1920 // Check if there are no files left in this page and
1921 // advance to the next page if this page was not empty.
1922 if ( !$this->valid() && count( $this->bufferIter
) ) {
1923 $this->bufferIter
= $this->pageFromList(
1924 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1925 ); // updates $this->bufferAfter
1930 * @see Iterator::rewind()
1932 public function rewind() {
1934 $this->bufferAfter
= null;
1935 $this->bufferIter
= $this->pageFromList(
1936 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1937 ); // updates $this->bufferAfter
1941 * @see Iterator::valid()
1944 public function valid() {
1945 if ( $this->bufferIter
=== null ) {
1946 return false; // some failure?
1948 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1953 * Get the given list portion (page)
1955 * @param string $container Resolved container name
1956 * @param string $dir Resolved path relative to container
1957 * @param string &$after
1959 * @param array $params
1960 * @return Traversable|array
1962 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1966 * Iterator for listing directories
1968 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1970 * @see Iterator::current()
1971 * @return string|bool String (relative path) or false
1973 public function current() {
1974 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1977 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1978 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1983 * Iterator for listing regular files
1985 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1987 * @see Iterator::current()
1988 * @return string|bool String (relative path) or false
1990 public function current() {
1991 list( $path, $stat ) = current( $this->bufferIter
);
1992 $relPath = substr( $path, $this->suffixStart
);
1993 if ( is_array( $stat ) ) {
1994 $storageDir = rtrim( $this->params
['dir'], '/' );
1995 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
2001 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
2002 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );