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 $swiftAnonUser; // string; username to handle unauthenticated requests
44 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
45 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
46 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
48 /** @var CF_Connection */
49 protected $conn; // Swift connection handle
50 protected $sessionStarted = 0; // integer UNIX timestamp
52 /** @var CloudFilesException */
53 protected $connException;
54 protected $connErrorTime = 0; // UNIX timestamp
59 /** @var ProcessCacheLRU */
60 protected $connContainerCache; // container object cache
63 * @see FileBackendStore::__construct()
64 * Additional $config params include:
65 * - swiftAuthUrl : Swift authentication server URL
66 * - swiftUser : Swift user used by MediaWiki (account:username)
67 * - swiftKey : Swift authentication key for the above user
68 * - swiftAuthTTL : Swift authentication TTL (seconds)
69 * - swiftAnonUser : Swift user used for end-user requests (account:username).
70 * If set, then views of public containers are assumed to go
71 * through this user. If not set, then public containers are
72 * accessible to unauthenticated requests via ".r:*" in the ACL.
73 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
74 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
75 * If files may likely change, this should probably not exceed
76 * a few days. For example, deletions may take this long to apply.
77 * If object purging is enabled, however, this is not an issue.
78 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
79 * - shardViaHashLevels : Map of container names to sharding config with:
80 * - base : base of hash characters, 16 or 36
81 * - levels : the number of hash levels (and digits)
82 * - repeat : hash subdirectories are prefixed with all the
83 * parent hash directory names (e.g. "a/ab/abc")
84 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
85 * If those are not available, then the main cache will be used.
86 * This is probably insecure in shared hosting environments.
88 public function __construct( array $config ) {
89 parent
::__construct( $config );
90 if ( !MWInit
::classExists( 'CF_Constants' ) ) {
91 throw new MWException( 'SwiftCloudFiles extension not installed.' );
94 $this->auth
= new CF_Authentication(
97 null, // account; unused
98 $config['swiftAuthUrl']
101 $this->authTTL
= isset( $config['swiftAuthTTL'] )
102 ?
$config['swiftAuthTTL']
103 : 5 * 60; // some sane number
104 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
105 ?
$config['swiftAnonUser']
107 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
108 ?
$config['shardViaHashLevels']
110 $this->swiftUseCDN
= isset( $config['swiftUseCDN'] )
111 ?
$config['swiftUseCDN']
113 $this->swiftCDNExpiry
= isset( $config['swiftCDNExpiry'] )
114 ?
$config['swiftCDNExpiry']
115 : 12*3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
116 $this->swiftCDNPurgable
= isset( $config['swiftCDNPurgable'] )
117 ?
$config['swiftCDNPurgable']
119 // Cache container information to mask latency
120 $this->memCache
= wfGetMainCache();
121 // Process cache for container info
122 $this->connContainerCache
= new ProcessCacheLRU( 300 );
123 // Cache auth token information to avoid RTTs
124 if ( !empty( $config['cacheAuthInfo'] ) ) {
125 if ( php_sapi_name() === 'cli' ) {
126 $this->srvCache
= wfGetMainCache(); // preferrably memcached
128 try { // look for APC, XCache, WinCache, ect...
129 $this->srvCache
= ObjectCache
::newAccelerator( array() );
130 } catch ( Exception
$e ) {}
133 $this->srvCache
= $this->srvCache ?
$this->srvCache
: new EmptyBagOStuff();
137 * @see FileBackendStore::resolveContainerPath()
140 protected function resolveContainerPath( $container, $relStoragePath ) {
141 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
142 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
143 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
144 return null; // too long for Swift
146 return $relStoragePath;
150 * @see FileBackendStore::isPathUsableInternal()
153 public function isPathUsableInternal( $storagePath ) {
154 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
155 if ( $rel === null ) {
156 return false; // invalid
160 $this->getContainer( $container );
161 return true; // container exists
162 } catch ( NoSuchContainerException
$e ) {
163 } catch ( CloudFilesException
$e ) { // some other exception?
164 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
171 * @param $disposition string Content-Disposition header value
172 * @return string Truncated Content-Disposition header value to meet Swift limits
174 protected function truncDisp( $disposition ) {
176 foreach ( explode( ';', $disposition ) as $part ) {
177 $part = trim( $part );
178 $new = ( $res === '' ) ?
$part : "{$res};{$part}";
179 if ( strlen( $new ) <= 255 ) {
182 break; // too long; sigh
189 * @see FileBackendStore::doCreateInternal()
192 protected function doCreateInternal( array $params ) {
193 $status = Status
::newGood();
195 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
196 if ( $dstRel === null ) {
197 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
201 // (a) Check the destination container and object
203 $dContObj = $this->getContainer( $dstCont );
204 } catch ( NoSuchContainerException
$e ) {
205 $status->fatal( 'backend-fail-create', $params['dst'] );
207 } catch ( CloudFilesException
$e ) { // some other exception?
208 $this->handleException( $e, $status, __METHOD__
, $params );
212 // (b) Get a SHA-1 hash of the object
213 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
215 // (c) Actually create the object
217 // Create a fresh CF_Object with no fields preloaded.
218 // We don't want to preserve headers, metadata, and such.
219 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
220 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
221 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
222 // The MD5 here will be checked within Swift against its own MD5.
223 $obj->set_etag( md5( $params['content'] ) );
224 // Use the same content type as StreamFile for security
225 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
226 if ( !strlen( $obj->content_type
) ) { // special case
227 $obj->content_type
= 'unknown/unknown';
229 // Set the Content-Disposition header if requested
230 if ( isset( $params['disposition'] ) ) {
231 $obj->headers
['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
233 if ( !empty( $params['async'] ) ) { // deferred
234 $op = $obj->write_async( $params['content'] );
235 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $op );
236 $status->value
->affectedObjects
[] = $obj;
237 } else { // actually write the object in Swift
238 $obj->write( $params['content'] );
239 $this->purgeCDNCache( array( $obj ) );
241 } catch ( CDNNotEnabledException
$e ) {
242 // CDN not enabled; nothing to see here
243 } catch ( BadContentTypeException
$e ) {
244 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
245 } catch ( CloudFilesException
$e ) { // some other exception?
246 $this->handleException( $e, $status, __METHOD__
, $params );
253 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
255 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
257 $cfOp->getLastResponse();
258 } catch ( BadContentTypeException
$e ) {
259 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
264 * @see FileBackendStore::doStoreInternal()
267 protected function doStoreInternal( array $params ) {
268 $status = Status
::newGood();
270 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
271 if ( $dstRel === null ) {
272 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
276 // (a) Check the destination container and object
278 $dContObj = $this->getContainer( $dstCont );
279 } catch ( NoSuchContainerException
$e ) {
280 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
282 } catch ( CloudFilesException
$e ) { // some other exception?
283 $this->handleException( $e, $status, __METHOD__
, $params );
287 // (b) Get a SHA-1 hash of the object
288 $sha1Hash = sha1_file( $params['src'] );
289 if ( $sha1Hash === false ) { // source doesn't exist?
290 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
293 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
295 // (c) Actually store the object
297 // Create a fresh CF_Object with no fields preloaded.
298 // We don't want to preserve headers, metadata, and such.
299 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
300 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
301 // The MD5 here will be checked within Swift against its own MD5.
302 $obj->set_etag( md5_file( $params['src'] ) );
303 // Use the same content type as StreamFile for security
304 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
305 if ( !strlen( $obj->content_type
) ) { // special case
306 $obj->content_type
= 'unknown/unknown';
308 // Set the Content-Disposition header if requested
309 if ( isset( $params['disposition'] ) ) {
310 $obj->headers
['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
312 if ( !empty( $params['async'] ) ) { // deferred
313 wfSuppressWarnings();
314 $fp = fopen( $params['src'], 'rb' );
317 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
319 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
320 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $op );
321 $status->value
->resourcesToClose
[] = $fp;
322 $status->value
->affectedObjects
[] = $obj;
324 } else { // actually write the object in Swift
325 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
326 $this->purgeCDNCache( array( $obj ) );
328 } catch ( CDNNotEnabledException
$e ) {
329 // CDN not enabled; nothing to see here
330 } catch ( BadContentTypeException
$e ) {
331 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
332 } catch ( IOException
$e ) {
333 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
334 } catch ( CloudFilesException
$e ) { // some other exception?
335 $this->handleException( $e, $status, __METHOD__
, $params );
342 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
344 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
346 $cfOp->getLastResponse();
347 } catch ( BadContentTypeException
$e ) {
348 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
349 } catch ( IOException
$e ) {
350 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
355 * @see FileBackendStore::doCopyInternal()
358 protected function doCopyInternal( array $params ) {
359 $status = Status
::newGood();
361 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
362 if ( $srcRel === null ) {
363 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
367 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
368 if ( $dstRel === null ) {
369 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
373 // (a) Check the source/destination containers and destination object
375 $sContObj = $this->getContainer( $srcCont );
376 $dContObj = $this->getContainer( $dstCont );
377 } catch ( NoSuchContainerException
$e ) {
378 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
380 } catch ( CloudFilesException
$e ) { // some other exception?
381 $this->handleException( $e, $status, __METHOD__
, $params );
385 // (b) Actually copy the file to the destination
387 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
388 $hdrs = array(); // source file headers to override with new values
389 if ( isset( $params['disposition'] ) ) {
390 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
392 if ( !empty( $params['async'] ) ) { // deferred
393 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
394 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $op );
395 $status->value
->affectedObjects
[] = $dstObj;
396 } else { // actually write the object in Swift
397 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
398 $this->purgeCDNCache( array( $dstObj ) );
400 } catch ( CDNNotEnabledException
$e ) {
401 // CDN not enabled; nothing to see here
402 } catch ( NoSuchObjectException
$e ) { // source object does not exist
403 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
404 } catch ( CloudFilesException
$e ) { // some other exception?
405 $this->handleException( $e, $status, __METHOD__
, $params );
412 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
414 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
416 $cfOp->getLastResponse();
417 } catch ( NoSuchObjectException
$e ) { // source object does not exist
418 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
423 * @see FileBackendStore::doMoveInternal()
426 protected function doMoveInternal( array $params ) {
427 $status = Status
::newGood();
429 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
430 if ( $srcRel === null ) {
431 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
435 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
436 if ( $dstRel === null ) {
437 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
441 // (a) Check the source/destination containers and destination object
443 $sContObj = $this->getContainer( $srcCont );
444 $dContObj = $this->getContainer( $dstCont );
445 } catch ( NoSuchContainerException
$e ) {
446 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
448 } catch ( CloudFilesException
$e ) { // some other exception?
449 $this->handleException( $e, $status, __METHOD__
, $params );
453 // (b) Actually move the file to the destination
455 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
456 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
457 $hdrs = array(); // source file headers to override with new values
458 if ( isset( $params['disposition'] ) ) {
459 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
461 if ( !empty( $params['async'] ) ) { // deferred
462 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
463 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
464 $status->value
->affectedObjects
[] = $srcObj;
465 $status->value
->affectedObjects
[] = $dstObj;
466 } else { // actually write the object in Swift
467 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
468 $this->purgeCDNCache( array( $srcObj ) );
469 $this->purgeCDNCache( array( $dstObj ) );
471 } catch ( CDNNotEnabledException
$e ) {
472 // CDN not enabled; nothing to see here
473 } catch ( NoSuchObjectException
$e ) { // source object does not exist
474 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
475 } catch ( CloudFilesException
$e ) { // some other exception?
476 $this->handleException( $e, $status, __METHOD__
, $params );
483 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
485 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
487 $cfOp->getLastResponse();
488 } catch ( NoSuchObjectException
$e ) { // source object does not exist
489 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
494 * @see FileBackendStore::doDeleteInternal()
497 protected function doDeleteInternal( array $params ) {
498 $status = Status
::newGood();
500 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
501 if ( $srcRel === null ) {
502 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
507 $sContObj = $this->getContainer( $srcCont );
508 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
509 if ( !empty( $params['async'] ) ) { // deferred
510 $op = $sContObj->delete_object_async( $srcRel );
511 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
512 $status->value
->affectedObjects
[] = $srcObj;
513 } else { // actually write the object in Swift
514 $sContObj->delete_object( $srcRel );
515 $this->purgeCDNCache( array( $srcObj ) );
517 } catch ( CDNNotEnabledException
$e ) {
518 // CDN not enabled; nothing to see here
519 } catch ( NoSuchContainerException
$e ) {
520 $status->fatal( 'backend-fail-delete', $params['src'] );
521 } catch ( NoSuchObjectException
$e ) {
522 if ( empty( $params['ignoreMissingSource'] ) ) {
523 $status->fatal( 'backend-fail-delete', $params['src'] );
525 } catch ( CloudFilesException
$e ) { // some other exception?
526 $this->handleException( $e, $status, __METHOD__
, $params );
533 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
535 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
537 $cfOp->getLastResponse();
538 } catch ( NoSuchContainerException
$e ) {
539 $status->fatal( 'backend-fail-delete', $params['src'] );
540 } catch ( NoSuchObjectException
$e ) {
541 if ( empty( $params['ignoreMissingSource'] ) ) {
542 $status->fatal( 'backend-fail-delete', $params['src'] );
548 * @see FileBackendStore::doPrepareInternal()
551 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
552 $status = Status
::newGood();
554 // (a) Check if container already exists
556 $contObj = $this->getContainer( $fullCont );
557 // NoSuchContainerException not thrown: container must exist
558 return $status; // already exists
559 } catch ( NoSuchContainerException
$e ) {
560 // NoSuchContainerException thrown: container does not exist
561 } catch ( CloudFilesException
$e ) { // some other exception?
562 $this->handleException( $e, $status, __METHOD__
, $params );
566 // (b) Create container as needed
568 $contObj = $this->createContainer( $fullCont );
569 if ( !empty( $params['noAccess'] ) ) {
570 // Make container private to end-users...
571 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
573 // Make container public to end-users...
574 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
576 if ( $this->swiftUseCDN
) { // Rackspace style CDN
577 $contObj->make_public( $this->swiftCDNExpiry
);
579 } catch ( CDNNotEnabledException
$e ) {
580 // CDN not enabled; nothing to see here
581 } catch ( CloudFilesException
$e ) { // some other exception?
582 $this->handleException( $e, $status, __METHOD__
, $params );
590 * @see FileBackendStore::doSecureInternal()
593 protected function doSecureInternal( $fullCont, $dir, array $params ) {
594 $status = Status
::newGood();
595 if ( empty( $params['noAccess'] ) ) {
596 return $status; // nothing to do
599 // Restrict container from end-users...
601 // doPrepareInternal() should have been called,
602 // so the Swift container should already exist...
603 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
604 // NoSuchContainerException not thrown: container must exist
606 // Make container private to end-users...
607 $status->merge( $this->setContainerAccess(
609 array( $this->auth
->username
), // read
610 array( $this->auth
->username
) // write
612 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
613 $contObj->make_private();
615 } catch ( CDNNotEnabledException
$e ) {
616 // CDN not enabled; nothing to see here
617 } catch ( CloudFilesException
$e ) { // some other exception?
618 $this->handleException( $e, $status, __METHOD__
, $params );
625 * @see FileBackendStore::doPublishInternal()
628 protected function doPublishInternal( $fullCont, $dir, array $params ) {
629 $status = Status
::newGood();
631 // Unrestrict container from end-users...
633 // doPrepareInternal() should have been called,
634 // so the Swift container should already exist...
635 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
636 // NoSuchContainerException not thrown: container must exist
638 // Make container public to end-users...
639 if ( $this->swiftAnonUser
!= '' ) {
640 $status->merge( $this->setContainerAccess(
642 array( $this->auth
->username
, $this->swiftAnonUser
), // read
643 array( $this->auth
->username
, $this->swiftAnonUser
) // write
646 $status->merge( $this->setContainerAccess(
648 array( $this->auth
->username
, '.r:*' ), // read
649 array( $this->auth
->username
) // write
652 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
653 $contObj->make_public();
655 } catch ( CDNNotEnabledException
$e ) {
656 // CDN not enabled; nothing to see here
657 } catch ( CloudFilesException
$e ) { // some other exception?
658 $this->handleException( $e, $status, __METHOD__
, $params );
665 * @see FileBackendStore::doCleanInternal()
668 protected function doCleanInternal( $fullCont, $dir, array $params ) {
669 $status = Status
::newGood();
671 // Only containers themselves can be removed, all else is virtual
673 return $status; // nothing to do
676 // (a) Check the container
678 $contObj = $this->getContainer( $fullCont, true );
679 } catch ( NoSuchContainerException
$e ) {
680 return $status; // ok, nothing to do
681 } catch ( CloudFilesException
$e ) { // some other exception?
682 $this->handleException( $e, $status, __METHOD__
, $params );
686 // (b) Delete the container if empty
687 if ( $contObj->object_count
== 0 ) {
689 $this->deleteContainer( $fullCont );
690 } catch ( NoSuchContainerException
$e ) {
691 return $status; // race?
692 } catch ( NonEmptyContainerException
$e ) {
693 return $status; // race? consistency delay?
694 } catch ( CloudFilesException
$e ) { // some other exception?
695 $this->handleException( $e, $status, __METHOD__
, $params );
704 * @see FileBackendStore::doFileExists()
705 * @return array|bool|null
707 protected function doGetFileStat( array $params ) {
708 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
709 if ( $srcRel === null ) {
710 return false; // invalid storage path
715 $contObj = $this->getContainer( $srcCont );
716 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
717 $this->addMissingMetadata( $srcObj, $params['src'] );
719 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
720 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
721 'size' => (int)$srcObj->content_length
,
722 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
724 } catch ( NoSuchContainerException
$e ) {
725 } catch ( NoSuchObjectException
$e ) {
726 } catch ( CloudFilesException
$e ) { // some other exception?
728 $this->handleException( $e, null, __METHOD__
, $params );
735 * Fill in any missing object metadata and save it to Swift
737 * @param $obj CF_Object
738 * @param $path string Storage path to object
739 * @return bool Success
740 * @throws Exception cloudfiles exceptions
742 protected function addMissingMetadata( CF_Object
$obj, $path ) {
743 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
744 return true; // nothing to do
746 wfProfileIn( __METHOD__
);
747 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
748 $status = Status
::newGood();
749 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
750 if ( $status->isOK() ) {
751 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
753 $hash = $tmpFile->getSha1Base36();
754 if ( $hash !== false ) {
755 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
756 $obj->sync_metadata(); // save to Swift
757 wfProfileOut( __METHOD__
);
758 return true; // success
762 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
763 wfProfileOut( __METHOD__
);
764 return false; // failed
768 * @see FileBackendStore::doGetFileContentsMulti()
771 protected function doGetFileContentsMulti( array $params ) {
774 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
775 // Blindly create tmp files and stream to them, catching any exception if the file does
776 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
777 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
778 $cfOps = array(); // (path => CF_Async_Op)
780 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
781 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
782 if ( $srcRel === null ) {
783 $contents[$path] = false;
788 $sContObj = $this->getContainer( $srcCont );
789 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
790 // Get source file extension
791 $ext = FileBackend
::extensionFromPath( $path );
792 // Create a new temporary memory file...
793 $handle = fopen( 'php://temp', 'wb' );
795 $headers = $this->headersFromParams( $params );
796 if ( count( $pathBatch ) > 1 ) {
797 $cfOps[$path] = $obj->stream_async( $handle, $headers );
798 $cfOps[$path]->_file_handle
= $handle; // close this later
800 $obj->stream( $handle, $headers );
801 rewind( $handle ); // start from the beginning
802 $data = stream_get_contents( $handle );
808 } catch ( NoSuchContainerException
$e ) {
810 } catch ( NoSuchObjectException
$e ) {
812 } catch ( CloudFilesException
$e ) { // some other exception?
814 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
816 $contents[$path] = $data;
819 $batch = new CF_Async_Op_Batch( $cfOps );
820 $cfOps = $batch->execute();
821 foreach ( $cfOps as $path => $cfOp ) {
823 $cfOp->getLastResponse();
824 rewind( $cfOp->_file_handle
); // start from the beginning
825 $contents[$path] = stream_get_contents( $cfOp->_file_handle
);
826 } catch ( NoSuchContainerException
$e ) {
827 $contents[$path] = false;
828 } catch ( NoSuchObjectException
$e ) {
829 $contents[$path] = false;
830 } catch ( CloudFilesException
$e ) { // some other exception?
831 $contents[$path] = false;
832 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
834 fclose( $cfOp->_file_handle
); // close open handle
842 * @see FileBackendStore::doDirectoryExists()
845 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
847 $container = $this->getContainer( $fullCont );
848 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
849 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
850 } catch ( NoSuchContainerException
$e ) {
852 } catch ( CloudFilesException
$e ) { // some other exception?
853 $this->handleException( $e, null, __METHOD__
,
854 array( 'cont' => $fullCont, 'dir' => $dir ) );
857 return null; // error
861 * @see FileBackendStore::getDirectoryListInternal()
862 * @return SwiftFileBackendDirList
864 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
865 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
869 * @see FileBackendStore::getFileListInternal()
870 * @return SwiftFileBackendFileList
872 public function getFileListInternal( $fullCont, $dir, array $params ) {
873 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
877 * Do not call this function outside of SwiftFileBackendFileList
879 * @param $fullCont string Resolved container name
880 * @param $dir string Resolved storage directory with no trailing slash
881 * @param $after string|null Storage path of file to list items after
882 * @param $limit integer Max number of items to list
883 * @param $params Array Includes flag for 'topOnly'
884 * @return Array List of relative paths of dirs directly under $dir
886 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
888 if ( $after === INF
) {
889 return $dirs; // nothing more
891 wfProfileIn( __METHOD__
. '-' . $this->name
);
894 $container = $this->getContainer( $fullCont );
895 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
896 // Non-recursive: only list dirs right under $dir
897 if ( !empty( $params['topOnly'] ) ) {
898 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
899 foreach ( $objects as $object ) { // files and dirs
900 if ( substr( $object, -1 ) === '/' ) {
901 $dirs[] = $object; // directories end in '/'
904 // Recursive: list all dirs under $dir and its subdirs
906 // Get directory from last item of prior page
907 $lastDir = $this->getParentDir( $after ); // must be first page
908 $objects = $container->list_objects( $limit, $after, $prefix );
909 foreach ( $objects as $object ) { // files
910 $objectDir = $this->getParentDir( $object ); // directory of object
911 if ( $objectDir !== false ) { // file has a parent dir
912 // Swift stores paths in UTF-8, using binary sorting.
913 // See function "create_container_table" in common/db.py.
914 // If a directory is not "greater" than the last one,
915 // then it was already listed by the calling iterator.
916 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
918 do { // add dir and all its parent dirs
919 $dirs[] = "{$pDir}/";
920 $pDir = $this->getParentDir( $pDir );
921 } while ( $pDir !== false // sanity
922 && strcmp( $pDir, $lastDir ) > 0 // not done already
923 && strlen( $pDir ) > strlen( $dir ) // within $dir
926 $lastDir = $objectDir;
930 if ( count( $objects ) < $limit ) {
931 $after = INF
; // avoid a second RTT
933 $after = end( $objects ); // update last item
935 } catch ( NoSuchContainerException
$e ) {
936 } catch ( CloudFilesException
$e ) { // some other exception?
937 $this->handleException( $e, null, __METHOD__
,
938 array( 'cont' => $fullCont, 'dir' => $dir ) );
941 wfProfileOut( __METHOD__
. '-' . $this->name
);
945 protected function getParentDir( $path ) {
946 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
950 * Do not call this function outside of SwiftFileBackendFileList
952 * @param $fullCont string Resolved container name
953 * @param $dir string Resolved storage directory with no trailing slash
954 * @param $after string|null Storage path of file to list items after
955 * @param $limit integer Max number of items to list
956 * @param $params Array Includes flag for 'topOnly'
957 * @return Array List of relative paths of files under $dir
959 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
961 if ( $after === INF
) {
962 return $files; // nothing more
964 wfProfileIn( __METHOD__
. '-' . $this->name
);
967 $container = $this->getContainer( $fullCont );
968 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
969 // Non-recursive: only list files right under $dir
970 if ( !empty( $params['topOnly'] ) ) { // files and dirs
971 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
972 foreach ( $objects as $object ) {
973 if ( substr( $object, -1 ) !== '/' ) {
974 $files[] = $object; // directories end in '/'
977 // Recursive: list all files under $dir and its subdirs
979 $objects = $container->list_objects( $limit, $after, $prefix );
982 if ( count( $objects ) < $limit ) {
983 $after = INF
; // avoid a second RTT
985 $after = end( $objects ); // update last item
987 } catch ( NoSuchContainerException
$e ) {
988 } catch ( CloudFilesException
$e ) { // some other exception?
989 $this->handleException( $e, null, __METHOD__
,
990 array( 'cont' => $fullCont, 'dir' => $dir ) );
993 wfProfileOut( __METHOD__
. '-' . $this->name
);
998 * @see FileBackendStore::doGetFileSha1base36()
1001 protected function doGetFileSha1base36( array $params ) {
1002 $stat = $this->getFileStat( $params );
1004 return $stat['sha1'];
1011 * @see FileBackendStore::doStreamFile()
1014 protected function doStreamFile( array $params ) {
1015 $status = Status
::newGood();
1017 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1018 if ( $srcRel === null ) {
1019 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1023 $cont = $this->getContainer( $srcCont );
1024 } catch ( NoSuchContainerException
$e ) {
1025 $status->fatal( 'backend-fail-stream', $params['src'] );
1027 } catch ( CloudFilesException
$e ) { // some other exception?
1028 $this->handleException( $e, $status, __METHOD__
, $params );
1033 $output = fopen( 'php://output', 'wb' );
1034 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1035 $obj->stream( $output, $this->headersFromParams( $params ) );
1036 } catch ( NoSuchObjectException
$e ) {
1037 $status->fatal( 'backend-fail-stream', $params['src'] );
1038 } catch ( CloudFilesException
$e ) { // some other exception?
1039 $this->handleException( $e, $status, __METHOD__
, $params );
1046 * @see FileBackendStore::doGetLocalCopyMulti()
1047 * @return null|TempFSFile
1049 protected function doGetLocalCopyMulti( array $params ) {
1050 $tmpFiles = array();
1052 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1053 // Blindly create tmp files and stream to them, catching any exception if the file does
1054 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1055 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1056 $cfOps = array(); // (path => CF_Async_Op)
1058 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1059 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1060 if ( $srcRel === null ) {
1061 $tmpFiles[$path] = null;
1066 $sContObj = $this->getContainer( $srcCont );
1067 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1068 // Get source file extension
1069 $ext = FileBackend
::extensionFromPath( $path );
1070 // Create a new temporary file...
1071 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1073 $handle = fopen( $tmpFile->getPath(), 'wb' );
1075 $headers = $this->headersFromParams( $params );
1076 if ( count( $pathBatch ) > 1 ) {
1077 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1078 $cfOps[$path]->_file_handle
= $handle; // close this later
1080 $obj->stream( $handle, $headers );
1087 } catch ( NoSuchContainerException
$e ) {
1089 } catch ( NoSuchObjectException
$e ) {
1091 } catch ( CloudFilesException
$e ) { // some other exception?
1093 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1095 $tmpFiles[$path] = $tmpFile;
1098 $batch = new CF_Async_Op_Batch( $cfOps );
1099 $cfOps = $batch->execute();
1100 foreach ( $cfOps as $path => $cfOp ) {
1102 $cfOp->getLastResponse();
1103 } catch ( NoSuchContainerException
$e ) {
1104 $tmpFiles[$path] = null;
1105 } catch ( NoSuchObjectException
$e ) {
1106 $tmpFiles[$path] = null;
1107 } catch ( CloudFilesException
$e ) { // some other exception?
1108 $tmpFiles[$path] = null;
1109 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1111 fclose( $cfOp->_file_handle
); // close open handle
1119 * @see FileBackendStore::directoriesAreVirtual()
1122 protected function directoriesAreVirtual() {
1127 * Get headers to send to Swift when reading a file based
1128 * on a FileBackend params array, e.g. that of getLocalCopy().
1129 * $params is currently only checked for a 'latest' flag.
1131 * @param $params Array
1134 protected function headersFromParams( array $params ) {
1136 if ( !empty( $params['latest'] ) ) {
1137 $hdrs[] = 'X-Newest: true';
1143 * @see FileBackendStore::doExecuteOpHandlesInternal()
1144 * @return Array List of corresponding Status objects
1146 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1147 $statuses = array();
1149 $cfOps = array(); // list of CF_Async_Op objects
1150 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1151 $cfOps[$index] = $fileOpHandle->cfOp
;
1153 $batch = new CF_Async_Op_Batch( $cfOps );
1155 $cfOps = $batch->execute();
1156 foreach ( $cfOps as $index => $cfOp ) {
1157 $status = Status
::newGood();
1158 try { // catch exceptions; update status
1159 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1160 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1161 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1162 } catch ( CloudFilesException
$e ) { // some other exception?
1163 $this->handleException( $e, $status,
1164 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1166 $statuses[$index] = $status;
1173 * Set read/write permissions for a Swift container.
1175 * $readGrps is a list of the possible criteria for a request to have
1176 * access to read a container. Each item is one of the following formats:
1177 * - account:user : Grants access if the request is by the given user
1178 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1179 * matches the expression and the request is not for a listing.
1180 * Setting this to '*' effectively makes a container public.
1181 * -".rlistings:<regex>": Grants access if the request is from a referrer host that
1182 * matches the expression and the request for a listing.
1184 * $writeGrps is a list of the possible criteria for a request to have
1185 * access to write to a container. Each item is of the following format:
1186 * - account:user : Grants access if the request is by the given user
1188 * @see http://swift.openstack.org/misc.html#acls
1190 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1191 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1193 * @param $contObj CF_Container Swift container
1194 * @param $readGrps Array List of read access routes
1195 * @param $writeGrps Array List of write access routes
1198 protected function setContainerAccess(
1199 CF_Container
$contObj, array $readGrps, array $writeGrps
1201 $creds = $contObj->cfs_auth
->export_credentials();
1203 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1205 // Note: 10 second timeout consistent with php-cloudfiles
1206 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1207 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1208 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1209 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1211 return $req->execute(); // should return 204
1215 * Purge the CDN cache of affected objects if CDN caching is enabled.
1216 * This is for Rackspace/Akamai CDNs.
1218 * @param $objects Array List of CF_Object items
1221 public function purgeCDNCache( array $objects ) {
1222 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1223 foreach ( $objects as $object ) {
1225 $object->purge_from_cdn();
1226 } catch ( CDNNotEnabledException
$e ) {
1227 // CDN not enabled; nothing to see here
1228 } catch ( CloudFilesException
$e ) {
1229 $this->handleException( $e, null, __METHOD__
,
1230 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1237 * Get an authenticated connection handle to the Swift proxy
1239 * @return CF_Connection|bool False on failure
1240 * @throws CloudFilesException
1242 protected function getConnection() {
1243 if ( $this->connException
instanceof CloudFilesException
) {
1244 if ( ( time() - $this->connErrorTime
) < 60 ) {
1245 throw $this->connException
; // failed last attempt; don't bother
1246 } else { // actually retry this time
1247 $this->connException
= null;
1248 $this->connErrorTime
= 0;
1251 // Session keys expire after a while, so we renew them periodically
1252 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1253 // Authenticate with proxy and get a session key...
1254 if ( !$this->conn ||
$reAuth ) {
1255 $this->sessionStarted
= 0;
1256 $this->connContainerCache
->clear();
1257 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1258 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1259 if ( is_array( $creds ) ) { // cache hit
1260 $this->auth
->load_cached_credentials(
1261 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1262 $this->sessionStarted
= time() - ceil( $this->authTTL
/2 ); // skew for worst case
1263 } else { // cache miss
1265 $this->auth
->authenticate();
1266 $creds = $this->auth
->export_credentials();
1267 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/2 ) ); // cache
1268 $this->sessionStarted
= time();
1269 } catch ( CloudFilesException
$e ) {
1270 $this->connException
= $e; // don't keep re-trying
1271 $this->connErrorTime
= time();
1272 throw $e; // throw it back
1275 if ( $this->conn
) { // re-authorizing?
1276 $this->conn
->close(); // close active cURL handles in CF_Http object
1278 $this->conn
= new CF_Connection( $this->auth
);
1284 * Close the connection to the Swift proxy
1288 protected function closeConnection() {
1289 if ( $this->conn
) {
1290 $this->conn
->close(); // close active cURL handles in CF_Http object
1291 $this->sessionStarted
= 0;
1292 $this->connContainerCache
->clear();
1297 * Get the cache key for a container
1299 * @param $username string
1302 private function getCredsCacheKey( $username ) {
1303 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1307 * Get a Swift container object, possibly from process cache.
1308 * Use $reCache if the file count or byte count is needed.
1310 * @param $container string Container name
1311 * @param $bypassCache bool Bypass all caches and load from Swift
1312 * @return CF_Container
1313 * @throws CloudFilesException
1315 protected function getContainer( $container, $bypassCache = false ) {
1316 $conn = $this->getConnection(); // Swift proxy connection
1317 if ( $bypassCache ) { // purge cache
1318 $this->connContainerCache
->clear( $container );
1319 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1320 $this->primeContainerCache( array( $container ) ); // check persistent cache
1322 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1323 $contObj = $conn->get_container( $container );
1324 // NoSuchContainerException not thrown: container must exist
1325 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1326 if ( !$bypassCache ) {
1327 $this->setContainerCache( $container, // update persistent cache
1328 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1332 return $this->connContainerCache
->get( $container, 'obj' );
1336 * Create a Swift container
1338 * @param $container string Container name
1339 * @return CF_Container
1340 * @throws CloudFilesException
1342 protected function createContainer( $container ) {
1343 $conn = $this->getConnection(); // Swift proxy connection
1344 $contObj = $conn->create_container( $container );
1345 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1350 * Delete a Swift container
1352 * @param $container string Container name
1354 * @throws CloudFilesException
1356 protected function deleteContainer( $container ) {
1357 $conn = $this->getConnection(); // Swift proxy connection
1358 $this->connContainerCache
->clear( $container ); // purge
1359 $conn->delete_container( $container );
1363 * @see FileBackendStore::doPrimeContainerCache()
1366 protected function doPrimeContainerCache( array $containerInfo ) {
1368 $conn = $this->getConnection(); // Swift proxy connection
1369 foreach ( $containerInfo as $container => $info ) {
1370 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1371 $container, $info['count'], $info['bytes'] );
1372 $this->connContainerCache
->set( $container, 'obj', $contObj );
1374 } catch ( CloudFilesException
$e ) { // some other exception?
1375 $this->handleException( $e, null, __METHOD__
, array() );
1380 * Log an unexpected exception for this backend.
1381 * This also sets the Status object to have a fatal error.
1383 * @param $e Exception
1384 * @param $status Status|null
1385 * @param $func string
1386 * @param $params Array
1389 protected function handleException( Exception
$e, $status, $func, array $params ) {
1390 if ( $status instanceof Status
) {
1391 if ( $e instanceof AuthenticationException
) {
1392 $status->fatal( 'backend-fail-connect', $this->name
);
1394 $status->fatal( 'backend-fail-internal', $this->name
);
1397 if ( $e->getMessage() ) {
1398 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1400 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1401 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1402 $this->closeConnection(); // force a re-connect and re-auth next time
1404 wfDebugLog( 'SwiftBackend',
1405 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1406 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1412 * @see FileBackendStoreOpHandle
1414 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1415 /** @var CF_Async_Op */
1418 public $affectedObjects = array();
1420 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1421 $this->backend
= $backend;
1422 $this->params
= $params;
1423 $this->call
= $call;
1424 $this->cfOp
= $cfOp;
1429 * SwiftFileBackend helper class to page through listings.
1430 * Swift also has a listing limit of 10,000 objects for sanity.
1431 * Do not use this class from places outside SwiftFileBackend.
1433 * @ingroup FileBackend
1435 abstract class SwiftFileBackendList
implements Iterator
{
1437 protected $bufferIter = array();
1438 protected $bufferAfter = null; // string; list items *after* this path
1439 protected $pos = 0; // integer
1441 protected $params = array();
1443 /** @var SwiftFileBackend */
1445 protected $container; // string; container name
1446 protected $dir; // string; storage directory
1447 protected $suffixStart; // integer
1449 const PAGE_SIZE
= 9000; // file listing buffer size
1452 * @param $backend SwiftFileBackend
1453 * @param $fullCont string Resolved container name
1454 * @param $dir string Resolved directory relative to container
1455 * @param $params Array
1457 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1458 $this->backend
= $backend;
1459 $this->container
= $fullCont;
1461 if ( substr( $this->dir
, -1 ) === '/' ) {
1462 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1464 if ( $this->dir
== '' ) { // whole container
1465 $this->suffixStart
= 0;
1466 } else { // dir within container
1467 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1469 $this->params
= $params;
1473 * @see Iterator::key()
1476 public function key() {
1481 * @see Iterator::next()
1484 public function next() {
1485 // Advance to the next file in the page
1486 next( $this->bufferIter
);
1488 // Check if there are no files left in this page and
1489 // advance to the next page if this page was not empty.
1490 if ( !$this->valid() && count( $this->bufferIter
) ) {
1491 $this->bufferIter
= $this->pageFromList(
1492 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1493 ); // updates $this->bufferAfter
1498 * @see Iterator::rewind()
1501 public function rewind() {
1503 $this->bufferAfter
= null;
1504 $this->bufferIter
= $this->pageFromList(
1505 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1506 ); // updates $this->bufferAfter
1510 * @see Iterator::valid()
1513 public function valid() {
1514 if ( $this->bufferIter
=== null ) {
1515 return false; // some failure?
1517 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1522 * Get the given list portion (page)
1524 * @param $container string Resolved container name
1525 * @param $dir string Resolved path relative to container
1526 * @param $after string|null
1527 * @param $limit integer
1528 * @param $params Array
1529 * @return Traversable|Array|null Returns null on failure
1531 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1535 * Iterator for listing directories
1537 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1539 * @see Iterator::current()
1540 * @return string|bool String (relative path) or false
1542 public function current() {
1543 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1547 * @see SwiftFileBackendList::pageFromList()
1548 * @return Array|null
1550 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1551 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1556 * Iterator for listing regular files
1558 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1560 * @see Iterator::current()
1561 * @return string|bool String (relative path) or false
1563 public function current() {
1564 return substr( current( $this->bufferIter
), $this->suffixStart
);
1568 * @see SwiftFileBackendList::pageFromList()
1569 * @return Array|null
1571 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1572 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );