3 * OpenStack Swift based file backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 * @author Aaron Schulz
27 * @brief Class for an OpenStack Swift (or Ceph RGW) based file backend.
29 * This requires the SwiftCloudFiles MediaWiki extension, which includes
30 * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
31 * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
33 * Status messages should avoid mentioning the Swift account name.
34 * Likewise, error suppression should be used to avoid path disclosure.
36 * @ingroup FileBackend
39 class SwiftFileBackend
extends FileBackendStore
{
40 /** @var CF_Authentication Swift authentication handler */
43 /** @var int TTL in seconds */
46 /** @var string Shared secret value for making temp URLs */
47 protected $swiftTempUrlKey;
49 /** @var string Username to handle unauthenticated requests */
50 protected $swiftAnonUser;
52 /** @var bool Whether CloudFiles CDN is enabled */
53 protected $swiftUseCDN;
55 /** @var int How long to cache things in the CDN */
56 protected $swiftCDNExpiry;
58 /** @var bool Whether object CDN purging is enabled */
59 protected $swiftCDNPurgable;
61 // Rados Gateway specific options
62 /** @var string S3 access key */
63 protected $rgwS3AccessKey;
65 /** @var string S3 authentication key */
66 protected $rgwS3SecretKey;
68 /** @var CF_Connection Swift connection handle*/
71 /** @var int UNIX timestamp */
72 protected $sessionStarted = 0;
74 /** @var CloudFilesException */
75 protected $connException;
77 /** @var int UNIX timestamp */
78 protected $connErrorTime = 0;
83 /** @var ProcessCacheLRU */
84 protected $connContainerCache; // container object cache
87 * @see FileBackendStore::__construct()
88 * Additional $config params include:
89 * - swiftAuthUrl : Swift authentication server URL
90 * - swiftUser : Swift user used by MediaWiki (account:username)
91 * - swiftKey : Swift authentication key for the above user
92 * - swiftAuthTTL : Swift authentication TTL (seconds)
93 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
94 * Do not set this until it has been set in the backend.
95 * - swiftAnonUser : Swift user used for end-user requests (account:username).
96 * If set, then views of public containers are assumed to go
97 * through this user. If not set, then public containers are
98 * accessible to unauthenticated requests via ".r:*" in the ACL.
99 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
100 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
101 * If files may likely change, this should probably not exceed
102 * a few days. For example, deletions may take this long to apply.
103 * If object purging is enabled, however, this is not an issue.
104 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
105 * - shardViaHashLevels : Map of container names to sharding config with:
106 * - base : base of hash characters, 16 or 36
107 * - levels : the number of hash levels (and digits)
108 * - repeat : hash subdirectories are prefixed with all the
109 * parent hash directory names (e.g. "a/ab/abc")
110 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
111 * If those are not available, then the main cache will be used.
112 * This is probably insecure in shared hosting environments.
113 * - rgwS3AccessKey : Ragos Gateway S3 "access key" value on the account.
114 * Do not set this until it has been set in the backend.
115 * This is used for generating expiring pre-authenticated URLs.
116 * Only use this when using rgw and to work around
117 * http://tracker.newdream.net/issues/3454.
118 * - rgwS3SecretKey : Ragos Gateway S3 "secret key" value on the account.
119 * Do not set this until it has been set in the backend.
120 * This is used for generating expiring pre-authenticated URLs.
121 * Only use this when using rgw and to work around
122 * http://tracker.newdream.net/issues/3454.
124 public function __construct( array $config ) {
125 parent
::__construct( $config );
126 if ( !class_exists( 'CF_Constants' ) ) {
127 throw new MWException( 'SwiftCloudFiles extension not installed.' );
130 $this->auth
= new CF_Authentication(
131 $config['swiftUser'],
133 null, // account; unused
134 $config['swiftAuthUrl']
137 $this->authTTL
= isset( $config['swiftAuthTTL'] )
138 ?
$config['swiftAuthTTL']
139 : 5 * 60; // some sane number
140 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
141 ?
$config['swiftAnonUser']
143 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
144 ?
$config['swiftTempUrlKey']
146 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
147 ?
$config['shardViaHashLevels']
149 $this->swiftUseCDN
= isset( $config['swiftUseCDN'] )
150 ?
$config['swiftUseCDN']
152 $this->swiftCDNExpiry
= isset( $config['swiftCDNExpiry'] )
153 ?
$config['swiftCDNExpiry']
154 : 12 * 3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
155 $this->swiftCDNPurgable
= isset( $config['swiftCDNPurgable'] )
156 ?
$config['swiftCDNPurgable']
158 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
159 ?
$config['rgwS3AccessKey']
161 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
162 ?
$config['rgwS3SecretKey']
164 // Cache container information to mask latency
165 $this->memCache
= wfGetMainCache();
166 // Process cache for container info
167 $this->connContainerCache
= new ProcessCacheLRU( 300 );
168 // Cache auth token information to avoid RTTs
169 if ( !empty( $config['cacheAuthInfo'] ) ) {
170 if ( PHP_SAPI
=== 'cli' ) {
171 $this->srvCache
= wfGetMainCache(); // preferrably memcached
173 try { // look for APC, XCache, WinCache, ect...
174 $this->srvCache
= ObjectCache
::newAccelerator( array() );
175 } catch ( Exception
$e ) {
179 $this->srvCache
= $this->srvCache ?
$this->srvCache
: new EmptyBagOStuff();
183 * @see FileBackendStore::resolveContainerPath()
184 * @param string $container
185 * @param string $relStoragePath
186 * @return string|null Returns null when the URL encoded storage path is
187 * longer than 1024 characters or not UTF-8 encoded.
189 protected function resolveContainerPath( $container, $relStoragePath ) {
190 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
191 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
192 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
193 return null; // too long for Swift
196 return $relStoragePath;
199 public function isPathUsableInternal( $storagePath ) {
200 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
201 if ( $rel === null ) {
202 return false; // invalid
206 $this->getContainer( $container );
208 return true; // container exists
209 } catch ( NoSuchContainerException
$e ) {
210 } catch ( CloudFilesException
$e ) { // some other exception?
211 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
218 * @param array $headers
221 protected function sanitizeHdrs( array $headers ) {
222 // By default, Swift has annoyingly low maximum header value limits
223 if ( isset( $headers['Content-Disposition'] ) ) {
224 $headers['Content-Disposition'] = $this->truncDisp( $headers['Content-Disposition'] );
231 * @param string $disposition Content-Disposition header value
232 * @return string Truncated Content-Disposition header value to meet Swift limits
234 protected function truncDisp( $disposition ) {
236 foreach ( explode( ';', $disposition ) as $part ) {
237 $part = trim( $part );
238 $new = ( $res === '' ) ?
$part : "{$res};{$part}";
239 if ( strlen( $new ) <= 255 ) {
242 break; // too long; sigh
249 protected function doCreateInternal( array $params ) {
250 $status = Status
::newGood();
252 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
253 if ( $dstRel === null ) {
254 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
259 // (a) Check the destination container and object
261 $dContObj = $this->getContainer( $dstCont );
262 } catch ( NoSuchContainerException
$e ) {
263 $status->fatal( 'backend-fail-create', $params['dst'] );
266 } catch ( CloudFilesException
$e ) { // some other exception?
267 $this->handleException( $e, $status, __METHOD__
, $params );
272 // (b) Get a SHA-1 hash of the object
273 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
275 // (c) Actually create the object
277 // Create a fresh CF_Object with no fields preloaded.
278 // We don't want to preserve headers, metadata, and such.
279 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
280 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
281 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
282 // The MD5 here will be checked within Swift against its own MD5.
283 $obj->set_etag( md5( $params['content'] ) );
284 // Use the same content type as StreamFile for security
285 $obj->content_type
= $this->getContentType( $params['dst'], $params['content'], null );
286 // Set any other custom headers if requested
287 if ( isset( $params['headers'] ) ) {
288 $obj->headers +
= $this->sanitizeHdrs( $params['headers'] );
290 if ( !empty( $params['async'] ) ) { // deferred
291 $op = $obj->write_async( $params['content'] );
292 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $op );
293 $status->value
->affectedObjects
[] = $obj;
294 } else { // actually write the object in Swift
295 $obj->write( $params['content'] );
296 $this->purgeCDNCache( array( $obj ) );
298 } catch ( CDNNotEnabledException
$e ) {
299 // CDN not enabled; nothing to see here
300 } catch ( BadContentTypeException
$e ) {
301 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
302 } catch ( CloudFilesException
$e ) { // some other exception?
303 $this->handleException( $e, $status, __METHOD__
, $params );
310 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
312 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
314 $cfOp->getLastResponse();
315 } catch ( BadContentTypeException
$e ) {
316 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
320 protected function doStoreInternal( array $params ) {
321 $status = Status
::newGood();
323 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
324 if ( $dstRel === null ) {
325 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
330 // (a) Check the destination container and object
332 $dContObj = $this->getContainer( $dstCont );
333 } catch ( NoSuchContainerException
$e ) {
334 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
337 } catch ( CloudFilesException
$e ) { // some other exception?
338 $this->handleException( $e, $status, __METHOD__
, $params );
343 // (b) Get a SHA-1 hash of the object
344 wfSuppressWarnings();
345 $sha1Hash = sha1_file( $params['src'] );
347 if ( $sha1Hash === false ) { // source doesn't exist?
348 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
352 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
354 // (c) Actually store the object
356 // Create a fresh CF_Object with no fields preloaded.
357 // We don't want to preserve headers, metadata, and such.
358 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
359 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
360 // The MD5 here will be checked within Swift against its own MD5.
361 $obj->set_etag( md5_file( $params['src'] ) );
362 // Use the same content type as StreamFile for security
363 $obj->content_type
= $this->getContentType( $params['dst'], null, $params['src'] );
364 // Set any other custom headers if requested
365 if ( isset( $params['headers'] ) ) {
366 $obj->headers +
= $this->sanitizeHdrs( $params['headers'] );
368 if ( !empty( $params['async'] ) ) { // deferred
369 wfSuppressWarnings();
370 $fp = fopen( $params['src'], 'rb' );
373 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
375 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
376 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $op );
377 $status->value
->resourcesToClose
[] = $fp;
378 $status->value
->affectedObjects
[] = $obj;
380 } else { // actually write the object in Swift
381 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
382 $this->purgeCDNCache( array( $obj ) );
384 } catch ( CDNNotEnabledException
$e ) {
385 // CDN not enabled; nothing to see here
386 } catch ( BadContentTypeException
$e ) {
387 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
388 } catch ( IOException
$e ) {
389 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
390 } catch ( CloudFilesException
$e ) { // some other exception?
391 $this->handleException( $e, $status, __METHOD__
, $params );
398 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
400 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
402 $cfOp->getLastResponse();
403 } catch ( BadContentTypeException
$e ) {
404 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
405 } catch ( IOException
$e ) {
406 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
410 protected function doCopyInternal( array $params ) {
411 $status = Status
::newGood();
413 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
414 if ( $srcRel === null ) {
415 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
420 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
421 if ( $dstRel === null ) {
422 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
427 // (a) Check the source/destination containers and destination object
429 $sContObj = $this->getContainer( $srcCont );
430 $dContObj = $this->getContainer( $dstCont );
431 } catch ( NoSuchContainerException
$e ) {
432 if ( empty( $params['ignoreMissingSource'] ) ||
isset( $sContObj ) ) {
433 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
437 } catch ( CloudFilesException
$e ) { // some other exception?
438 $this->handleException( $e, $status, __METHOD__
, $params );
443 // (b) Actually copy the file to the destination
445 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
446 $hdrs = array(); // source file headers to override with new values
447 // Set any other custom headers if requested
448 if ( isset( $params['headers'] ) ) {
449 $hdrs +
= $this->sanitizeHdrs( $params['headers'] );
451 if ( !empty( $params['async'] ) ) { // deferred
452 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
453 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $op );
454 $status->value
->affectedObjects
[] = $dstObj;
455 } else { // actually write the object in Swift
456 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
457 $this->purgeCDNCache( array( $dstObj ) );
459 } catch ( CDNNotEnabledException
$e ) {
460 // CDN not enabled; nothing to see here
461 } catch ( NoSuchObjectException
$e ) { // source object does not exist
462 if ( empty( $params['ignoreMissingSource'] ) ) {
463 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
465 } catch ( CloudFilesException
$e ) { // some other exception?
466 $this->handleException( $e, $status, __METHOD__
, $params );
473 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
475 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
477 $cfOp->getLastResponse();
478 } catch ( NoSuchObjectException
$e ) { // source object does not exist
479 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
483 protected function doMoveInternal( array $params ) {
484 $status = Status
::newGood();
486 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
487 if ( $srcRel === null ) {
488 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
493 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
494 if ( $dstRel === null ) {
495 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
500 // (a) Check the source/destination containers and destination object
502 $sContObj = $this->getContainer( $srcCont );
503 $dContObj = $this->getContainer( $dstCont );
504 } catch ( NoSuchContainerException
$e ) {
505 if ( empty( $params['ignoreMissingSource'] ) ||
isset( $sContObj ) ) {
506 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
510 } catch ( CloudFilesException
$e ) { // some other exception?
511 $this->handleException( $e, $status, __METHOD__
, $params );
516 // (b) Actually move the file to the destination
518 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
519 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
520 $hdrs = array(); // source file headers to override with new values
521 // Set any other custom headers if requested
522 if ( isset( $params['headers'] ) ) {
523 $hdrs +
= $this->sanitizeHdrs( $params['headers'] );
525 if ( !empty( $params['async'] ) ) { // deferred
526 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
527 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
528 $status->value
->affectedObjects
[] = $srcObj;
529 $status->value
->affectedObjects
[] = $dstObj;
530 } else { // actually write the object in Swift
531 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
532 $this->purgeCDNCache( array( $srcObj ) );
533 $this->purgeCDNCache( array( $dstObj ) );
535 } catch ( CDNNotEnabledException
$e ) {
536 // CDN not enabled; nothing to see here
537 } catch ( NoSuchObjectException
$e ) { // source object does not exist
538 if ( empty( $params['ignoreMissingSource'] ) ) {
539 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
541 } catch ( CloudFilesException
$e ) { // some other exception?
542 $this->handleException( $e, $status, __METHOD__
, $params );
549 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
551 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
553 $cfOp->getLastResponse();
554 } catch ( NoSuchObjectException
$e ) { // source object does not exist
555 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
559 protected function doDeleteInternal( array $params ) {
560 $status = Status
::newGood();
562 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
563 if ( $srcRel === null ) {
564 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
570 $sContObj = $this->getContainer( $srcCont );
571 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
572 if ( !empty( $params['async'] ) ) { // deferred
573 $op = $sContObj->delete_object_async( $srcRel );
574 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
575 $status->value
->affectedObjects
[] = $srcObj;
576 } else { // actually write the object in Swift
577 $sContObj->delete_object( $srcRel );
578 $this->purgeCDNCache( array( $srcObj ) );
580 } catch ( CDNNotEnabledException
$e ) {
581 // CDN not enabled; nothing to see here
582 } catch ( NoSuchContainerException
$e ) {
583 if ( empty( $params['ignoreMissingSource'] ) ) {
584 $status->fatal( 'backend-fail-delete', $params['src'] );
586 } catch ( NoSuchObjectException
$e ) {
587 if ( empty( $params['ignoreMissingSource'] ) ) {
588 $status->fatal( 'backend-fail-delete', $params['src'] );
590 } catch ( CloudFilesException
$e ) { // some other exception?
591 $this->handleException( $e, $status, __METHOD__
, $params );
598 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
600 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
602 $cfOp->getLastResponse();
603 } catch ( NoSuchContainerException
$e ) {
604 $status->fatal( 'backend-fail-delete', $params['src'] );
605 } catch ( NoSuchObjectException
$e ) {
606 if ( empty( $params['ignoreMissingSource'] ) ) {
607 $status->fatal( 'backend-fail-delete', $params['src'] );
612 protected function doDescribeInternal( array $params ) {
613 $status = Status
::newGood();
615 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
616 if ( $srcRel === null ) {
617 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
623 $sContObj = $this->getContainer( $srcCont );
624 // Get the latest version of the current metadata
625 $srcObj = $sContObj->get_object( $srcRel,
626 $this->headersFromParams( array( 'latest' => true ) ) );
627 // Merge in the metadata updates...
628 if ( isset( $params['headers'] ) ) {
629 $srcObj->headers
= $this->sanitizeHdrs( $params['headers'] ) +
$srcObj->headers
;
631 $srcObj->sync_metadata(); // save to Swift
632 $this->purgeCDNCache( array( $srcObj ) );
633 } catch ( CDNNotEnabledException
$e ) {
634 // CDN not enabled; nothing to see here
635 } catch ( NoSuchContainerException
$e ) {
636 $status->fatal( 'backend-fail-describe', $params['src'] );
637 } catch ( NoSuchObjectException
$e ) {
638 $status->fatal( 'backend-fail-describe', $params['src'] );
639 } catch ( CloudFilesException
$e ) { // some other exception?
640 $this->handleException( $e, $status, __METHOD__
, $params );
646 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
647 $status = Status
::newGood();
649 // (a) Check if container already exists
651 $this->getContainer( $fullCont );
653 // NoSuchContainerException not thrown: container must exist
654 return $status; // already exists
655 } catch ( NoSuchContainerException
$e ) {
656 // NoSuchContainerException thrown: container does not exist
657 } catch ( CloudFilesException
$e ) { // some other exception?
658 $this->handleException( $e, $status, __METHOD__
, $params );
663 // (b) Create container as needed
665 $contObj = $this->createContainer( $fullCont );
666 if ( !empty( $params['noAccess'] ) ) {
667 // Make container private to end-users...
668 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
670 // Make container public to end-users...
671 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
673 if ( $this->swiftUseCDN
) { // Rackspace style CDN
674 $contObj->make_public( $this->swiftCDNExpiry
);
676 } catch ( CDNNotEnabledException
$e ) {
677 // CDN not enabled; nothing to see here
678 } catch ( CloudFilesException
$e ) { // some other exception?
679 $this->handleException( $e, $status, __METHOD__
, $params );
688 * @see FileBackendStore::doSecureInternal()
689 * @param string $fullCont
691 * @param array $params
694 protected function doSecureInternal( $fullCont, $dir, array $params ) {
695 $status = Status
::newGood();
696 if ( empty( $params['noAccess'] ) ) {
697 return $status; // nothing to do
700 // Restrict container from end-users...
702 // doPrepareInternal() should have been called,
703 // so the Swift container should already exist...
704 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
705 // NoSuchContainerException not thrown: container must exist
707 // Make container private to end-users...
708 $status->merge( $this->setContainerAccess(
710 array( $this->auth
->username
), // read
711 array( $this->auth
->username
) // write
713 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
714 $contObj->make_private();
716 } catch ( CDNNotEnabledException
$e ) {
717 // CDN not enabled; nothing to see here
718 } catch ( CloudFilesException
$e ) { // some other exception?
719 $this->handleException( $e, $status, __METHOD__
, $params );
726 * @see FileBackendStore::doPublishInternal()
727 * @param string $fullCont
729 * @param array $params
732 protected function doPublishInternal( $fullCont, $dir, array $params ) {
733 $status = Status
::newGood();
735 // Unrestrict container from end-users...
737 // doPrepareInternal() should have been called,
738 // so the Swift container should already exist...
739 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
740 // NoSuchContainerException not thrown: container must exist
742 // Make container public to end-users...
743 if ( $this->swiftAnonUser
!= '' ) {
744 $status->merge( $this->setContainerAccess(
746 array( $this->auth
->username
, $this->swiftAnonUser
), // read
747 array( $this->auth
->username
, $this->swiftAnonUser
) // write
750 $status->merge( $this->setContainerAccess(
752 array( $this->auth
->username
, '.r:*' ), // read
753 array( $this->auth
->username
) // write
756 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
757 $contObj->make_public();
759 } catch ( CDNNotEnabledException
$e ) {
760 // CDN not enabled; nothing to see here
761 } catch ( CloudFilesException
$e ) { // some other exception?
762 $this->handleException( $e, $status, __METHOD__
, $params );
768 protected function doCleanInternal( $fullCont, $dir, array $params ) {
769 $status = Status
::newGood();
771 // Only containers themselves can be removed, all else is virtual
773 return $status; // nothing to do
776 // (a) Check the container
778 $contObj = $this->getContainer( $fullCont, true );
779 } catch ( NoSuchContainerException
$e ) {
780 return $status; // ok, nothing to do
781 } catch ( CloudFilesException
$e ) { // some other exception?
782 $this->handleException( $e, $status, __METHOD__
, $params );
787 // (b) Delete the container if empty
788 if ( $contObj->object_count
== 0 ) {
790 $this->deleteContainer( $fullCont );
791 } catch ( NoSuchContainerException
$e ) {
792 return $status; // race?
793 } catch ( NonEmptyContainerException
$e ) {
794 return $status; // race? consistency delay?
795 } catch ( CloudFilesException
$e ) { // some other exception?
796 $this->handleException( $e, $status, __METHOD__
, $params );
805 protected function doGetFileStat( array $params ) {
806 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
807 if ( $srcRel === null ) {
808 return false; // invalid storage path
813 $contObj = $this->getContainer( $srcCont );
814 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
815 $this->addMissingMetadata( $srcObj, $params['src'] );
817 // Convert various random Swift dates to TS_MW
818 'mtime' => $this->convertSwiftDate( $srcObj->last_modified
, TS_MW
),
819 'size' => (int)$srcObj->content_length
,
820 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
822 } catch ( NoSuchContainerException
$e ) {
823 } catch ( NoSuchObjectException
$e ) {
824 } catch ( CloudFilesException
$e ) { // some other exception?
826 $this->handleException( $e, null, __METHOD__
, $params );
833 * Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT"/"2013-05-11T07:37:27.678360Z".
834 * Dates might also come in like "2013-05-11T07:37:27.678360" from Swift listings,
835 * missing the timezone suffix (though Ceph RGW does not appear to have this bug).
838 * @param int $format Output format (TS_* constant)
840 * @throws MWException
842 protected function convertSwiftDate( $ts, $format = TS_MW
) {
843 $timestamp = new MWTimestamp( $ts );
845 return $timestamp->getTimestamp( $format );
849 * Fill in any missing object metadata and save it to Swift
851 * @param CF_Object $obj
852 * @param string $path Storage path to object
853 * @return bool Success
854 * @throws Exception cloudfiles exceptions
856 protected function addMissingMetadata( CF_Object
$obj, $path ) {
857 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
858 return true; // nothing to do
860 wfProfileIn( __METHOD__
);
861 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
862 $status = Status
::newGood();
863 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
864 if ( $status->isOK() ) {
865 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
867 $hash = $tmpFile->getSha1Base36();
868 if ( $hash !== false ) {
869 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
870 $obj->sync_metadata(); // save to Swift
871 wfProfileOut( __METHOD__
);
873 return true; // success
877 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING
);
878 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
879 wfProfileOut( __METHOD__
);
881 return false; // failed
884 protected function doGetFileContentsMulti( array $params ) {
887 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
888 // Blindly create tmp files and stream to them, catching any exception if the file does
889 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
890 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
891 $cfOps = array(); // (path => CF_Async_Op)
893 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
894 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
895 if ( $srcRel === null ) {
896 $contents[$path] = false;
901 $sContObj = $this->getContainer( $srcCont );
902 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
903 // Create a new temporary memory file...
904 $handle = fopen( 'php://temp', 'wb' );
906 $headers = $this->headersFromParams( $params );
907 if ( count( $pathBatch ) > 1 ) {
908 $cfOps[$path] = $obj->stream_async( $handle, $headers );
909 $cfOps[$path]->_file_handle
= $handle; // close this later
911 $obj->stream( $handle, $headers );
912 rewind( $handle ); // start from the beginning
913 $data = stream_get_contents( $handle );
919 } catch ( NoSuchContainerException
$e ) {
921 } catch ( NoSuchObjectException
$e ) {
923 } catch ( CloudFilesException
$e ) { // some other exception?
925 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
927 $contents[$path] = $data;
930 $batch = new CF_Async_Op_Batch( $cfOps );
931 $cfOps = $batch->execute();
932 foreach ( $cfOps as $path => $cfOp ) {
934 $cfOp->getLastResponse();
935 rewind( $cfOp->_file_handle
); // start from the beginning
936 $contents[$path] = stream_get_contents( $cfOp->_file_handle
);
937 } catch ( NoSuchContainerException
$e ) {
938 $contents[$path] = false;
939 } catch ( NoSuchObjectException
$e ) {
940 $contents[$path] = false;
941 } catch ( CloudFilesException
$e ) { // some other exception?
942 $contents[$path] = false;
943 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
945 fclose( $cfOp->_file_handle
); // close open handle
953 * @see FileBackendStore::doDirectoryExists()
954 * @param string $fullCont
956 * @param array $params
959 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
961 $container = $this->getContainer( $fullCont );
962 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
964 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
965 } catch ( NoSuchContainerException
$e ) {
967 } catch ( CloudFilesException
$e ) { // some other exception?
968 $this->handleException( $e, null, __METHOD__
,
969 array( 'cont' => $fullCont, 'dir' => $dir ) );
972 return null; // error
976 * @see FileBackendStore::getDirectoryListInternal()
977 * @param string $fullCont
979 * @param array $params
980 * @return SwiftFileBackendDirList
982 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
983 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
987 * @see FileBackendStore::getFileListInternal()
988 * @param string $fullCont
990 * @param array $params
991 * @return SwiftFileBackendFileList
993 public function getFileListInternal( $fullCont, $dir, array $params ) {
994 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
998 * Do not call this function outside of SwiftFileBackendFileList
1000 * @param string $fullCont Resolved container name
1001 * @param string $dir Resolved storage directory with no trailing slash
1002 * @param string|null $after Resolved container relative path to list items after
1003 * @param int $limit Max number of items to list
1004 * @param array $params Parameters for getDirectoryList()
1005 * @return array List of container relative resolved paths of directories directly under $dir
1006 * @throws FileBackendError
1008 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1010 if ( $after === INF
) {
1011 return $dirs; // nothing more
1014 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
1016 $container = $this->getContainer( $fullCont );
1017 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
1018 // Non-recursive: only list dirs right under $dir
1019 if ( !empty( $params['topOnly'] ) ) {
1020 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1021 foreach ( $objects as $object ) { // files and directories
1022 if ( substr( $object, -1 ) === '/' ) {
1023 $dirs[] = $object; // directories end in '/'
1026 // Recursive: list all dirs under $dir and its subdirs
1028 // Get directory from last item of prior page
1029 $lastDir = $this->getParentDir( $after ); // must be first page
1030 $objects = $container->list_objects( $limit, $after, $prefix );
1031 foreach ( $objects as $object ) { // files
1032 $objectDir = $this->getParentDir( $object ); // directory of object
1033 if ( $objectDir !== false && $objectDir !== $dir ) {
1034 // Swift stores paths in UTF-8, using binary sorting.
1035 // See function "create_container_table" in common/db.py.
1036 // If a directory is not "greater" than the last one,
1037 // then it was already listed by the calling iterator.
1038 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1040 do { // add dir and all its parent dirs
1041 $dirs[] = "{$pDir}/";
1042 $pDir = $this->getParentDir( $pDir );
1043 } while ( $pDir !== false // sanity
1044 && strcmp( $pDir, $lastDir ) > 0 // not done already
1045 && strlen( $pDir ) > strlen( $dir ) // within $dir
1048 $lastDir = $objectDir;
1052 // Page on the unfiltered directory listing (what is returned may be filtered)
1053 if ( count( $objects ) < $limit ) {
1054 $after = INF
; // avoid a second RTT
1056 $after = end( $objects ); // update last item
1058 } catch ( NoSuchContainerException
$e ) {
1059 } catch ( CloudFilesException
$e ) { // some other exception?
1060 $this->handleException( $e, null, __METHOD__
,
1061 array( 'cont' => $fullCont, 'dir' => $dir ) );
1062 throw new FileBackendError( "Got " . get_class( $e ) . " exception." );
1068 protected function getParentDir( $path ) {
1069 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
1073 * Do not call this function outside of SwiftFileBackendFileList
1075 * @param string $fullCont Resolved container name
1076 * @param string $dir Resolved storage directory with no trailing slash
1077 * @param string|null $after Resolved container relative path of file to list items after
1078 * @param int $limit Max number of items to list
1079 * @param array $params Parameters for getDirectoryList()
1080 * @return array List of resolved container relative paths of files under $dir
1081 * @throws FileBackendError
1083 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1084 $files = array(); // list of (path, stat array or null) entries
1085 if ( $after === INF
) {
1086 return $files; // nothing more
1089 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
1091 $container = $this->getContainer( $fullCont );
1092 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
1093 $objects = array(); // list of unfiltered names or CF_Object items
1094 // Non-recursive: only list files right under $dir
1095 if ( !empty( $params['topOnly'] ) ) {
1096 if ( !empty( $params['adviseStat'] ) ) {
1097 // Note: get_objects() does not include directories
1098 $objects = $container->get_objects( $limit, $after, $prefix, null, '/' );
1100 // Note: list_objects() includes directories here
1101 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1103 $files = $this->buildFileObjectListing( $params, $dir, $objects );
1104 // Recursive: list all files under $dir and its subdirs
1106 // Note: get_objects()/list_objects() here only return file objects
1107 if ( !empty( $params['adviseStat'] ) ) {
1108 $objects = $container->get_objects( $limit, $after, $prefix );
1110 $objects = $container->list_objects( $limit, $after, $prefix );
1112 $files = $this->buildFileObjectListing( $params, $dir, $objects );
1114 // Page on the unfiltered object listing (what is returned may be filtered)
1115 if ( count( $objects ) < $limit ) {
1116 $after = INF
; // avoid a second RTT
1118 $after = end( $objects ); // update last item
1119 $after = is_object( $after ) ?
$after->name
: $after;
1121 } catch ( NoSuchContainerException
$e ) {
1122 } catch ( CloudFilesException
$e ) { // some other exception?
1123 $this->handleException( $e, null, __METHOD__
,
1124 array( 'cont' => $fullCont, 'dir' => $dir ) );
1125 throw new FileBackendError( "Got " . get_class( $e ) . " exception." );
1132 * Build a list of file objects, filtering out any directories
1133 * and extracting any stat info if provided in $objects (for CF_Objects)
1135 * @param array $params Parameters for getDirectoryList()
1136 * @param string $dir Resolved container directory path
1137 * @param array $objects List of CF_Object items or object names
1138 * @return array List of (names,stat array or null) entries
1140 private function buildFileObjectListing( array $params, $dir, array $objects ) {
1142 foreach ( $objects as $object ) {
1143 if ( is_object( $object ) ) {
1145 // Convert various random Swift dates to TS_MW
1146 'mtime' => $this->convertSwiftDate( $object->last_modified
, TS_MW
),
1147 'size' => (int)$object->content_length
,
1148 'latest' => false // eventually consistent
1150 $names[] = array( $object->name
, $stat );
1151 } elseif ( substr( $object, -1 ) !== '/' ) {
1152 // Omit directories, which end in '/' in listings
1153 $names[] = array( $object, null );
1161 * Do not call this function outside of SwiftFileBackendFileList
1163 * @param string $path Storage path
1164 * @param array $val Stat value
1166 public function loadListingStatInternal( $path, array $val ) {
1167 $this->cheapCache
->set( $path, 'stat', $val );
1170 protected function doGetFileSha1base36( array $params ) {
1171 $stat = $this->getFileStat( $params );
1173 if ( !isset( $stat['sha1'] ) ) {
1174 // Stat entries filled by file listings don't include SHA1
1175 $this->clearCache( array( $params['src'] ) );
1176 $stat = $this->getFileStat( $params );
1179 return $stat['sha1'];
1185 protected function doStreamFile( array $params ) {
1186 $status = Status
::newGood();
1188 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1189 if ( $srcRel === null ) {
1190 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1194 $cont = $this->getContainer( $srcCont );
1195 } catch ( NoSuchContainerException
$e ) {
1196 $status->fatal( 'backend-fail-stream', $params['src'] );
1199 } catch ( CloudFilesException
$e ) { // some other exception?
1200 $this->handleException( $e, $status, __METHOD__
, $params );
1206 $output = fopen( 'php://output', 'wb' );
1207 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1208 $obj->stream( $output, $this->headersFromParams( $params ) );
1209 } catch ( NoSuchObjectException
$e ) {
1210 $status->fatal( 'backend-fail-stream', $params['src'] );
1211 } catch ( CloudFilesException
$e ) { // some other exception?
1212 $this->handleException( $e, $status, __METHOD__
, $params );
1218 protected function doGetLocalCopyMulti( array $params ) {
1219 $tmpFiles = array();
1221 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1222 // Blindly create tmp files and stream to them, catching any exception if the file does
1223 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1224 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1225 $cfOps = array(); // (path => CF_Async_Op)
1227 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1228 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1229 if ( $srcRel === null ) {
1230 $tmpFiles[$path] = null;
1235 $sContObj = $this->getContainer( $srcCont );
1236 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1237 // Get source file extension
1238 $ext = FileBackend
::extensionFromPath( $path );
1239 // Create a new temporary file...
1240 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1242 $handle = fopen( $tmpFile->getPath(), 'wb' );
1244 $headers = $this->headersFromParams( $params );
1245 if ( count( $pathBatch ) > 1 ) {
1246 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1247 $cfOps[$path]->_file_handle
= $handle; // close this later
1249 $obj->stream( $handle, $headers );
1256 } catch ( NoSuchContainerException
$e ) {
1258 } catch ( NoSuchObjectException
$e ) {
1260 } catch ( CloudFilesException
$e ) { // some other exception?
1262 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1264 $tmpFiles[$path] = $tmpFile;
1267 $batch = new CF_Async_Op_Batch( $cfOps );
1268 $cfOps = $batch->execute();
1269 foreach ( $cfOps as $path => $cfOp ) {
1271 $cfOp->getLastResponse();
1272 } catch ( NoSuchContainerException
$e ) {
1273 $tmpFiles[$path] = null;
1274 } catch ( NoSuchObjectException
$e ) {
1275 $tmpFiles[$path] = null;
1276 } catch ( CloudFilesException
$e ) { // some other exception?
1277 $tmpFiles[$path] = null;
1278 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1280 fclose( $cfOp->_file_handle
); // close open handle
1287 public function getFileHttpUrl( array $params ) {
1288 if ( $this->swiftTempUrlKey
!= '' ||
1289 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' )
1291 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1292 if ( $srcRel === null ) {
1293 return null; // invalid path
1296 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1297 $sContObj = $this->getContainer( $srcCont );
1298 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1299 if ( $this->swiftTempUrlKey
!= '' ) {
1300 return $obj->get_temp_url( $this->swiftTempUrlKey
, $ttl, "GET" );
1301 } else { // give S3 API URL for rgw
1302 $expires = time() +
$ttl;
1303 // Path for signature starts with the bucket
1304 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1305 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1306 // Calculate the hash
1307 $signature = base64_encode( hash_hmac(
1309 "GET\n\n\n{$expires}\n{$spath}",
1310 $this->rgwS3SecretKey
,
1314 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1315 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1316 return wfAppendQuery(
1317 str_replace( '/swift/v1', '', // S3 API is the rgw default
1318 $sContObj->cfs_http
->getStorageUrl() . $spath ),
1320 'Signature' => $signature,
1321 'Expires' => $expires,
1322 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1325 } catch ( NoSuchContainerException
$e ) {
1326 } catch ( CloudFilesException
$e ) { // some other exception?
1327 $this->handleException( $e, null, __METHOD__
, $params );
1334 protected function directoriesAreVirtual() {
1339 * Get headers to send to Swift when reading a file based
1340 * on a FileBackend params array, e.g. that of getLocalCopy().
1341 * $params is currently only checked for a 'latest' flag.
1343 * @param array $params
1346 protected function headersFromParams( array $params ) {
1348 if ( !empty( $params['latest'] ) ) {
1349 $hdrs[] = 'X-Newest: true';
1355 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1356 $statuses = array();
1358 $cfOps = array(); // list of CF_Async_Op objects
1359 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1360 $cfOps[$index] = $fileOpHandle->cfOp
;
1362 $batch = new CF_Async_Op_Batch( $cfOps );
1364 $cfOps = $batch->execute();
1365 foreach ( $cfOps as $index => $cfOp ) {
1366 $status = Status
::newGood();
1367 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1368 try { // catch exceptions; update status
1369 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1370 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1371 } catch ( CloudFilesException
$e ) { // some other exception?
1372 $this->handleException( $e, $status,
1373 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1375 $statuses[$index] = $status;
1382 * Set read/write permissions for a Swift container.
1384 * @see http://swift.openstack.org/misc.html#acls
1386 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1387 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1389 * @param CF_Container $contObj Swift container
1390 * @param array $readGrps List of the possible criteria for a request to have
1391 * access to read a container. Each item is one of the following formats:
1392 * - account:user : Grants access if the request is by the given user
1393 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1394 * matches the expression and the request is not for a listing.
1395 * Setting this to '*' effectively makes a container public.
1396 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1397 * matches the expression and the request is for a listing.
1398 * @param array $writeGrps A list of the possible criteria for a request to have
1399 * access to write to a container. Each item is of the following format:
1400 * - account:user : Grants access if the request is by the given user
1403 protected function setContainerAccess(
1404 CF_Container
$contObj, array $readGrps, array $writeGrps
1406 $creds = $contObj->cfs_auth
->export_credentials();
1408 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1410 // Note: 10 second timeout consistent with php-cloudfiles
1411 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1412 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1413 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1414 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1416 return $req->execute(); // should return 204
1420 * Purge the CDN cache of affected objects if CDN caching is enabled.
1421 * This is for Rackspace/Akamai CDNs.
1423 * @param array $objects List of CF_Object items
1425 public function purgeCDNCache( array $objects ) {
1426 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1427 foreach ( $objects as $object ) {
1429 $object->purge_from_cdn();
1430 } catch ( CDNNotEnabledException
$e ) {
1431 // CDN not enabled; nothing to see here
1432 } catch ( CloudFilesException
$e ) {
1433 $this->handleException( $e, null, __METHOD__
,
1434 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1441 * Get an authenticated connection handle to the Swift proxy
1443 * @throws CloudFilesException
1444 * @throws CloudFilesException|Exception
1445 * @return CF_Connection|bool False on failure
1447 protected function getConnection() {
1448 if ( $this->connException
instanceof CloudFilesException
) {
1449 if ( ( time() - $this->connErrorTime
) < 60 ) {
1450 throw $this->connException
; // failed last attempt; don't bother
1451 } else { // actually retry this time
1452 $this->connException
= null;
1453 $this->connErrorTime
= 0;
1456 // Session keys expire after a while, so we renew them periodically
1457 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1458 // Authenticate with proxy and get a session key...
1459 if ( !$this->conn ||
$reAuth ) {
1460 $this->sessionStarted
= 0;
1461 $this->connContainerCache
->clear();
1462 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1463 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1464 if ( is_array( $creds ) ) { // cache hit
1465 $this->auth
->load_cached_credentials(
1466 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1467 $this->sessionStarted
= time() - ceil( $this->authTTL
/ 2 ); // skew for worst case
1468 } else { // cache miss
1470 $this->auth
->authenticate();
1471 $creds = $this->auth
->export_credentials();
1472 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/ 2 ) ); // cache
1473 $this->sessionStarted
= time();
1474 } catch ( CloudFilesException
$e ) {
1475 $this->connException
= $e; // don't keep re-trying
1476 $this->connErrorTime
= time();
1477 throw $e; // throw it back
1480 if ( $this->conn
) { // re-authorizing?
1481 $this->conn
->close(); // close active cURL handles in CF_Http object
1483 $this->conn
= new CF_Connection( $this->auth
);
1490 * Close the connection to the Swift proxy
1492 protected function closeConnection() {
1493 if ( $this->conn
) {
1494 $this->conn
->close(); // close active cURL handles in CF_Http object
1496 $this->sessionStarted
= 0;
1497 $this->connContainerCache
->clear();
1502 * Get the cache key for a container
1504 * @param string $username
1507 private function getCredsCacheKey( $username ) {
1508 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1512 * Get a Swift container object, possibly from process cache.
1513 * Use $reCache if the file count or byte count is needed.
1515 * @param string $container Container name
1516 * @param bool $bypassCache Bypass all caches and load from Swift
1517 * @return CF_Container
1518 * @throws CloudFilesException
1520 protected function getContainer( $container, $bypassCache = false ) {
1521 $conn = $this->getConnection(); // Swift proxy connection
1522 if ( $bypassCache ) { // purge cache
1523 $this->connContainerCache
->clear( $container );
1524 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1525 $this->primeContainerCache( array( $container ) ); // check persistent cache
1527 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1528 $contObj = $conn->get_container( $container );
1529 // NoSuchContainerException not thrown: container must exist
1530 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1531 if ( !$bypassCache ) {
1532 $this->setContainerCache( $container, // update persistent cache
1533 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1538 return $this->connContainerCache
->get( $container, 'obj' );
1542 * Create a Swift container
1544 * @param string $container Container name
1545 * @return CF_Container
1546 * @throws CloudFilesException
1548 protected function createContainer( $container ) {
1549 $conn = $this->getConnection(); // Swift proxy connection
1550 $contObj = $conn->create_container( $container );
1551 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1556 * Delete a Swift container
1558 * @param string $container Container name
1559 * @throws CloudFilesException
1561 protected function deleteContainer( $container ) {
1562 $conn = $this->getConnection(); // Swift proxy connection
1563 $this->connContainerCache
->clear( $container ); // purge
1564 $conn->delete_container( $container );
1567 protected function doPrimeContainerCache( array $containerInfo ) {
1569 $conn = $this->getConnection(); // Swift proxy connection
1570 foreach ( $containerInfo as $container => $info ) {
1571 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1572 $container, $info['count'], $info['bytes'] );
1573 $this->connContainerCache
->set( $container, 'obj', $contObj );
1575 } catch ( CloudFilesException
$e ) { // some other exception?
1576 $this->handleException( $e, null, __METHOD__
, array() );
1581 * Log an unexpected exception for this backend.
1582 * This also sets the Status object to have a fatal error.
1584 * @param Exception $e
1585 * @param Status $status null
1586 * @param string $func
1587 * @param array $params
1589 protected function handleException( Exception
$e, $status, $func, array $params ) {
1590 if ( $status instanceof Status
) {
1591 if ( $e instanceof AuthenticationException
) {
1592 $status->fatal( 'backend-fail-connect', $this->name
);
1594 $status->fatal( 'backend-fail-internal', $this->name
);
1597 if ( $e->getMessage() ) {
1598 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1600 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1601 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1602 $this->closeConnection(); // force a re-connect and re-auth next time
1604 wfDebugLog( 'SwiftBackend',
1605 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1606 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1612 * @see FileBackendStoreOpHandle
1614 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1615 /** @var CF_Async_Op */
1619 public $affectedObjects = array();
1622 * @param SwiftFileBackend $backend
1623 * @param array $params
1624 * @param string $call
1625 * @param CF_Async_Op $cfOp
1627 public function __construct(
1628 SwiftFileBackend
$backend, array $params, $call, CF_Async_Op
$cfOp
1630 $this->backend
= $backend;
1631 $this->params
= $params;
1632 $this->call
= $call;
1633 $this->cfOp
= $cfOp;
1638 * SwiftFileBackend helper class to page through listings.
1639 * Swift also has a listing limit of 10,000 objects for sanity.
1640 * Do not use this class from places outside SwiftFileBackend.
1642 * @ingroup FileBackend
1644 abstract class SwiftFileBackendList
implements Iterator
{
1645 /** @var array List of path or (path,stat array) entries */
1646 protected $bufferIter = array();
1648 /** @var string List items *after* this path */
1649 protected $bufferAfter = null;
1655 protected $params = array();
1657 /** @var SwiftFileBackend */
1660 /** @var string Container name */
1661 protected $container;
1663 /** @var string Storage directory */
1667 protected $suffixStart;
1669 const PAGE_SIZE
= 9000; // file listing buffer size
1672 * @param SwiftFileBackend $backend
1673 * @param string $fullCont Resolved container name
1674 * @param string $dir Resolved directory relative to container
1675 * @param array $params
1677 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1678 $this->backend
= $backend;
1679 $this->container
= $fullCont;
1681 if ( substr( $this->dir
, -1 ) === '/' ) {
1682 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1684 if ( $this->dir
== '' ) { // whole container
1685 $this->suffixStart
= 0;
1686 } else { // dir within container
1687 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1689 $this->params
= $params;
1693 * @see Iterator::key()
1696 public function key() {
1701 * @see Iterator::next()
1703 public function next() {
1704 // Advance to the next file in the page
1705 next( $this->bufferIter
);
1707 // Check if there are no files left in this page and
1708 // advance to the next page if this page was not empty.
1709 if ( !$this->valid() && count( $this->bufferIter
) ) {
1710 $this->bufferIter
= $this->pageFromList(
1711 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1712 ); // updates $this->bufferAfter
1717 * @see Iterator::rewind()
1719 public function rewind() {
1721 $this->bufferAfter
= null;
1722 $this->bufferIter
= $this->pageFromList(
1723 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1724 ); // updates $this->bufferAfter
1728 * @see Iterator::valid()
1731 public function valid() {
1732 if ( $this->bufferIter
=== null ) {
1733 return false; // some failure?
1735 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1740 * Get the given list portion (page)
1742 * @param string $container Resolved container name
1743 * @param string $dir Resolved path relative to container
1744 * @param string $after null
1746 * @param array $params
1747 * @return Traversable|array
1749 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1753 * Iterator for listing directories
1755 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1757 * @see Iterator::current()
1758 * @return string|bool String (relative path) or false
1760 public function current() {
1761 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1765 * @see SwiftFileBackendList::pageFromList()
1766 * @param string $container
1767 * @param string $dir
1768 * @param string $after
1770 * @param array $params
1773 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1774 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1779 * Iterator for listing regular files
1781 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1783 * @see Iterator::current()
1784 * @return string|bool String (relative path) or false
1786 public function current() {
1787 list( $path, $stat ) = current( $this->bufferIter
);
1788 $relPath = substr( $path, $this->suffixStart
);
1789 if ( is_array( $stat ) ) {
1790 $storageDir = rtrim( $this->params
['dir'], '/' );
1791 $this->backend
->loadListingStatInternal( "$storageDir/$relPath", $stat );
1798 * @see SwiftFileBackendList::pageFromList()
1799 * @param string $container
1800 * @param string $dir
1801 * @param string $after
1803 * @param array $params
1806 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1807 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );