Implement extension registration from an extension.json file
[mediawiki.git] / includes / filebackend / SwiftFileBackend.php
blob1f7ebc9a176d8043e5e51a2b7be5bf3c7af365e7
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 $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_UNICODE_PATHS |
150 FileBackend::ATTR_HEADERS | FileBackend::ATTR_METADATA );
153 protected function resolveContainerPath( $container, $relStoragePath ) {
154 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
155 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
156 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
157 return null; // too long for Swift
160 return $relStoragePath;
163 public function isPathUsableInternal( $storagePath ) {
164 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
165 if ( $rel === null ) {
166 return false; // invalid
169 return is_array( $this->getContainerStat( $container ) );
173 * Sanitize and filter the custom headers from a $params array.
174 * We only allow certain Content- and X-Content- headers.
176 * @param array $params
177 * @return array Sanitized value of 'headers' field in $params
179 protected function sanitizeHdrs( array $params ) {
180 $headers = array();
182 // Normalize casing, and strip out illegal headers
183 if ( isset( $params['headers'] ) ) {
184 foreach ( $params['headers'] as $name => $value ) {
185 $name = strtolower( $name );
186 if ( preg_match( '/^content-(type|length)$/', $name ) ) {
187 continue; // blacklisted
188 } elseif ( preg_match( '/^(x-)?content-/', $name ) ) {
189 $headers[$name] = $value; // allowed
190 } elseif ( preg_match( '/^content-(disposition)/', $name ) ) {
191 $headers[$name] = $value; // allowed
195 // By default, Swift has annoyingly low maximum header value limits
196 if ( isset( $headers['content-disposition'] ) ) {
197 $disposition = '';
198 foreach ( explode( ';', $headers['content-disposition'] ) as $part ) {
199 $part = trim( $part );
200 $new = ( $disposition === '' ) ? $part : "{$disposition};{$part}";
201 if ( strlen( $new ) <= 255 ) {
202 $disposition = $new;
203 } else {
204 break; // too long; sigh
207 $headers['content-disposition'] = $disposition;
210 return $headers;
213 protected function doCreateInternal( array $params ) {
214 $status = Status::newGood();
216 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
217 if ( $dstRel === null ) {
218 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
220 return $status;
223 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
224 $contentType = $this->getContentType( $params['dst'], $params['content'], null );
226 $reqs = array( array(
227 'method' => 'PUT',
228 'url' => array( $dstCont, $dstRel ),
229 'headers' => array(
230 'content-length' => strlen( $params['content'] ),
231 'etag' => md5( $params['content'] ),
232 'content-type' => $contentType,
233 'x-object-meta-sha1base36' => $sha1Hash
234 ) + $this->sanitizeHdrs( $params ),
235 'body' => $params['content']
236 ) );
238 $be = $this;
239 $method = __METHOD__;
240 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
241 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
242 if ( $rcode === 201 ) {
243 // good
244 } elseif ( $rcode === 412 ) {
245 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
246 } else {
247 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
251 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
252 if ( !empty( $params['async'] ) ) { // deferred
253 $status->value = $opHandle;
254 } else { // actually write the object in Swift
255 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
258 return $status;
261 protected function doStoreInternal( array $params ) {
262 $status = Status::newGood();
264 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
265 if ( $dstRel === null ) {
266 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
268 return $status;
271 wfSuppressWarnings();
272 $sha1Hash = sha1_file( $params['src'] );
273 wfRestoreWarnings();
274 if ( $sha1Hash === false ) { // source doesn't exist?
275 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
277 return $status;
279 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
280 $contentType = $this->getContentType( $params['dst'], null, $params['src'] );
282 $handle = fopen( $params['src'], 'rb' );
283 if ( $handle === false ) { // source doesn't exist?
284 $status->fatal( 'backend-fail-store', $params['src'], $params['dst'] );
286 return $status;
289 $reqs = array( array(
290 'method' => 'PUT',
291 'url' => array( $dstCont, $dstRel ),
292 'headers' => array(
293 'content-length' => filesize( $params['src'] ),
294 'etag' => md5_file( $params['src'] ),
295 'content-type' => $contentType,
296 'x-object-meta-sha1base36' => $sha1Hash
297 ) + $this->sanitizeHdrs( $params ),
298 'body' => $handle // resource
299 ) );
301 $be = $this;
302 $method = __METHOD__;
303 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
304 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
305 if ( $rcode === 201 ) {
306 // good
307 } elseif ( $rcode === 412 ) {
308 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
309 } else {
310 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
314 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
315 if ( !empty( $params['async'] ) ) { // deferred
316 $status->value = $opHandle;
317 } else { // actually write the object in Swift
318 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
321 return $status;
324 protected function doCopyInternal( array $params ) {
325 $status = Status::newGood();
327 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
328 if ( $srcRel === null ) {
329 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
331 return $status;
334 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
335 if ( $dstRel === null ) {
336 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
338 return $status;
341 $reqs = array( array(
342 'method' => 'PUT',
343 'url' => array( $dstCont, $dstRel ),
344 'headers' => array(
345 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
346 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
347 ) + $this->sanitizeHdrs( $params ), // extra headers merged into object
348 ) );
350 $be = $this;
351 $method = __METHOD__;
352 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
353 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
354 if ( $rcode === 201 ) {
355 // good
356 } elseif ( $rcode === 404 ) {
357 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
358 } else {
359 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
363 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
364 if ( !empty( $params['async'] ) ) { // deferred
365 $status->value = $opHandle;
366 } else { // actually write the object in Swift
367 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
370 return $status;
373 protected function doMoveInternal( array $params ) {
374 $status = Status::newGood();
376 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
377 if ( $srcRel === null ) {
378 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
380 return $status;
383 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
384 if ( $dstRel === null ) {
385 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
387 return $status;
390 $reqs = array(
391 array(
392 'method' => 'PUT',
393 'url' => array( $dstCont, $dstRel ),
394 'headers' => array(
395 'x-copy-from' => '/' . rawurlencode( $srcCont ) .
396 '/' . str_replace( "%2F", "/", rawurlencode( $srcRel ) )
397 ) + $this->sanitizeHdrs( $params ) // extra headers merged into object
400 if ( "{$srcCont}/{$srcRel}" !== "{$dstCont}/{$dstRel}" ) {
401 $reqs[] = array(
402 'method' => 'DELETE',
403 'url' => array( $srcCont, $srcRel ),
404 'headers' => array()
408 $be = $this;
409 $method = __METHOD__;
410 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
411 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
412 if ( $request['method'] === 'PUT' && $rcode === 201 ) {
413 // good
414 } elseif ( $request['method'] === 'DELETE' && $rcode === 204 ) {
415 // good
416 } elseif ( $rcode === 404 ) {
417 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
418 } else {
419 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
423 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
424 if ( !empty( $params['async'] ) ) { // deferred
425 $status->value = $opHandle;
426 } else { // actually move the object in Swift
427 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
430 return $status;
433 protected function doDeleteInternal( array $params ) {
434 $status = Status::newGood();
436 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
437 if ( $srcRel === null ) {
438 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
440 return $status;
443 $reqs = array( array(
444 'method' => 'DELETE',
445 'url' => array( $srcCont, $srcRel ),
446 'headers' => array()
447 ) );
449 $be = $this;
450 $method = __METHOD__;
451 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
452 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
453 if ( $rcode === 204 ) {
454 // good
455 } elseif ( $rcode === 404 ) {
456 if ( empty( $params['ignoreMissingSource'] ) ) {
457 $status->fatal( 'backend-fail-delete', $params['src'] );
459 } else {
460 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
464 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
465 if ( !empty( $params['async'] ) ) { // deferred
466 $status->value = $opHandle;
467 } else { // actually delete the object in Swift
468 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
471 return $status;
474 protected function doDescribeInternal( array $params ) {
475 $status = Status::newGood();
477 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
478 if ( $srcRel === null ) {
479 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
481 return $status;
484 // Fetch the old object headers/metadata...this should be in stat cache by now
485 $stat = $this->getFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
486 if ( $stat && !isset( $stat['xattr'] ) ) { // older cache entry
487 $stat = $this->doGetFileStat( array( 'src' => $params['src'], 'latest' => 1 ) );
489 if ( !$stat ) {
490 $status->fatal( 'backend-fail-describe', $params['src'] );
492 return $status;
495 // POST clears prior headers, so we need to merge the changes in to the old ones
496 $metaHdrs = array();
497 foreach ( $stat['xattr']['metadata'] as $name => $value ) {
498 $metaHdrs["x-object-meta-$name"] = $value;
500 $customHdrs = $this->sanitizeHdrs( $params ) + $stat['xattr']['headers'];
502 $reqs = array( array(
503 'method' => 'POST',
504 'url' => array( $srcCont, $srcRel ),
505 'headers' => $metaHdrs + $customHdrs
506 ) );
508 $be = $this;
509 $method = __METHOD__;
510 $handler = function ( array $request, Status $status ) use ( $be, $method, $params ) {
511 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $request['response'];
512 if ( $rcode === 202 ) {
513 // good
514 } elseif ( $rcode === 404 ) {
515 $status->fatal( 'backend-fail-describe', $params['src'] );
516 } else {
517 $be->onError( $status, $method, $params, $rerr, $rcode, $rdesc );
521 $opHandle = new SwiftFileOpHandle( $this, $handler, $reqs );
522 if ( !empty( $params['async'] ) ) { // deferred
523 $status->value = $opHandle;
524 } else { // actually change the object in Swift
525 $status->merge( current( $this->doExecuteOpHandlesInternal( array( $opHandle ) ) ) );
528 return $status;
531 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
532 $status = Status::newGood();
534 // (a) Check if container already exists
535 $stat = $this->getContainerStat( $fullCont );
536 if ( is_array( $stat ) ) {
537 return $status; // already there
538 } elseif ( $stat === null ) {
539 $status->fatal( 'backend-fail-internal', $this->name );
540 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
542 return $status;
545 // (b) Create container as needed with proper ACLs
546 if ( $stat === false ) {
547 $params['op'] = 'prepare';
548 $status->merge( $this->createContainer( $fullCont, $params ) );
551 return $status;
554 protected function doSecureInternal( $fullCont, $dir, array $params ) {
555 $status = Status::newGood();
556 if ( empty( $params['noAccess'] ) ) {
557 return $status; // nothing to do
560 $stat = $this->getContainerStat( $fullCont );
561 if ( is_array( $stat ) ) {
562 // Make container private to end-users...
563 $status->merge( $this->setContainerAccess(
564 $fullCont,
565 array( $this->swiftUser ), // read
566 array( $this->swiftUser ) // write
567 ) );
568 } elseif ( $stat === false ) {
569 $status->fatal( 'backend-fail-usable', $params['dir'] );
570 } else {
571 $status->fatal( 'backend-fail-internal', $this->name );
572 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
575 return $status;
578 protected function doPublishInternal( $fullCont, $dir, array $params ) {
579 $status = Status::newGood();
581 $stat = $this->getContainerStat( $fullCont );
582 if ( is_array( $stat ) ) {
583 // Make container public to end-users...
584 $status->merge( $this->setContainerAccess(
585 $fullCont,
586 array( $this->swiftUser, '.r:*' ), // read
587 array( $this->swiftUser ) // write
588 ) );
589 } elseif ( $stat === false ) {
590 $status->fatal( 'backend-fail-usable', $params['dir'] );
591 } else {
592 $status->fatal( 'backend-fail-internal', $this->name );
593 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
596 return $status;
599 protected function doCleanInternal( $fullCont, $dir, array $params ) {
600 $status = Status::newGood();
602 // Only containers themselves can be removed, all else is virtual
603 if ( $dir != '' ) {
604 return $status; // nothing to do
607 // (a) Check the container
608 $stat = $this->getContainerStat( $fullCont, true );
609 if ( $stat === false ) {
610 return $status; // ok, nothing to do
611 } elseif ( !is_array( $stat ) ) {
612 $status->fatal( 'backend-fail-internal', $this->name );
613 wfDebugLog( 'SwiftBackend', __METHOD__ . ': cannot get container stat' );
615 return $status;
618 // (b) Delete the container if empty
619 if ( $stat['count'] == 0 ) {
620 $params['op'] = 'clean';
621 $status->merge( $this->deleteContainer( $fullCont, $params ) );
624 return $status;
627 protected function doGetFileStat( array $params ) {
628 $params = array( 'srcs' => array( $params['src'] ), 'concurrency' => 1 ) + $params;
629 unset( $params['src'] );
630 $stats = $this->doGetFileStatMulti( $params );
632 return reset( $stats );
636 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
637 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
638 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
640 * @param string $ts
641 * @param int $format Output format (TS_* constant)
642 * @return string
643 * @throws FileBackendError
645 protected function convertSwiftDate( $ts, $format = TS_MW ) {
646 try {
647 $timestamp = new MWTimestamp( $ts );
649 return $timestamp->getTimestamp( $format );
650 } catch ( MWException $e ) {
651 throw new FileBackendError( $e->getMessage() );
656 * Fill in any missing object metadata and save it to Swift
658 * @param array $objHdrs Object response headers
659 * @param string $path Storage path to object
660 * @return array New headers
662 protected function addMissingMetadata( array $objHdrs, $path ) {
663 if ( isset( $objHdrs['x-object-meta-sha1base36'] ) ) {
664 return $objHdrs; // nothing to do
667 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
668 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING );
670 $auth = $this->getAuthentication();
671 if ( !$auth ) {
672 $objHdrs['x-object-meta-sha1base36'] = false;
674 return $objHdrs; // failed
677 $status = Status::newGood();
678 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
679 if ( $status->isOK() ) {
680 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
681 if ( $tmpFile ) {
682 $hash = $tmpFile->getSha1Base36();
683 if ( $hash !== false ) {
684 $objHdrs['x-object-meta-sha1base36'] = $hash;
685 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
686 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
687 'method' => 'POST',
688 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
689 'headers' => $this->authTokenHeaders( $auth ) + $objHdrs
690 ) );
691 if ( $rcode >= 200 && $rcode <= 299 ) {
692 return $objHdrs; // success
697 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING );
698 $objHdrs['x-object-meta-sha1base36'] = false;
700 return $objHdrs; // failed
703 protected function doGetFileContentsMulti( array $params ) {
704 $contents = array();
706 $auth = $this->getAuthentication();
708 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
709 // Blindly create tmp files and stream to them, catching any exception if the file does
710 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
711 $reqs = array(); // (path => op)
713 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
714 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
715 if ( $srcRel === null || !$auth ) {
716 $contents[$path] = false;
717 continue;
719 // Create a new temporary memory file...
720 $handle = fopen( 'php://temp', 'wb' );
721 if ( $handle ) {
722 $reqs[$path] = array(
723 'method' => 'GET',
724 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
725 'headers' => $this->authTokenHeaders( $auth )
726 + $this->headersFromParams( $params ),
727 'stream' => $handle,
730 $contents[$path] = false;
733 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
734 $reqs = $this->http->runMulti( $reqs, $opts );
735 foreach ( $reqs as $path => $op ) {
736 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
737 if ( $rcode >= 200 && $rcode <= 299 ) {
738 rewind( $op['stream'] ); // start from the beginning
739 $contents[$path] = stream_get_contents( $op['stream'] );
740 } elseif ( $rcode === 404 ) {
741 $contents[$path] = false;
742 } else {
743 $this->onError( null, __METHOD__,
744 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
746 fclose( $op['stream'] ); // close open handle
749 return $contents;
752 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
753 $prefix = ( $dir == '' ) ? null : "{$dir}/";
754 $status = $this->objectListing( $fullCont, 'names', 1, null, $prefix );
755 if ( $status->isOk() ) {
756 return ( count( $status->value ) ) > 0;
759 return null; // error
763 * @see FileBackendStore::getDirectoryListInternal()
764 * @param string $fullCont
765 * @param string $dir
766 * @param array $params
767 * @return SwiftFileBackendDirList
769 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
770 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
774 * @see FileBackendStore::getFileListInternal()
775 * @param string $fullCont
776 * @param string $dir
777 * @param array $params
778 * @return SwiftFileBackendFileList
780 public function getFileListInternal( $fullCont, $dir, array $params ) {
781 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
785 * Do not call this function outside of SwiftFileBackendFileList
787 * @param string $fullCont Resolved container name
788 * @param string $dir Resolved storage directory with no trailing slash
789 * @param string|null $after Resolved container relative path to list items after
790 * @param int $limit Max number of items to list
791 * @param array $params Parameters for getDirectoryList()
792 * @return array List of container relative resolved paths of directories directly under $dir
793 * @throws FileBackendError
795 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
796 $dirs = array();
797 if ( $after === INF ) {
798 return $dirs; // nothing more
801 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
803 $prefix = ( $dir == '' ) ? null : "{$dir}/";
804 // Non-recursive: only list dirs right under $dir
805 if ( !empty( $params['topOnly'] ) ) {
806 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
807 if ( !$status->isOk() ) {
808 return $dirs; // error
810 $objects = $status->value;
811 foreach ( $objects as $object ) { // files and directories
812 if ( substr( $object, -1 ) === '/' ) {
813 $dirs[] = $object; // directories end in '/'
816 } else {
817 // Recursive: list all dirs under $dir and its subdirs
818 $getParentDir = function ( $path ) {
819 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
822 // Get directory from last item of prior page
823 $lastDir = $getParentDir( $after ); // must be first page
824 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
826 if ( !$status->isOk() ) {
827 return $dirs; // error
830 $objects = $status->value;
832 foreach ( $objects as $object ) { // files
833 $objectDir = $getParentDir( $object ); // directory of object
835 if ( $objectDir !== false && $objectDir !== $dir ) {
836 // Swift stores paths in UTF-8, using binary sorting.
837 // See function "create_container_table" in common/db.py.
838 // If a directory is not "greater" than the last one,
839 // then it was already listed by the calling iterator.
840 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
841 $pDir = $objectDir;
842 do { // add dir and all its parent dirs
843 $dirs[] = "{$pDir}/";
844 $pDir = $getParentDir( $pDir );
845 } while ( $pDir !== false // sanity
846 && strcmp( $pDir, $lastDir ) > 0 // not done already
847 && strlen( $pDir ) > strlen( $dir ) // within $dir
850 $lastDir = $objectDir;
854 // Page on the unfiltered directory listing (what is returned may be filtered)
855 if ( count( $objects ) < $limit ) {
856 $after = INF; // avoid a second RTT
857 } else {
858 $after = end( $objects ); // update last item
861 return $dirs;
865 * Do not call this function outside of SwiftFileBackendFileList
867 * @param string $fullCont Resolved container name
868 * @param string $dir Resolved storage directory with no trailing slash
869 * @param string|null $after Resolved container relative path of file to list items after
870 * @param int $limit Max number of items to list
871 * @param array $params Parameters for getDirectoryList()
872 * @return array List of resolved container relative paths of files under $dir
873 * @throws FileBackendError
875 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
876 $files = array(); // list of (path, stat array or null) entries
877 if ( $after === INF ) {
878 return $files; // nothing more
881 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
883 $prefix = ( $dir == '' ) ? null : "{$dir}/";
884 // $objects will contain a list of unfiltered names or CF_Object items
885 // Non-recursive: only list files right under $dir
886 if ( !empty( $params['topOnly'] ) ) {
887 if ( !empty( $params['adviseStat'] ) ) {
888 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix, '/' );
889 } else {
890 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix, '/' );
892 } else {
893 // Recursive: list all files under $dir and its subdirs
894 if ( !empty( $params['adviseStat'] ) ) {
895 $status = $this->objectListing( $fullCont, 'info', $limit, $after, $prefix );
896 } else {
897 $status = $this->objectListing( $fullCont, 'names', $limit, $after, $prefix );
901 // Reformat this list into a list of (name, stat array or null) entries
902 if ( !$status->isOk() ) {
903 return $files; // error
906 $objects = $status->value;
907 $files = $this->buildFileObjectListing( $params, $dir, $objects );
909 // Page on the unfiltered object listing (what is returned may be filtered)
910 if ( count( $objects ) < $limit ) {
911 $after = INF; // avoid a second RTT
912 } else {
913 $after = end( $objects ); // update last item
914 $after = is_object( $after ) ? $after->name : $after;
917 return $files;
921 * Build a list of file objects, filtering out any directories
922 * and extracting any stat info if provided in $objects (for CF_Objects)
924 * @param array $params Parameters for getDirectoryList()
925 * @param string $dir Resolved container directory path
926 * @param array $objects List of CF_Object items or object names
927 * @return array List of (names,stat array or null) entries
929 private function buildFileObjectListing( array $params, $dir, array $objects ) {
930 $names = array();
931 foreach ( $objects as $object ) {
932 if ( is_object( $object ) ) {
933 if ( isset( $object->subdir ) || !isset( $object->name ) ) {
934 continue; // virtual directory entry; ignore
936 $stat = array(
937 // Convert various random Swift dates to TS_MW
938 'mtime' => $this->convertSwiftDate( $object->last_modified, TS_MW ),
939 'size' => (int)$object->bytes,
940 // Note: manifiest ETags are not an MD5 of the file
941 'md5' => ctype_xdigit( $object->hash ) ? $object->hash : null,
942 'latest' => false // eventually consistent
944 $names[] = array( $object->name, $stat );
945 } elseif ( substr( $object, -1 ) !== '/' ) {
946 // Omit directories, which end in '/' in listings
947 $names[] = array( $object, null );
951 return $names;
955 * Do not call this function outside of SwiftFileBackendFileList
957 * @param string $path Storage path
958 * @param array $val Stat value
960 public function loadListingStatInternal( $path, array $val ) {
961 $this->cheapCache->set( $path, 'stat', $val );
964 protected function doGetFileXAttributes( array $params ) {
965 $stat = $this->getFileStat( $params );
966 if ( $stat ) {
967 if ( !isset( $stat['xattr'] ) ) {
968 // Stat entries filled by file listings don't include metadata/headers
969 $this->clearCache( array( $params['src'] ) );
970 $stat = $this->getFileStat( $params );
973 return $stat['xattr'];
974 } else {
975 return false;
979 protected function doGetFileSha1base36( array $params ) {
980 $stat = $this->getFileStat( $params );
981 if ( $stat ) {
982 if ( !isset( $stat['sha1'] ) ) {
983 // Stat entries filled by file listings don't include SHA1
984 $this->clearCache( array( $params['src'] ) );
985 $stat = $this->getFileStat( $params );
988 return $stat['sha1'];
989 } else {
990 return false;
994 protected function doStreamFile( array $params ) {
995 $status = Status::newGood();
997 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
998 if ( $srcRel === null ) {
999 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1002 $auth = $this->getAuthentication();
1003 if ( !$auth || !is_array( $this->getContainerStat( $srcCont ) ) ) {
1004 $status->fatal( 'backend-fail-stream', $params['src'] );
1006 return $status;
1009 $handle = fopen( 'php://output', 'wb' );
1011 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1012 'method' => 'GET',
1013 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1014 'headers' => $this->authTokenHeaders( $auth )
1015 + $this->headersFromParams( $params ),
1016 'stream' => $handle,
1017 ) );
1019 if ( $rcode >= 200 && $rcode <= 299 ) {
1020 // good
1021 } elseif ( $rcode === 404 ) {
1022 $status->fatal( 'backend-fail-stream', $params['src'] );
1023 } else {
1024 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1027 return $status;
1030 protected function doGetLocalCopyMulti( array $params ) {
1031 $tmpFiles = array();
1033 $auth = $this->getAuthentication();
1035 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1036 // Blindly create tmp files and stream to them, catching any exception if the file does
1037 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1038 $reqs = array(); // (path => op)
1040 foreach ( $params['srcs'] as $path ) { // each path in this concurrent batch
1041 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1042 if ( $srcRel === null || !$auth ) {
1043 $tmpFiles[$path] = null;
1044 continue;
1046 // Get source file extension
1047 $ext = FileBackend::extensionFromPath( $path );
1048 // Create a new temporary file...
1049 $tmpFile = TempFSFile::factory( 'localcopy_', $ext );
1050 if ( $tmpFile ) {
1051 $handle = fopen( $tmpFile->getPath(), 'wb' );
1052 if ( $handle ) {
1053 $reqs[$path] = array(
1054 'method' => 'GET',
1055 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1056 'headers' => $this->authTokenHeaders( $auth )
1057 + $this->headersFromParams( $params ),
1058 'stream' => $handle,
1060 } else {
1061 $tmpFile = null;
1064 $tmpFiles[$path] = $tmpFile;
1067 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1068 $reqs = $this->http->runMulti( $reqs, $opts );
1069 foreach ( $reqs as $path => $op ) {
1070 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $op['response'];
1071 fclose( $op['stream'] ); // close open handle
1072 if ( $rcode >= 200 && $rcode <= 299 ) {
1073 $size = $tmpFiles[$path] ? $tmpFiles[$path]->getSize() : 0;
1074 // Double check that the disk is not full/broken
1075 if ( $size != $rhdrs['content-length'] ) {
1076 $tmpFiles[$path] = null;
1077 $rerr = "Got {$size}/{$rhdrs['content-length']} bytes";
1078 $this->onError( null, __METHOD__,
1079 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1081 } elseif ( $rcode === 404 ) {
1082 $tmpFiles[$path] = false;
1083 } else {
1084 $tmpFiles[$path] = null;
1085 $this->onError( null, __METHOD__,
1086 array( 'src' => $path ) + $ep, $rerr, $rcode, $rdesc );
1090 return $tmpFiles;
1093 public function getFileHttpUrl( array $params ) {
1094 if ( $this->swiftTempUrlKey != '' ||
1095 ( $this->rgwS3AccessKey != '' && $this->rgwS3SecretKey != '' )
1097 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1098 if ( $srcRel === null ) {
1099 return null; // invalid path
1102 $auth = $this->getAuthentication();
1103 if ( !$auth ) {
1104 return null;
1107 $ttl = isset( $params['ttl'] ) ? $params['ttl'] : 86400;
1108 $expires = time() + $ttl;
1110 if ( $this->swiftTempUrlKey != '' ) {
1111 $url = $this->storageUrl( $auth, $srcCont, $srcRel );
1112 // Swift wants the signature based on the unencoded object name
1113 $contPath = parse_url( $this->storageUrl( $auth, $srcCont ), PHP_URL_PATH );
1114 $signature = hash_hmac( 'sha1',
1115 "GET\n{$expires}\n{$contPath}/{$srcRel}",
1116 $this->swiftTempUrlKey
1119 return "{$url}?temp_url_sig={$signature}&temp_url_expires={$expires}";
1120 } else { // give S3 API URL for rgw
1121 // Path for signature starts with the bucket
1122 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1123 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1124 // Calculate the hash
1125 $signature = base64_encode( hash_hmac(
1126 'sha1',
1127 "GET\n\n\n{$expires}\n{$spath}",
1128 $this->rgwS3SecretKey,
1129 true // raw
1130 ) );
1131 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1132 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1133 return wfAppendQuery(
1134 str_replace( '/swift/v1', '', // S3 API is the rgw default
1135 $this->storageUrl( $auth ) . $spath ),
1136 array(
1137 'Signature' => $signature,
1138 'Expires' => $expires,
1139 'AWSAccessKeyId' => $this->rgwS3AccessKey )
1144 return null;
1147 protected function directoriesAreVirtual() {
1148 return true;
1152 * Get headers to send to Swift when reading a file based
1153 * on a FileBackend params array, e.g. that of getLocalCopy().
1154 * $params is currently only checked for a 'latest' flag.
1156 * @param array $params
1157 * @return array
1159 protected function headersFromParams( array $params ) {
1160 $hdrs = array();
1161 if ( !empty( $params['latest'] ) ) {
1162 $hdrs['x-newest'] = 'true';
1165 return $hdrs;
1168 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1169 $statuses = array();
1171 $auth = $this->getAuthentication();
1172 if ( !$auth ) {
1173 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1174 $statuses[$index] = Status::newFatal( 'backend-fail-connect', $this->name );
1177 return $statuses;
1180 // Split the HTTP requests into stages that can be done concurrently
1181 $httpReqsByStage = array(); // map of (stage => index => HTTP request)
1182 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1183 $reqs = $fileOpHandle->httpOp;
1184 // Convert the 'url' parameter to an actual URL using $auth
1185 foreach ( $reqs as $stage => &$req ) {
1186 list( $container, $relPath ) = $req['url'];
1187 $req['url'] = $this->storageUrl( $auth, $container, $relPath );
1188 $req['headers'] = isset( $req['headers'] ) ? $req['headers'] : array();
1189 $req['headers'] = $this->authTokenHeaders( $auth ) + $req['headers'];
1190 $httpReqsByStage[$stage][$index] = $req;
1192 $statuses[$index] = Status::newGood();
1195 // Run all requests for the first stage, then the next, and so on
1196 $reqCount = count( $httpReqsByStage );
1197 for ( $stage = 0; $stage < $reqCount; ++$stage ) {
1198 $httpReqs = $this->http->runMulti( $httpReqsByStage[$stage] );
1199 foreach ( $httpReqs as $index => $httpReq ) {
1200 // Run the callback for each request of this operation
1201 $callback = $fileOpHandles[$index]->callback;
1202 call_user_func_array( $callback, array( $httpReq, $statuses[$index] ) );
1203 // On failure, abort all remaining requests for this operation
1204 // (e.g. abort the DELETE request if the COPY request fails for a move)
1205 if ( !$statuses[$index]->isOK() ) {
1206 $stages = count( $fileOpHandles[$index]->httpOp );
1207 for ( $s = ( $stage + 1 ); $s < $stages; ++$s ) {
1208 unset( $httpReqsByStage[$s][$index] );
1214 return $statuses;
1218 * Set read/write permissions for a Swift container.
1220 * @see http://swift.openstack.org/misc.html#acls
1222 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1223 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1225 * @param string $container Resolved Swift container
1226 * @param array $readGrps List of the possible criteria for a request to have
1227 * access to read a container. Each item is one of the following formats:
1228 * - account:user : Grants access if the request is by the given user
1229 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1230 * matches the expression and the request is not for a listing.
1231 * Setting this to '*' effectively makes a container public.
1232 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1233 * matches the expression and the request is for a listing.
1234 * @param array $writeGrps A list of the possible criteria for a request to have
1235 * access to write to a container. Each item is of the following format:
1236 * - account:user : Grants access if the request is by the given user
1237 * @return Status
1239 protected function setContainerAccess( $container, array $readGrps, array $writeGrps ) {
1240 $status = Status::newGood();
1241 $auth = $this->getAuthentication();
1243 if ( !$auth ) {
1244 $status->fatal( 'backend-fail-connect', $this->name );
1246 return $status;
1249 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1250 'method' => 'POST',
1251 'url' => $this->storageUrl( $auth, $container ),
1252 'headers' => $this->authTokenHeaders( $auth ) + array(
1253 'x-container-read' => implode( ',', $readGrps ),
1254 'x-container-write' => implode( ',', $writeGrps )
1256 ) );
1258 if ( $rcode != 204 && $rcode !== 202 ) {
1259 $status->fatal( 'backend-fail-internal', $this->name );
1260 wfDebugLog( 'SwiftBackend', __METHOD__ . ': unexpected rcode value (' . $rcode . ')' );
1263 return $status;
1267 * Get a Swift container stat array, possibly from process cache.
1268 * Use $reCache if the file count or byte count is needed.
1270 * @param string $container Container name
1271 * @param bool $bypassCache Bypass all caches and load from Swift
1272 * @return array|bool|null False on 404, null on failure
1274 protected function getContainerStat( $container, $bypassCache = false ) {
1275 $ps = Profiler::instance()->scopedProfileIn( __METHOD__ . "-{$this->name}" );
1277 if ( $bypassCache ) { // purge cache
1278 $this->containerStatCache->clear( $container );
1279 } elseif ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1280 $this->primeContainerCache( array( $container ) ); // check persistent cache
1282 if ( !$this->containerStatCache->has( $container, 'stat' ) ) {
1283 $auth = $this->getAuthentication();
1284 if ( !$auth ) {
1285 return null;
1288 wfProfileIn( __METHOD__ . "-{$this->name}-miss" );
1289 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1290 'method' => 'HEAD',
1291 'url' => $this->storageUrl( $auth, $container ),
1292 'headers' => $this->authTokenHeaders( $auth )
1293 ) );
1294 wfProfileOut( __METHOD__ . "-{$this->name}-miss" );
1296 if ( $rcode === 204 ) {
1297 $stat = array(
1298 'count' => $rhdrs['x-container-object-count'],
1299 'bytes' => $rhdrs['x-container-bytes-used']
1301 if ( $bypassCache ) {
1302 return $stat;
1303 } else {
1304 $this->containerStatCache->set( $container, 'stat', $stat ); // cache it
1305 $this->setContainerCache( $container, $stat ); // update persistent cache
1307 } elseif ( $rcode === 404 ) {
1308 return false;
1309 } else {
1310 $this->onError( null, __METHOD__,
1311 array( 'cont' => $container ), $rerr, $rcode, $rdesc );
1313 return null;
1317 return $this->containerStatCache->get( $container, 'stat' );
1321 * Create a Swift container
1323 * @param string $container Container name
1324 * @param array $params
1325 * @return Status
1327 protected function createContainer( $container, array $params ) {
1328 $status = Status::newGood();
1330 $auth = $this->getAuthentication();
1331 if ( !$auth ) {
1332 $status->fatal( 'backend-fail-connect', $this->name );
1334 return $status;
1337 // @see SwiftFileBackend::setContainerAccess()
1338 if ( empty( $params['noAccess'] ) ) {
1339 $readGrps = array( '.r:*', $this->swiftUser ); // public
1340 } else {
1341 $readGrps = array( $this->swiftUser ); // private
1343 $writeGrps = array( $this->swiftUser ); // sanity
1345 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1346 'method' => 'PUT',
1347 'url' => $this->storageUrl( $auth, $container ),
1348 'headers' => $this->authTokenHeaders( $auth ) + array(
1349 'x-container-read' => implode( ',', $readGrps ),
1350 'x-container-write' => implode( ',', $writeGrps )
1352 ) );
1354 if ( $rcode === 201 ) { // new
1355 // good
1356 } elseif ( $rcode === 202 ) { // already there
1357 // this shouldn't really happen, but is OK
1358 } else {
1359 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1362 return $status;
1366 * Delete a Swift container
1368 * @param string $container Container name
1369 * @param array $params
1370 * @return Status
1372 protected function deleteContainer( $container, array $params ) {
1373 $status = Status::newGood();
1375 $auth = $this->getAuthentication();
1376 if ( !$auth ) {
1377 $status->fatal( 'backend-fail-connect', $this->name );
1379 return $status;
1382 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1383 'method' => 'DELETE',
1384 'url' => $this->storageUrl( $auth, $container ),
1385 'headers' => $this->authTokenHeaders( $auth )
1386 ) );
1388 if ( $rcode >= 200 && $rcode <= 299 ) { // deleted
1389 $this->containerStatCache->clear( $container ); // purge
1390 } elseif ( $rcode === 404 ) { // not there
1391 // this shouldn't really happen, but is OK
1392 } elseif ( $rcode === 409 ) { // not empty
1393 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc ); // race?
1394 } else {
1395 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1398 return $status;
1402 * Get a list of objects under a container.
1403 * Either just the names or a list of stdClass objects with details can be returned.
1405 * @param string $fullCont
1406 * @param string $type ('info' for a list of object detail maps, 'names' for names only)
1407 * @param int $limit
1408 * @param string|null $after
1409 * @param string|null $prefix
1410 * @param string|null $delim
1411 * @return Status With the list as value
1413 private function objectListing(
1414 $fullCont, $type, $limit, $after = null, $prefix = null, $delim = null
1416 $status = Status::newGood();
1418 $auth = $this->getAuthentication();
1419 if ( !$auth ) {
1420 $status->fatal( 'backend-fail-connect', $this->name );
1422 return $status;
1425 $query = array( 'limit' => $limit );
1426 if ( $type === 'info' ) {
1427 $query['format'] = 'json';
1429 if ( $after !== null ) {
1430 $query['marker'] = $after;
1432 if ( $prefix !== null ) {
1433 $query['prefix'] = $prefix;
1435 if ( $delim !== null ) {
1436 $query['delimiter'] = $delim;
1439 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1440 'method' => 'GET',
1441 'url' => $this->storageUrl( $auth, $fullCont ),
1442 'query' => $query,
1443 'headers' => $this->authTokenHeaders( $auth )
1444 ) );
1446 $params = array( 'cont' => $fullCont, 'prefix' => $prefix, 'delim' => $delim );
1447 if ( $rcode === 200 ) { // good
1448 if ( $type === 'info' ) {
1449 $status->value = FormatJson::decode( trim( $rbody ) );
1450 } else {
1451 $status->value = explode( "\n", trim( $rbody ) );
1453 } elseif ( $rcode === 204 ) {
1454 $status->value = array(); // empty container
1455 } elseif ( $rcode === 404 ) {
1456 $status->value = array(); // no container
1457 } else {
1458 $this->onError( $status, __METHOD__, $params, $rerr, $rcode, $rdesc );
1461 return $status;
1464 protected function doPrimeContainerCache( array $containerInfo ) {
1465 foreach ( $containerInfo as $container => $info ) {
1466 $this->containerStatCache->set( $container, 'stat', $info );
1470 protected function doGetFileStatMulti( array $params ) {
1471 $stats = array();
1473 $auth = $this->getAuthentication();
1475 $reqs = array();
1476 foreach ( $params['srcs'] as $path ) {
1477 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1478 if ( $srcRel === null ) {
1479 $stats[$path] = false;
1480 continue; // invalid storage path
1481 } elseif ( !$auth ) {
1482 $stats[$path] = null;
1483 continue;
1486 // (a) Check the container
1487 $cstat = $this->getContainerStat( $srcCont );
1488 if ( $cstat === false ) {
1489 $stats[$path] = false;
1490 continue; // ok, nothing to do
1491 } elseif ( !is_array( $cstat ) ) {
1492 $stats[$path] = null;
1493 continue;
1496 $reqs[$path] = array(
1497 'method' => 'HEAD',
1498 'url' => $this->storageUrl( $auth, $srcCont, $srcRel ),
1499 'headers' => $this->authTokenHeaders( $auth ) + $this->headersFromParams( $params )
1503 $opts = array( 'maxConnsPerHost' => $params['concurrency'] );
1504 $reqs = $this->http->runMulti( $reqs, $opts );
1506 foreach ( $params['srcs'] as $path ) {
1507 if ( array_key_exists( $path, $stats ) ) {
1508 continue; // some sort of failure above
1510 // (b) Check the file
1511 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $reqs[$path]['response'];
1512 if ( $rcode === 200 || $rcode === 204 ) {
1513 // Update the object if it is missing some headers
1514 $rhdrs = $this->addMissingMetadata( $rhdrs, $path );
1515 // Fetch all of the custom metadata headers
1516 $metadata = array();
1517 foreach ( $rhdrs as $name => $value ) {
1518 if ( strpos( $name, 'x-object-meta-' ) === 0 ) {
1519 $metadata[substr( $name, strlen( 'x-object-meta-' ) )] = $value;
1522 // Fetch all of the custom raw HTTP headers
1523 $headers = $this->sanitizeHdrs( array( 'headers' => $rhdrs ) );
1524 $stat = array(
1525 // Convert various random Swift dates to TS_MW
1526 'mtime' => $this->convertSwiftDate( $rhdrs['last-modified'], TS_MW ),
1527 // Empty objects actually return no content-length header in Ceph
1528 'size' => isset( $rhdrs['content-length'] ) ? (int)$rhdrs['content-length'] : 0,
1529 'sha1' => $rhdrs['x-object-meta-sha1base36'],
1530 // Note: manifiest ETags are not an MD5 of the file
1531 'md5' => ctype_xdigit( $rhdrs['etag'] ) ? $rhdrs['etag'] : null,
1532 'xattr' => array( 'metadata' => $metadata, 'headers' => $headers )
1534 if ( $this->isRGW ) {
1535 $stat['latest'] = true; // strong consistency
1537 } elseif ( $rcode === 404 ) {
1538 $stat = false;
1539 } else {
1540 $stat = null;
1541 $this->onError( null, __METHOD__, $params, $rerr, $rcode, $rdesc );
1543 $stats[$path] = $stat;
1546 return $stats;
1550 * @return array|null Credential map
1552 protected function getAuthentication() {
1553 if ( $this->authErrorTimestamp !== null ) {
1554 if ( ( time() - $this->authErrorTimestamp ) < 60 ) {
1555 return null; // failed last attempt; don't bother
1556 } else { // actually retry this time
1557 $this->authErrorTimestamp = null;
1560 // Session keys expire after a while, so we renew them periodically
1561 $reAuth = ( ( time() - $this->authSessionTimestamp ) > $this->authTTL );
1562 // Authenticate with proxy and get a session key...
1563 if ( !$this->authCreds || $reAuth ) {
1564 $this->authSessionTimestamp = 0;
1565 $cacheKey = $this->getCredsCacheKey( $this->swiftUser );
1566 $creds = $this->srvCache->get( $cacheKey ); // credentials
1567 // Try to use the credential cache
1568 if ( isset( $creds['auth_token'] ) && isset( $creds['storage_url'] ) ) {
1569 $this->authCreds = $creds;
1570 // Skew the timestamp for worst case to avoid using stale credentials
1571 $this->authSessionTimestamp = time() - ceil( $this->authTTL / 2 );
1572 } else { // cache miss
1573 list( $rcode, $rdesc, $rhdrs, $rbody, $rerr ) = $this->http->run( array(
1574 'method' => 'GET',
1575 'url' => "{$this->swiftAuthUrl}/v1.0",
1576 'headers' => array(
1577 'x-auth-user' => $this->swiftUser,
1578 'x-auth-key' => $this->swiftKey
1580 ) );
1582 if ( $rcode >= 200 && $rcode <= 299 ) { // OK
1583 $this->authCreds = array(
1584 'auth_token' => $rhdrs['x-auth-token'],
1585 'storage_url' => $rhdrs['x-storage-url']
1587 $this->srvCache->set( $cacheKey, $this->authCreds, ceil( $this->authTTL / 2 ) );
1588 $this->authSessionTimestamp = time();
1589 } elseif ( $rcode === 401 ) {
1590 $this->onError( null, __METHOD__, array(), "Authentication failed.", $rcode );
1591 $this->authErrorTimestamp = time();
1593 return null;
1594 } else {
1595 $this->onError( null, __METHOD__, array(), "HTTP return code: $rcode", $rcode );
1596 $this->authErrorTimestamp = time();
1598 return null;
1601 // Ceph RGW does not use <account> in URLs (OpenStack Swift uses "/v1/<account>")
1602 if ( substr( $this->authCreds['storage_url'], -3 ) === '/v1' ) {
1603 $this->isRGW = true; // take advantage of strong consistency
1607 return $this->authCreds;
1611 * @param array $creds From getAuthentication()
1612 * @param string $container
1613 * @param string $object
1614 * @return array
1616 protected function storageUrl( array $creds, $container = null, $object = null ) {
1617 $parts = array( $creds['storage_url'] );
1618 if ( strlen( $container ) ) {
1619 $parts[] = rawurlencode( $container );
1621 if ( strlen( $object ) ) {
1622 $parts[] = str_replace( "%2F", "/", rawurlencode( $object ) );
1625 return implode( '/', $parts );
1629 * @param array $creds From getAuthentication()
1630 * @return array
1632 protected function authTokenHeaders( array $creds ) {
1633 return array( 'x-auth-token' => $creds['auth_token'] );
1637 * Get the cache key for a container
1639 * @param string $username
1640 * @return string
1642 private function getCredsCacheKey( $username ) {
1643 return 'swiftcredentials:' . md5( $username . ':' . $this->swiftAuthUrl );
1647 * Log an unexpected exception for this backend.
1648 * This also sets the Status object to have a fatal error.
1650 * @param Status|null $status
1651 * @param string $func
1652 * @param array $params
1653 * @param string $err Error string
1654 * @param int $code HTTP status
1655 * @param string $desc HTTP status description
1657 public function onError( $status, $func, array $params, $err = '', $code = 0, $desc = '' ) {
1658 if ( $status instanceof Status ) {
1659 $status->fatal( 'backend-fail-internal', $this->name );
1661 if ( $code == 401 ) { // possibly a stale token
1662 $this->srvCache->delete( $this->getCredsCacheKey( $this->swiftUser ) );
1664 wfDebugLog( 'SwiftBackend',
1665 "HTTP $code ($desc) in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1666 ( $err ? ": $err" : "" )
1672 * @see FileBackendStoreOpHandle
1674 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1675 /** @var array List of Requests for MultiHttpClient */
1676 public $httpOp;
1677 /** @var Closure */
1678 public $callback;
1681 * @param SwiftFileBackend $backend
1682 * @param Closure $callback Function that takes (HTTP request array, status)
1683 * @param array $httpOp MultiHttpClient op
1685 public function __construct( SwiftFileBackend $backend, Closure $callback, array $httpOp ) {
1686 $this->backend = $backend;
1687 $this->callback = $callback;
1688 $this->httpOp = $httpOp;
1693 * SwiftFileBackend helper class to page through listings.
1694 * Swift also has a listing limit of 10,000 objects for sanity.
1695 * Do not use this class from places outside SwiftFileBackend.
1697 * @ingroup FileBackend
1699 abstract class SwiftFileBackendList implements Iterator {
1700 /** @var array List of path or (path,stat array) entries */
1701 protected $bufferIter = array();
1703 /** @var string List items *after* this path */
1704 protected $bufferAfter = null;
1706 /** @var int */
1707 protected $pos = 0;
1709 /** @var array */
1710 protected $params = array();
1712 /** @var SwiftFileBackend */
1713 protected $backend;
1715 /** @var string Container name */
1716 protected $container;
1718 /** @var string Storage directory */
1719 protected $dir;
1721 /** @var int */
1722 protected $suffixStart;
1724 const PAGE_SIZE = 9000; // file listing buffer size
1727 * @param SwiftFileBackend $backend
1728 * @param string $fullCont Resolved container name
1729 * @param string $dir Resolved directory relative to container
1730 * @param array $params
1732 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1733 $this->backend = $backend;
1734 $this->container = $fullCont;
1735 $this->dir = $dir;
1736 if ( substr( $this->dir, -1 ) === '/' ) {
1737 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1739 if ( $this->dir == '' ) { // whole container
1740 $this->suffixStart = 0;
1741 } else { // dir within container
1742 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1744 $this->params = $params;
1748 * @see Iterator::key()
1749 * @return int
1751 public function key() {
1752 return $this->pos;
1756 * @see Iterator::next()
1758 public function next() {
1759 // Advance to the next file in the page
1760 next( $this->bufferIter );
1761 ++$this->pos;
1762 // Check if there are no files left in this page and
1763 // advance to the next page if this page was not empty.
1764 if ( !$this->valid() && count( $this->bufferIter ) ) {
1765 $this->bufferIter = $this->pageFromList(
1766 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1767 ); // updates $this->bufferAfter
1772 * @see Iterator::rewind()
1774 public function rewind() {
1775 $this->pos = 0;
1776 $this->bufferAfter = null;
1777 $this->bufferIter = $this->pageFromList(
1778 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1779 ); // updates $this->bufferAfter
1783 * @see Iterator::valid()
1784 * @return bool
1786 public function valid() {
1787 if ( $this->bufferIter === null ) {
1788 return false; // some failure?
1789 } else {
1790 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1795 * Get the given list portion (page)
1797 * @param string $container Resolved container name
1798 * @param string $dir Resolved path relative to container
1799 * @param string $after
1800 * @param int $limit
1801 * @param array $params
1802 * @return Traversable|array
1804 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1808 * Iterator for listing directories
1810 class SwiftFileBackendDirList extends SwiftFileBackendList {
1812 * @see Iterator::current()
1813 * @return string|bool String (relative path) or false
1815 public function current() {
1816 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1819 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1820 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1825 * Iterator for listing regular files
1827 class SwiftFileBackendFileList extends SwiftFileBackendList {
1829 * @see Iterator::current()
1830 * @return string|bool String (relative path) or false
1832 public function current() {
1833 list( $path, $stat ) = current( $this->bufferIter );
1834 $relPath = substr( $path, $this->suffixStart );
1835 if ( is_array( $stat ) ) {
1836 $storageDir = rtrim( $this->params['dir'], '/' );
1837 $this->backend->loadListingStatInternal( "$storageDir/$relPath", $stat );
1840 return $relPath;
1843 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1844 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );