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 if ( empty( $params['ignoreMissingSource'] ) ) {
404 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
406 } catch ( CloudFilesException
$e ) { // some other exception?
407 $this->handleException( $e, $status, __METHOD__
, $params );
414 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
416 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
418 $cfOp->getLastResponse();
419 } catch ( NoSuchObjectException
$e ) { // source object does not exist
420 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
425 * @see FileBackendStore::doMoveInternal()
428 protected function doMoveInternal( array $params ) {
429 $status = Status
::newGood();
431 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
432 if ( $srcRel === null ) {
433 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
437 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
438 if ( $dstRel === null ) {
439 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
443 // (a) Check the source/destination containers and destination object
445 $sContObj = $this->getContainer( $srcCont );
446 $dContObj = $this->getContainer( $dstCont );
447 } catch ( NoSuchContainerException
$e ) {
448 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
450 } catch ( CloudFilesException
$e ) { // some other exception?
451 $this->handleException( $e, $status, __METHOD__
, $params );
455 // (b) Actually move the file to the destination
457 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
458 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
459 $hdrs = array(); // source file headers to override with new values
460 if ( isset( $params['disposition'] ) ) {
461 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
463 if ( !empty( $params['async'] ) ) { // deferred
464 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
465 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
466 $status->value
->affectedObjects
[] = $srcObj;
467 $status->value
->affectedObjects
[] = $dstObj;
468 } else { // actually write the object in Swift
469 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
470 $this->purgeCDNCache( array( $srcObj ) );
471 $this->purgeCDNCache( array( $dstObj ) );
473 } catch ( CDNNotEnabledException
$e ) {
474 // CDN not enabled; nothing to see here
475 } catch ( NoSuchObjectException
$e ) { // source object does not exist
476 if ( empty( $params['ignoreMissingSource'] ) ) {
477 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
479 } catch ( CloudFilesException
$e ) { // some other exception?
480 $this->handleException( $e, $status, __METHOD__
, $params );
487 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
489 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
491 $cfOp->getLastResponse();
492 } catch ( NoSuchObjectException
$e ) { // source object does not exist
493 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
498 * @see FileBackendStore::doDeleteInternal()
501 protected function doDeleteInternal( array $params ) {
502 $status = Status
::newGood();
504 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
505 if ( $srcRel === null ) {
506 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
511 $sContObj = $this->getContainer( $srcCont );
512 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
513 if ( !empty( $params['async'] ) ) { // deferred
514 $op = $sContObj->delete_object_async( $srcRel );
515 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
516 $status->value
->affectedObjects
[] = $srcObj;
517 } else { // actually write the object in Swift
518 $sContObj->delete_object( $srcRel );
519 $this->purgeCDNCache( array( $srcObj ) );
521 } catch ( CDNNotEnabledException
$e ) {
522 // CDN not enabled; nothing to see here
523 } catch ( NoSuchContainerException
$e ) {
524 $status->fatal( 'backend-fail-delete', $params['src'] );
525 } catch ( NoSuchObjectException
$e ) {
526 if ( empty( $params['ignoreMissingSource'] ) ) {
527 $status->fatal( 'backend-fail-delete', $params['src'] );
529 } catch ( CloudFilesException
$e ) { // some other exception?
530 $this->handleException( $e, $status, __METHOD__
, $params );
537 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
539 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
541 $cfOp->getLastResponse();
542 } catch ( NoSuchContainerException
$e ) {
543 $status->fatal( 'backend-fail-delete', $params['src'] );
544 } catch ( NoSuchObjectException
$e ) {
545 if ( empty( $params['ignoreMissingSource'] ) ) {
546 $status->fatal( 'backend-fail-delete', $params['src'] );
552 * @see FileBackendStore::doPrepareInternal()
555 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
556 $status = Status
::newGood();
558 // (a) Check if container already exists
560 $contObj = $this->getContainer( $fullCont );
561 // NoSuchContainerException not thrown: container must exist
562 return $status; // already exists
563 } catch ( NoSuchContainerException
$e ) {
564 // NoSuchContainerException thrown: container does not exist
565 } catch ( CloudFilesException
$e ) { // some other exception?
566 $this->handleException( $e, $status, __METHOD__
, $params );
570 // (b) Create container as needed
572 $contObj = $this->createContainer( $fullCont );
573 if ( !empty( $params['noAccess'] ) ) {
574 // Make container private to end-users...
575 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
577 // Make container public to end-users...
578 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
580 if ( $this->swiftUseCDN
) { // Rackspace style CDN
581 $contObj->make_public( $this->swiftCDNExpiry
);
583 } catch ( CDNNotEnabledException
$e ) {
584 // CDN not enabled; nothing to see here
585 } catch ( CloudFilesException
$e ) { // some other exception?
586 $this->handleException( $e, $status, __METHOD__
, $params );
594 * @see FileBackendStore::doSecureInternal()
597 protected function doSecureInternal( $fullCont, $dir, array $params ) {
598 $status = Status
::newGood();
599 if ( empty( $params['noAccess'] ) ) {
600 return $status; // nothing to do
603 // Restrict container from end-users...
605 // doPrepareInternal() should have been called,
606 // so the Swift container should already exist...
607 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
608 // NoSuchContainerException not thrown: container must exist
610 // Make container private to end-users...
611 $status->merge( $this->setContainerAccess(
613 array( $this->auth
->username
), // read
614 array( $this->auth
->username
) // write
616 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
617 $contObj->make_private();
619 } catch ( CDNNotEnabledException
$e ) {
620 // CDN not enabled; nothing to see here
621 } catch ( CloudFilesException
$e ) { // some other exception?
622 $this->handleException( $e, $status, __METHOD__
, $params );
629 * @see FileBackendStore::doPublishInternal()
632 protected function doPublishInternal( $fullCont, $dir, array $params ) {
633 $status = Status
::newGood();
635 // Unrestrict container from end-users...
637 // doPrepareInternal() should have been called,
638 // so the Swift container should already exist...
639 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
640 // NoSuchContainerException not thrown: container must exist
642 // Make container public to end-users...
643 if ( $this->swiftAnonUser
!= '' ) {
644 $status->merge( $this->setContainerAccess(
646 array( $this->auth
->username
, $this->swiftAnonUser
), // read
647 array( $this->auth
->username
, $this->swiftAnonUser
) // write
650 $status->merge( $this->setContainerAccess(
652 array( $this->auth
->username
, '.r:*' ), // read
653 array( $this->auth
->username
) // write
656 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
657 $contObj->make_public();
659 } catch ( CDNNotEnabledException
$e ) {
660 // CDN not enabled; nothing to see here
661 } catch ( CloudFilesException
$e ) { // some other exception?
662 $this->handleException( $e, $status, __METHOD__
, $params );
669 * @see FileBackendStore::doCleanInternal()
672 protected function doCleanInternal( $fullCont, $dir, array $params ) {
673 $status = Status
::newGood();
675 // Only containers themselves can be removed, all else is virtual
677 return $status; // nothing to do
680 // (a) Check the container
682 $contObj = $this->getContainer( $fullCont, true );
683 } catch ( NoSuchContainerException
$e ) {
684 return $status; // ok, nothing to do
685 } catch ( CloudFilesException
$e ) { // some other exception?
686 $this->handleException( $e, $status, __METHOD__
, $params );
690 // (b) Delete the container if empty
691 if ( $contObj->object_count
== 0 ) {
693 $this->deleteContainer( $fullCont );
694 } catch ( NoSuchContainerException
$e ) {
695 return $status; // race?
696 } catch ( NonEmptyContainerException
$e ) {
697 return $status; // race? consistency delay?
698 } catch ( CloudFilesException
$e ) { // some other exception?
699 $this->handleException( $e, $status, __METHOD__
, $params );
708 * @see FileBackendStore::doFileExists()
709 * @return array|bool|null
711 protected function doGetFileStat( array $params ) {
712 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
713 if ( $srcRel === null ) {
714 return false; // invalid storage path
719 $contObj = $this->getContainer( $srcCont );
720 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
721 $this->addMissingMetadata( $srcObj, $params['src'] );
723 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
724 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
725 'size' => (int)$srcObj->content_length
,
726 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
728 } catch ( NoSuchContainerException
$e ) {
729 } catch ( NoSuchObjectException
$e ) {
730 } catch ( CloudFilesException
$e ) { // some other exception?
732 $this->handleException( $e, null, __METHOD__
, $params );
739 * Fill in any missing object metadata and save it to Swift
741 * @param $obj CF_Object
742 * @param $path string Storage path to object
743 * @return bool Success
744 * @throws Exception cloudfiles exceptions
746 protected function addMissingMetadata( CF_Object
$obj, $path ) {
747 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
748 return true; // nothing to do
750 wfProfileIn( __METHOD__
);
751 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
752 $status = Status
::newGood();
753 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
754 if ( $status->isOK() ) {
755 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
757 $hash = $tmpFile->getSha1Base36();
758 if ( $hash !== false ) {
759 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
760 $obj->sync_metadata(); // save to Swift
761 wfProfileOut( __METHOD__
);
762 return true; // success
766 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
767 wfProfileOut( __METHOD__
);
768 return false; // failed
772 * @see FileBackendStore::doGetFileContentsMulti()
775 protected function doGetFileContentsMulti( array $params ) {
778 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
779 // Blindly create tmp files and stream to them, catching any exception if the file does
780 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
781 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
782 $cfOps = array(); // (path => CF_Async_Op)
784 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
785 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
786 if ( $srcRel === null ) {
787 $contents[$path] = false;
792 $sContObj = $this->getContainer( $srcCont );
793 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
794 // Get source file extension
795 $ext = FileBackend
::extensionFromPath( $path );
796 // Create a new temporary memory file...
797 $handle = fopen( 'php://temp', 'wb' );
799 $headers = $this->headersFromParams( $params );
800 if ( count( $pathBatch ) > 1 ) {
801 $cfOps[$path] = $obj->stream_async( $handle, $headers );
802 $cfOps[$path]->_file_handle
= $handle; // close this later
804 $obj->stream( $handle, $headers );
805 rewind( $handle ); // start from the beginning
806 $data = stream_get_contents( $handle );
812 } catch ( NoSuchContainerException
$e ) {
814 } catch ( NoSuchObjectException
$e ) {
816 } catch ( CloudFilesException
$e ) { // some other exception?
818 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
820 $contents[$path] = $data;
823 $batch = new CF_Async_Op_Batch( $cfOps );
824 $cfOps = $batch->execute();
825 foreach ( $cfOps as $path => $cfOp ) {
827 $cfOp->getLastResponse();
828 rewind( $cfOp->_file_handle
); // start from the beginning
829 $contents[$path] = stream_get_contents( $cfOp->_file_handle
);
830 } catch ( NoSuchContainerException
$e ) {
831 $contents[$path] = false;
832 } catch ( NoSuchObjectException
$e ) {
833 $contents[$path] = false;
834 } catch ( CloudFilesException
$e ) { // some other exception?
835 $contents[$path] = false;
836 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
838 fclose( $cfOp->_file_handle
); // close open handle
846 * @see FileBackendStore::doDirectoryExists()
849 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
851 $container = $this->getContainer( $fullCont );
852 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
853 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
854 } catch ( NoSuchContainerException
$e ) {
856 } catch ( CloudFilesException
$e ) { // some other exception?
857 $this->handleException( $e, null, __METHOD__
,
858 array( 'cont' => $fullCont, 'dir' => $dir ) );
861 return null; // error
865 * @see FileBackendStore::getDirectoryListInternal()
866 * @return SwiftFileBackendDirList
868 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
869 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
873 * @see FileBackendStore::getFileListInternal()
874 * @return SwiftFileBackendFileList
876 public function getFileListInternal( $fullCont, $dir, array $params ) {
877 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
881 * Do not call this function outside of SwiftFileBackendFileList
883 * @param $fullCont string Resolved container name
884 * @param $dir string Resolved storage directory with no trailing slash
885 * @param $after string|null Storage path of file to list items after
886 * @param $limit integer Max number of items to list
887 * @param $params Array Includes flag for 'topOnly'
888 * @return Array List of relative paths of dirs directly under $dir
890 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
892 if ( $after === INF
) {
893 return $dirs; // nothing more
895 wfProfileIn( __METHOD__
. '-' . $this->name
);
898 $container = $this->getContainer( $fullCont );
899 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
900 // Non-recursive: only list dirs right under $dir
901 if ( !empty( $params['topOnly'] ) ) {
902 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
903 foreach ( $objects as $object ) { // files and dirs
904 if ( substr( $object, -1 ) === '/' ) {
905 $dirs[] = $object; // directories end in '/'
908 // Recursive: list all dirs under $dir and its subdirs
910 // Get directory from last item of prior page
911 $lastDir = $this->getParentDir( $after ); // must be first page
912 $objects = $container->list_objects( $limit, $after, $prefix );
913 foreach ( $objects as $object ) { // files
914 $objectDir = $this->getParentDir( $object ); // directory of object
915 if ( $objectDir !== false ) { // file has a parent dir
916 // Swift stores paths in UTF-8, using binary sorting.
917 // See function "create_container_table" in common/db.py.
918 // If a directory is not "greater" than the last one,
919 // then it was already listed by the calling iterator.
920 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
922 do { // add dir and all its parent dirs
923 $dirs[] = "{$pDir}/";
924 $pDir = $this->getParentDir( $pDir );
925 } while ( $pDir !== false // sanity
926 && strcmp( $pDir, $lastDir ) > 0 // not done already
927 && strlen( $pDir ) > strlen( $dir ) // within $dir
930 $lastDir = $objectDir;
934 if ( count( $objects ) < $limit ) {
935 $after = INF
; // avoid a second RTT
937 $after = end( $objects ); // update last item
939 } catch ( NoSuchContainerException
$e ) {
940 } catch ( CloudFilesException
$e ) { // some other exception?
941 $this->handleException( $e, null, __METHOD__
,
942 array( 'cont' => $fullCont, 'dir' => $dir ) );
945 wfProfileOut( __METHOD__
. '-' . $this->name
);
949 protected function getParentDir( $path ) {
950 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
954 * Do not call this function outside of SwiftFileBackendFileList
956 * @param $fullCont string Resolved container name
957 * @param $dir string Resolved storage directory with no trailing slash
958 * @param $after string|null Storage path of file to list items after
959 * @param $limit integer Max number of items to list
960 * @param $params Array Includes flag for 'topOnly'
961 * @return Array List of relative paths of files under $dir
963 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
965 if ( $after === INF
) {
966 return $files; // nothing more
968 wfProfileIn( __METHOD__
. '-' . $this->name
);
971 $container = $this->getContainer( $fullCont );
972 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
973 // Non-recursive: only list files right under $dir
974 if ( !empty( $params['topOnly'] ) ) { // files and dirs
975 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
976 foreach ( $objects as $object ) {
977 if ( substr( $object, -1 ) !== '/' ) {
978 $files[] = $object; // directories end in '/'
981 // Recursive: list all files under $dir and its subdirs
983 $objects = $container->list_objects( $limit, $after, $prefix );
986 if ( count( $objects ) < $limit ) {
987 $after = INF
; // avoid a second RTT
989 $after = end( $objects ); // update last item
991 } catch ( NoSuchContainerException
$e ) {
992 } catch ( CloudFilesException
$e ) { // some other exception?
993 $this->handleException( $e, null, __METHOD__
,
994 array( 'cont' => $fullCont, 'dir' => $dir ) );
997 wfProfileOut( __METHOD__
. '-' . $this->name
);
1002 * @see FileBackendStore::doGetFileSha1base36()
1005 protected function doGetFileSha1base36( array $params ) {
1006 $stat = $this->getFileStat( $params );
1008 return $stat['sha1'];
1015 * @see FileBackendStore::doStreamFile()
1018 protected function doStreamFile( array $params ) {
1019 $status = Status
::newGood();
1021 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1022 if ( $srcRel === null ) {
1023 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1027 $cont = $this->getContainer( $srcCont );
1028 } catch ( NoSuchContainerException
$e ) {
1029 $status->fatal( 'backend-fail-stream', $params['src'] );
1031 } catch ( CloudFilesException
$e ) { // some other exception?
1032 $this->handleException( $e, $status, __METHOD__
, $params );
1037 $output = fopen( 'php://output', 'wb' );
1038 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1039 $obj->stream( $output, $this->headersFromParams( $params ) );
1040 } catch ( NoSuchObjectException
$e ) {
1041 $status->fatal( 'backend-fail-stream', $params['src'] );
1042 } catch ( CloudFilesException
$e ) { // some other exception?
1043 $this->handleException( $e, $status, __METHOD__
, $params );
1050 * @see FileBackendStore::doGetLocalCopyMulti()
1051 * @return null|TempFSFile
1053 protected function doGetLocalCopyMulti( array $params ) {
1054 $tmpFiles = array();
1056 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1057 // Blindly create tmp files and stream to them, catching any exception if the file does
1058 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1059 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1060 $cfOps = array(); // (path => CF_Async_Op)
1062 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1063 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1064 if ( $srcRel === null ) {
1065 $tmpFiles[$path] = null;
1070 $sContObj = $this->getContainer( $srcCont );
1071 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1072 // Get source file extension
1073 $ext = FileBackend
::extensionFromPath( $path );
1074 // Create a new temporary file...
1075 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1077 $handle = fopen( $tmpFile->getPath(), 'wb' );
1079 $headers = $this->headersFromParams( $params );
1080 if ( count( $pathBatch ) > 1 ) {
1081 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1082 $cfOps[$path]->_file_handle
= $handle; // close this later
1084 $obj->stream( $handle, $headers );
1091 } catch ( NoSuchContainerException
$e ) {
1093 } catch ( NoSuchObjectException
$e ) {
1095 } catch ( CloudFilesException
$e ) { // some other exception?
1097 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1099 $tmpFiles[$path] = $tmpFile;
1102 $batch = new CF_Async_Op_Batch( $cfOps );
1103 $cfOps = $batch->execute();
1104 foreach ( $cfOps as $path => $cfOp ) {
1106 $cfOp->getLastResponse();
1107 } catch ( NoSuchContainerException
$e ) {
1108 $tmpFiles[$path] = null;
1109 } catch ( NoSuchObjectException
$e ) {
1110 $tmpFiles[$path] = null;
1111 } catch ( CloudFilesException
$e ) { // some other exception?
1112 $tmpFiles[$path] = null;
1113 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1115 fclose( $cfOp->_file_handle
); // close open handle
1123 * @see FileBackendStore::directoriesAreVirtual()
1126 protected function directoriesAreVirtual() {
1131 * Get headers to send to Swift when reading a file based
1132 * on a FileBackend params array, e.g. that of getLocalCopy().
1133 * $params is currently only checked for a 'latest' flag.
1135 * @param $params Array
1138 protected function headersFromParams( array $params ) {
1140 if ( !empty( $params['latest'] ) ) {
1141 $hdrs[] = 'X-Newest: true';
1147 * @see FileBackendStore::doExecuteOpHandlesInternal()
1148 * @return Array List of corresponding Status objects
1150 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1151 $statuses = array();
1153 $cfOps = array(); // list of CF_Async_Op objects
1154 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1155 $cfOps[$index] = $fileOpHandle->cfOp
;
1157 $batch = new CF_Async_Op_Batch( $cfOps );
1159 $cfOps = $batch->execute();
1160 foreach ( $cfOps as $index => $cfOp ) {
1161 $status = Status
::newGood();
1162 try { // catch exceptions; update status
1163 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1164 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1165 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1166 } catch ( CloudFilesException
$e ) { // some other exception?
1167 $this->handleException( $e, $status,
1168 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1170 $statuses[$index] = $status;
1177 * Set read/write permissions for a Swift container.
1179 * $readGrps is a list of the possible criteria for a request to have
1180 * access to read a container. Each item is one of the following formats:
1181 * - account:user : Grants access if the request is by the given user
1182 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1183 * matches the expression and the request is not for a listing.
1184 * Setting this to '*' effectively makes a container public.
1185 * -".rlistings:<regex>": Grants access if the request is from a referrer host that
1186 * matches the expression and the request for a listing.
1188 * $writeGrps is a list of the possible criteria for a request to have
1189 * access to write to a container. Each item is of the following format:
1190 * - account:user : Grants access if the request is by the given user
1192 * @see http://swift.openstack.org/misc.html#acls
1194 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1195 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1197 * @param $contObj CF_Container Swift container
1198 * @param $readGrps Array List of read access routes
1199 * @param $writeGrps Array List of write access routes
1202 protected function setContainerAccess(
1203 CF_Container
$contObj, array $readGrps, array $writeGrps
1205 $creds = $contObj->cfs_auth
->export_credentials();
1207 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1209 // Note: 10 second timeout consistent with php-cloudfiles
1210 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1211 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1212 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1213 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1215 return $req->execute(); // should return 204
1219 * Purge the CDN cache of affected objects if CDN caching is enabled.
1220 * This is for Rackspace/Akamai CDNs.
1222 * @param $objects Array List of CF_Object items
1225 public function purgeCDNCache( array $objects ) {
1226 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1227 foreach ( $objects as $object ) {
1229 $object->purge_from_cdn();
1230 } catch ( CDNNotEnabledException
$e ) {
1231 // CDN not enabled; nothing to see here
1232 } catch ( CloudFilesException
$e ) {
1233 $this->handleException( $e, null, __METHOD__
,
1234 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1241 * Get an authenticated connection handle to the Swift proxy
1243 * @return CF_Connection|bool False on failure
1244 * @throws CloudFilesException
1246 protected function getConnection() {
1247 if ( $this->connException
instanceof CloudFilesException
) {
1248 if ( ( time() - $this->connErrorTime
) < 60 ) {
1249 throw $this->connException
; // failed last attempt; don't bother
1250 } else { // actually retry this time
1251 $this->connException
= null;
1252 $this->connErrorTime
= 0;
1255 // Session keys expire after a while, so we renew them periodically
1256 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1257 // Authenticate with proxy and get a session key...
1258 if ( !$this->conn ||
$reAuth ) {
1259 $this->sessionStarted
= 0;
1260 $this->connContainerCache
->clear();
1261 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1262 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1263 if ( is_array( $creds ) ) { // cache hit
1264 $this->auth
->load_cached_credentials(
1265 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1266 $this->sessionStarted
= time() - ceil( $this->authTTL
/2 ); // skew for worst case
1267 } else { // cache miss
1269 $this->auth
->authenticate();
1270 $creds = $this->auth
->export_credentials();
1271 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/2 ) ); // cache
1272 $this->sessionStarted
= time();
1273 } catch ( CloudFilesException
$e ) {
1274 $this->connException
= $e; // don't keep re-trying
1275 $this->connErrorTime
= time();
1276 throw $e; // throw it back
1279 if ( $this->conn
) { // re-authorizing?
1280 $this->conn
->close(); // close active cURL handles in CF_Http object
1282 $this->conn
= new CF_Connection( $this->auth
);
1288 * Close the connection to the Swift proxy
1292 protected function closeConnection() {
1293 if ( $this->conn
) {
1294 $this->conn
->close(); // close active cURL handles in CF_Http object
1295 $this->sessionStarted
= 0;
1296 $this->connContainerCache
->clear();
1301 * Get the cache key for a container
1303 * @param $username string
1306 private function getCredsCacheKey( $username ) {
1307 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1311 * Get a Swift container object, possibly from process cache.
1312 * Use $reCache if the file count or byte count is needed.
1314 * @param $container string Container name
1315 * @param $bypassCache bool Bypass all caches and load from Swift
1316 * @return CF_Container
1317 * @throws CloudFilesException
1319 protected function getContainer( $container, $bypassCache = false ) {
1320 $conn = $this->getConnection(); // Swift proxy connection
1321 if ( $bypassCache ) { // purge cache
1322 $this->connContainerCache
->clear( $container );
1323 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1324 $this->primeContainerCache( array( $container ) ); // check persistent cache
1326 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1327 $contObj = $conn->get_container( $container );
1328 // NoSuchContainerException not thrown: container must exist
1329 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1330 if ( !$bypassCache ) {
1331 $this->setContainerCache( $container, // update persistent cache
1332 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1336 return $this->connContainerCache
->get( $container, 'obj' );
1340 * Create a Swift container
1342 * @param $container string Container name
1343 * @return CF_Container
1344 * @throws CloudFilesException
1346 protected function createContainer( $container ) {
1347 $conn = $this->getConnection(); // Swift proxy connection
1348 $contObj = $conn->create_container( $container );
1349 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1354 * Delete a Swift container
1356 * @param $container string Container name
1358 * @throws CloudFilesException
1360 protected function deleteContainer( $container ) {
1361 $conn = $this->getConnection(); // Swift proxy connection
1362 $this->connContainerCache
->clear( $container ); // purge
1363 $conn->delete_container( $container );
1367 * @see FileBackendStore::doPrimeContainerCache()
1370 protected function doPrimeContainerCache( array $containerInfo ) {
1372 $conn = $this->getConnection(); // Swift proxy connection
1373 foreach ( $containerInfo as $container => $info ) {
1374 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1375 $container, $info['count'], $info['bytes'] );
1376 $this->connContainerCache
->set( $container, 'obj', $contObj );
1378 } catch ( CloudFilesException
$e ) { // some other exception?
1379 $this->handleException( $e, null, __METHOD__
, array() );
1384 * Log an unexpected exception for this backend.
1385 * This also sets the Status object to have a fatal error.
1387 * @param $e Exception
1388 * @param $status Status|null
1389 * @param $func string
1390 * @param $params Array
1393 protected function handleException( Exception
$e, $status, $func, array $params ) {
1394 if ( $status instanceof Status
) {
1395 if ( $e instanceof AuthenticationException
) {
1396 $status->fatal( 'backend-fail-connect', $this->name
);
1398 $status->fatal( 'backend-fail-internal', $this->name
);
1401 if ( $e->getMessage() ) {
1402 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1404 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1405 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1406 $this->closeConnection(); // force a re-connect and re-auth next time
1408 wfDebugLog( 'SwiftBackend',
1409 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1410 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1416 * @see FileBackendStoreOpHandle
1418 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1419 /** @var CF_Async_Op */
1422 public $affectedObjects = array();
1424 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1425 $this->backend
= $backend;
1426 $this->params
= $params;
1427 $this->call
= $call;
1428 $this->cfOp
= $cfOp;
1433 * SwiftFileBackend helper class to page through listings.
1434 * Swift also has a listing limit of 10,000 objects for sanity.
1435 * Do not use this class from places outside SwiftFileBackend.
1437 * @ingroup FileBackend
1439 abstract class SwiftFileBackendList
implements Iterator
{
1441 protected $bufferIter = array();
1442 protected $bufferAfter = null; // string; list items *after* this path
1443 protected $pos = 0; // integer
1445 protected $params = array();
1447 /** @var SwiftFileBackend */
1449 protected $container; // string; container name
1450 protected $dir; // string; storage directory
1451 protected $suffixStart; // integer
1453 const PAGE_SIZE
= 9000; // file listing buffer size
1456 * @param $backend SwiftFileBackend
1457 * @param $fullCont string Resolved container name
1458 * @param $dir string Resolved directory relative to container
1459 * @param $params Array
1461 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1462 $this->backend
= $backend;
1463 $this->container
= $fullCont;
1465 if ( substr( $this->dir
, -1 ) === '/' ) {
1466 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1468 if ( $this->dir
== '' ) { // whole container
1469 $this->suffixStart
= 0;
1470 } else { // dir within container
1471 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1473 $this->params
= $params;
1477 * @see Iterator::key()
1480 public function key() {
1485 * @see Iterator::next()
1488 public function next() {
1489 // Advance to the next file in the page
1490 next( $this->bufferIter
);
1492 // Check if there are no files left in this page and
1493 // advance to the next page if this page was not empty.
1494 if ( !$this->valid() && count( $this->bufferIter
) ) {
1495 $this->bufferIter
= $this->pageFromList(
1496 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1497 ); // updates $this->bufferAfter
1502 * @see Iterator::rewind()
1505 public function rewind() {
1507 $this->bufferAfter
= null;
1508 $this->bufferIter
= $this->pageFromList(
1509 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1510 ); // updates $this->bufferAfter
1514 * @see Iterator::valid()
1517 public function valid() {
1518 if ( $this->bufferIter
=== null ) {
1519 return false; // some failure?
1521 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1526 * Get the given list portion (page)
1528 * @param $container string Resolved container name
1529 * @param $dir string Resolved path relative to container
1530 * @param $after string|null
1531 * @param $limit integer
1532 * @param $params Array
1533 * @return Traversable|Array|null Returns null on failure
1535 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1539 * Iterator for listing directories
1541 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1543 * @see Iterator::current()
1544 * @return string|bool String (relative path) or false
1546 public function current() {
1547 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1551 * @see SwiftFileBackendList::pageFromList()
1552 * @return Array|null
1554 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1555 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1560 * Iterator for listing regular files
1562 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1564 * @see Iterator::current()
1565 * @return string|bool String (relative path) or false
1567 public function current() {
1568 return substr( current( $this->bufferIter
), $this->suffixStart
);
1572 * @see SwiftFileBackendList::pageFromList()
1573 * @return Array|null
1575 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1576 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );