MWException: Don't send headers multiple times
[mediawiki.git] / includes / filebackend / SwiftFileBackend.php
blob2f4be9ed4a74bca93dd2388299885410ea695143
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 : 5 * 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 $this->memCache = wfGetMainCache();
132 // Process cache for container info
133 $this->containerStatCache = new ProcessCacheLRU( 300 );
134 // Cache auth token information to avoid RTTs
135 if ( !empty( $config['cacheAuthInfo'] ) ) {
136 if ( PHP_SAPI === 'cli' ) {
137 $this->srvCache = wfGetMainCache(); // preferrably memcached
138 } else {
139 try { // look for APC, XCache, WinCache, ect...
140 $this->srvCache = ObjectCache::newAccelerator( array() );
141 } catch ( Exception $e ) {
145 $this->srvCache = $this->srvCache ?: new EmptyBagOStuff();
148 public function getFeatures() {
149 return ( FileBackend::ATTR_HEADERS | FileBackend::ATTR_METADATA );
152 protected function resolveContainerPath( $container, $relStoragePath ) {
153 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
154 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
155 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
156 return null; // too long for Swift
159 return $relStoragePath;
162 public function isPathUsableInternal( $storagePath ) {
163 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
164 if ( $rel === null ) {
165 return false; // invalid
168 return is_array( $this->getContainerStat( $container ) );
172 * Sanitize and filter the custom headers from a $params array.
173 * We only allow certain Content- and X-Content- headers.
175 * @param array $headers
176 * @return array Sanitized value of 'headers' field in $params
178 protected function sanitizeHdrs( array $params ) {
179 $headers = array();
181 // Normalize casing, and strip out illegal headers
182 if ( isset( $params['headers'] ) ) {
183 foreach ( $params['headers'] as $name => $value ) {
184 $name = strtolower( $name );
185 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
186 continue; // blacklisted
187 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
188 $headers[$name] = $value; // allowed
189 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
190 $headers[$name] = $value; // allowed
194 // By default, Swift has annoyingly low maximum header value limits
195 if ( isset( $headers['content-disposition'] ) ) {
196 $disposition = '';
197 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
198 $part = trim( $part );
199 $new = ( $disposition === '' ) ? $part : "{$disposition};{$part}";
200 if ( strlen( $new ) <= 255 ) {
201 $disposition = $new;
202 } else {
203 break; // too long; sigh
206 $headers['content-disposition'] = $disposition;
209 return $headers;
212 protected function doCreateInternal( array $params ) {
213 $status = Status::newGood();
215 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
216 if ( $dstRel === null ) {
217 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
219 return $status;
222 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
223 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
225 $reqs = array( array(
226 'method' => 'PUT',
227 'url' => array( $dstCont, $dstRel ),
228 'headers' => array(
229 'content-length' => strlen( $params['content'] ),
230 'etag' => md5( $params['content'] ),
231 'content-type' => $contentType,
232 'x-object-meta-sha1base36' => $sha1Hash
233 ) + $this->sanitizeHdrs( $params ),
234 'body' => $params['content']
235 ) );
237 $be = $this;
238 $method = __METHOD__;
239 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
240 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
241 if ( $rcode === 201 ) {
242 // good
243 } elseif ( $rcode === 412 ) {
244 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
245 } else {
246 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
250 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
251 if ( !empty( $params['async'] ) ) { // deferred
252 $status->value = $opHandle;
253 } else { // actually write the object in Swift
254 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
257 return $status;
260 protected function doStoreInternal( array $params ) {
261 $status = Status::newGood();
263 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
264 if ( $dstRel === null ) {
265 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
267 return $status;
270 wfSuppressWarnings();
271 $sha1Hash = sha1_file( $params['src'] );
272 wfRestoreWarnings();
273 if ( $sha1Hash === false ) { // source doesn't exist?
274 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
276 return $status;
278 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
279 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
281 $handle = fopen( $params['src'], 'rb' );
282 if ( $handle === false ) { // source doesn't exist?
283 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
285 return $status;
288 $reqs = array( array(
289 'method' => 'PUT',
290 'url' => array( $dstCont, $dstRel ),
291 'headers' => array(
292 'content-length' => filesize( $params['src'] ),
293 'etag' => md5_file( $params['src'] ),
294 'content-type' => $contentType,
295 'x-object-meta-sha1base36' => $sha1Hash
296 ) + $this->sanitizeHdrs( $params ),
297 'body' => $handle // resource
298 ) );
300 $be = $this;
301 $method = __METHOD__;
302 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
303 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
304 if ( $rcode === 201 ) {
305 // good
306 } elseif ( $rcode === 412 ) {
307 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
308 } else {
309 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
313 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
314 if ( !empty( $params['async'] ) ) { // deferred
315 $status->value = $opHandle;
316 } else { // actually write the object in Swift
317 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
320 return $status;
323 protected function doCopyInternal( array $params ) {
324 $status = Status::newGood();
326 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
327 if ( $srcRel === null ) {
328 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
330 return $status;
333 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
334 if ( $dstRel === null ) {
335 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
337 return $status;
340 $reqs = array( array(
341 'method' => 'PUT',
342 'url' => array( $dstCont, $dstRel ),
343 'headers' => array(
344 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
345 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
346 ) + $this->sanitizeHdrs( $params ), // extra headers merged into object
347 ) );
349 $be = $this;
350 $method = __METHOD__;
351 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
352 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
353 if ( $rcode === 201 ) {
354 // good
355 } elseif ( $rcode === 404 ) {
356 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
357 } else {
358 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
362 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
363 if ( !empty( $params['async'] ) ) { // deferred
364 $status->value = $opHandle;
365 } else { // actually write the object in Swift
366 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
369 return $status;
372 protected function doMoveInternal( array $params ) {
373 $status = Status::newGood();
375 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
376 if ( $srcRel === null ) {
377 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
379 return $status;
382 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
383 if ( $dstRel === null ) {
384 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
386 return $status;
389 $reqs = array(
390 array(
391 'method' => 'PUT',
392 'url' => array( $dstCont, $dstRel ),
393 'headers' => array(
394 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
395 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
396 ) + $this->sanitizeHdrs( $params ) // extra headers merged into object
399 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
400 $reqs[] = array(
401 'method' => 'DELETE',
402 'url' => array( $srcCont, $srcRel ),
403 'headers' => array()
407 $be = $this;
408 $method = __METHOD__;
409 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
410 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
411 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
412 // good
413 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
414 // good
415 } elseif ( $rcode === 404 ) {
416 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
417 } else {
418 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
422 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
423 if ( !empty( $params['async'] ) ) { // deferred
424 $status->value = $opHandle;
425 } else { // actually move the object in Swift
426 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
429 return $status;
432 protected function doDeleteInternal( array $params ) {
433 $status = Status::newGood();
435 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
436 if ( $srcRel === null ) {
437 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
439 return $status;
442 $reqs = array( array(
443 'method' => 'DELETE',
444 'url' => array( $srcCont, $srcRel ),
445 'headers' => array()
446 ) );
448 $be = $this;
449 $method = __METHOD__;
450 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
451 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
452 if ( $rcode === 204 ) {
453 // good
454 } elseif ( $rcode === 404 ) {
455 if ( empty( $params['ignoreMissingSource'] ) ) {
456 $status->fatal( 'backend-fail-delete', $params['src'] );
458 } else {
459 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
463 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
464 if ( !empty( $params['async'] ) ) { // deferred
465 $status->value = $opHandle;
466 } else { // actually delete the object in Swift
467 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
470 return $status;
473 protected function doDescribeInternal( array $params ) {
474 $status = Status::newGood();
476 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
477 if ( $srcRel === null ) {
478 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
480 return $status;
483 // Fetch the old object headers/metadata...this should be in stat cache by now
484 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
485 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
486 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
488 if ( !$stat ) {
489 $status->fatal( 'backend-fail-describe', $params['src'] );
491 return $status;
494 // POST clears prior headers, so we need to merge the changes in to the old ones
495 $metaHdrs = array();
496 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
497 $metaHdrs["x-object-meta-$name"] = $value;
499 $customHdrs = $this->sanitizeHdrs( $params ) + $stat['xattr']['headers'];
501 $reqs = array( array(
502 'method' => 'POST',
503 'url' => array( $srcCont, $srcRel ),
504 'headers' => $metaHdrs + $customHdrs
505 ) );
507 $be = $this;
508 $method = __METHOD__;
509 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
510 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
511 if ( $rcode === 202 ) {
512 // good
513 } elseif ( $rcode === 404 ) {
514 $status->fatal( 'backend-fail-describe', $params['src'] );
515 } else {
516 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
520 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
521 if ( !empty( $params['async'] ) ) { // deferred
522 $status->value = $opHandle;
523 } else { // actually change the object in Swift
524 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
527 return $status;
530 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
531 $status = Status::newGood();
533 // (a) Check if container already exists
534 $stat = $this->getContainerStat( $fullCont );
535 if ( is_array( $stat ) ) {
536 return $status; // already there
537 } elseif ( $stat === null ) {
538 $status->fatal( 'backend-fail-internal', $this->name );
540 return $status;
543 // (b) Create container as needed with proper ACLs
544 if ( $stat === false ) {
545 $params['op'] = 'prepare';
546 $status->merge( $this->createContainer( $fullCont, $params ) );
549 return $status;
552 protected function doSecureInternal( $fullCont, $dir, array $params ) {
553 $status = Status::newGood();
554 if ( empty( $params['noAccess'] ) ) {
555 return $status; // nothing to do
558 $stat = $this->getContainerStat( $fullCont );
559 if ( is_array( $stat ) ) {
560 // Make container private to end-users...
561 $status->merge( $this->setContainerAccess(
562 $fullCont,
563 array( $this->swiftUser ), // read
564 array( $this->swiftUser ) // write
565 ) );
566 } elseif ( $stat === false ) {
567 $status->fatal( 'backend-fail-usable', $params['dir'] );
568 } else {
569 $status->fatal( 'backend-fail-internal', $this->name );
572 return $status;
575 protected function doPublishInternal( $fullCont, $dir, array $params ) {
576 $status = Status::newGood();
578 $stat = $this->getContainerStat( $fullCont );
579 if ( is_array( $stat ) ) {
580 // Make container public to end-users...
581 $status->merge( $this->setContainerAccess(
582 $fullCont,
583 array( $this->swiftUser, '.r:*' ), // read
584 array( $this->swiftUser ) // write
585 ) );
586 } elseif ( $stat === false ) {
587 $status->fatal( 'backend-fail-usable', $params['dir'] );
588 } else {
589 $status->fatal( 'backend-fail-internal', $this->name );
592 return $status;
595 protected function doCleanInternal( $fullCont, $dir, array $params ) {
596 $status = Status::newGood();
598 // Only containers themselves can be removed, all else is virtual
599 if ( $dir != '' ) {
600 return $status; // nothing to do
603 // (a) Check the container
604 $stat = $this->getContainerStat( $fullCont, true );
605 if ( $stat === false ) {
606 return $status; // ok, nothing to do
607 } elseif ( !is_array( $stat ) ) {
608 $status->fatal( 'backend-fail-internal', $this->name );
610 return $status;
613 // (b) Delete the container if empty
614 if ( $stat['count'] == 0 ) {
615 $params['op'] = 'clean';
616 $status->merge( $this->deleteContainer( $fullCont, $params ) );
619 return $status;
622 protected function doGetFileStat( array $params ) {
623 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) + $params;
624 unset( $params['src'] );
625 $stats = $this->doGetFileStatMulti( $params );
627 return reset( $stats );
631 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
632 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
633 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
635 * @param string $ts
636 * @param int $format Output format (TS_* constant)
637 * @return string
638 * @throws FileBackendError
640 protected function convertSwiftDate( $ts, $format = TS_MW ) {
641 try {
642 $timestamp = new MWTimestamp( $ts );
644 return $timestamp->getTimestamp( $format );
645 } catch ( MWException $e ) {
646 throw new FileBackendError( $e->getMessage() );
651 * Fill in any missing object metadata and save it to Swift
653 * @param array $objHdrs Object response headers
654 * @param string $path Storage path to object
655 * @return array New headers
657 protected function addMissingMetadata( array $objHdrs, $path ) {
658 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
659 return $objHdrs; // nothing to do
662 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
663 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING );
665 $auth = $this->getAuthentication();
666 if ( !$auth ) {
667 $objHdrs['x-object-meta-sha1base36'] = false;
669 return $objHdrs; // failed
672 $status = Status::newGood();
673 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
674 if ( $status->isOK() ) {
675 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
676 if ( $tmpFile ) {
677 $hash = $tmpFile->getSha1Base36();
678 if ( $hash !== false ) {
679 $objHdrs['x-object-meta-sha1base36'] = $hash;
680 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
681 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
682 'method' => 'POST',
683 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
684 'headers' => $this->authTokenHeaders( $auth ) + $objHdrs
685 ) );
686 if ( $rcode >= 200 && $rcode <= 299 ) {
687 return $objHdrs; // success
692 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING );
693 $objHdrs['x-object-meta-sha1base36'] = false;
695 return $objHdrs; // failed
698 protected function doGetFileContentsMulti( array $params ) {
699 $contents = array();
701 $auth = $this->getAuthentication();
703 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
704 // Blindly create tmp files and stream to them, catching any exception if the file does
705 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
706 $reqs = array(); // (path => op)
708 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
709 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
710 if ( $srcRel === null || !$auth ) {
711 $contents[$path] = false;
712 continue;
714 // Create a new temporary memory file...
715 $handle = fopen( 'php://temp', 'wb' );
716 if ( $handle ) {
717 $reqs[$path] = array(
718 'method' => 'GET',
719 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
720 'headers' => $this->authTokenHeaders( $auth )
721 + $this->headersFromParams( $params ),
722 'stream' => $handle,
725 $contents[$path] = false;
728 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
729 $reqs = $this->http->runMulti( $reqs, $opts );
730 foreach ( $reqs as $path => $op ) {
731 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
732 if ( $rcode >= 200 && $rcode <= 299 ) {
733 rewind( $op['stream'] ); // start from the beginning
734 $contents[$path] = stream_get_contents( $op['stream'] );
735 } elseif ( $rcode === 404 ) {
736 $contents[$path] = false;
737 } else {
738 $this->onError( null, __METHOD__,
739 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
741 fclose( $op['stream'] ); // close open handle
744 return $contents;
747 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
748 $prefix = ( $dir == '' ) ? null : "{$dir}/";
749 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
750 if ( $status->isOk() ) {
751 return ( count( $status->value ) ) > 0;
754 return null; // error
758 * @see FileBackendStore::getDirectoryListInternal()
759 * @param string $fullCont
760 * @param string $dir
761 * @param array $params
762 * @return SwiftFileBackendDirList
764 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
765 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
769 * @see FileBackendStore::getFileListInternal()
770 * @param string $fullCont
771 * @param string $dir
772 * @param array $params
773 * @return SwiftFileBackendFileList
775 public function getFileListInternal( $fullCont, $dir, array $params ) {
776 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
780 * Do not call this function outside of SwiftFileBackendFileList
782 * @param string $fullCont Resolved container name
783 * @param string $dir Resolved storage directory with no trailing slash
784 * @param string|null $after Resolved container relative path to list items after
785 * @param int $limit Max number of items to list
786 * @param array $params Parameters for getDirectoryList()
787 * @return array List of container relative resolved paths of directories directly under $dir
788 * @throws FileBackendError
790 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
791 $dirs = array();
792 if ( $after === INF ) {
793 return $dirs; // nothing more
796 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
798 $prefix = ( $dir == '' ) ? null : "{$dir}/";
799 // Non-recursive: only list dirs right under $dir
800 if ( !empty( $params['topOnly'] ) ) {
801 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
802 if ( !$status->isOk() ) {
803 return $dirs; // error
805 $objects = $status->value;
806 foreach ( $objects as $object ) { // files and directories
807 if ( substr( $object, -1 ) === '/' ) {
808 $dirs[] = $object; // directories end in '/'
811 } else {
812 // Recursive: list all dirs under $dir and its subdirs
813 $getParentDir = function ( $path ) {
814 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
817 // Get directory from last item of prior page
818 $lastDir = $getParentDir( $after ); // must be first page
819 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
821 if ( !$status->isOk() ) {
822 return $dirs; // error
825 $objects = $status->value;
827 foreach ( $objects as $object ) { // files
828 $objectDir = $getParentDir( $object ); // directory of object
830 if ( $objectDir !== false && $objectDir !== $dir ) {
831 // Swift stores paths in UTF-8, using binary sorting.
832 // See function "create_container_table" in common/db.py.
833 // If a directory is not "greater" than the last one,
834 // then it was already listed by the calling iterator.
835 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
836 $pDir = $objectDir;
837 do { // add dir and all its parent dirs
838 $dirs[] = "{$pDir}/";
839 $pDir = $getParentDir( $pDir );
840 } while ( $pDir !== false // sanity
841 && strcmp( $pDir, $lastDir ) > 0 // not done already
842 && strlen( $pDir ) > strlen( $dir ) // within $dir
845 $lastDir = $objectDir;
849 // Page on the unfiltered directory listing (what is returned may be filtered)
850 if ( count( $objects ) < $limit ) {
851 $after = INF; // avoid a second RTT
852 } else {
853 $after = end( $objects ); // update last item
856 return $dirs;
860 * Do not call this function outside of SwiftFileBackendFileList
862 * @param string $fullCont Resolved container name
863 * @param string $dir Resolved storage directory with no trailing slash
864 * @param string|null $after Resolved container relative path of file to list items after
865 * @param int $limit Max number of items to list
866 * @param array $params Parameters for getDirectoryList()
867 * @return array List of resolved container relative paths of files under $dir
868 * @throws FileBackendError
870 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
871 $files = array(); // list of (path, stat array or null) entries
872 if ( $after === INF ) {
873 return $files; // nothing more
876 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
878 $prefix = ( $dir == '' ) ? null : "{$dir}/";
879 // $objects will contain a list of unfiltered names or CF_Object items
880 // Non-recursive: only list files right under $dir
881 if ( !empty( $params['topOnly'] ) ) {
882 if ( !empty( $params['adviseStat'] ) ) {
883 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
884 } else {
885 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
887 } else {
888 // Recursive: list all files under $dir and its subdirs
889 if ( !empty( $params['adviseStat'] ) ) {
890 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
891 } else {
892 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
896 // Reformat this list into a list of (name, stat array or null) entries
897 if ( !$status->isOk() ) {
898 return $files; // error
901 $objects = $status->value;
902 $files = $this->buildFileObjectListing( $params, $dir, $objects );
904 // Page on the unfiltered object listing (what is returned may be filtered)
905 if ( count( $objects ) < $limit ) {
906 $after = INF; // avoid a second RTT
907 } else {
908 $after = end( $objects ); // update last item
909 $after = is_object( $after ) ? $after->name : $after;
912 return $files;
916 * Build a list of file objects, filtering out any directories
917 * and extracting any stat info if provided in $objects (for CF_Objects)
919 * @param array $params Parameters for getDirectoryList()
920 * @param string $dir Resolved container directory path
921 * @param array $objects List of CF_Object items or object names
922 * @return array List of (names,stat array or null) entries
924 private function buildFileObjectListing( array $params, $dir, array $objects ) {
925 $names = array();
926 foreach ( $objects as $object ) {
927 if ( is_object( $object ) ) {
928 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
929 continue; // virtual directory entry; ignore
931 $stat = array(
932 // Convert various random Swift dates to TS_MW
933 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
934 'size' => (int)$object->bytes,
935 // Note: manifiest ETags are not an MD5 of the file
936 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
937 'latest' => false // eventually consistent
939 $names[] = array( $object->name, $stat );
940 } elseif ( substr( $object, -1 ) !== '/' ) {
941 // Omit directories, which end in '/' in listings
942 $names[] = array( $object, null );
946 return $names;
950 * Do not call this function outside of SwiftFileBackendFileList
952 * @param string $path Storage path
953 * @param array $val Stat value
955 public function loadListingStatInternal( $path, array $val ) {
956 $this->cheapCache->set( $path, 'stat', $val );
959 protected function doGetFileXAttributes( array $params ) {
960 $stat = $this->getFileStat( $params );
961 if ( $stat ) {
962 if ( !isset( $stat['xattr'] ) ) {
963 // Stat entries filled by file listings don't include metadata/headers
964 $this->clearCache( array( $params['src'] ) );
965 $stat = $this->getFileStat( $params );
968 return $stat['xattr'];
969 } else {
970 return false;
974 protected function doGetFileSha1base36( array $params ) {
975 $stat = $this->getFileStat( $params );
976 if ( $stat ) {
977 if ( !isset( $stat['sha1'] ) ) {
978 // Stat entries filled by file listings don't include SHA1
979 $this->clearCache( array( $params['src'] ) );
980 $stat = $this->getFileStat( $params );
983 return $stat['sha1'];
984 } else {
985 return false;
989 protected function doStreamFile( array $params ) {
990 $status = Status::newGood();
992 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
993 if ( $srcRel === null ) {
994 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
997 $auth = $this->getAuthentication();
998 if ( !$auth || !is_array( $this->getContainerStat( $srcCont ) ) ) {
999 $status->fatal( 'backend-fail-stream', $params['src'] );
1001 return $status;
1004 $handle = fopen( 'php://output', 'wb' );
1006 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1007 'method' => 'GET',
1008 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1009 'headers' => $this->authTokenHeaders( $auth )
1010 + $this->headersFromParams( $params ),
1011 'stream' => $handle,
1012 ) );
1014 if ( $rcode >= 200 && $rcode <= 299 ) {
1015 // good
1016 } elseif ( $rcode === 404 ) {
1017 $status->fatal( 'backend-fail-stream', $params['src'] );
1018 } else {
1019 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1022 return $status;
1025 protected function doGetLocalCopyMulti( array $params ) {
1026 $tmpFiles = array();
1028 $auth = $this->getAuthentication();
1030 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1031 // Blindly create tmp files and stream to them, catching any exception if the file does
1032 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1033 $reqs = array(); // (path => op)
1035 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1036 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1037 if ( $srcRel === null || !$auth ) {
1038 $tmpFiles[$path] = null;
1039 continue;
1041 // Get source file extension
1042 $ext = FileBackend::extensionFromPath( $path );
1043 // Create a new temporary file...
1044 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1045 if ( $tmpFile ) {
1046 $handle = fopen( $tmpFile->getPath(), 'wb' );
1047 if ( $handle ) {
1048 $reqs[$path] = array(
1049 'method' => 'GET',
1050 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1051 'headers' => $this->authTokenHeaders( $auth )
1052 + $this->headersFromParams( $params ),
1053 'stream' => $handle,
1055 } else {
1056 $tmpFile = null;
1059 $tmpFiles[$path] = $tmpFile;
1062 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1063 $reqs = $this->http->runMulti( $reqs, $opts );
1064 foreach ( $reqs as $path => $op ) {
1065 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1066 fclose( $op['stream'] ); // close open handle
1067 if ( $rcode >= 200 && $rcode <= 299 ) {
1068 // Double check that the disk is not full/broken
1069 if ( $tmpFiles[$path]->getSize() != $rhdrs['content-length'] ) {
1070 $tmpFiles[$path] = null;
1071 $rerr = "Got {$tmpFiles[$path]->getSize()}/{$rhdrs['content-length']} bytes";
1072 $this->onError( null, __METHOD__,
1073 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1075 } elseif ( $rcode === 404 ) {
1076 $tmpFiles[$path] = false;
1077 } else {
1078 $tmpFiles[$path] = null;
1079 $this->onError( null, __METHOD__,
1080 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1084 return $tmpFiles;
1087 public function getFileHttpUrl( array $params ) {
1088 if ( $this->swiftTempUrlKey != '' ||
1089 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1091 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1092 if ( $srcRel === null ) {
1093 return null; // invalid path
1096 $auth = $this->getAuthentication();
1097 if ( !$auth ) {
1098 return null;
1101 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1102 $expires = time() + $ttl;
1104 if ( $this->swiftTempUrlKey != '' ) {
1105 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1106 // Swift wants the signature based on the unencoded object name
1107 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1108 $signature = hash_hmac( 'sha1',
1109 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1110 $this->swiftTempUrlKey
1113 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1114 } else { // give S3 API URL for rgw
1115 // Path for signature starts with the bucket
1116 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1117 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1118 // Calculate the hash
1119 $signature = base64_encode( hash_hmac(
1120 'sha1',
1121 "GET\n\n\n{$expires}\n{$spath}",
1122 $this->rgwS3SecretKey,
1123 true // raw
1124 ) );
1125 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1126 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1127 return wfAppendQuery(
1128 str_replace( '/swift/v1', '', // S3 API is the rgw default
1129 $this->storageUrl( $auth ) . $spath ),
1130 array(
1131 'Signature' => $signature,
1132 'Expires' => $expires,
1133 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1138 return null;
1141 protected function directoriesAreVirtual() {
1142 return true;
1146 * Get headers to send to Swift when reading a file based
1147 * on a FileBackend params array, e.g. that of getLocalCopy().
1148 * $params is currently only checked for a 'latest' flag.
1150 * @param array $params
1151 * @return array
1153 protected function headersFromParams( array $params ) {
1154 $hdrs = array();
1155 if ( !empty( $params['latest'] ) ) {
1156 $hdrs['x-newest'] = 'true';
1159 return $hdrs;
1162 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1163 $statuses = array();
1165 $auth = $this->getAuthentication();
1166 if ( !$auth ) {
1167 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1168 $statuses[$index] = Status::newFatal( 'backend-fail-connect', $this->name );
1171 return $statuses;
1174 // Split the HTTP requests into stages that can be done concurrently
1175 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1176 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1177 $reqs = $fileOpHandle->httpOp;
1178 // Convert the 'url' parameter to an actual URL using $auth
1179 foreach ( $reqs as $stage => &$req ) {
1180 list( $container, $relPath ) = $req['url'];
1181 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1182 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : array();
1183 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1184 $httpReqsByStage[$stage][$index] = $req;
1186 $statuses[$index] = Status::newGood();
1189 // Run all requests for the first stage, then the next, and so on
1190 $reqCount = count( $httpReqsByStage );
1191 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1192 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1193 foreach ( $httpReqs as $index => $httpReq ) {
1194 // Run the callback for each request of this operation
1195 $callback = $fileOpHandles[$index]->callback;
1196 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1197 // On failure, abort all remaining requests for this operation
1198 // (e.g. abort the DELETE request if the COPY request fails for a move)
1199 if ( !$statuses[$index]->isOK() ) {
1200 $stages = count( $fileOpHandles[$index]->httpOp );
1201 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1202 unset( $httpReqsByStage[$s][$index] );
1208 return $statuses;
1212 * Set read/write permissions for a Swift container.
1214 * @see http://swift.openstack.org/misc.html#acls
1216 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1217 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1219 * @param string $container Resolved Swift container
1220 * @param array $readGrps List of the possible criteria for a request to have
1221 * access to read a container. Each item is one of the following formats:
1222 * - account:user : Grants access if the request is by the given user
1223 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1224 * matches the expression and the request is not for a listing.
1225 * Setting this to '*' effectively makes a container public.
1226 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1227 * matches the expression and the request is for a listing.
1228 * @param array $writeGrps A list of the possible criteria for a request to have
1229 * access to write to a container. Each item is of the following format:
1230 * - account:user : Grants access if the request is by the given user
1231 * @return Status
1233 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1234 $status = Status::newGood();
1235 $auth = $this->getAuthentication();
1237 if ( !$auth ) {
1238 $status->fatal( 'backend-fail-connect', $this->name );
1240 return $status;
1243 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1244 'method' => 'POST',
1245 'url' => $this->storageUrl( $auth, $container ),
1246 'headers' => $this->authTokenHeaders( $auth ) + array(
1247 'x-container-read' => implode( ',', $readGrps ),
1248 'x-container-write' => implode( ',', $writeGrps )
1250 ) );
1252 if ( $rcode != 204 && $rcode !== 202 ) {
1253 $status->fatal( 'backend-fail-internal', $this->name );
1256 return $status;
1260 * Get a Swift container stat array, possibly from process cache.
1261 * Use $reCache if the file count or byte count is needed.
1263 * @param string $container Container name
1264 * @param bool $bypassCache Bypass all caches and load from Swift
1265 * @return array|bool|null False on 404, null on failure
1267 protected function getContainerStat( $container, $bypassCache = false ) {
1268 $section = new ProfileSection( __METHOD__ . '-' . $this->name );
1270 if ( $bypassCache ) { // purge cache
1271 $this->containerStatCache->clear( $container );
1272 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1273 $this->primeContainerCache( array( $container ) ); // check persistent cache
1275 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1276 $auth = $this->getAuthentication();
1277 if ( !$auth ) {
1278 return null;
1281 wfProfileIn( __METHOD__ . "-{$this->name}-miss" );
1282 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1283 'method' => 'HEAD',
1284 'url' => $this->storageUrl( $auth, $container ),
1285 'headers' => $this->authTokenHeaders( $auth )
1286 ) );
1287 wfProfileOut( __METHOD__ . "-{$this->name}-miss" );
1289 if ( $rcode === 204 ) {
1290 $stat = array(
1291 'count' => $rhdrs['x-container-object-count'],
1292 'bytes' => $rhdrs['x-container-bytes-used']
1294 if ( $bypassCache ) {
1295 return $stat;
1296 } else {
1297 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1298 $this->setContainerCache( $container, $stat ); // update persistent cache
1300 } elseif ( $rcode === 404 ) {
1301 return false;
1302 } else {
1303 $this->onError( null, __METHOD__,
1304 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1306 return null;
1310 return $this->containerStatCache->get( $container, 'stat' );
1314 * Create a Swift container
1316 * @param string $container Container name
1317 * @param array $params
1318 * @return Status
1320 protected function createContainer( $container, array $params ) {
1321 $status = Status::newGood();
1323 $auth = $this->getAuthentication();
1324 if ( !$auth ) {
1325 $status->fatal( 'backend-fail-connect', $this->name );
1327 return $status;
1330 // @see SwiftFileBackend::setContainerAccess()
1331 if ( empty( $params['noAccess'] ) ) {
1332 $readGrps = array( '.r:*', $this->swiftUser ); // public
1333 } else {
1334 $readGrps = array( $this->swiftUser ); // private
1336 $writeGrps = array( $this->swiftUser ); // sanity
1338 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1339 'method' => 'PUT',
1340 'url' => $this->storageUrl( $auth, $container ),
1341 'headers' => $this->authTokenHeaders( $auth ) + array(
1342 'x-container-read' => implode( ',', $readGrps ),
1343 'x-container-write' => implode( ',', $writeGrps )
1345 ) );
1347 if ( $rcode === 201 ) { // new
1348 // good
1349 } elseif ( $rcode === 202 ) { // already there
1350 // this shouldn't really happen, but is OK
1351 } else {
1352 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1355 return $status;
1359 * Delete a Swift container
1361 * @param string $container Container name
1362 * @param array $params
1363 * @return Status
1365 protected function deleteContainer( $container, array $params ) {
1366 $status = Status::newGood();
1368 $auth = $this->getAuthentication();
1369 if ( !$auth ) {
1370 $status->fatal( 'backend-fail-connect', $this->name );
1372 return $status;
1375 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1376 'method' => 'DELETE',
1377 'url' => $this->storageUrl( $auth, $container ),
1378 'headers' => $this->authTokenHeaders( $auth )
1379 ) );
1381 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1382 $this->containerStatCache->clear( $container ); // purge
1383 } elseif ( $rcode === 404 ) { // not there
1384 // this shouldn't really happen, but is OK
1385 } elseif ( $rcode === 409 ) { // not empty
1386 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1387 } else {
1388 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1391 return $status;
1395 * Get a list of objects under a container.
1396 * Either just the names or a list of stdClass objects with details can be returned.
1398 * @param string $fullCont
1399 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1400 * @param int $limit
1401 * @param string|null $after
1402 * @param string|null $prefix
1403 * @param string|null $delim
1404 * @return Status With the list as value
1406 private function objectListing(
1407 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1409 $status = Status::newGood();
1411 $auth = $this->getAuthentication();
1412 if ( !$auth ) {
1413 $status->fatal( 'backend-fail-connect', $this->name );
1415 return $status;
1418 $query = array( 'limit' => $limit );
1419 if ( $type === 'info' ) {
1420 $query['format'] = 'json';
1422 if ( $after !== null ) {
1423 $query['marker'] = $after;
1425 if ( $prefix !== null ) {
1426 $query['prefix'] = $prefix;
1428 if ( $delim !== null ) {
1429 $query['delimiter'] = $delim;
1432 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1433 'method' => 'GET',
1434 'url' => $this->storageUrl( $auth, $fullCont ),
1435 'query' => $query,
1436 'headers' => $this->authTokenHeaders( $auth )
1437 ) );
1439 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1440 if ( $rcode === 200 ) { // good
1441 if ( $type === 'info' ) {
1442 $status->value = FormatJson::decode( trim( $rbody ) );
1443 } else {
1444 $status->value = explode( "\n", trim( $rbody ) );
1446 } elseif ( $rcode === 204 ) {
1447 $status->value = array(); // empty container
1448 } elseif ( $rcode === 404 ) {
1449 $status->value = array(); // no container
1450 } else {
1451 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1454 return $status;
1457 protected function doPrimeContainerCache( array $containerInfo ) {
1458 foreach ( $containerInfo as $container => $info ) {
1459 $this->containerStatCache->set( $container, 'stat', $info );
1463 protected function doGetFileStatMulti( array $params ) {
1464 $stats = array();
1466 $auth = $this->getAuthentication();
1468 $reqs = array();
1469 foreach ( $params['srcs'] as $path ) {
1470 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1471 if ( $srcRel === null ) {
1472 $stats[$path] = false;
1473 continue; // invalid storage path
1474 } elseif ( !$auth ) {
1475 $stats[$path] = null;
1476 continue;
1479 // (a) Check the container
1480 $cstat = $this->getContainerStat( $srcCont );
1481 if ( $cstat === false ) {
1482 $stats[$path] = false;
1483 continue; // ok, nothing to do
1484 } elseif ( !is_array( $cstat ) ) {
1485 $stats[$path] = null;
1486 continue;
1489 $reqs[$path] = array(
1490 'method' => 'HEAD',
1491 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1492 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1496 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1497 $reqs = $this->http->runMulti( $reqs, $opts );
1499 foreach ( $params['srcs'] as $path ) {
1500 if ( array_key_exists( $path, $stats ) ) {
1501 continue; // some sort of failure above
1503 // (b) Check the file
1504 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1505 if ( $rcode === 200 || $rcode === 204 ) {
1506 // Update the object if it is missing some headers
1507 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1508 // Fetch all of the custom metadata headers
1509 $metadata = array();
1510 foreach ( $rhdrs as $name => $value ) {
1511 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
1512 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
1515 // Fetch all of the custom raw HTTP headers
1516 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1517 $stat = array(
1518 // Convert various random Swift dates to TS_MW
1519 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1520 // Empty objects actually return no content-length header in Ceph
1521 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1522 'sha1' => $rhdrs[ 'x-object-meta-sha1base36'],
1523 // Note: manifiest ETags are not an MD5 of the file
1524 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1525 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1527 if ( $this->isRGW ) {
1528 $stat['latest'] = true; // strong consistency
1530 } elseif ( $rcode === 404 ) {
1531 $stat = false;
1532 } else {
1533 $stat = null;
1534 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1536 $stats[$path] = $stat;
1539 return $stats;
1543 * @return array|null Credential map
1545 protected function getAuthentication() {
1546 if ( $this->authErrorTimestamp !== null ) {
1547 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1548 return null; // failed last attempt; don't bother
1549 } else { // actually retry this time
1550 $this->authErrorTimestamp = null;
1553 // Session keys expire after a while, so we renew them periodically
1554 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1555 // Authenticate with proxy and get a session key...
1556 if ( !$this->authCreds || $reAuth ) {
1557 $this->authSessionTimestamp = 0;
1558 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1559 $creds = $this->srvCache->get( $cacheKey ); // credentials
1560 // Try to use the credential cache
1561 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1562 $this->authCreds = $creds;
1563 // Skew the timestamp for worst case to avoid using stale credentials
1564 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1565 } else { // cache miss
1566 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1567 'method' => 'GET',
1568 'url' => "{$this->swiftAuthUrl}/v1.0",
1569 'headers' => array(
1570 'x-auth-user' => $this->swiftUser,
1571 'x-auth-key' => $this->swiftKey
1573 ) );
1575 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1576 $this->authCreds = array(
1577 'auth_token' => $rhdrs['x-auth-token'],
1578 'storage_url' => $rhdrs['x-storage-url']
1580 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1581 $this->authSessionTimestamp = time();
1582 } elseif ( $rcode === 401 ) {
1583 $this->onError( null, __METHOD__, array(), "Authentication failed.", $rcode );
1584 $this->authErrorTimestamp = time();
1586 return null;
1587 } else {
1588 $this->onError( null, __METHOD__, array(), "HTTP return code: $rcode", $rcode );
1589 $this->authErrorTimestamp = time();
1591 return null;
1594 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1595 if ( substr( $this->authCreds['storage_url'], -3 ) === '/v1' ) {
1596 $this->isRGW = true; // take advantage of strong consistency
1600 return $this->authCreds;
1604 * @param array $creds From getAuthentication()
1605 * @param string $container
1606 * @param string $object
1607 * @return array
1609 protected function storageUrl( array $creds, $container = null, $object = null ) {
1610 $parts = array( $creds['storage_url'] );
1611 if ( strlen( $container ) ) {
1612 $parts[] = rawurlencode( $container );
1614 if ( strlen( $object ) ) {
1615 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1618 return implode( '/', $parts );
1622 * @param array $creds From getAuthentication()
1623 * @return array
1625 protected function authTokenHeaders( array $creds ) {
1626 return array( 'x-auth-token' => $creds['auth_token'] );
1630 * Get the cache key for a container
1632 * @param string $username
1633 * @return string
1635 private function getCredsCacheKey( $username ) {
1636 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1640 * Log an unexpected exception for this backend.
1641 * This also sets the Status object to have a fatal error.
1643 * @param Status|null $status
1644 * @param string $func
1645 * @param array $params
1646 * @param string $err Error string
1647 * @param int $code HTTP status
1648 * @param string $desc HTTP status description
1650 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1651 if ( $status instanceof Status ) {
1652 $status->fatal( 'backend-fail-internal', $this->name );
1654 if ( $code == 401 ) { // possibly a stale token
1655 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1657 wfDebugLog( 'SwiftBackend',
1658 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1659 ( $err ? ": $err" : "" )
1665 * @see FileBackendStoreOpHandle
1667 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1668 /** @var array List of Requests for MultiHttpClient */
1669 public $httpOp;
1670 /** @var Closure */
1671 public $callback;
1674 * @param SwiftFileBackend $backend
1675 * @param Closure $callback Function that takes (HTTP request array, status)
1676 * @param array $httpOp MultiHttpClient op
1678 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1679 $this->backend = $backend;
1680 $this->callback = $callback;
1681 $this->httpOp = $httpOp;
1686 * SwiftFileBackend helper class to page through listings.
1687 * Swift also has a listing limit of 10,000 objects for sanity.
1688 * Do not use this class from places outside SwiftFileBackend.
1690 * @ingroup FileBackend
1692 abstract class SwiftFileBackendList implements Iterator {
1693 /** @var array List of path or (path,stat array) entries */
1694 protected $bufferIter = array();
1696 /** @var string List items *after* this path */
1697 protected $bufferAfter = null;
1699 /** @var int */
1700 protected $pos = 0;
1702 /** @var array */
1703 protected $params = array();
1705 /** @var SwiftFileBackend */
1706 protected $backend;
1708 /** @var string Container name */
1709 protected $container;
1711 /** @var string Storage directory */
1712 protected $dir;
1714 /** @var int */
1715 protected $suffixStart;
1717 const PAGE_SIZE = 9000; // file listing buffer size
1720 * @param SwiftFileBackend $backend
1721 * @param string $fullCont Resolved container name
1722 * @param string $dir Resolved directory relative to container
1723 * @param array $params
1725 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1726 $this->backend = $backend;
1727 $this->container = $fullCont;
1728 $this->dir = $dir;
1729 if ( substr( $this->dir, -1 ) === '/' ) {
1730 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1732 if ( $this->dir == '' ) { // whole container
1733 $this->suffixStart = 0;
1734 } else { // dir within container
1735 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1737 $this->params = $params;
1741 * @see Iterator::key()
1742 * @return int
1744 public function key() {
1745 return $this->pos;
1749 * @see Iterator::next()
1751 public function next() {
1752 // Advance to the next file in the page
1753 next( $this->bufferIter );
1754 ++$this->pos;
1755 // Check if there are no files left in this page and
1756 // advance to the next page if this page was not empty.
1757 if ( !$this->valid() && count( $this->bufferIter ) ) {
1758 $this->bufferIter = $this->pageFromList(
1759 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1760 ); // updates $this->bufferAfter
1765 * @see Iterator::rewind()
1767 public function rewind() {
1768 $this->pos = 0;
1769 $this->bufferAfter = null;
1770 $this->bufferIter = $this->pageFromList(
1771 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1772 ); // updates $this->bufferAfter
1776 * @see Iterator::valid()
1777 * @return bool
1779 public function valid() {
1780 if ( $this->bufferIter === null ) {
1781 return false; // some failure?
1782 } else {
1783 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1788 * Get the given list portion (page)
1790 * @param string $container Resolved container name
1791 * @param string $dir Resolved path relative to container
1792 * @param string $after null
1793 * @param int $limit
1794 * @param array $params
1795 * @return Traversable|array
1797 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1801 * Iterator for listing directories
1803 class SwiftFileBackendDirList extends SwiftFileBackendList {
1805 * @see Iterator::current()
1806 * @return string|bool String (relative path) or false
1808 public function current() {
1809 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1812 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1813 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1818 * Iterator for listing regular files
1820 class SwiftFileBackendFileList extends SwiftFileBackendList {
1822 * @see Iterator::current()
1823 * @return string|bool String (relative path) or false
1825 public function current() {
1826 list( $path, $stat ) = current( $this->bufferIter );
1827 $relPath = substr( $path, $this->suffixStart );
1828 if ( is_array( $stat ) ) {
1829 $storageDir = rtrim( $this->params['dir'], '/' );
1830 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1833 return $relPath;
1836 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1837 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );