Import: Handle uploads with sha1 starting with 0 properly
[mediawiki.git] / includes / filebackend / SwiftFileBackend.php
blob93d8d07a98bb8d3e51dfe35e22f8120388465f8e
1 <?php
2 /**
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
20 * @file
21 * @ingroup FileBackend
22 * @author Russ Nelson
23 * @author Aaron Schulz
26 /**
27 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
29 * Status messages should avoid mentioning the Swift account name.
30 * Likewise, error suppression should be used to avoid path disclosure.
32 * @ingroup FileBackend
33 * @since 1.19
35 class SwiftFileBackend extends FileBackendStore {
36 /** @var MultiHttpClient */
37 protected $http;
39 /** @var int TTL in seconds */
40 protected $authTTL;
42 /** @var string Authentication base URL (without version) */
43 protected $swiftAuthUrl;
45 /** @var string Swift user (account:user) to authenticate as */
46 protected $swiftUser;
48 /** @var string Secret key for user */
49 protected $swiftKey;
51 /** @var string Shared secret value for making temp URLs */
52 protected $swiftTempUrlKey;
54 /** @var string S3 access key (RADOS Gateway) */
55 protected $rgwS3AccessKey;
57 /** @var string S3 authentication key (RADOS Gateway) */
58 protected $rgwS3SecretKey;
60 /** @var BagOStuff */
61 protected $srvCache;
63 /** @var ProcessCacheLRU Container stat cache */
64 protected $containerStatCache;
66 /** @var array */
67 protected $authCreds;
69 /** @var int UNIX timestamp */
70 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;
78 /**
79 * @see FileBackendStore::__construct()
80 * Additional $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 * - shardViaHashLevels : Map of container names to sharding config with:
88 * - base : base of hash characters, 16 or 36
89 * - levels : the number of hash levels (and digits)
90 * - repeat : hash subdirectories are prefixed with all the
91 * parent hash directory names (e.g. "a/ab/abc")
92 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
93 * If those are not available, then the main cache will be used.
94 * This is probably insecure in shared hosting environments.
95 * - rgwS3AccessKey : Rados Gateway S3 "access key" value on the account.
96 * Do not set this until it has been set in the backend.
97 * This is used for generating expiring pre-authenticated URLs.
98 * Only use this when using rgw and to work around
99 * http://tracker.newdream.net/issues/3454.
100 * - rgwS3SecretKey : Rados Gateway S3 "secret key" value on the account.
101 * Do not set this until it has been set in the backend.
102 * This is used for generating expiring pre-authenticated URLs.
103 * Only use this when using rgw and to work around
104 * http://tracker.newdream.net/issues/3454.
106 public function __construct( array $config ) {
107 parent::__construct( $config );
108 // Required settings
109 $this->swiftAuthUrl = $config['swiftAuthUrl'];
110 $this->swiftUser = $config['swiftUser'];
111 $this->swiftKey = $config['swiftKey'];
112 // Optional settings
113 $this->authTTL = isset( $config['swiftAuthTTL'] )
114 ? $config['swiftAuthTTL']
115 : 15 * 60; // some sane number
116 $this->swiftTempUrlKey = isset( $config['swiftTempUrlKey'] )
117 ? $config['swiftTempUrlKey']
118 : '';
119 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
120 ? $config['shardViaHashLevels']
121 : '';
122 $this->rgwS3AccessKey = isset( $config['rgwS3AccessKey'] )
123 ? $config['rgwS3AccessKey']
124 : '';
125 $this->rgwS3SecretKey = isset( $config['rgwS3SecretKey'] )
126 ? $config['rgwS3SecretKey']
127 : '';
128 // HTTP helper client
129 $this->http = new MultiHttpClient( array() );
130 // Cache container information to mask latency
131 if ( isset( $config['wanCache'] ) && $config['wanCache'] instanceof WANObjectCache ) {
132 $this->memCache = $config['wanCache'];
134 // Process cache for container info
135 $this->containerStatCache = new ProcessCacheLRU( 300 );
136 // Cache auth token information to avoid RTTs
137 if ( !empty( $config['cacheAuthInfo'] ) ) {
138 if ( PHP_SAPI === 'cli' ) {
139 // Preferrably memcached
140 $this->srvCache = ObjectCache::getLocalClusterInstance();
141 } else {
142 // Look for APC, XCache, WinCache, ect...
143 $this->srvCache = ObjectCache::getLocalServerInstance( CACHE_NONE );
145 } else {
146 $this->srvCache = new EmptyBagOStuff();
150 public function getFeatures() {
151 return ( FileBackend::ATTR_UNICODE_PATHS |
152 FileBackend::ATTR_HEADERS | FileBackend::ATTR_METADATA );
155 protected function resolveContainerPath( $container, $relStoragePath ) {
156 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
157 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
158 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
159 return null; // too long for Swift
162 return $relStoragePath;
165 public function isPathUsableInternal( $storagePath ) {
166 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
167 if ( $rel === null ) {
168 return false; // invalid
171 return is_array( $this->getContainerStat( $container ) );
175 * Sanitize and filter the custom headers from a $params array.
176 * Only allows certain "standard" Content- and X-Content- headers.
178 * @param array $params
179 * @return array Sanitized value of 'headers' field in $params
181 protected function sanitizeHdrs( array $params ) {
182 return isset( $params['headers'] )
183 ? $this->getCustomHeaders( $params['headers'] )
184 : array();
189 * @param array $rawHeaders
190 * @return array Custom non-metadata HTTP headers
192 protected function getCustomHeaders( array $rawHeaders ) {
193 $headers = array();
195 // Normalize casing, and strip out illegal headers
196 foreach ( $rawHeaders as $name => $value ) {
197 $name = strtolower( $name );
198 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
199 continue; // blacklisted
200 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
201 $headers[$name] = $value; // allowed
202 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
203 $headers[$name] = $value; // allowed
206 // By default, Swift has annoyingly low maximum header value limits
207 if ( isset( $headers['content-disposition'] ) ) {
208 $disposition = '';
209 // @note: assume FileBackend::makeContentDisposition() already used
210 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
211 $part = trim( $part );
212 $new = ( $disposition === '' ) ? $part : "{$disposition};{$part}";
213 if ( strlen( $new ) <= 255 ) {
214 $disposition = $new;
215 } else {
216 break; // too long; sigh
219 $headers['content-disposition'] = $disposition;
222 return $headers;
226 * @param array $rawHeaders
227 * @return array Custom metadata headers
229 protected function getMetadataHeaders( array $rawHeaders ) {
230 $headers = array();
231 foreach ( $rawHeaders as $name => $value ) {
232 $name = strtolower( $name );
233 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
234 $headers[$name] = $value;
238 return $headers;
242 * @param array $rawHeaders
243 * @return array Custom metadata headers with prefix removed
245 protected function getMetadata( array $rawHeaders ) {
246 $metadata = array();
247 foreach ( $this->getMetadataHeaders( $rawHeaders ) as $name => $value ) {
248 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
251 return $metadata;
254 protected function doCreateInternal( array $params ) {
255 $status = Status::newGood();
257 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
258 if ( $dstRel === null ) {
259 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
261 return $status;
264 $sha1Hash = Wikimedia\base_convert( sha1( $params['content'] ), 16, 36, 31 );
265 $contentType = isset( $params['headers']['content-type'] )
266 ? $params['headers']['content-type']
267 : $this->getContentType( $params['dst'], $params['content'], null );
269 $reqs = array( array(
270 'method' => 'PUT',
271 'url' => array( $dstCont, $dstRel ),
272 'headers' => array(
273 'content-length' => strlen( $params['content'] ),
274 'etag' => md5( $params['content'] ),
275 'content-type' => $contentType,
276 'x-object-meta-sha1base36' => $sha1Hash
277 ) + $this->sanitizeHdrs( $params ),
278 'body' => $params['content']
279 ) );
281 $that = $this;
282 $method = __METHOD__;
283 $handler = function ( array $request, Status $status ) use ( $that, $method, $params ) {
284 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
285 if ( $rcode === 201 ) {
286 // good
287 } elseif ( $rcode === 412 ) {
288 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
289 } else {
290 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
294 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
295 if ( !empty( $params['async'] ) ) { // deferred
296 $status->value = $opHandle;
297 } else { // actually write the object in Swift
298 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
301 return $status;
304 protected function doStoreInternal( array $params ) {
305 $status = Status::newGood();
307 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
308 if ( $dstRel === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
311 return $status;
314 MediaWiki\suppressWarnings();
315 $sha1Hash = sha1_file( $params['src'] );
316 MediaWiki\restoreWarnings();
317 if ( $sha1Hash === false ) { // source doesn't exist?
318 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
320 return $status;
322 $sha1Hash = Wikimedia\base_convert( $sha1Hash, 16, 36, 31 );
323 $contentType = isset( $params['headers']['content-type'] )
324 ? $params['headers']['content-type']
325 : $this->getContentType( $params['dst'], null, $params['src'] );
327 $handle = fopen( $params['src'], 'rb' );
328 if ( $handle === false ) { // source doesn't exist?
329 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
331 return $status;
334 $reqs = array( array(
335 'method' => 'PUT',
336 'url' => array( $dstCont, $dstRel ),
337 'headers' => array(
338 'content-length' => filesize( $params['src'] ),
339 'etag' => md5_file( $params['src'] ),
340 'content-type' => $contentType,
341 'x-object-meta-sha1base36' => $sha1Hash
342 ) + $this->sanitizeHdrs( $params ),
343 'body' => $handle // resource
344 ) );
346 $that = $this;
347 $method = __METHOD__;
348 $handler = function ( array $request, Status $status ) use ( $that, $method, $params ) {
349 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
350 if ( $rcode === 201 ) {
351 // good
352 } elseif ( $rcode === 412 ) {
353 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
354 } else {
355 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
359 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
360 if ( !empty( $params['async'] ) ) { // deferred
361 $status->value = $opHandle;
362 } else { // actually write the object in Swift
363 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
366 return $status;
369 protected function doCopyInternal( array $params ) {
370 $status = Status::newGood();
372 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
373 if ( $srcRel === null ) {
374 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
376 return $status;
379 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
380 if ( $dstRel === null ) {
381 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
383 return $status;
386 $reqs = array( array(
387 'method' => 'PUT',
388 'url' => array( $dstCont, $dstRel ),
389 'headers' => array(
390 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
391 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
392 ) + $this->sanitizeHdrs( $params ), // extra headers merged into object
393 ) );
395 $that = $this;
396 $method = __METHOD__;
397 $handler = function ( array $request, Status $status ) use ( $that, $method, $params ) {
398 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
399 if ( $rcode === 201 ) {
400 // good
401 } elseif ( $rcode === 404 ) {
402 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
403 } else {
404 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
408 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
409 if ( !empty( $params['async'] ) ) { // deferred
410 $status->value = $opHandle;
411 } else { // actually write the object in Swift
412 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
415 return $status;
418 protected function doMoveInternal( array $params ) {
419 $status = Status::newGood();
421 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
422 if ( $srcRel === null ) {
423 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
425 return $status;
428 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
429 if ( $dstRel === null ) {
430 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
432 return $status;
435 $reqs = array(
436 array(
437 'method' => 'PUT',
438 'url' => array( $dstCont, $dstRel ),
439 'headers' => array(
440 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
441 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
442 ) + $this->sanitizeHdrs( $params ) // extra headers merged into object
445 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
446 $reqs[] = array(
447 'method' => 'DELETE',
448 'url' => array( $srcCont, $srcRel ),
449 'headers' => array()
453 $that = $this;
454 $method = __METHOD__;
455 $handler = function ( array $request, Status $status ) use ( $that, $method, $params ) {
456 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
457 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
458 // good
459 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
460 // good
461 } elseif ( $rcode === 404 ) {
462 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
463 } else {
464 $that->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->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
475 return $status;
478 protected function doDeleteInternal( array $params ) {
479 $status = Status::newGood();
481 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
482 if ( $srcRel === null ) {
483 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
485 return $status;
488 $reqs = array( array(
489 'method' => 'DELETE',
490 'url' => array( $srcCont, $srcRel ),
491 'headers' => array()
492 ) );
494 $that = $this;
495 $method = __METHOD__;
496 $handler = function ( array $request, Status $status ) use ( $that, $method, $params ) {
497 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
498 if ( $rcode === 204 ) {
499 // good
500 } elseif ( $rcode === 404 ) {
501 if ( empty( $params['ignoreMissingSource'] ) ) {
502 $status->fatal( 'backend-fail-delete', $params['src'] );
504 } else {
505 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
509 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
510 if ( !empty( $params['async'] ) ) { // deferred
511 $status->value = $opHandle;
512 } else { // actually delete the object in Swift
513 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
516 return $status;
519 protected function doDescribeInternal( array $params ) {
520 $status = Status::newGood();
522 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
523 if ( $srcRel === null ) {
524 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
526 return $status;
529 // Fetch the old object headers/metadata...this should be in stat cache by now
530 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
531 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
532 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
534 if ( !$stat ) {
535 $status->fatal( 'backend-fail-describe', $params['src'] );
537 return $status;
540 // POST clears prior headers, so we need to merge the changes in to the old ones
541 $metaHdrs = array();
542 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
543 $metaHdrs["x-object-meta-$name"] = $value;
545 $customHdrs = $this->sanitizeHdrs( $params ) + $stat['xattr']['headers'];
547 $reqs = array( array(
548 'method' => 'POST',
549 'url' => array( $srcCont, $srcRel ),
550 'headers' => $metaHdrs + $customHdrs
551 ) );
553 $that = $this;
554 $method = __METHOD__;
555 $handler = function ( array $request, Status $status ) use ( $that, $method, $params ) {
556 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
557 if ( $rcode === 202 ) {
558 // good
559 } elseif ( $rcode === 404 ) {
560 $status->fatal( 'backend-fail-describe', $params['src'] );
561 } else {
562 $that->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
566 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
567 if ( !empty( $params['async'] ) ) { // deferred
568 $status->value = $opHandle;
569 } else { // actually change the object in Swift
570 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
573 return $status;
576 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
577 $status = Status::newGood();
579 // (a) Check if container already exists
580 $stat = $this->getContainerStat( $fullCont );
581 if ( is_array( $stat ) ) {
582 return $status; // already there
583 } elseif ( $stat === null ) {
584 $status->fatal( 'backend-fail-internal', $this->name );
585 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
587 return $status;
590 // (b) Create container as needed with proper ACLs
591 if ( $stat === false ) {
592 $params['op'] = 'prepare';
593 $status->merge( $this->createContainer( $fullCont, $params ) );
596 return $status;
599 protected function doSecureInternal( $fullCont, $dir, array $params ) {
600 $status = Status::newGood();
601 if ( empty( $params['noAccess'] ) ) {
602 return $status; // nothing to do
605 $stat = $this->getContainerStat( $fullCont );
606 if ( is_array( $stat ) ) {
607 // Make container private to end-users...
608 $status->merge( $this->setContainerAccess(
609 $fullCont,
610 array( $this->swiftUser ), // read
611 array( $this->swiftUser ) // write
612 ) );
613 } elseif ( $stat === false ) {
614 $status->fatal( 'backend-fail-usable', $params['dir'] );
615 } else {
616 $status->fatal( 'backend-fail-internal', $this->name );
617 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
620 return $status;
623 protected function doPublishInternal( $fullCont, $dir, array $params ) {
624 $status = Status::newGood();
626 $stat = $this->getContainerStat( $fullCont );
627 if ( is_array( $stat ) ) {
628 // Make container public to end-users...
629 $status->merge( $this->setContainerAccess(
630 $fullCont,
631 array( $this->swiftUser, '.r:*' ), // read
632 array( $this->swiftUser ) // write
633 ) );
634 } elseif ( $stat === false ) {
635 $status->fatal( 'backend-fail-usable', $params['dir'] );
636 } else {
637 $status->fatal( 'backend-fail-internal', $this->name );
638 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
641 return $status;
644 protected function doCleanInternal( $fullCont, $dir, array $params ) {
645 $status = Status::newGood();
647 // Only containers themselves can be removed, all else is virtual
648 if ( $dir != '' ) {
649 return $status; // nothing to do
652 // (a) Check the container
653 $stat = $this->getContainerStat( $fullCont, true );
654 if ( $stat === false ) {
655 return $status; // ok, nothing to do
656 } elseif ( !is_array( $stat ) ) {
657 $status->fatal( 'backend-fail-internal', $this->name );
658 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
660 return $status;
663 // (b) Delete the container if empty
664 if ( $stat['count'] == 0 ) {
665 $params['op'] = 'clean';
666 $status->merge( $this->deleteContainer( $fullCont, $params ) );
669 return $status;
672 protected function doGetFileStat( array $params ) {
673 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) + $params;
674 unset( $params['src'] );
675 $stats = $this->doGetFileStatMulti( $params );
677 return reset( $stats );
681 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
682 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
683 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
685 * @param string $ts
686 * @param int $format Output format (TS_* constant)
687 * @return string
688 * @throws FileBackendError
690 protected function convertSwiftDate( $ts, $format = TS_MW ) {
691 try {
692 $timestamp = new MWTimestamp( $ts );
694 return $timestamp->getTimestamp( $format );
695 } catch ( Exception $e ) {
696 throw new FileBackendError( $e->getMessage() );
701 * Fill in any missing object metadata and save it to Swift
703 * @param array $objHdrs Object response headers
704 * @param string $path Storage path to object
705 * @return array New headers
707 protected function addMissingMetadata( array $objHdrs, $path ) {
708 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
709 return $objHdrs; // nothing to do
712 /** @noinspection PhpUnusedLocalVariableInspection */
713 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
714 wfDebugLog( 'SwiftBackend', __METHOD__ . ": $path was not stored with SHA-1 metadata." );
716 $objHdrs['x-object-meta-sha1base36'] = false;
718 $auth = $this->getAuthentication();
719 if ( !$auth ) {
720 return $objHdrs; // failed
723 // Find prior custom HTTP headers
724 $postHeaders = $this->getCustomHeaders( $objHdrs );
725 // Find prior metadata headers
726 $postHeaders += $this->getMetadataHeaders( $objHdrs );
728 $status = Status::newGood();
729 /** @noinspection PhpUnusedLocalVariableInspection */
730 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
731 if ( $status->isOK() ) {
732 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
733 if ( $tmpFile ) {
734 $hash = $tmpFile->getSha1Base36();
735 if ( $hash !== false ) {
736 $objHdrs['x-object-meta-sha1base36'] = $hash;
737 // Merge new SHA1 header into the old ones
738 $postHeaders['x-object-meta-sha1base36'] = $hash;
739 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
740 list( $rcode ) = $this->http->run( array(
741 'method' => 'POST',
742 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
743 'headers' => $this->authTokenHeaders( $auth ) + $postHeaders
744 ) );
745 if ( $rcode >= 200 && $rcode <= 299 ) {
746 $this->deleteFileCache( $path );
748 return $objHdrs; // success
754 wfDebugLog( 'SwiftBackend', __METHOD__ . ": unable to set SHA-1 metadata for $path" );
756 return $objHdrs; // failed
759 protected function doGetFileContentsMulti( array $params ) {
760 $contents = array();
762 $auth = $this->getAuthentication();
764 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
765 // Blindly create tmp files and stream to them, catching any exception if the file does
766 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
767 $reqs = array(); // (path => op)
769 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
770 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
771 if ( $srcRel === null || !$auth ) {
772 $contents[$path] = false;
773 continue;
775 // Create a new temporary memory file...
776 $handle = fopen( 'php://temp', 'wb' );
777 if ( $handle ) {
778 $reqs[$path] = array(
779 'method' => 'GET',
780 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
781 'headers' => $this->authTokenHeaders( $auth )
782 + $this->headersFromParams( $params ),
783 'stream' => $handle,
786 $contents[$path] = false;
789 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
790 $reqs = $this->http->runMulti( $reqs, $opts );
791 foreach ( $reqs as $path => $op ) {
792 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
793 if ( $rcode >= 200 && $rcode <= 299 ) {
794 rewind( $op['stream'] ); // start from the beginning
795 $contents[$path] = stream_get_contents( $op['stream'] );
796 } elseif ( $rcode === 404 ) {
797 $contents[$path] = false;
798 } else {
799 $this->onError( null, __METHOD__,
800 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
802 fclose( $op['stream'] ); // close open handle
805 return $contents;
808 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
809 $prefix = ( $dir == '' ) ? null : "{$dir}/";
810 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
811 if ( $status->isOk() ) {
812 return ( count( $status->value ) ) > 0;
815 return null; // error
819 * @see FileBackendStore::getDirectoryListInternal()
820 * @param string $fullCont
821 * @param string $dir
822 * @param array $params
823 * @return SwiftFileBackendDirList
825 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
826 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
830 * @see FileBackendStore::getFileListInternal()
831 * @param string $fullCont
832 * @param string $dir
833 * @param array $params
834 * @return SwiftFileBackendFileList
836 public function getFileListInternal( $fullCont, $dir, array $params ) {
837 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
841 * Do not call this function outside of SwiftFileBackendFileList
843 * @param string $fullCont Resolved container name
844 * @param string $dir Resolved storage directory with no trailing slash
845 * @param string|null $after Resolved container relative path to list items after
846 * @param int $limit Max number of items to list
847 * @param array $params Parameters for getDirectoryList()
848 * @return array List of container relative resolved paths of directories directly under $dir
849 * @throws FileBackendError
851 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
852 $dirs = array();
853 if ( $after === INF ) {
854 return $dirs; // nothing more
857 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
859 $prefix = ( $dir == '' ) ? null : "{$dir}/";
860 // Non-recursive: only list dirs right under $dir
861 if ( !empty( $params['topOnly'] ) ) {
862 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
863 if ( !$status->isOk() ) {
864 throw new FileBackendError( "Iterator page I/O error: {$status->getMessage()}" );
866 $objects = $status->value;
867 foreach ( $objects as $object ) { // files and directories
868 if ( substr( $object, -1 ) === '/' ) {
869 $dirs[] = $object; // directories end in '/'
872 } else {
873 // Recursive: list all dirs under $dir and its subdirs
874 $getParentDir = function ( $path ) {
875 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
878 // Get directory from last item of prior page
879 $lastDir = $getParentDir( $after ); // must be first page
880 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
882 if ( !$status->isOk() ) {
883 throw new FileBackendError( "Iterator page I/O error: {$status->getMessage()}" );
886 $objects = $status->value;
888 foreach ( $objects as $object ) { // files
889 $objectDir = $getParentDir( $object ); // directory of object
891 if ( $objectDir !== false && $objectDir !== $dir ) {
892 // Swift stores paths in UTF-8, using binary sorting.
893 // See function "create_container_table" in common/db.py.
894 // If a directory is not "greater" than the last one,
895 // then it was already listed by the calling iterator.
896 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
897 $pDir = $objectDir;
898 do { // add dir and all its parent dirs
899 $dirs[] = "{$pDir}/";
900 $pDir = $getParentDir( $pDir );
901 } while ( $pDir !== false // sanity
902 && strcmp( $pDir, $lastDir ) > 0 // not done already
903 && strlen( $pDir ) > strlen( $dir ) // within $dir
906 $lastDir = $objectDir;
910 // Page on the unfiltered directory listing (what is returned may be filtered)
911 if ( count( $objects ) < $limit ) {
912 $after = INF; // avoid a second RTT
913 } else {
914 $after = end( $objects ); // update last item
917 return $dirs;
921 * Do not call this function outside of SwiftFileBackendFileList
923 * @param string $fullCont Resolved container name
924 * @param string $dir Resolved storage directory with no trailing slash
925 * @param string|null $after Resolved container relative path of file to list items after
926 * @param int $limit Max number of items to list
927 * @param array $params Parameters for getDirectoryList()
928 * @return array List of resolved container relative paths of files under $dir
929 * @throws FileBackendError
931 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
932 $files = array(); // list of (path, stat array or null) entries
933 if ( $after === INF ) {
934 return $files; // nothing more
937 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
939 $prefix = ( $dir == '' ) ? null : "{$dir}/";
940 // $objects will contain a list of unfiltered names or CF_Object items
941 // Non-recursive: only list files right under $dir
942 if ( !empty( $params['topOnly'] ) ) {
943 if ( !empty( $params['adviseStat'] ) ) {
944 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
945 } else {
946 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
948 } else {
949 // Recursive: list all files under $dir and its subdirs
950 if ( !empty( $params['adviseStat'] ) ) {
951 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
952 } else {
953 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
957 // Reformat this list into a list of (name, stat array or null) entries
958 if ( !$status->isOk() ) {
959 throw new FileBackendError( "Iterator page I/O error: {$status->getMessage()}" );
962 $objects = $status->value;
963 $files = $this->buildFileObjectListing( $params, $dir, $objects );
965 // Page on the unfiltered object listing (what is returned may be filtered)
966 if ( count( $objects ) < $limit ) {
967 $after = INF; // avoid a second RTT
968 } else {
969 $after = end( $objects ); // update last item
970 $after = is_object( $after ) ? $after->name : $after;
973 return $files;
977 * Build a list of file objects, filtering out any directories
978 * and extracting any stat info if provided in $objects (for CF_Objects)
980 * @param array $params Parameters for getDirectoryList()
981 * @param string $dir Resolved container directory path
982 * @param array $objects List of CF_Object items or object names
983 * @return array List of (names,stat array or null) entries
985 private function buildFileObjectListing( array $params, $dir, array $objects ) {
986 $names = array();
987 foreach ( $objects as $object ) {
988 if ( is_object( $object ) ) {
989 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
990 continue; // virtual directory entry; ignore
992 $stat = array(
993 // Convert various random Swift dates to TS_MW
994 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
995 'size' => (int)$object->bytes,
996 'sha1' => null,
997 // Note: manifiest ETags are not an MD5 of the file
998 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
999 'latest' => false // eventually consistent
1001 $names[] = array( $object->name, $stat );
1002 } elseif ( substr( $object, -1 ) !== '/' ) {
1003 // Omit directories, which end in '/' in listings
1004 $names[] = array( $object, null );
1008 return $names;
1012 * Do not call this function outside of SwiftFileBackendFileList
1014 * @param string $path Storage path
1015 * @param array $val Stat value
1017 public function loadListingStatInternal( $path, array $val ) {
1018 $this->cheapCache->set( $path, 'stat', $val );
1021 protected function doGetFileXAttributes( array $params ) {
1022 $stat = $this->getFileStat( $params );
1023 if ( $stat ) {
1024 if ( !isset( $stat['xattr'] ) ) {
1025 // Stat entries filled by file listings don't include metadata/headers
1026 $this->clearCache( array( $params['src'] ) );
1027 $stat = $this->getFileStat( $params );
1030 return $stat['xattr'];
1031 } else {
1032 return false;
1036 protected function doGetFileSha1base36( array $params ) {
1037 $stat = $this->getFileStat( $params );
1038 if ( $stat ) {
1039 if ( !isset( $stat['sha1'] ) ) {
1040 // Stat entries filled by file listings don't include SHA1
1041 $this->clearCache( array( $params['src'] ) );
1042 $stat = $this->getFileStat( $params );
1045 return $stat['sha1'];
1046 } else {
1047 return false;
1051 protected function doStreamFile( array $params ) {
1052 $status = Status::newGood();
1054 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1055 if ( $srcRel === null ) {
1056 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1059 $auth = $this->getAuthentication();
1060 if ( !$auth || !is_array( $this->getContainerStat( $srcCont ) ) ) {
1061 $status->fatal( 'backend-fail-stream', $params['src'] );
1063 return $status;
1066 $handle = fopen( 'php://output', 'wb' );
1068 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1069 'method' => 'GET',
1070 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1071 'headers' => $this->authTokenHeaders( $auth )
1072 + $this->headersFromParams( $params ),
1073 'stream' => $handle,
1074 ) );
1076 if ( $rcode >= 200 && $rcode <= 299 ) {
1077 // good
1078 } elseif ( $rcode === 404 ) {
1079 $status->fatal( 'backend-fail-stream', $params['src'] );
1080 } else {
1081 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1084 return $status;
1087 protected function doGetLocalCopyMulti( array $params ) {
1088 $tmpFiles = array();
1090 $auth = $this->getAuthentication();
1092 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1093 // Blindly create tmp files and stream to them, catching any exception if the file does
1094 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1095 $reqs = array(); // (path => op)
1097 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1098 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1099 if ( $srcRel === null || !$auth ) {
1100 $tmpFiles[$path] = null;
1101 continue;
1103 // Get source file extension
1104 $ext = FileBackend::extensionFromPath( $path );
1105 // Create a new temporary file...
1106 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1107 if ( $tmpFile ) {
1108 $handle = fopen( $tmpFile->getPath(), 'wb' );
1109 if ( $handle ) {
1110 $reqs[$path] = array(
1111 'method' => 'GET',
1112 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1113 'headers' => $this->authTokenHeaders( $auth )
1114 + $this->headersFromParams( $params ),
1115 'stream' => $handle,
1117 } else {
1118 $tmpFile = null;
1121 $tmpFiles[$path] = $tmpFile;
1124 $isLatest = ( $this->isRGW || !empty( $params['latest'] ) );
1125 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1126 $reqs = $this->http->runMulti( $reqs, $opts );
1127 foreach ( $reqs as $path => $op ) {
1128 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1129 fclose( $op['stream'] ); // close open handle
1130 if ( $rcode >= 200 && $rcode <= 299 ) {
1131 $size = $tmpFiles[$path] ? $tmpFiles[$path]->getSize() : 0;
1132 // Double check that the disk is not full/broken
1133 if ( $size != $rhdrs['content-length'] ) {
1134 $tmpFiles[$path] = null;
1135 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1136 $this->onError( null, __METHOD__,
1137 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1139 // Set the file stat process cache in passing
1140 $stat = $this->getStatFromHeaders( $rhdrs );
1141 $stat['latest'] = $isLatest;
1142 $this->cheapCache->set( $path, 'stat', $stat );
1143 } elseif ( $rcode === 404 ) {
1144 $tmpFiles[$path] = false;
1145 } else {
1146 $tmpFiles[$path] = null;
1147 $this->onError( null, __METHOD__,
1148 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1152 return $tmpFiles;
1155 public function getFileHttpUrl( array $params ) {
1156 if ( $this->swiftTempUrlKey != '' ||
1157 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1159 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1160 if ( $srcRel === null ) {
1161 return null; // invalid path
1164 $auth = $this->getAuthentication();
1165 if ( !$auth ) {
1166 return null;
1169 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1170 $expires = time() + $ttl;
1172 if ( $this->swiftTempUrlKey != '' ) {
1173 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1174 // Swift wants the signature based on the unencoded object name
1175 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1176 $signature = hash_hmac( 'sha1',
1177 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1178 $this->swiftTempUrlKey
1181 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1182 } else { // give S3 API URL for rgw
1183 // Path for signature starts with the bucket
1184 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1185 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1186 // Calculate the hash
1187 $signature = base64_encode( hash_hmac(
1188 'sha1',
1189 "GET\n\n\n{$expires}\n{$spath}",
1190 $this->rgwS3SecretKey,
1191 true // raw
1192 ) );
1193 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1194 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1195 return wfAppendQuery(
1196 str_replace( '/swift/v1', '', // S3 API is the rgw default
1197 $this->storageUrl( $auth ) . $spath ),
1198 array(
1199 'Signature' => $signature,
1200 'Expires' => $expires,
1201 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1206 return null;
1209 protected function directoriesAreVirtual() {
1210 return true;
1214 * Get headers to send to Swift when reading a file based
1215 * on a FileBackend params array, e.g. that of getLocalCopy().
1216 * $params is currently only checked for a 'latest' flag.
1218 * @param array $params
1219 * @return array
1221 protected function headersFromParams( array $params ) {
1222 $hdrs = array();
1223 if ( !empty( $params['latest'] ) ) {
1224 $hdrs['x-newest'] = 'true';
1227 return $hdrs;
1231 * @param FileBackendStoreOpHandle[] $fileOpHandles
1233 * @return Status[]
1235 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1236 $statuses = array();
1238 $auth = $this->getAuthentication();
1239 if ( !$auth ) {
1240 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1241 $statuses[$index] = Status::newFatal( 'backend-fail-connect', $this->name );
1244 return $statuses;
1247 // Split the HTTP requests into stages that can be done concurrently
1248 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1249 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1250 $reqs = $fileOpHandle->httpOp;
1251 // Convert the 'url' parameter to an actual URL using $auth
1252 foreach ( $reqs as $stage => &$req ) {
1253 list( $container, $relPath ) = $req['url'];
1254 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1255 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : array();
1256 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1257 $httpReqsByStage[$stage][$index] = $req;
1259 $statuses[$index] = Status::newGood();
1262 // Run all requests for the first stage, then the next, and so on
1263 $reqCount = count( $httpReqsByStage );
1264 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1265 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1266 foreach ( $httpReqs as $index => $httpReq ) {
1267 // Run the callback for each request of this operation
1268 $callback = $fileOpHandles[$index]->callback;
1269 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1270 // On failure, abort all remaining requests for this operation
1271 // (e.g. abort the DELETE request if the COPY request fails for a move)
1272 if ( !$statuses[$index]->isOK() ) {
1273 $stages = count( $fileOpHandles[$index]->httpOp );
1274 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1275 unset( $httpReqsByStage[$s][$index] );
1281 return $statuses;
1285 * Set read/write permissions for a Swift container.
1287 * @see http://swift.openstack.org/misc.html#acls
1289 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1290 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1292 * @param string $container Resolved Swift container
1293 * @param array $readGrps List of the possible criteria for a request to have
1294 * access to read a container. Each item is one of the following formats:
1295 * - account:user : Grants access if the request is by the given user
1296 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1297 * matches the expression and the request is not for a listing.
1298 * Setting this to '*' effectively makes a container public.
1299 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1300 * matches the expression and the request is for a listing.
1301 * @param array $writeGrps A list of the possible criteria for a request to have
1302 * access to write to a container. Each item is of the following format:
1303 * - account:user : Grants access if the request is by the given user
1304 * @return Status
1306 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1307 $status = Status::newGood();
1308 $auth = $this->getAuthentication();
1310 if ( !$auth ) {
1311 $status->fatal( 'backend-fail-connect', $this->name );
1313 return $status;
1316 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1317 'method' => 'POST',
1318 'url' => $this->storageUrl( $auth, $container ),
1319 'headers' => $this->authTokenHeaders( $auth ) + array(
1320 'x-container-read' => implode( ',', $readGrps ),
1321 'x-container-write' => implode( ',', $writeGrps )
1323 ) );
1325 if ( $rcode != 204 && $rcode !== 202 ) {
1326 $status->fatal( 'backend-fail-internal', $this->name );
1327 wfDebugLog( 'SwiftBackend', __METHOD__ . ': unexpected rcode value (' . $rcode . ')' );
1330 return $status;
1334 * Get a Swift container stat array, possibly from process cache.
1335 * Use $reCache if the file count or byte count is needed.
1337 * @param string $container Container name
1338 * @param bool $bypassCache Bypass all caches and load from Swift
1339 * @return array|bool|null False on 404, null on failure
1341 protected function getContainerStat( $container, $bypassCache = false ) {
1342 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1344 if ( $bypassCache ) { // purge cache
1345 $this->containerStatCache->clear( $container );
1346 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1347 $this->primeContainerCache( array( $container ) ); // check persistent cache
1349 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1350 $auth = $this->getAuthentication();
1351 if ( !$auth ) {
1352 return null;
1355 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1356 'method' => 'HEAD',
1357 'url' => $this->storageUrl( $auth, $container ),
1358 'headers' => $this->authTokenHeaders( $auth )
1359 ) );
1361 if ( $rcode === 204 ) {
1362 $stat = array(
1363 'count' => $rhdrs['x-container-object-count'],
1364 'bytes' => $rhdrs['x-container-bytes-used']
1366 if ( $bypassCache ) {
1367 return $stat;
1368 } else {
1369 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1370 $this->setContainerCache( $container, $stat ); // update persistent cache
1372 } elseif ( $rcode === 404 ) {
1373 return false;
1374 } else {
1375 $this->onError( null, __METHOD__,
1376 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1378 return null;
1382 return $this->containerStatCache->get( $container, 'stat' );
1386 * Create a Swift container
1388 * @param string $container Container name
1389 * @param array $params
1390 * @return Status
1392 protected function createContainer( $container, array $params ) {
1393 $status = Status::newGood();
1395 $auth = $this->getAuthentication();
1396 if ( !$auth ) {
1397 $status->fatal( 'backend-fail-connect', $this->name );
1399 return $status;
1402 // @see SwiftFileBackend::setContainerAccess()
1403 if ( empty( $params['noAccess'] ) ) {
1404 $readGrps = array( '.r:*', $this->swiftUser ); // public
1405 } else {
1406 $readGrps = array( $this->swiftUser ); // private
1408 $writeGrps = array( $this->swiftUser ); // sanity
1410 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1411 'method' => 'PUT',
1412 'url' => $this->storageUrl( $auth, $container ),
1413 'headers' => $this->authTokenHeaders( $auth ) + array(
1414 'x-container-read' => implode( ',', $readGrps ),
1415 'x-container-write' => implode( ',', $writeGrps )
1417 ) );
1419 if ( $rcode === 201 ) { // new
1420 // good
1421 } elseif ( $rcode === 202 ) { // already there
1422 // this shouldn't really happen, but is OK
1423 } else {
1424 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1427 return $status;
1431 * Delete a Swift container
1433 * @param string $container Container name
1434 * @param array $params
1435 * @return Status
1437 protected function deleteContainer( $container, array $params ) {
1438 $status = Status::newGood();
1440 $auth = $this->getAuthentication();
1441 if ( !$auth ) {
1442 $status->fatal( 'backend-fail-connect', $this->name );
1444 return $status;
1447 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1448 'method' => 'DELETE',
1449 'url' => $this->storageUrl( $auth, $container ),
1450 'headers' => $this->authTokenHeaders( $auth )
1451 ) );
1453 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1454 $this->containerStatCache->clear( $container ); // purge
1455 } elseif ( $rcode === 404 ) { // not there
1456 // this shouldn't really happen, but is OK
1457 } elseif ( $rcode === 409 ) { // not empty
1458 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1459 } else {
1460 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1463 return $status;
1467 * Get a list of objects under a container.
1468 * Either just the names or a list of stdClass objects with details can be returned.
1470 * @param string $fullCont
1471 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1472 * @param int $limit
1473 * @param string|null $after
1474 * @param string|null $prefix
1475 * @param string|null $delim
1476 * @return Status With the list as value
1478 private function objectListing(
1479 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1481 $status = Status::newGood();
1483 $auth = $this->getAuthentication();
1484 if ( !$auth ) {
1485 $status->fatal( 'backend-fail-connect', $this->name );
1487 return $status;
1490 $query = array( 'limit' => $limit );
1491 if ( $type === 'info' ) {
1492 $query['format'] = 'json';
1494 if ( $after !== null ) {
1495 $query['marker'] = $after;
1497 if ( $prefix !== null ) {
1498 $query['prefix'] = $prefix;
1500 if ( $delim !== null ) {
1501 $query['delimiter'] = $delim;
1504 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1505 'method' => 'GET',
1506 'url' => $this->storageUrl( $auth, $fullCont ),
1507 'query' => $query,
1508 'headers' => $this->authTokenHeaders( $auth )
1509 ) );
1511 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1512 if ( $rcode === 200 ) { // good
1513 if ( $type === 'info' ) {
1514 $status->value = FormatJson::decode( trim( $rbody ) );
1515 } else {
1516 $status->value = explode( "\n", trim( $rbody ) );
1518 } elseif ( $rcode === 204 ) {
1519 $status->value = array(); // empty container
1520 } elseif ( $rcode === 404 ) {
1521 $status->value = array(); // no container
1522 } else {
1523 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1526 return $status;
1529 protected function doPrimeContainerCache( array $containerInfo ) {
1530 foreach ( $containerInfo as $container => $info ) {
1531 $this->containerStatCache->set( $container, 'stat', $info );
1535 protected function doGetFileStatMulti( array $params ) {
1536 $stats = array();
1538 $auth = $this->getAuthentication();
1540 $reqs = array();
1541 foreach ( $params['srcs'] as $path ) {
1542 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1543 if ( $srcRel === null ) {
1544 $stats[$path] = false;
1545 continue; // invalid storage path
1546 } elseif ( !$auth ) {
1547 $stats[$path] = null;
1548 continue;
1551 // (a) Check the container
1552 $cstat = $this->getContainerStat( $srcCont );
1553 if ( $cstat === false ) {
1554 $stats[$path] = false;
1555 continue; // ok, nothing to do
1556 } elseif ( !is_array( $cstat ) ) {
1557 $stats[$path] = null;
1558 continue;
1561 $reqs[$path] = array(
1562 'method' => 'HEAD',
1563 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1564 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1568 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1569 $reqs = $this->http->runMulti( $reqs, $opts );
1571 foreach ( $params['srcs'] as $path ) {
1572 if ( array_key_exists( $path, $stats ) ) {
1573 continue; // some sort of failure above
1575 // (b) Check the file
1576 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1577 if ( $rcode === 200 || $rcode === 204 ) {
1578 // Update the object if it is missing some headers
1579 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1580 // Load the stat array from the headers
1581 $stat = $this->getStatFromHeaders( $rhdrs );
1582 if ( $this->isRGW ) {
1583 $stat['latest'] = true; // strong consistency
1585 } elseif ( $rcode === 404 ) {
1586 $stat = false;
1587 } else {
1588 $stat = null;
1589 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1591 $stats[$path] = $stat;
1594 return $stats;
1598 * @param array $rhdrs
1599 * @return array
1601 protected function getStatFromHeaders( array $rhdrs ) {
1602 // Fetch all of the custom metadata headers
1603 $metadata = $this->getMetadata( $rhdrs );
1604 // Fetch all of the custom raw HTTP headers
1605 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1607 return array(
1608 // Convert various random Swift dates to TS_MW
1609 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1610 // Empty objects actually return no content-length header in Ceph
1611 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1612 'sha1' => isset( $metadata['sha1base36'] ) ? $metadata['sha1base36'] : null,
1613 // Note: manifiest ETags are not an MD5 of the file
1614 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1615 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1620 * @return array|null Credential map
1622 protected function getAuthentication() {
1623 if ( $this->authErrorTimestamp !== null ) {
1624 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1625 return null; // failed last attempt; don't bother
1626 } else { // actually retry this time
1627 $this->authErrorTimestamp = null;
1630 // Session keys expire after a while, so we renew them periodically
1631 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1632 // Authenticate with proxy and get a session key...
1633 if ( !$this->authCreds || $reAuth ) {
1634 $this->authSessionTimestamp = 0;
1635 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1636 $creds = $this->srvCache->get( $cacheKey ); // credentials
1637 // Try to use the credential cache
1638 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1639 $this->authCreds = $creds;
1640 // Skew the timestamp for worst case to avoid using stale credentials
1641 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1642 } else { // cache miss
1643 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1644 'method' => 'GET',
1645 'url' => "{$this->swiftAuthUrl}/v1.0",
1646 'headers' => array(
1647 'x-auth-user' => $this->swiftUser,
1648 'x-auth-key' => $this->swiftKey
1650 ) );
1652 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1653 $this->authCreds = array(
1654 'auth_token' => $rhdrs['x-auth-token'],
1655 'storage_url' => $rhdrs['x-storage-url']
1657 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1658 $this->authSessionTimestamp = time();
1659 } elseif ( $rcode === 401 ) {
1660 $this->onError( null, __METHOD__, array(), "Authentication failed.", $rcode );
1661 $this->authErrorTimestamp = time();
1663 return null;
1664 } else {
1665 $this->onError( null, __METHOD__, array(), "HTTP return code: $rcode", $rcode );
1666 $this->authErrorTimestamp = time();
1668 return null;
1671 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1672 if ( substr( $this->authCreds['storage_url'], -3 ) === '/v1' ) {
1673 $this->isRGW = true; // take advantage of strong consistency in Ceph
1677 return $this->authCreds;
1681 * @param array $creds From getAuthentication()
1682 * @param string $container
1683 * @param string $object
1684 * @return array
1686 protected function storageUrl( array $creds, $container = null, $object = null ) {
1687 $parts = array( $creds['storage_url'] );
1688 if ( strlen( $container ) ) {
1689 $parts[] = rawurlencode( $container );
1691 if ( strlen( $object ) ) {
1692 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1695 return implode( '/', $parts );
1699 * @param array $creds From getAuthentication()
1700 * @return array
1702 protected function authTokenHeaders( array $creds ) {
1703 return array( 'x-auth-token' => $creds['auth_token'] );
1707 * Get the cache key for a container
1709 * @param string $username
1710 * @return string
1712 private function getCredsCacheKey( $username ) {
1713 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1717 * Log an unexpected exception for this backend.
1718 * This also sets the Status object to have a fatal error.
1720 * @param Status|null $status
1721 * @param string $func
1722 * @param array $params
1723 * @param string $err Error string
1724 * @param int $code HTTP status
1725 * @param string $desc HTTP status description
1727 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1728 if ( $status instanceof Status ) {
1729 $status->fatal( 'backend-fail-internal', $this->name );
1731 if ( $code == 401 ) { // possibly a stale token
1732 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1734 wfDebugLog( 'SwiftBackend',
1735 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1736 ( $err ? ": $err" : "" )
1742 * @see FileBackendStoreOpHandle
1744 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1745 /** @var array List of Requests for MultiHttpClient */
1746 public $httpOp;
1747 /** @var Closure */
1748 public $callback;
1751 * @param SwiftFileBackend $backend
1752 * @param Closure $callback Function that takes (HTTP request array, status)
1753 * @param array $httpOp MultiHttpClient op
1755 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1756 $this->backend = $backend;
1757 $this->callback = $callback;
1758 $this->httpOp = $httpOp;
1763 * SwiftFileBackend helper class to page through listings.
1764 * Swift also has a listing limit of 10,000 objects for sanity.
1765 * Do not use this class from places outside SwiftFileBackend.
1767 * @ingroup FileBackend
1769 abstract class SwiftFileBackendList implements Iterator {
1770 /** @var array List of path or (path,stat array) entries */
1771 protected $bufferIter = array();
1773 /** @var string List items *after* this path */
1774 protected $bufferAfter = null;
1776 /** @var int */
1777 protected $pos = 0;
1779 /** @var array */
1780 protected $params = array();
1782 /** @var SwiftFileBackend */
1783 protected $backend;
1785 /** @var string Container name */
1786 protected $container;
1788 /** @var string Storage directory */
1789 protected $dir;
1791 /** @var int */
1792 protected $suffixStart;
1794 const PAGE_SIZE = 9000; // file listing buffer size
1797 * @param SwiftFileBackend $backend
1798 * @param string $fullCont Resolved container name
1799 * @param string $dir Resolved directory relative to container
1800 * @param array $params
1802 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1803 $this->backend = $backend;
1804 $this->container = $fullCont;
1805 $this->dir = $dir;
1806 if ( substr( $this->dir, -1 ) === '/' ) {
1807 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1809 if ( $this->dir == '' ) { // whole container
1810 $this->suffixStart = 0;
1811 } else { // dir within container
1812 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1814 $this->params = $params;
1818 * @see Iterator::key()
1819 * @return int
1821 public function key() {
1822 return $this->pos;
1826 * @see Iterator::next()
1828 public function next() {
1829 // Advance to the next file in the page
1830 next( $this->bufferIter );
1831 ++$this->pos;
1832 // Check if there are no files left in this page and
1833 // advance to the next page if this page was not empty.
1834 if ( !$this->valid() && count( $this->bufferIter ) ) {
1835 $this->bufferIter = $this->pageFromList(
1836 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1837 ); // updates $this->bufferAfter
1842 * @see Iterator::rewind()
1844 public function rewind() {
1845 $this->pos = 0;
1846 $this->bufferAfter = null;
1847 $this->bufferIter = $this->pageFromList(
1848 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1849 ); // updates $this->bufferAfter
1853 * @see Iterator::valid()
1854 * @return bool
1856 public function valid() {
1857 if ( $this->bufferIter === null ) {
1858 return false; // some failure?
1859 } else {
1860 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1865 * Get the given list portion (page)
1867 * @param string $container Resolved container name
1868 * @param string $dir Resolved path relative to container
1869 * @param string $after
1870 * @param int $limit
1871 * @param array $params
1872 * @return Traversable|array
1874 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1878 * Iterator for listing directories
1880 class SwiftFileBackendDirList extends SwiftFileBackendList {
1882 * @see Iterator::current()
1883 * @return string|bool String (relative path) or false
1885 public function current() {
1886 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1889 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1890 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1895 * Iterator for listing regular files
1897 class SwiftFileBackendFileList extends SwiftFileBackendList {
1899 * @see Iterator::current()
1900 * @return string|bool String (relative path) or false
1902 public function current() {
1903 list( $path, $stat ) = current( $this->bufferIter );
1904 $relPath = substr( $path, $this->suffixStart );
1905 if ( is_array( $stat ) ) {
1906 $storageDir = rtrim( $this->params['dir'], '/' );
1907 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1910 return $relPath;
1913 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1914 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );