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 if ( empty( $params['overwrite'] ) &&
205 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
207 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
210 } catch ( NoSuchContainerException
$e ) {
211 $status->fatal( 'backend-fail-create', $params['dst'] );
213 } catch ( CloudFilesException
$e ) { // some other exception?
214 $this->handleException( $e, $status, __METHOD__
, $params );
218 // (b) Get a SHA-1 hash of the object
219 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
221 // (c) Actually create the object
223 // Create a fresh CF_Object with no fields preloaded.
224 // We don't want to preserve headers, metadata, and such.
225 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
226 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
227 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
228 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
229 // The MD5 here will be checked within Swift against its own MD5.
230 $obj->set_etag( md5( $params['content'] ) );
231 // Use the same content type as StreamFile for security
232 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
233 if ( !strlen( $obj->content_type
) ) { // special case
234 $obj->content_type
= 'unknown/unknown';
236 // Set the Content-Disposition header if requested
237 if ( isset( $params['disposition'] ) ) {
238 $obj->headers
['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
240 if ( !empty( $params['async'] ) ) { // deferred
241 $op = $obj->write_async( $params['content'] );
242 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $op );
243 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
244 $status->value
->affectedObjects
[] = $obj;
246 } else { // actually write the object in Swift
247 $obj->write( $params['content'] );
248 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
249 $this->purgeCDNCache( array( $obj ) );
252 } catch ( CDNNotEnabledException
$e ) {
253 // CDN not enabled; nothing to see here
254 } catch ( BadContentTypeException
$e ) {
255 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
256 } catch ( CloudFilesException
$e ) { // some other exception?
257 $this->handleException( $e, $status, __METHOD__
, $params );
264 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
266 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
268 $cfOp->getLastResponse();
269 } catch ( BadContentTypeException
$e ) {
270 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
275 * @see FileBackendStore::doStoreInternal()
278 protected function doStoreInternal( array $params ) {
279 $status = Status
::newGood();
281 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
282 if ( $dstRel === null ) {
283 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
287 // (a) Check the destination container and object
289 $dContObj = $this->getContainer( $dstCont );
290 if ( empty( $params['overwrite'] ) &&
291 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
293 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
296 } catch ( NoSuchContainerException
$e ) {
297 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
299 } catch ( CloudFilesException
$e ) { // some other exception?
300 $this->handleException( $e, $status, __METHOD__
, $params );
304 // (b) Get a SHA-1 hash of the object
305 $sha1Hash = sha1_file( $params['src'] );
306 if ( $sha1Hash === false ) { // source doesn't exist?
307 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
310 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
312 // (c) Actually store the object
314 // Create a fresh CF_Object with no fields preloaded.
315 // We don't want to preserve headers, metadata, and such.
316 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
317 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
318 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
319 // The MD5 here will be checked within Swift against its own MD5.
320 $obj->set_etag( md5_file( $params['src'] ) );
321 // Use the same content type as StreamFile for security
322 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
323 if ( !strlen( $obj->content_type
) ) { // special case
324 $obj->content_type
= 'unknown/unknown';
326 // Set the Content-Disposition header if requested
327 if ( isset( $params['disposition'] ) ) {
328 $obj->headers
['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
330 if ( !empty( $params['async'] ) ) { // deferred
331 wfSuppressWarnings();
332 $fp = fopen( $params['src'], 'rb' );
335 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
337 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
338 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $op );
339 $status->value
->resourcesToClose
[] = $fp;
340 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
341 $status->value
->affectedObjects
[] = $obj;
344 } else { // actually write the object in Swift
345 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
346 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
347 $this->purgeCDNCache( array( $obj ) );
350 } catch ( CDNNotEnabledException
$e ) {
351 // CDN not enabled; nothing to see here
352 } catch ( BadContentTypeException
$e ) {
353 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
354 } catch ( IOException
$e ) {
355 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
356 } catch ( CloudFilesException
$e ) { // some other exception?
357 $this->handleException( $e, $status, __METHOD__
, $params );
364 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
366 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
368 $cfOp->getLastResponse();
369 } catch ( BadContentTypeException
$e ) {
370 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
371 } catch ( IOException
$e ) {
372 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
377 * @see FileBackendStore::doCopyInternal()
380 protected function doCopyInternal( array $params ) {
381 $status = Status
::newGood();
383 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
384 if ( $srcRel === null ) {
385 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
389 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
390 if ( $dstRel === null ) {
391 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
395 // (a) Check the source/destination containers and destination object
397 $sContObj = $this->getContainer( $srcCont );
398 $dContObj = $this->getContainer( $dstCont );
399 if ( empty( $params['overwrite'] ) &&
400 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
402 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
405 } catch ( NoSuchContainerException
$e ) {
406 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
408 } catch ( CloudFilesException
$e ) { // some other exception?
409 $this->handleException( $e, $status, __METHOD__
, $params );
413 // (b) Actually copy the file to the destination
415 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
416 $hdrs = array(); // source file headers to override with new values
417 if ( isset( $params['disposition'] ) ) {
418 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
420 if ( !empty( $params['async'] ) ) { // deferred
421 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
422 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $op );
423 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
424 $status->value
->affectedObjects
[] = $dstObj;
426 } else { // actually write the object in Swift
427 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
428 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
429 $this->purgeCDNCache( array( $dstObj ) );
432 } catch ( CDNNotEnabledException
$e ) {
433 // CDN not enabled; nothing to see here
434 } catch ( NoSuchObjectException
$e ) { // source object does not exist
435 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
436 } catch ( CloudFilesException
$e ) { // some other exception?
437 $this->handleException( $e, $status, __METHOD__
, $params );
444 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
446 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
448 $cfOp->getLastResponse();
449 } catch ( NoSuchObjectException
$e ) { // source object does not exist
450 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
455 * @see FileBackendStore::doMoveInternal()
458 protected function doMoveInternal( array $params ) {
459 $status = Status
::newGood();
461 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
462 if ( $srcRel === null ) {
463 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
467 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
468 if ( $dstRel === null ) {
469 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
473 // (a) Check the source/destination containers and destination object
475 $sContObj = $this->getContainer( $srcCont );
476 $dContObj = $this->getContainer( $dstCont );
477 if ( empty( $params['overwrite'] ) &&
478 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
480 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
483 } catch ( NoSuchContainerException
$e ) {
484 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
486 } catch ( CloudFilesException
$e ) { // some other exception?
487 $this->handleException( $e, $status, __METHOD__
, $params );
491 // (b) Actually move the file to the destination
493 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
494 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
495 $hdrs = array(); // source file headers to override with new values
496 if ( isset( $params['disposition'] ) ) {
497 $hdrs['Content-Disposition'] = $this->truncDisp( $params['disposition'] );
499 if ( !empty( $params['async'] ) ) { // deferred
500 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
501 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
502 $status->value
->affectedObjects
[] = $srcObj;
503 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
504 $status->value
->affectedObjects
[] = $dstObj;
506 } else { // actually write the object in Swift
507 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
508 $this->purgeCDNCache( array( $srcObj ) );
509 if ( !empty( $params['overwrite'] ) ) { // file possibly mutated
510 $this->purgeCDNCache( array( $dstObj ) );
513 } catch ( CDNNotEnabledException
$e ) {
514 // CDN not enabled; nothing to see here
515 } catch ( NoSuchObjectException
$e ) { // source object does not exist
516 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
517 } catch ( CloudFilesException
$e ) { // some other exception?
518 $this->handleException( $e, $status, __METHOD__
, $params );
525 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
527 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
529 $cfOp->getLastResponse();
530 } catch ( NoSuchObjectException
$e ) { // source object does not exist
531 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
536 * @see FileBackendStore::doDeleteInternal()
539 protected function doDeleteInternal( array $params ) {
540 $status = Status
::newGood();
542 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
543 if ( $srcRel === null ) {
544 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
549 $sContObj = $this->getContainer( $srcCont );
550 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
551 if ( !empty( $params['async'] ) ) { // deferred
552 $op = $sContObj->delete_object_async( $srcRel );
553 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
554 $status->value
->affectedObjects
[] = $srcObj;
555 } else { // actually write the object in Swift
556 $sContObj->delete_object( $srcRel );
557 $this->purgeCDNCache( array( $srcObj ) );
559 } catch ( CDNNotEnabledException
$e ) {
560 // CDN not enabled; nothing to see here
561 } catch ( NoSuchContainerException
$e ) {
562 $status->fatal( 'backend-fail-delete', $params['src'] );
563 } catch ( NoSuchObjectException
$e ) {
564 if ( empty( $params['ignoreMissingSource'] ) ) {
565 $status->fatal( 'backend-fail-delete', $params['src'] );
567 } catch ( CloudFilesException
$e ) { // some other exception?
568 $this->handleException( $e, $status, __METHOD__
, $params );
575 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
577 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
579 $cfOp->getLastResponse();
580 } catch ( NoSuchContainerException
$e ) {
581 $status->fatal( 'backend-fail-delete', $params['src'] );
582 } catch ( NoSuchObjectException
$e ) {
583 if ( empty( $params['ignoreMissingSource'] ) ) {
584 $status->fatal( 'backend-fail-delete', $params['src'] );
590 * @see FileBackendStore::doPrepareInternal()
593 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
594 $status = Status
::newGood();
596 // (a) Check if container already exists
598 $contObj = $this->getContainer( $fullCont );
599 // NoSuchContainerException not thrown: container must exist
600 return $status; // already exists
601 } catch ( NoSuchContainerException
$e ) {
602 // NoSuchContainerException thrown: container does not exist
603 } catch ( CloudFilesException
$e ) { // some other exception?
604 $this->handleException( $e, $status, __METHOD__
, $params );
608 // (b) Create container as needed
610 $contObj = $this->createContainer( $fullCont );
611 if ( !empty( $params['noAccess'] ) ) {
612 // Make container private to end-users...
613 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
615 // Make container public to end-users...
616 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
618 if ( $this->swiftUseCDN
) { // Rackspace style CDN
619 $contObj->make_public( $this->swiftCDNExpiry
);
621 } catch ( CDNNotEnabledException
$e ) {
622 // CDN not enabled; nothing to see here
623 } catch ( CloudFilesException
$e ) { // some other exception?
624 $this->handleException( $e, $status, __METHOD__
, $params );
632 * @see FileBackendStore::doSecureInternal()
635 protected function doSecureInternal( $fullCont, $dir, array $params ) {
636 $status = Status
::newGood();
637 if ( empty( $params['noAccess'] ) ) {
638 return $status; // nothing to do
641 // Restrict container from end-users...
643 // doPrepareInternal() should have been called,
644 // so the Swift container should already exist...
645 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
646 // NoSuchContainerException not thrown: container must exist
648 // Make container private to end-users...
649 $status->merge( $this->setContainerAccess(
651 array( $this->auth
->username
), // read
652 array( $this->auth
->username
) // write
654 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
655 $contObj->make_private();
657 } catch ( CDNNotEnabledException
$e ) {
658 // CDN not enabled; nothing to see here
659 } catch ( CloudFilesException
$e ) { // some other exception?
660 $this->handleException( $e, $status, __METHOD__
, $params );
667 * @see FileBackendStore::doPublishInternal()
670 protected function doPublishInternal( $fullCont, $dir, array $params ) {
671 $status = Status
::newGood();
673 // Unrestrict container from end-users...
675 // doPrepareInternal() should have been called,
676 // so the Swift container should already exist...
677 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
678 // NoSuchContainerException not thrown: container must exist
680 // Make container public to end-users...
681 if ( $this->swiftAnonUser
!= '' ) {
682 $status->merge( $this->setContainerAccess(
684 array( $this->auth
->username
, $this->swiftAnonUser
), // read
685 array( $this->auth
->username
, $this->swiftAnonUser
) // write
688 $status->merge( $this->setContainerAccess(
690 array( $this->auth
->username
, '.r:*' ), // read
691 array( $this->auth
->username
) // write
694 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
695 $contObj->make_public();
697 } catch ( CDNNotEnabledException
$e ) {
698 // CDN not enabled; nothing to see here
699 } catch ( CloudFilesException
$e ) { // some other exception?
700 $this->handleException( $e, $status, __METHOD__
, $params );
707 * @see FileBackendStore::doCleanInternal()
710 protected function doCleanInternal( $fullCont, $dir, array $params ) {
711 $status = Status
::newGood();
713 // Only containers themselves can be removed, all else is virtual
715 return $status; // nothing to do
718 // (a) Check the container
720 $contObj = $this->getContainer( $fullCont, true );
721 } catch ( NoSuchContainerException
$e ) {
722 return $status; // ok, nothing to do
723 } catch ( CloudFilesException
$e ) { // some other exception?
724 $this->handleException( $e, $status, __METHOD__
, $params );
728 // (b) Delete the container if empty
729 if ( $contObj->object_count
== 0 ) {
731 $this->deleteContainer( $fullCont );
732 } catch ( NoSuchContainerException
$e ) {
733 return $status; // race?
734 } catch ( NonEmptyContainerException
$e ) {
735 return $status; // race? consistency delay?
736 } catch ( CloudFilesException
$e ) { // some other exception?
737 $this->handleException( $e, $status, __METHOD__
, $params );
746 * @see FileBackendStore::doFileExists()
747 * @return array|bool|null
749 protected function doGetFileStat( array $params ) {
750 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
751 if ( $srcRel === null ) {
752 return false; // invalid storage path
757 $contObj = $this->getContainer( $srcCont );
758 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
759 $this->addMissingMetadata( $srcObj, $params['src'] );
761 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
762 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
763 'size' => (int)$srcObj->content_length
,
764 'sha1' => $srcObj->metadata
['Sha1base36']
766 } catch ( NoSuchContainerException
$e ) {
767 } catch ( NoSuchObjectException
$e ) {
768 } catch ( CloudFilesException
$e ) { // some other exception?
770 $this->handleException( $e, null, __METHOD__
, $params );
777 * Fill in any missing object metadata and save it to Swift
779 * @param $obj CF_Object
780 * @param $path string Storage path to object
781 * @return bool Success
782 * @throws Exception cloudfiles exceptions
784 protected function addMissingMetadata( CF_Object
$obj, $path ) {
785 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
786 return true; // nothing to do
788 wfProfileIn( __METHOD__
);
789 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
790 $status = Status
::newGood();
791 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
792 if ( $status->isOK() ) {
793 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
795 $hash = $tmpFile->getSha1Base36();
796 if ( $hash !== false ) {
797 $obj->metadata
['Sha1base36'] = $hash;
798 $obj->sync_metadata(); // save to Swift
799 wfProfileOut( __METHOD__
);
800 return true; // success
804 $obj->metadata
['Sha1base36'] = false;
805 wfProfileOut( __METHOD__
);
806 return false; // failed
810 * @see FileBackendStore::doGetFileContentsMulti()
813 protected function doGetFileContentsMulti( array $params ) {
816 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
817 // Blindly create tmp files and stream to them, catching any exception if the file does
818 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
819 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
820 $cfOps = array(); // (path => CF_Async_Op)
822 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
823 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
824 if ( $srcRel === null ) {
825 $contents[$path] = false;
830 $sContObj = $this->getContainer( $srcCont );
831 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
832 // Get source file extension
833 $ext = FileBackend
::extensionFromPath( $path );
834 // Create a new temporary memory file...
835 $handle = fopen( 'php://temp', 'wb' );
837 $headers = $this->headersFromParams( $params );
838 if ( count( $pathBatch ) > 1 ) {
839 $cfOps[$path] = $obj->stream_async( $handle, $headers );
840 $cfOps[$path]->_file_handle
= $handle; // close this later
842 $obj->stream( $handle, $headers );
843 rewind( $handle ); // start from the beginning
844 $data = stream_get_contents( $handle );
850 } catch ( NoSuchContainerException
$e ) {
852 } catch ( NoSuchObjectException
$e ) {
854 } catch ( CloudFilesException
$e ) { // some other exception?
856 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
858 $contents[$path] = $data;
861 $batch = new CF_Async_Op_Batch( $cfOps );
862 $cfOps = $batch->execute();
863 foreach ( $cfOps as $path => $cfOp ) {
865 $cfOp->getLastResponse();
866 rewind( $cfOp->_file_handle
); // start from the beginning
867 $contents[$path] = stream_get_contents( $cfOp->_file_handle
);
868 } catch ( NoSuchContainerException
$e ) {
869 $contents[$path] = false;
870 } catch ( NoSuchObjectException
$e ) {
871 $contents[$path] = false;
872 } catch ( CloudFilesException
$e ) { // some other exception?
873 $contents[$path] = false;
874 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
876 fclose( $cfOp->_file_handle
); // close open handle
884 * @see FileBackendStore::doDirectoryExists()
887 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
889 $container = $this->getContainer( $fullCont );
890 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
891 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
892 } catch ( NoSuchContainerException
$e ) {
894 } catch ( CloudFilesException
$e ) { // some other exception?
895 $this->handleException( $e, null, __METHOD__
,
896 array( 'cont' => $fullCont, 'dir' => $dir ) );
899 return null; // error
903 * @see FileBackendStore::getDirectoryListInternal()
904 * @return SwiftFileBackendDirList
906 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
907 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
911 * @see FileBackendStore::getFileListInternal()
912 * @return SwiftFileBackendFileList
914 public function getFileListInternal( $fullCont, $dir, array $params ) {
915 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
919 * Do not call this function outside of SwiftFileBackendFileList
921 * @param $fullCont string Resolved container name
922 * @param $dir string Resolved storage directory with no trailing slash
923 * @param $after string|null Storage path of file to list items after
924 * @param $limit integer Max number of items to list
925 * @param $params Array Includes flag for 'topOnly'
926 * @return Array List of relative paths of dirs directly under $dir
928 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
930 if ( $after === INF
) {
931 return $dirs; // nothing more
933 wfProfileIn( __METHOD__
. '-' . $this->name
);
936 $container = $this->getContainer( $fullCont );
937 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
938 // Non-recursive: only list dirs right under $dir
939 if ( !empty( $params['topOnly'] ) ) {
940 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
941 foreach ( $objects as $object ) { // files and dirs
942 if ( substr( $object, -1 ) === '/' ) {
943 $dirs[] = $object; // directories end in '/'
946 // Recursive: list all dirs under $dir and its subdirs
948 // Get directory from last item of prior page
949 $lastDir = $this->getParentDir( $after ); // must be first page
950 $objects = $container->list_objects( $limit, $after, $prefix );
951 foreach ( $objects as $object ) { // files
952 $objectDir = $this->getParentDir( $object ); // directory of object
953 if ( $objectDir !== false ) { // file has a parent dir
954 // Swift stores paths in UTF-8, using binary sorting.
955 // See function "create_container_table" in common/db.py.
956 // If a directory is not "greater" than the last one,
957 // then it was already listed by the calling iterator.
958 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
960 do { // add dir and all its parent dirs
961 $dirs[] = "{$pDir}/";
962 $pDir = $this->getParentDir( $pDir );
963 } while ( $pDir !== false // sanity
964 && strcmp( $pDir, $lastDir ) > 0 // not done already
965 && strlen( $pDir ) > strlen( $dir ) // within $dir
968 $lastDir = $objectDir;
972 if ( count( $objects ) < $limit ) {
973 $after = INF
; // avoid a second RTT
975 $after = end( $objects ); // update last item
977 } catch ( NoSuchContainerException
$e ) {
978 } catch ( CloudFilesException
$e ) { // some other exception?
979 $this->handleException( $e, null, __METHOD__
,
980 array( 'cont' => $fullCont, 'dir' => $dir ) );
983 wfProfileOut( __METHOD__
. '-' . $this->name
);
987 protected function getParentDir( $path ) {
988 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
992 * Do not call this function outside of SwiftFileBackendFileList
994 * @param $fullCont string Resolved container name
995 * @param $dir string Resolved storage directory with no trailing slash
996 * @param $after string|null Storage path of file to list items after
997 * @param $limit integer Max number of items to list
998 * @param $params Array Includes flag for 'topOnly'
999 * @return Array List of relative paths of files under $dir
1001 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1003 if ( $after === INF
) {
1004 return $files; // nothing more
1006 wfProfileIn( __METHOD__
. '-' . $this->name
);
1009 $container = $this->getContainer( $fullCont );
1010 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
1011 // Non-recursive: only list files right under $dir
1012 if ( !empty( $params['topOnly'] ) ) { // files and dirs
1013 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1014 foreach ( $objects as $object ) {
1015 if ( substr( $object, -1 ) !== '/' ) {
1016 $files[] = $object; // directories end in '/'
1019 // Recursive: list all files under $dir and its subdirs
1021 $objects = $container->list_objects( $limit, $after, $prefix );
1024 if ( count( $objects ) < $limit ) {
1025 $after = INF
; // avoid a second RTT
1027 $after = end( $objects ); // update last item
1029 } catch ( NoSuchContainerException
$e ) {
1030 } catch ( CloudFilesException
$e ) { // some other exception?
1031 $this->handleException( $e, null, __METHOD__
,
1032 array( 'cont' => $fullCont, 'dir' => $dir ) );
1035 wfProfileOut( __METHOD__
. '-' . $this->name
);
1040 * @see FileBackendStore::doGetFileSha1base36()
1043 protected function doGetFileSha1base36( array $params ) {
1044 $stat = $this->getFileStat( $params );
1046 return $stat['sha1'];
1053 * @see FileBackendStore::doStreamFile()
1056 protected function doStreamFile( array $params ) {
1057 $status = Status
::newGood();
1059 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1060 if ( $srcRel === null ) {
1061 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1065 $cont = $this->getContainer( $srcCont );
1066 } catch ( NoSuchContainerException
$e ) {
1067 $status->fatal( 'backend-fail-stream', $params['src'] );
1069 } catch ( CloudFilesException
$e ) { // some other exception?
1070 $this->handleException( $e, $status, __METHOD__
, $params );
1075 $output = fopen( 'php://output', 'wb' );
1076 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1077 $obj->stream( $output, $this->headersFromParams( $params ) );
1078 } catch ( NoSuchObjectException
$e ) {
1079 $status->fatal( 'backend-fail-stream', $params['src'] );
1080 } catch ( CloudFilesException
$e ) { // some other exception?
1081 $this->handleException( $e, $status, __METHOD__
, $params );
1088 * @see FileBackendStore::doGetLocalCopyMulti()
1089 * @return null|TempFSFile
1091 protected function doGetLocalCopyMulti( array $params ) {
1092 $tmpFiles = array();
1094 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1095 // Blindly create tmp files and stream to them, catching any exception if the file does
1096 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1097 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1098 $cfOps = array(); // (path => CF_Async_Op)
1100 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1101 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1102 if ( $srcRel === null ) {
1103 $tmpFiles[$path] = null;
1108 $sContObj = $this->getContainer( $srcCont );
1109 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1110 // Get source file extension
1111 $ext = FileBackend
::extensionFromPath( $path );
1112 // Create a new temporary file...
1113 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1115 $handle = fopen( $tmpFile->getPath(), 'wb' );
1117 $headers = $this->headersFromParams( $params );
1118 if ( count( $pathBatch ) > 1 ) {
1119 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1120 $cfOps[$path]->_file_handle
= $handle; // close this later
1122 $obj->stream( $handle, $headers );
1129 } catch ( NoSuchContainerException
$e ) {
1131 } catch ( NoSuchObjectException
$e ) {
1133 } catch ( CloudFilesException
$e ) { // some other exception?
1135 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1137 $tmpFiles[$path] = $tmpFile;
1140 $batch = new CF_Async_Op_Batch( $cfOps );
1141 $cfOps = $batch->execute();
1142 foreach ( $cfOps as $path => $cfOp ) {
1144 $cfOp->getLastResponse();
1145 } catch ( NoSuchContainerException
$e ) {
1146 $tmpFiles[$path] = null;
1147 } catch ( NoSuchObjectException
$e ) {
1148 $tmpFiles[$path] = null;
1149 } catch ( CloudFilesException
$e ) { // some other exception?
1150 $tmpFiles[$path] = null;
1151 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1153 fclose( $cfOp->_file_handle
); // close open handle
1161 * @see FileBackendStore::directoriesAreVirtual()
1164 protected function directoriesAreVirtual() {
1169 * Get headers to send to Swift when reading a file based
1170 * on a FileBackend params array, e.g. that of getLocalCopy().
1171 * $params is currently only checked for a 'latest' flag.
1173 * @param $params Array
1176 protected function headersFromParams( array $params ) {
1178 if ( !empty( $params['latest'] ) ) {
1179 $hdrs[] = 'X-Newest: true';
1185 * @see FileBackendStore::doExecuteOpHandlesInternal()
1186 * @return Array List of corresponding Status objects
1188 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1189 $statuses = array();
1191 $cfOps = array(); // list of CF_Async_Op objects
1192 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1193 $cfOps[$index] = $fileOpHandle->cfOp
;
1195 $batch = new CF_Async_Op_Batch( $cfOps );
1197 $cfOps = $batch->execute();
1198 foreach ( $cfOps as $index => $cfOp ) {
1199 $status = Status
::newGood();
1200 try { // catch exceptions; update status
1201 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1202 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1203 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1204 } catch ( CloudFilesException
$e ) { // some other exception?
1205 $this->handleException( $e, $status,
1206 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1208 $statuses[$index] = $status;
1215 * Set read/write permissions for a Swift container.
1217 * $readGrps is a list of the possible criteria for a request to have
1218 * access to read a container. Each item is one of the following formats:
1219 * - account:user : Grants access if the request is by the given user
1220 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1221 * matches the expression and the request is not for a listing.
1222 * Setting this to '*' effectively makes a container public.
1223 * -".rlistings:<regex>": Grants access if the request is from a referrer host that
1224 * matches the expression and the request for a listing.
1226 * $writeGrps is a list of the possible criteria for a request to have
1227 * access to write to a container. Each item is of the following format:
1228 * - account:user : Grants access if the request is by the given user
1230 * @see http://swift.openstack.org/misc.html#acls
1232 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1233 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1235 * @param $contObj CF_Container Swift container
1236 * @param $readGrps Array List of read access routes
1237 * @param $writeGrps Array List of write access routes
1240 protected function setContainerAccess(
1241 CF_Container
$contObj, array $readGrps, array $writeGrps
1243 $creds = $contObj->cfs_auth
->export_credentials();
1245 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1247 // Note: 10 second timeout consistent with php-cloudfiles
1248 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1249 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1250 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1251 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1253 return $req->execute(); // should return 204
1257 * Purge the CDN cache of affected objects if CDN caching is enabled.
1258 * This is for Rackspace/Akamai CDNs.
1260 * @param $objects Array List of CF_Object items
1263 public function purgeCDNCache( array $objects ) {
1264 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1265 foreach ( $objects as $object ) {
1267 $object->purge_from_cdn();
1268 } catch ( CDNNotEnabledException
$e ) {
1269 // CDN not enabled; nothing to see here
1270 } catch ( CloudFilesException
$e ) {
1271 $this->handleException( $e, null, __METHOD__
,
1272 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1279 * Get an authenticated connection handle to the Swift proxy
1281 * @return CF_Connection|bool False on failure
1282 * @throws CloudFilesException
1284 protected function getConnection() {
1285 if ( $this->connException
instanceof CloudFilesException
) {
1286 if ( ( time() - $this->connErrorTime
) < 60 ) {
1287 throw $this->connException
; // failed last attempt; don't bother
1288 } else { // actually retry this time
1289 $this->connException
= null;
1290 $this->connErrorTime
= 0;
1293 // Session keys expire after a while, so we renew them periodically
1294 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1295 // Authenticate with proxy and get a session key...
1296 if ( !$this->conn ||
$reAuth ) {
1297 $this->sessionStarted
= 0;
1298 $this->connContainerCache
->clear();
1299 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1300 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1301 if ( is_array( $creds ) ) { // cache hit
1302 $this->auth
->load_cached_credentials(
1303 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1304 $this->sessionStarted
= time() - ceil( $this->authTTL
/2 ); // skew for worst case
1305 } else { // cache miss
1307 $this->auth
->authenticate();
1308 $creds = $this->auth
->export_credentials();
1309 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/2 ) ); // cache
1310 $this->sessionStarted
= time();
1311 } catch ( CloudFilesException
$e ) {
1312 $this->connException
= $e; // don't keep re-trying
1313 $this->connErrorTime
= time();
1314 throw $e; // throw it back
1317 if ( $this->conn
) { // re-authorizing?
1318 $this->conn
->close(); // close active cURL handles in CF_Http object
1320 $this->conn
= new CF_Connection( $this->auth
);
1326 * Close the connection to the Swift proxy
1330 protected function closeConnection() {
1331 if ( $this->conn
) {
1332 $this->conn
->close(); // close active cURL handles in CF_Http object
1333 $this->sessionStarted
= 0;
1334 $this->connContainerCache
->clear();
1339 * Get the cache key for a container
1341 * @param $username string
1344 private function getCredsCacheKey( $username ) {
1345 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1349 * Get a Swift container object, possibly from process cache.
1350 * Use $reCache if the file count or byte count is needed.
1352 * @param $container string Container name
1353 * @param $bypassCache bool Bypass all caches and load from Swift
1354 * @return CF_Container
1355 * @throws CloudFilesException
1357 protected function getContainer( $container, $bypassCache = false ) {
1358 $conn = $this->getConnection(); // Swift proxy connection
1359 if ( $bypassCache ) { // purge cache
1360 $this->connContainerCache
->clear( $container );
1361 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1362 $this->primeContainerCache( array( $container ) ); // check persistent cache
1364 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1365 $contObj = $conn->get_container( $container );
1366 // NoSuchContainerException not thrown: container must exist
1367 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1368 if ( !$bypassCache ) {
1369 $this->setContainerCache( $container, // update persistent cache
1370 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1374 return $this->connContainerCache
->get( $container, 'obj' );
1378 * Create a Swift container
1380 * @param $container string Container name
1381 * @return CF_Container
1382 * @throws CloudFilesException
1384 protected function createContainer( $container ) {
1385 $conn = $this->getConnection(); // Swift proxy connection
1386 $contObj = $conn->create_container( $container );
1387 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1392 * Delete a Swift container
1394 * @param $container string Container name
1396 * @throws CloudFilesException
1398 protected function deleteContainer( $container ) {
1399 $conn = $this->getConnection(); // Swift proxy connection
1400 $this->connContainerCache
->clear( $container ); // purge
1401 $conn->delete_container( $container );
1405 * @see FileBackendStore::doPrimeContainerCache()
1408 protected function doPrimeContainerCache( array $containerInfo ) {
1410 $conn = $this->getConnection(); // Swift proxy connection
1411 foreach ( $containerInfo as $container => $info ) {
1412 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1413 $container, $info['count'], $info['bytes'] );
1414 $this->connContainerCache
->set( $container, 'obj', $contObj );
1416 } catch ( CloudFilesException
$e ) { // some other exception?
1417 $this->handleException( $e, null, __METHOD__
, array() );
1422 * Log an unexpected exception for this backend.
1423 * This also sets the Status object to have a fatal error.
1425 * @param $e Exception
1426 * @param $status Status|null
1427 * @param $func string
1428 * @param $params Array
1431 protected function handleException( Exception
$e, $status, $func, array $params ) {
1432 if ( $status instanceof Status
) {
1433 if ( $e instanceof AuthenticationException
) {
1434 $status->fatal( 'backend-fail-connect', $this->name
);
1436 $status->fatal( 'backend-fail-internal', $this->name
);
1439 if ( $e->getMessage() ) {
1440 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1442 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1443 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1444 $this->closeConnection(); // force a re-connect and re-auth next time
1446 wfDebugLog( 'SwiftBackend',
1447 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1448 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1454 * @see FileBackendStoreOpHandle
1456 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1457 /** @var CF_Async_Op */
1460 public $affectedObjects = array();
1462 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1463 $this->backend
= $backend;
1464 $this->params
= $params;
1465 $this->call
= $call;
1466 $this->cfOp
= $cfOp;
1471 * SwiftFileBackend helper class to page through listings.
1472 * Swift also has a listing limit of 10,000 objects for sanity.
1473 * Do not use this class from places outside SwiftFileBackend.
1475 * @ingroup FileBackend
1477 abstract class SwiftFileBackendList
implements Iterator
{
1479 protected $bufferIter = array();
1480 protected $bufferAfter = null; // string; list items *after* this path
1481 protected $pos = 0; // integer
1483 protected $params = array();
1485 /** @var SwiftFileBackend */
1487 protected $container; // string; container name
1488 protected $dir; // string; storage directory
1489 protected $suffixStart; // integer
1491 const PAGE_SIZE
= 9000; // file listing buffer size
1494 * @param $backend SwiftFileBackend
1495 * @param $fullCont string Resolved container name
1496 * @param $dir string Resolved directory relative to container
1497 * @param $params Array
1499 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1500 $this->backend
= $backend;
1501 $this->container
= $fullCont;
1503 if ( substr( $this->dir
, -1 ) === '/' ) {
1504 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1506 if ( $this->dir
== '' ) { // whole container
1507 $this->suffixStart
= 0;
1508 } else { // dir within container
1509 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1511 $this->params
= $params;
1515 * @see Iterator::key()
1518 public function key() {
1523 * @see Iterator::next()
1526 public function next() {
1527 // Advance to the next file in the page
1528 next( $this->bufferIter
);
1530 // Check if there are no files left in this page and
1531 // advance to the next page if this page was not empty.
1532 if ( !$this->valid() && count( $this->bufferIter
) ) {
1533 $this->bufferIter
= $this->pageFromList(
1534 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1535 ); // updates $this->bufferAfter
1540 * @see Iterator::rewind()
1543 public function rewind() {
1545 $this->bufferAfter
= null;
1546 $this->bufferIter
= $this->pageFromList(
1547 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1548 ); // updates $this->bufferAfter
1552 * @see Iterator::valid()
1555 public function valid() {
1556 if ( $this->bufferIter
=== null ) {
1557 return false; // some failure?
1559 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1564 * Get the given list portion (page)
1566 * @param $container string Resolved container name
1567 * @param $dir string Resolved path relative to container
1568 * @param $after string|null
1569 * @param $limit integer
1570 * @param $params Array
1571 * @return Traversable|Array|null Returns null on failure
1573 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1577 * Iterator for listing directories
1579 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1581 * @see Iterator::current()
1582 * @return string|bool String (relative path) or false
1584 public function current() {
1585 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1589 * @see SwiftFileBackendList::pageFromList()
1590 * @return Array|null
1592 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1593 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1598 * Iterator for listing regular files
1600 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1602 * @see Iterator::current()
1603 * @return string|bool String (relative path) or false
1605 public function current() {
1606 return substr( current( $this->bufferIter
), $this->suffixStart
);
1610 * @see SwiftFileBackendList::pageFromList()
1611 * @return Array|null
1613 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1614 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );