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 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 */
41 protected $auth; // Swift authentication handler
42 protected $authTTL; // integer seconds
43 protected $swiftTempUrlKey; // string; shared secret value for making temp urls
44 protected $swiftAnonUser; // string; username to handle unauthenticated requests
45 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
46 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
47 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
49 // Rados Gateway specific options
50 protected $rgwS3AccessKey; // string; S3 access key
51 protected $rgwS3SecretKey; // string; S3 authentication key
53 /** @var CF_Connection */
54 protected $conn; // Swift connection handle
55 protected $sessionStarted = 0; // integer UNIX timestamp
57 /** @var CloudFilesException */
58 protected $connException;
59 protected $connErrorTime = 0; // UNIX timestamp
64 /** @var ProcessCacheLRU */
65 protected $connContainerCache; // container object cache
68 * @see FileBackendStore::__construct()
69 * Additional $config params include:
70 * - swiftAuthUrl : Swift authentication server URL
71 * - swiftUser : Swift user used by MediaWiki (account:username)
72 * - swiftKey : Swift authentication key for the above user
73 * - swiftAuthTTL : Swift authentication TTL (seconds)
74 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
75 * Do not set this until it has been set in the backend.
76 * - swiftAnonUser : Swift user used for end-user requests (account:username).
77 * If set, then views of public containers are assumed to go
78 * through this user. If not set, then public containers are
79 * accessible to unauthenticated requests via ".r:*" in the ACL.
80 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
81 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
82 * If files may likely change, this should probably not exceed
83 * a few days. For example, deletions may take this long to apply.
84 * If object purging is enabled, however, this is not an issue.
85 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
86 * - shardViaHashLevels : Map of container names to sharding config with:
87 * - base : base of hash characters, 16 or 36
88 * - levels : the number of hash levels (and digits)
89 * - repeat : hash subdirectories are prefixed with all the
90 * parent hash directory names (e.g. "a/ab/abc")
91 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
92 * If those are not available, then the main cache will be used.
93 * This is probably insecure in shared hosting environments.
94 * - rgwS3AccessKey : Ragos Gateway S3 "access key" value on the account.
95 * Do not set this until it has been set in the backend.
96 * This is used for generating expiring pre-authenticated URLs.
97 * Only use this when using rgw and to work around
98 * http://tracker.newdream.net/issues/3454.
99 * - rgwS3SecretKey : Ragos Gateway S3 "secret key" value on the account.
100 * Do not set this until it has been set in the backend.
101 * This is used for generating expiring pre-authenticated URLs.
102 * Only use this when using rgw and to work around
103 * http://tracker.newdream.net/issues/3454.
105 public function __construct( array $config ) {
106 parent
::__construct( $config );
107 if ( !class_exists( 'CF_Constants' ) ) {
108 throw new MWException( 'SwiftCloudFiles extension not installed.' );
111 $this->auth
= new CF_Authentication(
112 $config['swiftUser'],
114 null, // account; unused
115 $config['swiftAuthUrl']
118 $this->authTTL
= isset( $config['swiftAuthTTL'] )
119 ?
$config['swiftAuthTTL']
120 : 5 * 60; // some sane number
121 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
122 ?
$config['swiftAnonUser']
124 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
125 ?
$config['swiftTempUrlKey']
127 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
128 ?
$config['shardViaHashLevels']
130 $this->swiftUseCDN
= isset( $config['swiftUseCDN'] )
131 ?
$config['swiftUseCDN']
133 $this->swiftCDNExpiry
= isset( $config['swiftCDNExpiry'] )
134 ?
$config['swiftCDNExpiry']
135 : 12 * 3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
136 $this->swiftCDNPurgable
= isset( $config['swiftCDNPurgable'] )
137 ?
$config['swiftCDNPurgable']
139 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
140 ?
$config['rgwS3AccessKey']
142 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
143 ?
$config['rgwS3SecretKey']
145 // Cache container information to mask latency
146 $this->memCache
= wfGetMainCache();
147 // Process cache for container info
148 $this->connContainerCache
= new ProcessCacheLRU( 300 );
149 // Cache auth token information to avoid RTTs
150 if ( !empty( $config['cacheAuthInfo'] ) ) {
151 if ( PHP_SAPI
=== 'cli' ) {
152 $this->srvCache
= wfGetMainCache(); // preferrably memcached
154 try { // look for APC, XCache, WinCache, ect...
155 $this->srvCache
= ObjectCache
::newAccelerator( array() );
156 } catch ( Exception
$e ) {}
159 $this->srvCache
= $this->srvCache ?
$this->srvCache
: new EmptyBagOStuff();
163 * @see FileBackendStore::resolveContainerPath()
166 protected function resolveContainerPath( $container, $relStoragePath ) {
167 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
168 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
169 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
170 return null; // too long for Swift
172 return $relStoragePath;
176 * @see FileBackendStore::isPathUsableInternal()
179 public function isPathUsableInternal( $storagePath ) {
180 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
181 if ( $rel === null ) {
182 return false; // invalid
186 $this->getContainer( $container );
187 return true; // container exists
188 } catch ( NoSuchContainerException
$e ) {
189 } catch ( CloudFilesException
$e ) { // some other exception?
190 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
197 * @param $headers array
200 protected function sanitizeHdrs( array $headers ) {
201 // By default, Swift has annoyingly low maximum header value limits
202 if ( isset( $headers['Content-Disposition'] ) ) {
203 $headers['Content-Disposition'] = $this->truncDisp( $headers['Content-Disposition'] );
209 * @param $disposition string Content-Disposition header value
210 * @return string Truncated Content-Disposition header value to meet Swift limits
212 protected function truncDisp( $disposition ) {
214 foreach ( explode( ';', $disposition ) as $part ) {
215 $part = trim( $part );
216 $new = ( $res === '' ) ?
$part : "{$res};{$part}";
217 if ( strlen( $new ) <= 255 ) {
220 break; // too long; sigh
227 * @see FileBackendStore::doCreateInternal()
230 protected function doCreateInternal( array $params ) {
231 $status = Status
::newGood();
233 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
234 if ( $dstRel === null ) {
235 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
239 // (a) Check the destination container and object
241 $dContObj = $this->getContainer( $dstCont );
242 } catch ( NoSuchContainerException
$e ) {
243 $status->fatal( 'backend-fail-create', $params['dst'] );
245 } catch ( CloudFilesException
$e ) { // some other exception?
246 $this->handleException( $e, $status, __METHOD__
, $params );
250 // (b) Get a SHA-1 hash of the object
251 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
253 // (c) Actually create the object
255 // Create a fresh CF_Object with no fields preloaded.
256 // We don't want to preserve headers, metadata, and such.
257 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
258 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
259 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
260 // The MD5 here will be checked within Swift against its own MD5.
261 $obj->set_etag( md5( $params['content'] ) );
262 // Use the same content type as StreamFile for security
263 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
264 if ( !strlen( $obj->content_type
) ) { // special case
265 $obj->content_type
= 'unknown/unknown';
267 // Set any other custom headers if requested
268 if ( isset( $params['headers'] ) ) {
269 $obj->headers +
= $this->sanitizeHdrs( $params['headers'] );
271 if ( !empty( $params['async'] ) ) { // deferred
272 $op = $obj->write_async( $params['content'] );
273 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $op );
274 $status->value
->affectedObjects
[] = $obj;
275 } else { // actually write the object in Swift
276 $obj->write( $params['content'] );
277 $this->purgeCDNCache( array( $obj ) );
279 } catch ( CDNNotEnabledException
$e ) {
280 // CDN not enabled; nothing to see here
281 } catch ( BadContentTypeException
$e ) {
282 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
283 } catch ( CloudFilesException
$e ) { // some other exception?
284 $this->handleException( $e, $status, __METHOD__
, $params );
291 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
293 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
295 $cfOp->getLastResponse();
296 } catch ( BadContentTypeException
$e ) {
297 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
302 * @see FileBackendStore::doStoreInternal()
305 protected function doStoreInternal( array $params ) {
306 $status = Status
::newGood();
308 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
309 if ( $dstRel === null ) {
310 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
314 // (a) Check the destination container and object
316 $dContObj = $this->getContainer( $dstCont );
317 } catch ( NoSuchContainerException
$e ) {
318 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
320 } catch ( CloudFilesException
$e ) { // some other exception?
321 $this->handleException( $e, $status, __METHOD__
, $params );
325 // (b) Get a SHA-1 hash of the object
326 wfSuppressWarnings();
327 $sha1Hash = sha1_file( $params['src'] );
329 if ( $sha1Hash === false ) { // source doesn't exist?
330 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
333 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
335 // (c) Actually store the object
337 // Create a fresh CF_Object with no fields preloaded.
338 // We don't want to preserve headers, metadata, and such.
339 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
340 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
341 // The MD5 here will be checked within Swift against its own MD5.
342 $obj->set_etag( md5_file( $params['src'] ) );
343 // Use the same content type as StreamFile for security
344 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
345 if ( !strlen( $obj->content_type
) ) { // special case
346 $obj->content_type
= 'unknown/unknown';
348 // Set any other custom headers if requested
349 if ( isset( $params['headers'] ) ) {
350 $obj->headers +
= $this->sanitizeHdrs( $params['headers'] );
352 if ( !empty( $params['async'] ) ) { // deferred
353 wfSuppressWarnings();
354 $fp = fopen( $params['src'], 'rb' );
357 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
359 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
360 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $op );
361 $status->value
->resourcesToClose
[] = $fp;
362 $status->value
->affectedObjects
[] = $obj;
364 } else { // actually write the object in Swift
365 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
366 $this->purgeCDNCache( array( $obj ) );
368 } catch ( CDNNotEnabledException
$e ) {
369 // CDN not enabled; nothing to see here
370 } catch ( BadContentTypeException
$e ) {
371 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
372 } catch ( IOException
$e ) {
373 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
374 } catch ( CloudFilesException
$e ) { // some other exception?
375 $this->handleException( $e, $status, __METHOD__
, $params );
382 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
384 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
386 $cfOp->getLastResponse();
387 } catch ( BadContentTypeException
$e ) {
388 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
389 } catch ( IOException
$e ) {
390 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
395 * @see FileBackendStore::doCopyInternal()
398 protected function doCopyInternal( array $params ) {
399 $status = Status
::newGood();
401 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
402 if ( $srcRel === null ) {
403 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
407 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
408 if ( $dstRel === null ) {
409 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
413 // (a) Check the source/destination containers and destination object
415 $sContObj = $this->getContainer( $srcCont );
416 $dContObj = $this->getContainer( $dstCont );
417 } catch ( NoSuchContainerException
$e ) {
418 if ( empty( $params['ignoreMissingSource'] ) ||
isset( $sContObj ) ) {
419 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
422 } catch ( CloudFilesException
$e ) { // some other exception?
423 $this->handleException( $e, $status, __METHOD__
, $params );
427 // (b) Actually copy the file to the destination
429 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
430 $hdrs = array(); // source file headers to override with new values
431 // Set any other custom headers if requested
432 if ( isset( $params['headers'] ) ) {
433 $hdrs +
= $this->sanitizeHdrs( $params['headers'] );
435 if ( !empty( $params['async'] ) ) { // deferred
436 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
437 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $op );
438 $status->value
->affectedObjects
[] = $dstObj;
439 } else { // actually write the object in Swift
440 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
441 $this->purgeCDNCache( array( $dstObj ) );
443 } catch ( CDNNotEnabledException
$e ) {
444 // CDN not enabled; nothing to see here
445 } catch ( NoSuchObjectException
$e ) { // source object does not exist
446 if ( empty( $params['ignoreMissingSource'] ) ) {
447 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
449 } catch ( CloudFilesException
$e ) { // some other exception?
450 $this->handleException( $e, $status, __METHOD__
, $params );
457 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
459 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
461 $cfOp->getLastResponse();
462 } catch ( NoSuchObjectException
$e ) { // source object does not exist
463 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
468 * @see FileBackendStore::doMoveInternal()
471 protected function doMoveInternal( array $params ) {
472 $status = Status
::newGood();
474 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
475 if ( $srcRel === null ) {
476 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
480 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
481 if ( $dstRel === null ) {
482 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
486 // (a) Check the source/destination containers and destination object
488 $sContObj = $this->getContainer( $srcCont );
489 $dContObj = $this->getContainer( $dstCont );
490 } catch ( NoSuchContainerException
$e ) {
491 if ( empty( $params['ignoreMissingSource'] ) ||
isset( $sContObj ) ) {
492 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
495 } catch ( CloudFilesException
$e ) { // some other exception?
496 $this->handleException( $e, $status, __METHOD__
, $params );
500 // (b) Actually move the file to the destination
502 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
503 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
504 $hdrs = array(); // source file headers to override with new values
505 // Set any other custom headers if requested
506 if ( isset( $params['headers'] ) ) {
507 $hdrs +
= $this->sanitizeHdrs( $params['headers'] );
509 if ( !empty( $params['async'] ) ) { // deferred
510 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
511 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
512 $status->value
->affectedObjects
[] = $srcObj;
513 $status->value
->affectedObjects
[] = $dstObj;
514 } else { // actually write the object in Swift
515 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
516 $this->purgeCDNCache( array( $srcObj ) );
517 $this->purgeCDNCache( array( $dstObj ) );
519 } catch ( CDNNotEnabledException
$e ) {
520 // CDN not enabled; nothing to see here
521 } catch ( NoSuchObjectException
$e ) { // source object does not exist
522 if ( empty( $params['ignoreMissingSource'] ) ) {
523 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
525 } catch ( CloudFilesException
$e ) { // some other exception?
526 $this->handleException( $e, $status, __METHOD__
, $params );
533 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
535 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
537 $cfOp->getLastResponse();
538 } catch ( NoSuchObjectException
$e ) { // source object does not exist
539 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
544 * @see FileBackendStore::doDeleteInternal()
547 protected function doDeleteInternal( array $params ) {
548 $status = Status
::newGood();
550 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
551 if ( $srcRel === null ) {
552 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
557 $sContObj = $this->getContainer( $srcCont );
558 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
559 if ( !empty( $params['async'] ) ) { // deferred
560 $op = $sContObj->delete_object_async( $srcRel );
561 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
562 $status->value
->affectedObjects
[] = $srcObj;
563 } else { // actually write the object in Swift
564 $sContObj->delete_object( $srcRel );
565 $this->purgeCDNCache( array( $srcObj ) );
567 } catch ( CDNNotEnabledException
$e ) {
568 // CDN not enabled; nothing to see here
569 } catch ( NoSuchContainerException
$e ) {
570 if ( empty( $params['ignoreMissingSource'] ) ) {
571 $status->fatal( 'backend-fail-delete', $params['src'] );
573 } catch ( NoSuchObjectException
$e ) {
574 if ( empty( $params['ignoreMissingSource'] ) ) {
575 $status->fatal( 'backend-fail-delete', $params['src'] );
577 } catch ( CloudFilesException
$e ) { // some other exception?
578 $this->handleException( $e, $status, __METHOD__
, $params );
585 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
587 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
589 $cfOp->getLastResponse();
590 } catch ( NoSuchContainerException
$e ) {
591 $status->fatal( 'backend-fail-delete', $params['src'] );
592 } catch ( NoSuchObjectException
$e ) {
593 if ( empty( $params['ignoreMissingSource'] ) ) {
594 $status->fatal( 'backend-fail-delete', $params['src'] );
600 * @see FileBackendStore::doDescribeInternal()
603 protected function doDescribeInternal( array $params ) {
604 $status = Status
::newGood();
606 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
607 if ( $srcRel === null ) {
608 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
613 $sContObj = $this->getContainer( $srcCont );
614 // Get the latest version of the current metadata
615 $srcObj = $sContObj->get_object( $srcRel,
616 $this->headersFromParams( array( 'latest' => true ) ) );
617 // Merge in the metadata updates...
618 if ( isset( $params['headers'] ) ) {
619 $srcObj->headers
= $this->sanitizeHdrs( $params['headers'] ) +
$srcObj->headers
;
621 $srcObj->sync_metadata(); // save to Swift
622 $this->purgeCDNCache( array( $srcObj ) );
623 } catch ( CDNNotEnabledException
$e ) {
624 // CDN not enabled; nothing to see here
625 } catch ( NoSuchContainerException
$e ) {
626 $status->fatal( 'backend-fail-describe', $params['src'] );
627 } catch ( NoSuchObjectException
$e ) {
628 $status->fatal( 'backend-fail-describe', $params['src'] );
629 } catch ( CloudFilesException
$e ) { // some other exception?
630 $this->handleException( $e, $status, __METHOD__
, $params );
637 * @see FileBackendStore::doPrepareInternal()
640 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
641 $status = Status
::newGood();
643 // (a) Check if container already exists
645 $this->getContainer( $fullCont );
646 // NoSuchContainerException not thrown: container must exist
647 return $status; // already exists
648 } catch ( NoSuchContainerException
$e ) {
649 // NoSuchContainerException thrown: container does not exist
650 } catch ( CloudFilesException
$e ) { // some other exception?
651 $this->handleException( $e, $status, __METHOD__
, $params );
655 // (b) Create container as needed
657 $contObj = $this->createContainer( $fullCont );
658 if ( !empty( $params['noAccess'] ) ) {
659 // Make container private to end-users...
660 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
662 // Make container public to end-users...
663 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
665 if ( $this->swiftUseCDN
) { // Rackspace style CDN
666 $contObj->make_public( $this->swiftCDNExpiry
);
668 } catch ( CDNNotEnabledException
$e ) {
669 // CDN not enabled; nothing to see here
670 } catch ( CloudFilesException
$e ) { // some other exception?
671 $this->handleException( $e, $status, __METHOD__
, $params );
679 * @see FileBackendStore::doSecureInternal()
682 protected function doSecureInternal( $fullCont, $dir, array $params ) {
683 $status = Status
::newGood();
684 if ( empty( $params['noAccess'] ) ) {
685 return $status; // nothing to do
688 // Restrict container from end-users...
690 // doPrepareInternal() should have been called,
691 // so the Swift container should already exist...
692 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
693 // NoSuchContainerException not thrown: container must exist
695 // Make container private to end-users...
696 $status->merge( $this->setContainerAccess(
698 array( $this->auth
->username
), // read
699 array( $this->auth
->username
) // write
701 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
702 $contObj->make_private();
704 } catch ( CDNNotEnabledException
$e ) {
705 // CDN not enabled; nothing to see here
706 } catch ( CloudFilesException
$e ) { // some other exception?
707 $this->handleException( $e, $status, __METHOD__
, $params );
714 * @see FileBackendStore::doPublishInternal()
717 protected function doPublishInternal( $fullCont, $dir, array $params ) {
718 $status = Status
::newGood();
720 // Unrestrict container from end-users...
722 // doPrepareInternal() should have been called,
723 // so the Swift container should already exist...
724 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
725 // NoSuchContainerException not thrown: container must exist
727 // Make container public to end-users...
728 if ( $this->swiftAnonUser
!= '' ) {
729 $status->merge( $this->setContainerAccess(
731 array( $this->auth
->username
, $this->swiftAnonUser
), // read
732 array( $this->auth
->username
, $this->swiftAnonUser
) // write
735 $status->merge( $this->setContainerAccess(
737 array( $this->auth
->username
, '.r:*' ), // read
738 array( $this->auth
->username
) // write
741 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
742 $contObj->make_public();
744 } catch ( CDNNotEnabledException
$e ) {
745 // CDN not enabled; nothing to see here
746 } catch ( CloudFilesException
$e ) { // some other exception?
747 $this->handleException( $e, $status, __METHOD__
, $params );
754 * @see FileBackendStore::doCleanInternal()
757 protected function doCleanInternal( $fullCont, $dir, array $params ) {
758 $status = Status
::newGood();
760 // Only containers themselves can be removed, all else is virtual
762 return $status; // nothing to do
765 // (a) Check the container
767 $contObj = $this->getContainer( $fullCont, true );
768 } catch ( NoSuchContainerException
$e ) {
769 return $status; // ok, nothing to do
770 } catch ( CloudFilesException
$e ) { // some other exception?
771 $this->handleException( $e, $status, __METHOD__
, $params );
775 // (b) Delete the container if empty
776 if ( $contObj->object_count
== 0 ) {
778 $this->deleteContainer( $fullCont );
779 } catch ( NoSuchContainerException
$e ) {
780 return $status; // race?
781 } catch ( NonEmptyContainerException
$e ) {
782 return $status; // race? consistency delay?
783 } catch ( CloudFilesException
$e ) { // some other exception?
784 $this->handleException( $e, $status, __METHOD__
, $params );
793 * @see FileBackendStore::doFileExists()
794 * @return array|bool|null
796 protected function doGetFileStat( array $params ) {
797 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
798 if ( $srcRel === null ) {
799 return false; // invalid storage path
804 $contObj = $this->getContainer( $srcCont );
805 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
806 $this->addMissingMetadata( $srcObj, $params['src'] );
808 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
809 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
810 'size' => (int)$srcObj->content_length
,
811 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
813 } catch ( NoSuchContainerException
$e ) {
814 } catch ( NoSuchObjectException
$e ) {
815 } catch ( CloudFilesException
$e ) { // some other exception?
817 $this->handleException( $e, null, __METHOD__
, $params );
824 * Fill in any missing object metadata and save it to Swift
826 * @param $obj CF_Object
827 * @param string $path Storage path to object
828 * @return bool Success
829 * @throws Exception cloudfiles exceptions
831 protected function addMissingMetadata( CF_Object
$obj, $path ) {
832 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
833 return true; // nothing to do
835 wfProfileIn( __METHOD__
);
836 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
837 $status = Status
::newGood();
838 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
839 if ( $status->isOK() ) {
840 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
842 $hash = $tmpFile->getSha1Base36();
843 if ( $hash !== false ) {
844 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
845 $obj->sync_metadata(); // save to Swift
846 wfProfileOut( __METHOD__
);
847 return true; // success
851 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING
);
852 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
853 wfProfileOut( __METHOD__
);
854 return false; // failed
858 * @see FileBackendStore::doGetFileContentsMulti()
861 protected function doGetFileContentsMulti( array $params ) {
864 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
865 // Blindly create tmp files and stream to them, catching any exception if the file does
866 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
867 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
868 $cfOps = array(); // (path => CF_Async_Op)
870 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
871 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
872 if ( $srcRel === null ) {
873 $contents[$path] = false;
878 $sContObj = $this->getContainer( $srcCont );
879 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
880 // Create a new temporary memory file...
881 $handle = fopen( 'php://temp', 'wb' );
883 $headers = $this->headersFromParams( $params );
884 if ( count( $pathBatch ) > 1 ) {
885 $cfOps[$path] = $obj->stream_async( $handle, $headers );
886 $cfOps[$path]->_file_handle
= $handle; // close this later
888 $obj->stream( $handle, $headers );
889 rewind( $handle ); // start from the beginning
890 $data = stream_get_contents( $handle );
896 } catch ( NoSuchContainerException
$e ) {
898 } catch ( NoSuchObjectException
$e ) {
900 } catch ( CloudFilesException
$e ) { // some other exception?
902 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
904 $contents[$path] = $data;
907 $batch = new CF_Async_Op_Batch( $cfOps );
908 $cfOps = $batch->execute();
909 foreach ( $cfOps as $path => $cfOp ) {
911 $cfOp->getLastResponse();
912 rewind( $cfOp->_file_handle
); // start from the beginning
913 $contents[$path] = stream_get_contents( $cfOp->_file_handle
);
914 } catch ( NoSuchContainerException
$e ) {
915 $contents[$path] = false;
916 } catch ( NoSuchObjectException
$e ) {
917 $contents[$path] = false;
918 } catch ( CloudFilesException
$e ) { // some other exception?
919 $contents[$path] = false;
920 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
922 fclose( $cfOp->_file_handle
); // close open handle
930 * @see FileBackendStore::doDirectoryExists()
933 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
935 $container = $this->getContainer( $fullCont );
936 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
937 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
938 } catch ( NoSuchContainerException
$e ) {
940 } catch ( CloudFilesException
$e ) { // some other exception?
941 $this->handleException( $e, null, __METHOD__
,
942 array( 'cont' => $fullCont, 'dir' => $dir ) );
945 return null; // error
949 * @see FileBackendStore::getDirectoryListInternal()
950 * @return SwiftFileBackendDirList
952 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
953 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
957 * @see FileBackendStore::getFileListInternal()
958 * @return SwiftFileBackendFileList
960 public function getFileListInternal( $fullCont, $dir, array $params ) {
961 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
965 * Do not call this function outside of SwiftFileBackendFileList
967 * @param string $fullCont Resolved container name
968 * @param string $dir Resolved storage directory with no trailing slash
969 * @param string|null $after Storage path of file to list items after
970 * @param $limit integer Max number of items to list
971 * @param array $params Parameters for getDirectoryList()
972 * @return Array List of resolved paths of directories directly under $dir
974 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
976 if ( $after === INF
) {
977 return $dirs; // nothing more
980 wfProfileIn( __METHOD__
. '-' . $this->name
);
982 $container = $this->getContainer( $fullCont );
983 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
984 // Non-recursive: only list dirs right under $dir
985 if ( !empty( $params['topOnly'] ) ) {
986 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
987 foreach ( $objects as $object ) { // files and directories
988 if ( substr( $object, -1 ) === '/' ) {
989 $dirs[] = $object; // directories end in '/'
992 // Recursive: list all dirs under $dir and its subdirs
994 // Get directory from last item of prior page
995 $lastDir = $this->getParentDir( $after ); // must be first page
996 $objects = $container->list_objects( $limit, $after, $prefix );
997 foreach ( $objects as $object ) { // files
998 $objectDir = $this->getParentDir( $object ); // directory of object
999 if ( $objectDir !== false && $objectDir !== $dir ) {
1000 // Swift stores paths in UTF-8, using binary sorting.
1001 // See function "create_container_table" in common/db.py.
1002 // If a directory is not "greater" than the last one,
1003 // then it was already listed by the calling iterator.
1004 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
1006 do { // add dir and all its parent dirs
1007 $dirs[] = "{$pDir}/";
1008 $pDir = $this->getParentDir( $pDir );
1009 } while ( $pDir !== false // sanity
1010 && strcmp( $pDir, $lastDir ) > 0 // not done already
1011 && strlen( $pDir ) > strlen( $dir ) // within $dir
1014 $lastDir = $objectDir;
1018 // Page on the unfiltered directory listing (what is returned may be filtered)
1019 if ( count( $objects ) < $limit ) {
1020 $after = INF
; // avoid a second RTT
1022 $after = end( $objects ); // update last item
1024 } catch ( NoSuchContainerException
$e ) {
1025 } catch ( CloudFilesException
$e ) { // some other exception?
1026 $this->handleException( $e, null, __METHOD__
,
1027 array( 'cont' => $fullCont, 'dir' => $dir ) );
1029 wfProfileOut( __METHOD__
. '-' . $this->name
);
1034 protected function getParentDir( $path ) {
1035 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
1039 * Do not call this function outside of SwiftFileBackendFileList
1041 * @param string $fullCont Resolved container name
1042 * @param string $dir Resolved storage directory with no trailing slash
1043 * @param string|null $after Storage path of file to list items after
1044 * @param $limit integer Max number of items to list
1045 * @param array $params Parameters for getDirectoryList()
1046 * @return Array List of resolved paths of files under $dir
1048 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1050 if ( $after === INF
) {
1051 return $files; // nothing more
1054 wfProfileIn( __METHOD__
. '-' . $this->name
);
1056 $container = $this->getContainer( $fullCont );
1057 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
1058 // Non-recursive: only list files right under $dir
1059 if ( !empty( $params['topOnly'] ) ) { // files and dirs
1060 if ( !empty( $params['adviseStat'] ) ) {
1061 $limit = min( $limit, self
::CACHE_CHEAP_SIZE
);
1062 // Note: get_objects() does not include directories
1063 $objects = $this->loadObjectListing( $params, $dir,
1064 $container->get_objects( $limit, $after, $prefix, null, '/' ) );
1067 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1068 foreach ( $objects as $object ) { // files and directories
1069 if ( substr( $object, -1 ) !== '/' ) {
1070 $files[] = $object; // directories end in '/'
1074 // Recursive: list all files under $dir and its subdirs
1076 if ( !empty( $params['adviseStat'] ) ) {
1077 $limit = min( $limit, self
::CACHE_CHEAP_SIZE
);
1078 $objects = $this->loadObjectListing( $params, $dir,
1079 $container->get_objects( $limit, $after, $prefix ) );
1081 $objects = $container->list_objects( $limit, $after, $prefix );
1085 // Page on the unfiltered object listing (what is returned may be filtered)
1086 if ( count( $objects ) < $limit ) {
1087 $after = INF
; // avoid a second RTT
1089 $after = end( $objects ); // update last item
1091 } catch ( NoSuchContainerException
$e ) {
1092 } catch ( CloudFilesException
$e ) { // some other exception?
1093 $this->handleException( $e, null, __METHOD__
,
1094 array( 'cont' => $fullCont, 'dir' => $dir ) );
1096 wfProfileOut( __METHOD__
. '-' . $this->name
);
1102 * Load a list of objects that belong under $dir into stat cache
1103 * and return a list of the names of the objects in the same order.
1105 * @param array $params Parameters for getDirectoryList()
1106 * @param string $dir Resolved container directory path
1107 * @param array $cfObjects List of CF_Object items
1108 * @return array List of object names
1110 private function loadObjectListing( array $params, $dir, array $cfObjects ) {
1112 $storageDir = rtrim( $params['dir'], '/' );
1113 $suffixStart = ( $dir === '' ) ?
0 : strlen( $dir ) +
1; // size of "path/to/dir/"
1114 foreach ( $cfObjects as $object ) {
1115 $path = "{$storageDir}/" . substr( $object->name
, $suffixStart );
1117 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
1118 'mtime' => wfTimestamp( TS_MW
, $object->last_modified
),
1119 'size' => (int)$object->content_length
,
1120 'latest' => false // eventually consistent
1122 $this->cheapCache
->set( $path, 'stat', $val );
1123 $names[] = $object->name
;
1129 * @see FileBackendStore::doGetFileSha1base36()
1132 protected function doGetFileSha1base36( array $params ) {
1133 $stat = $this->getFileStat( $params );
1135 if ( !isset( $stat['sha1'] ) ) {
1136 // Stat entries filled by file listings don't include SHA1
1137 $this->clearCache( array( $params['src'] ) );
1138 $stat = $this->getFileStat( $params );
1140 return $stat['sha1'];
1147 * @see FileBackendStore::doStreamFile()
1150 protected function doStreamFile( array $params ) {
1151 $status = Status
::newGood();
1153 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1154 if ( $srcRel === null ) {
1155 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1159 $cont = $this->getContainer( $srcCont );
1160 } catch ( NoSuchContainerException
$e ) {
1161 $status->fatal( 'backend-fail-stream', $params['src'] );
1163 } catch ( CloudFilesException
$e ) { // some other exception?
1164 $this->handleException( $e, $status, __METHOD__
, $params );
1169 $output = fopen( 'php://output', 'wb' );
1170 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1171 $obj->stream( $output, $this->headersFromParams( $params ) );
1172 } catch ( NoSuchObjectException
$e ) {
1173 $status->fatal( 'backend-fail-stream', $params['src'] );
1174 } catch ( CloudFilesException
$e ) { // some other exception?
1175 $this->handleException( $e, $status, __METHOD__
, $params );
1182 * @see FileBackendStore::doGetLocalCopyMulti()
1183 * @return null|TempFSFile
1185 protected function doGetLocalCopyMulti( array $params ) {
1186 $tmpFiles = array();
1188 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1189 // Blindly create tmp files and stream to them, catching any exception if the file does
1190 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1191 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1192 $cfOps = array(); // (path => CF_Async_Op)
1194 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1195 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1196 if ( $srcRel === null ) {
1197 $tmpFiles[$path] = null;
1202 $sContObj = $this->getContainer( $srcCont );
1203 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1204 // Get source file extension
1205 $ext = FileBackend
::extensionFromPath( $path );
1206 // Create a new temporary file...
1207 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1209 $handle = fopen( $tmpFile->getPath(), 'wb' );
1211 $headers = $this->headersFromParams( $params );
1212 if ( count( $pathBatch ) > 1 ) {
1213 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1214 $cfOps[$path]->_file_handle
= $handle; // close this later
1216 $obj->stream( $handle, $headers );
1223 } catch ( NoSuchContainerException
$e ) {
1225 } catch ( NoSuchObjectException
$e ) {
1227 } catch ( CloudFilesException
$e ) { // some other exception?
1229 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1231 $tmpFiles[$path] = $tmpFile;
1234 $batch = new CF_Async_Op_Batch( $cfOps );
1235 $cfOps = $batch->execute();
1236 foreach ( $cfOps as $path => $cfOp ) {
1238 $cfOp->getLastResponse();
1239 } catch ( NoSuchContainerException
$e ) {
1240 $tmpFiles[$path] = null;
1241 } catch ( NoSuchObjectException
$e ) {
1242 $tmpFiles[$path] = null;
1243 } catch ( CloudFilesException
$e ) { // some other exception?
1244 $tmpFiles[$path] = null;
1245 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1247 fclose( $cfOp->_file_handle
); // close open handle
1255 * @see FileBackendStore::getFileHttpUrl()
1256 * @return string|null
1258 public function getFileHttpUrl( array $params ) {
1259 if ( $this->swiftTempUrlKey
!= '' ||
1260 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' ) )
1262 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1263 if ( $srcRel === null ) {
1264 return null; // invalid path
1267 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1268 $sContObj = $this->getContainer( $srcCont );
1269 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1270 if ( $this->swiftTempUrlKey
!= '' ) {
1271 return $obj->get_temp_url( $this->swiftTempUrlKey
, $ttl, "GET" );
1272 } else { // give S3 API URL for rgw
1273 $expires = time() +
$ttl;
1274 // Path for signature starts with the bucket
1275 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1276 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1277 // Calculate the hash
1278 $signature = base64_encode( hash_hmac(
1280 "GET\n\n\n{$expires}\n{$spath}",
1281 $this->rgwS3SecretKey
,
1284 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1285 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1286 return wfAppendQuery(
1287 str_replace( '/swift/v1', '', // S3 API is the rgw default
1288 $sContObj->cfs_http
->getStorageUrl() . $spath ),
1290 'Signature' => $signature,
1291 'Expires' => $expires,
1292 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1295 } catch ( NoSuchContainerException
$e ) {
1296 } catch ( CloudFilesException
$e ) { // some other exception?
1297 $this->handleException( $e, null, __METHOD__
, $params );
1304 * @see FileBackendStore::directoriesAreVirtual()
1307 protected function directoriesAreVirtual() {
1312 * Get headers to send to Swift when reading a file based
1313 * on a FileBackend params array, e.g. that of getLocalCopy().
1314 * $params is currently only checked for a 'latest' flag.
1316 * @param array $params
1319 protected function headersFromParams( array $params ) {
1321 if ( !empty( $params['latest'] ) ) {
1322 $hdrs[] = 'X-Newest: true';
1328 * @see FileBackendStore::doExecuteOpHandlesInternal()
1329 * @return Array List of corresponding Status objects
1331 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1332 $statuses = array();
1334 $cfOps = array(); // list of CF_Async_Op objects
1335 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1336 $cfOps[$index] = $fileOpHandle->cfOp
;
1338 $batch = new CF_Async_Op_Batch( $cfOps );
1340 $cfOps = $batch->execute();
1341 foreach ( $cfOps as $index => $cfOp ) {
1342 $status = Status
::newGood();
1343 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1344 try { // catch exceptions; update status
1345 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1346 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1347 } catch ( CloudFilesException
$e ) { // some other exception?
1348 $this->handleException( $e, $status,
1349 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1351 $statuses[$index] = $status;
1358 * Set read/write permissions for a Swift container.
1360 * $readGrps is a list of the possible criteria for a request to have
1361 * access to read a container. Each item is one of the following formats:
1362 * - account:user : Grants access if the request is by the given user
1363 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1364 * matches the expression and the request is not for a listing.
1365 * Setting this to '*' effectively makes a container public.
1366 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1367 * matches the expression and the request is for a listing.
1369 * $writeGrps is a list of the possible criteria for a request to have
1370 * access to write to a container. Each item is of the following format:
1371 * - account:user : Grants access if the request is by the given user
1373 * @see http://swift.openstack.org/misc.html#acls
1375 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1376 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1378 * @param $contObj CF_Container Swift container
1379 * @param array $readGrps List of read access routes
1380 * @param array $writeGrps List of write access routes
1383 protected function setContainerAccess(
1384 CF_Container
$contObj, array $readGrps, array $writeGrps
1386 $creds = $contObj->cfs_auth
->export_credentials();
1388 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1390 // Note: 10 second timeout consistent with php-cloudfiles
1391 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1392 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1393 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1394 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1396 return $req->execute(); // should return 204
1400 * Purge the CDN cache of affected objects if CDN caching is enabled.
1401 * This is for Rackspace/Akamai CDNs.
1403 * @param array $objects List of CF_Object items
1406 public function purgeCDNCache( array $objects ) {
1407 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1408 foreach ( $objects as $object ) {
1410 $object->purge_from_cdn();
1411 } catch ( CDNNotEnabledException
$e ) {
1412 // CDN not enabled; nothing to see here
1413 } catch ( CloudFilesException
$e ) {
1414 $this->handleException( $e, null, __METHOD__
,
1415 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1422 * Get an authenticated connection handle to the Swift proxy
1424 * @throws CloudFilesException
1425 * @throws CloudFilesException|Exception
1426 * @return CF_Connection|bool False on failure
1428 protected function getConnection() {
1429 if ( $this->connException
instanceof CloudFilesException
) {
1430 if ( ( time() - $this->connErrorTime
) < 60 ) {
1431 throw $this->connException
; // failed last attempt; don't bother
1432 } else { // actually retry this time
1433 $this->connException
= null;
1434 $this->connErrorTime
= 0;
1437 // Session keys expire after a while, so we renew them periodically
1438 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1439 // Authenticate with proxy and get a session key...
1440 if ( !$this->conn ||
$reAuth ) {
1441 $this->sessionStarted
= 0;
1442 $this->connContainerCache
->clear();
1443 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1444 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1445 if ( is_array( $creds ) ) { // cache hit
1446 $this->auth
->load_cached_credentials(
1447 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1448 $this->sessionStarted
= time() - ceil( $this->authTTL
/ 2 ); // skew for worst case
1449 } else { // cache miss
1451 $this->auth
->authenticate();
1452 $creds = $this->auth
->export_credentials();
1453 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/ 2 ) ); // cache
1454 $this->sessionStarted
= time();
1455 } catch ( CloudFilesException
$e ) {
1456 $this->connException
= $e; // don't keep re-trying
1457 $this->connErrorTime
= time();
1458 throw $e; // throw it back
1461 if ( $this->conn
) { // re-authorizing?
1462 $this->conn
->close(); // close active cURL handles in CF_Http object
1464 $this->conn
= new CF_Connection( $this->auth
);
1470 * Close the connection to the Swift proxy
1474 protected function closeConnection() {
1475 if ( $this->conn
) {
1476 $this->conn
->close(); // close active cURL handles in CF_Http object
1478 $this->sessionStarted
= 0;
1479 $this->connContainerCache
->clear();
1484 * Get the cache key for a container
1486 * @param $username string
1489 private function getCredsCacheKey( $username ) {
1490 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1494 * Get a Swift container object, possibly from process cache.
1495 * Use $reCache if the file count or byte count is needed.
1497 * @param string $container Container name
1498 * @param bool $bypassCache Bypass all caches and load from Swift
1499 * @return CF_Container
1500 * @throws CloudFilesException
1502 protected function getContainer( $container, $bypassCache = false ) {
1503 $conn = $this->getConnection(); // Swift proxy connection
1504 if ( $bypassCache ) { // purge cache
1505 $this->connContainerCache
->clear( $container );
1506 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1507 $this->primeContainerCache( array( $container ) ); // check persistent cache
1509 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1510 $contObj = $conn->get_container( $container );
1511 // NoSuchContainerException not thrown: container must exist
1512 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1513 if ( !$bypassCache ) {
1514 $this->setContainerCache( $container, // update persistent cache
1515 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1519 return $this->connContainerCache
->get( $container, 'obj' );
1523 * Create a Swift container
1525 * @param string $container Container name
1526 * @return CF_Container
1527 * @throws CloudFilesException
1529 protected function createContainer( $container ) {
1530 $conn = $this->getConnection(); // Swift proxy connection
1531 $contObj = $conn->create_container( $container );
1532 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1537 * Delete a Swift container
1539 * @param string $container Container name
1541 * @throws CloudFilesException
1543 protected function deleteContainer( $container ) {
1544 $conn = $this->getConnection(); // Swift proxy connection
1545 $this->connContainerCache
->clear( $container ); // purge
1546 $conn->delete_container( $container );
1550 * @see FileBackendStore::doPrimeContainerCache()
1553 protected function doPrimeContainerCache( array $containerInfo ) {
1555 $conn = $this->getConnection(); // Swift proxy connection
1556 foreach ( $containerInfo as $container => $info ) {
1557 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1558 $container, $info['count'], $info['bytes'] );
1559 $this->connContainerCache
->set( $container, 'obj', $contObj );
1561 } catch ( CloudFilesException
$e ) { // some other exception?
1562 $this->handleException( $e, null, __METHOD__
, array() );
1567 * Log an unexpected exception for this backend.
1568 * This also sets the Status object to have a fatal error.
1570 * @param $e Exception
1571 * @param $status Status|null
1572 * @param $func string
1573 * @param array $params
1576 protected function handleException( Exception
$e, $status, $func, array $params ) {
1577 if ( $status instanceof Status
) {
1578 if ( $e instanceof AuthenticationException
) {
1579 $status->fatal( 'backend-fail-connect', $this->name
);
1581 $status->fatal( 'backend-fail-internal', $this->name
);
1584 if ( $e->getMessage() ) {
1585 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1587 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1588 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1589 $this->closeConnection(); // force a re-connect and re-auth next time
1591 wfDebugLog( 'SwiftBackend',
1592 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1593 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1599 * @see FileBackendStoreOpHandle
1601 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1602 /** @var CF_Async_Op */
1605 public $affectedObjects = array();
1607 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1608 $this->backend
= $backend;
1609 $this->params
= $params;
1610 $this->call
= $call;
1611 $this->cfOp
= $cfOp;
1616 * SwiftFileBackend helper class to page through listings.
1617 * Swift also has a listing limit of 10,000 objects for sanity.
1618 * Do not use this class from places outside SwiftFileBackend.
1620 * @ingroup FileBackend
1622 abstract class SwiftFileBackendList
implements Iterator
{
1624 protected $bufferIter = array();
1625 protected $bufferAfter = null; // string; list items *after* this path
1626 protected $pos = 0; // integer
1628 protected $params = array();
1630 /** @var SwiftFileBackend */
1632 protected $container; // string; container name
1633 protected $dir; // string; storage directory
1634 protected $suffixStart; // integer
1636 const PAGE_SIZE
= 9000; // file listing buffer size
1639 * @param $backend SwiftFileBackend
1640 * @param string $fullCont Resolved container name
1641 * @param string $dir Resolved directory relative to container
1642 * @param array $params
1644 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1645 $this->backend
= $backend;
1646 $this->container
= $fullCont;
1648 if ( substr( $this->dir
, -1 ) === '/' ) {
1649 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1651 if ( $this->dir
== '' ) { // whole container
1652 $this->suffixStart
= 0;
1653 } else { // dir within container
1654 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1656 $this->params
= $params;
1660 * @see Iterator::key()
1663 public function key() {
1668 * @see Iterator::next()
1671 public function next() {
1672 // Advance to the next file in the page
1673 next( $this->bufferIter
);
1675 // Check if there are no files left in this page and
1676 // advance to the next page if this page was not empty.
1677 if ( !$this->valid() && count( $this->bufferIter
) ) {
1678 $this->bufferIter
= $this->pageFromList(
1679 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1680 ); // updates $this->bufferAfter
1685 * @see Iterator::rewind()
1688 public function rewind() {
1690 $this->bufferAfter
= null;
1691 $this->bufferIter
= $this->pageFromList(
1692 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1693 ); // updates $this->bufferAfter
1697 * @see Iterator::valid()
1700 public function valid() {
1701 if ( $this->bufferIter
=== null ) {
1702 return false; // some failure?
1704 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1709 * Get the given list portion (page)
1711 * @param string $container Resolved container name
1712 * @param string $dir Resolved path relative to container
1713 * @param $after string|null
1714 * @param $limit integer
1715 * @param array $params
1716 * @return Traversable|Array|null Returns null on failure
1718 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1722 * Iterator for listing directories
1724 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1726 * @see Iterator::current()
1727 * @return string|bool String (relative path) or false
1729 public function current() {
1730 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1734 * @see SwiftFileBackendList::pageFromList()
1735 * @return Array|null
1737 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1738 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1743 * Iterator for listing regular files
1745 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1747 * @see Iterator::current()
1748 * @return string|bool String (relative path) or false
1750 public function current() {
1751 return substr( current( $this->bufferIter
), $this->suffixStart
);
1755 * @see SwiftFileBackendList::pageFromList()
1756 * @return Array|null
1758 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1759 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );