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 $maxContCacheSize = 300; // integer; max containers with entries
46 /** @var CF_Connection */
47 protected $conn; // Swift connection handle
48 protected $connStarted = 0; // integer UNIX timestamp
49 protected $connContainers = array(); // container object cache
50 protected $connException; // CloudFiles exception
53 * @see FileBackendStore::__construct()
54 * Additional $config params include:
55 * swiftAuthUrl : Swift authentication server URL
56 * swiftUser : Swift user used by MediaWiki (account:username)
57 * swiftKey : Swift authentication key for the above user
58 * swiftAuthTTL : Swift authentication TTL (seconds)
59 * swiftAnonUser : Swift user used for end-user requests (account:username)
60 * shardViaHashLevels : Map of container names to sharding config with:
61 * 'base' : base of hash characters, 16 or 36
62 * 'levels' : the number of hash levels (and digits)
63 * 'repeat' : hash subdirectories are prefixed with all the
64 * parent hash directory names (e.g. "a/ab/abc")
66 public function __construct( array $config ) {
67 parent
::__construct( $config );
68 if ( !MWInit
::classExists( 'CF_Constants' ) ) {
69 throw new MWException( 'SwiftCloudFiles extension not installed.' );
72 $this->auth
= new CF_Authentication(
75 null, // account; unused
76 $config['swiftAuthUrl']
79 $this->authTTL
= isset( $config['swiftAuthTTL'] )
80 ?
$config['swiftAuthTTL']
81 : 5 * 60; // some sane number
82 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
83 ?
$config['swiftAnonUser']
85 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
86 ?
$config['shardViaHashLevels']
88 // Cache container info to mask latency
89 $this->memCache
= wfGetMainCache();
93 * @see FileBackendStore::resolveContainerPath()
96 protected function resolveContainerPath( $container, $relStoragePath ) {
97 if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
98 return null; // too long for Swift
100 return $relStoragePath;
104 * @see FileBackendStore::isPathUsableInternal()
107 public function isPathUsableInternal( $storagePath ) {
108 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
109 if ( $rel === null ) {
110 return false; // invalid
114 $this->getContainer( $container );
115 return true; // container exists
116 } catch ( NoSuchContainerException
$e ) {
117 } catch ( CloudFilesException
$e ) { // some other exception?
118 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
125 * @see FileBackendStore::doCreateInternal()
128 protected function doCreateInternal( array $params ) {
129 $status = Status
::newGood();
131 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
132 if ( $dstRel === null ) {
133 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
137 // (a) Check the destination container and object
139 $dContObj = $this->getContainer( $dstCont );
140 if ( empty( $params['overwrite'] ) &&
141 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
143 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
146 } catch ( NoSuchContainerException
$e ) {
147 $status->fatal( 'backend-fail-create', $params['dst'] );
149 } catch ( CloudFilesException
$e ) { // some other exception?
150 $this->handleException( $e, $status, __METHOD__
, $params );
154 // (b) Get a SHA-1 hash of the object
155 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
157 // (c) Actually create the object
159 // Create a fresh CF_Object with no fields preloaded.
160 // We don't want to preserve headers, metadata, and such.
161 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
162 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
163 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
164 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
165 // The MD5 here will be checked within Swift against its own MD5.
166 $obj->set_etag( md5( $params['content'] ) );
167 // Use the same content type as StreamFile for security
168 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
169 if ( !empty( $params['async'] ) ) { // deferred
170 $handle = $obj->write_async( $params['content'] );
171 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $handle );
172 } else { // actually write the object in Swift
173 $obj->write( $params['content'] );
175 } catch ( BadContentTypeException
$e ) {
176 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
177 } catch ( CloudFilesException
$e ) { // some other exception?
178 $this->handleException( $e, $status, __METHOD__
, $params );
185 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
187 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
189 $cfOp->getLastResponse();
190 } catch ( BadContentTypeException
$e ) {
191 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
196 * @see FileBackendStore::doStoreInternal()
199 protected function doStoreInternal( array $params ) {
200 $status = Status
::newGood();
202 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
203 if ( $dstRel === null ) {
204 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
208 // (a) Check the destination container and object
210 $dContObj = $this->getContainer( $dstCont );
211 if ( empty( $params['overwrite'] ) &&
212 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
214 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
217 } catch ( NoSuchContainerException
$e ) {
218 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
220 } catch ( CloudFilesException
$e ) { // some other exception?
221 $this->handleException( $e, $status, __METHOD__
, $params );
225 // (b) Get a SHA-1 hash of the object
226 $sha1Hash = sha1_file( $params['src'] );
227 if ( $sha1Hash === false ) { // source doesn't exist?
228 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
231 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
233 // (c) Actually store the object
235 // Create a fresh CF_Object with no fields preloaded.
236 // We don't want to preserve headers, metadata, and such.
237 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
238 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
239 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
240 // The MD5 here will be checked within Swift against its own MD5.
241 $obj->set_etag( md5_file( $params['src'] ) );
242 // Use the same content type as StreamFile for security
243 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
244 if ( !empty( $params['async'] ) ) { // deferred
245 wfSuppressWarnings();
246 $fp = fopen( $params['src'], 'rb' );
249 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
251 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
252 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $handle );
253 $status->value
->resourcesToClose
[] = $fp;
255 } else { // actually write the object in Swift
256 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
258 } catch ( BadContentTypeException
$e ) {
259 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
260 } catch ( IOException
$e ) {
261 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
262 } catch ( CloudFilesException
$e ) { // some other exception?
263 $this->handleException( $e, $status, __METHOD__
, $params );
270 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
272 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
274 $cfOp->getLastResponse();
275 } catch ( BadContentTypeException
$e ) {
276 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
277 } catch ( IOException
$e ) {
278 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
283 * @see FileBackendStore::doCopyInternal()
286 protected function doCopyInternal( array $params ) {
287 $status = Status
::newGood();
289 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
290 if ( $srcRel === null ) {
291 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
295 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
296 if ( $dstRel === null ) {
297 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
301 // (a) Check the source/destination containers and destination object
303 $sContObj = $this->getContainer( $srcCont );
304 $dContObj = $this->getContainer( $dstCont );
305 if ( empty( $params['overwrite'] ) &&
306 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
308 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
311 } catch ( NoSuchContainerException
$e ) {
312 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
314 } catch ( CloudFilesException
$e ) { // some other exception?
315 $this->handleException( $e, $status, __METHOD__
, $params );
319 // (b) Actually copy the file to the destination
321 if ( !empty( $params['async'] ) ) { // deferred
322 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
323 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
324 } else { // actually write the object in Swift
325 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
327 } catch ( NoSuchObjectException
$e ) { // source object does not exist
328 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
329 } catch ( CloudFilesException
$e ) { // some other exception?
330 $this->handleException( $e, $status, __METHOD__
, $params );
337 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
339 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
341 $cfOp->getLastResponse();
342 } catch ( NoSuchObjectException
$e ) { // source object does not exist
343 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
348 * @see FileBackendStore::doMoveInternal()
351 protected function doMoveInternal( array $params ) {
352 $status = Status
::newGood();
354 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
355 if ( $srcRel === null ) {
356 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
360 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
361 if ( $dstRel === null ) {
362 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
366 // (a) Check the source/destination containers and destination object
368 $sContObj = $this->getContainer( $srcCont );
369 $dContObj = $this->getContainer( $dstCont );
370 if ( empty( $params['overwrite'] ) &&
371 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
373 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
376 } catch ( NoSuchContainerException
$e ) {
377 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
379 } catch ( CloudFilesException
$e ) { // some other exception?
380 $this->handleException( $e, $status, __METHOD__
, $params );
384 // (b) Actually move the file to the destination
386 if ( !empty( $params['async'] ) ) { // deferred
387 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
388 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $handle );
389 } else { // actually write the object in Swift
390 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
392 } catch ( NoSuchObjectException
$e ) { // source object does not exist
393 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
394 } catch ( CloudFilesException
$e ) { // some other exception?
395 $this->handleException( $e, $status, __METHOD__
, $params );
402 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
404 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
406 $cfOp->getLastResponse();
407 } catch ( NoSuchObjectException
$e ) { // source object does not exist
408 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
413 * @see FileBackendStore::doDeleteInternal()
416 protected function doDeleteInternal( array $params ) {
417 $status = Status
::newGood();
419 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
420 if ( $srcRel === null ) {
421 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
426 $sContObj = $this->getContainer( $srcCont );
427 if ( !empty( $params['async'] ) ) { // deferred
428 $handle = $sContObj->delete_object_async( $srcRel );
429 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
430 } else { // actually write the object in Swift
431 $sContObj->delete_object( $srcRel );
433 } catch ( NoSuchContainerException
$e ) {
434 $status->fatal( 'backend-fail-delete', $params['src'] );
435 } catch ( NoSuchObjectException
$e ) {
436 if ( empty( $params['ignoreMissingSource'] ) ) {
437 $status->fatal( 'backend-fail-delete', $params['src'] );
439 } catch ( CloudFilesException
$e ) { // some other exception?
440 $this->handleException( $e, $status, __METHOD__
, $params );
447 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
449 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
451 $cfOp->getLastResponse();
452 } catch ( NoSuchContainerException
$e ) {
453 $status->fatal( 'backend-fail-delete', $params['src'] );
454 } catch ( NoSuchObjectException
$e ) {
455 if ( empty( $params['ignoreMissingSource'] ) ) {
456 $status->fatal( 'backend-fail-delete', $params['src'] );
462 * @see FileBackendStore::doPrepareInternal()
465 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
466 $status = Status
::newGood();
468 // (a) Check if container already exists
470 $contObj = $this->getContainer( $fullCont );
471 // NoSuchContainerException not thrown: container must exist
472 return $status; // already exists
473 } catch ( NoSuchContainerException
$e ) {
474 // NoSuchContainerException thrown: container does not exist
475 } catch ( CloudFilesException
$e ) { // some other exception?
476 $this->handleException( $e, $status, __METHOD__
, $params );
480 // (b) Create container as needed
482 $contObj = $this->createContainer( $fullCont );
483 if ( $this->swiftAnonUser
!= '' ) {
484 // Make container public to end-users...
485 $status->merge( $this->setContainerAccess(
487 array( $this->auth
->username
, $this->swiftAnonUser
), // read
488 array( $this->auth
->username
) // write
491 } catch ( CloudFilesException
$e ) { // some other exception?
492 $this->handleException( $e, $status, __METHOD__
, $params );
500 * @see FileBackendStore::doSecureInternal()
503 protected function doSecureInternal( $fullCont, $dir, array $params ) {
504 $status = Status
::newGood();
506 if ( $this->swiftAnonUser
!= '' ) {
507 // Restrict container from end-users...
509 // doPrepareInternal() should have been called,
510 // so the Swift container should already exist...
511 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
512 // NoSuchContainerException not thrown: container must exist
513 if ( !isset( $contObj->mw_wasSecured
) ) {
514 $status->merge( $this->setContainerAccess(
516 array( $this->auth
->username
), // read
517 array( $this->auth
->username
) // write
519 // @TODO: when php-cloudfiles supports container
520 // metadata, we can make use of that to avoid RTTs
521 $contObj->mw_wasSecured
= true; // avoid useless RTTs
523 } catch ( CloudFilesException
$e ) { // some other exception?
524 $this->handleException( $e, $status, __METHOD__
, $params );
532 * @see FileBackendStore::doCleanInternal()
535 protected function doCleanInternal( $fullCont, $dir, array $params ) {
536 $status = Status
::newGood();
538 // Only containers themselves can be removed, all else is virtual
540 return $status; // nothing to do
543 // (a) Check the container
545 $contObj = $this->getContainer( $fullCont, true );
546 } catch ( NoSuchContainerException
$e ) {
547 return $status; // ok, nothing to do
548 } catch ( CloudFilesException
$e ) { // some other exception?
549 $this->handleException( $e, $status, __METHOD__
, $params );
553 // (b) Delete the container if empty
554 if ( $contObj->object_count
== 0 ) {
556 $this->deleteContainer( $fullCont );
557 } catch ( NoSuchContainerException
$e ) {
558 return $status; // race?
559 } catch ( NonEmptyContainerException
$e ) {
560 return $status; // race? consistency delay?
561 } catch ( CloudFilesException
$e ) { // some other exception?
562 $this->handleException( $e, $status, __METHOD__
, $params );
571 * @see FileBackendStore::doFileExists()
572 * @return array|bool|null
574 protected function doGetFileStat( array $params ) {
575 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
576 if ( $srcRel === null ) {
577 return false; // invalid storage path
582 $contObj = $this->getContainer( $srcCont );
583 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
584 $this->addMissingMetadata( $srcObj, $params['src'] );
586 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
587 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
588 'size' => $srcObj->content_length
,
589 'sha1' => $srcObj->metadata
['Sha1base36']
591 } catch ( NoSuchContainerException
$e ) {
592 } catch ( NoSuchObjectException
$e ) {
593 } catch ( CloudFilesException
$e ) { // some other exception?
595 $this->handleException( $e, null, __METHOD__
, $params );
602 * Fill in any missing object metadata and save it to Swift
604 * @param $obj CF_Object
605 * @param $path string Storage path to object
606 * @return bool Success
607 * @throws Exception cloudfiles exceptions
609 protected function addMissingMetadata( CF_Object
$obj, $path ) {
610 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
611 return true; // nothing to do
613 $status = Status
::newGood();
614 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
615 if ( $status->isOK() ) {
616 # Do not stat the file in getLocalCopy() to avoid infinite loops
617 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
619 $hash = $tmpFile->getSha1Base36();
620 if ( $hash !== false ) {
621 $obj->metadata
['Sha1base36'] = $hash;
622 $obj->sync_metadata(); // save to Swift
623 return true; // success
627 $obj->metadata
['Sha1base36'] = false;
628 return false; // failed
632 * @see FileBackend::getFileContents()
633 * @return bool|null|string
635 public function getFileContents( array $params ) {
636 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
637 if ( $srcRel === null ) {
638 return false; // invalid storage path
641 if ( !$this->fileExists( $params ) ) {
647 $sContObj = $this->getContainer( $srcCont );
648 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD request
649 $data = $obj->read( $this->headersFromParams( $params ) );
650 } catch ( NoSuchContainerException
$e ) {
651 } catch ( CloudFilesException
$e ) { // some other exception?
652 $this->handleException( $e, null, __METHOD__
, $params );
659 * @see FileBackendStore::doDirectoryExists()
662 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
664 $container = $this->getContainer( $fullCont );
665 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
666 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
667 } catch ( NoSuchContainerException
$e ) {
669 } catch ( CloudFilesException
$e ) { // some other exception?
670 $this->handleException( $e, null, __METHOD__
,
671 array( 'cont' => $fullCont, 'dir' => $dir ) );
674 return null; // error
678 * @see FileBackendStore::getDirectoryListInternal()
679 * @return SwiftFileBackendDirList
681 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
682 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
686 * @see FileBackendStore::getFileListInternal()
687 * @return SwiftFileBackendFileList
689 public function getFileListInternal( $fullCont, $dir, array $params ) {
690 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
694 * Do not call this function outside of SwiftFileBackendFileList
696 * @param $fullCont string Resolved container name
697 * @param $dir string Resolved storage directory with no trailing slash
698 * @param $after string|null Storage path of file to list items after
699 * @param $limit integer Max number of items to list
700 * @param $params Array Includes flag for 'topOnly'
701 * @return Array List of relative paths of dirs directly under $dir
703 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
707 $container = $this->getContainer( $fullCont );
708 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
709 // Non-recursive: only list dirs right under $dir
710 if ( !empty( $params['topOnly'] ) ) {
711 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
712 foreach ( $objects as $object ) { // files and dirs
713 if ( substr( $object, -1 ) === '/' ) {
714 $dirs[] = $object; // directories end in '/'
716 $after = $object; // update last item
718 // Recursive: list all dirs under $dir and its subdirs
720 // Get directory from last item of prior page
721 $lastDir = $this->getParentDir( $after ); // must be first page
722 $objects = $container->list_objects( $limit, $after, $prefix );
723 foreach ( $objects as $object ) { // files
724 $objectDir = $this->getParentDir( $object ); // directory of object
725 if ( $objectDir !== false ) { // file has a parent dir
726 // Swift stores paths in UTF-8, using binary sorting.
727 // See function "create_container_table" in common/db.py.
728 // If a directory is not "greater" than the last one,
729 // then it was already listed by the calling iterator.
730 if ( $objectDir > $lastDir ) {
732 do { // add dir and all its parent dirs
733 $dirs[] = "{$pDir}/";
734 $pDir = $this->getParentDir( $pDir );
735 } while ( $pDir !== false // sanity
736 && $pDir > $lastDir // not done already
737 && strlen( $pDir ) > strlen( $dir ) // within $dir
740 $lastDir = $objectDir;
742 $after = $object; // update last item
745 } catch ( NoSuchContainerException
$e ) {
746 } catch ( CloudFilesException
$e ) { // some other exception?
747 $this->handleException( $e, null, __METHOD__
,
748 array( 'cont' => $fullCont, 'dir' => $dir ) );
754 protected function getParentDir( $path ) {
755 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
759 * Do not call this function outside of SwiftFileBackendFileList
761 * @param $fullCont string Resolved container name
762 * @param $dir string Resolved storage directory with no trailing slash
763 * @param $after string|null Storage path of file to list items after
764 * @param $limit integer Max number of items to list
765 * @param $params Array Includes flag for 'topOnly'
766 * @return Array List of relative paths of files under $dir
768 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
772 $container = $this->getContainer( $fullCont );
773 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
774 // Non-recursive: only list files right under $dir
775 if ( !empty( $params['topOnly'] ) ) { // files and dirs
776 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
777 foreach ( $objects as $object ) {
778 if ( substr( $object, -1 ) !== '/' ) {
779 $files[] = $object; // directories end in '/'
782 // Recursive: list all files under $dir and its subdirs
784 $files = $container->list_objects( $limit, $after, $prefix );
786 $after = end( $files ); // update last item
787 reset( $files ); // reset pointer
788 } catch ( NoSuchContainerException
$e ) {
789 } catch ( CloudFilesException
$e ) { // some other exception?
790 $this->handleException( $e, null, __METHOD__
,
791 array( 'cont' => $fullCont, 'dir' => $dir ) );
798 * @see FileBackendStore::doGetFileSha1base36()
801 protected function doGetFileSha1base36( array $params ) {
802 $stat = $this->getFileStat( $params );
804 return $stat['sha1'];
811 * @see FileBackendStore::doStreamFile()
814 protected function doStreamFile( array $params ) {
815 $status = Status
::newGood();
817 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
818 if ( $srcRel === null ) {
819 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
823 $cont = $this->getContainer( $srcCont );
824 } catch ( NoSuchContainerException
$e ) {
825 $status->fatal( 'backend-fail-stream', $params['src'] );
827 } catch ( CloudFilesException
$e ) { // some other exception?
828 $this->handleException( $e, $status, __METHOD__
, $params );
833 $output = fopen( 'php://output', 'wb' );
834 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD request
835 $obj->stream( $output, $this->headersFromParams( $params ) );
836 } catch ( CloudFilesException
$e ) { // some other exception?
837 $this->handleException( $e, $status, __METHOD__
, $params );
844 * @see FileBackendStore::getLocalCopy()
845 * @return null|TempFSFile
847 public function getLocalCopy( array $params ) {
848 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
849 if ( $srcRel === null ) {
853 # Check the recursion guard to avoid loops when filling metadata
854 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
860 $sContObj = $this->getContainer( $srcCont );
861 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
862 // Get source file extension
863 $ext = FileBackend
::extensionFromPath( $srcRel );
864 // Create a new temporary file...
865 $tmpFile = TempFSFile
::factory( wfBaseName( $srcRel ) . '_', $ext );
867 $handle = fopen( $tmpFile->getPath(), 'wb' );
869 $obj->stream( $handle, $this->headersFromParams( $params ) );
872 $tmpFile = null; // couldn't open temp file
875 } catch ( NoSuchContainerException
$e ) {
877 } catch ( CloudFilesException
$e ) { // some other exception?
879 $this->handleException( $e, null, __METHOD__
, $params );
886 * @see FileBackendStore::directoriesAreVirtual()
889 protected function directoriesAreVirtual() {
894 * Get headers to send to Swift when reading a file based
895 * on a FileBackend params array, e.g. that of getLocalCopy().
896 * $params is currently only checked for a 'latest' flag.
898 * @param $params Array
901 protected function headersFromParams( array $params ) {
903 if ( !empty( $params['latest'] ) ) {
904 $hdrs[] = 'X-Newest: true';
910 * @see FileBackendStore::doExecuteOpHandlesInternal()
911 * @return Array List of corresponding Status objects
913 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
916 $cfOps = array(); // list of CF_Async_Op objects
917 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
918 $cfOps[$index] = $fileOpHandle->cfOp
;
920 $batch = new CF_Async_Op_Batch( $cfOps );
922 $cfOps = $batch->execute();
923 foreach ( $cfOps as $index => $cfOp ) {
924 $status = Status
::newGood();
925 try { // catch exceptions; update status
926 $function = '_getResponse' . $fileOpHandles[$index]->call
;
927 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
928 } catch ( CloudFilesException
$e ) { // some other exception?
929 $this->handleException( $e, $status,
930 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
932 $statuses[$index] = $status;
935 foreach ( $fileOpHandles as $fileOpHandle ) {
936 $fileOpHandle->closeResources();
943 * Set read/write permissions for a Swift container
945 * @param $contObj CF_Container Swift container
946 * @param $readGrps Array Swift users who can read (account:user)
947 * @param $writeGrps Array Swift users who can write (account:user)
950 protected function setContainerAccess(
951 CF_Container
$contObj, array $readGrps, array $writeGrps
953 $creds = $contObj->cfs_auth
->export_credentials();
955 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
957 // Note: 10 second timeout consistent with php-cloudfiles
958 $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
959 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
960 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
961 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
963 return $req->execute(); // should return 204
967 * Get a connection to the Swift proxy
969 * @return CF_Connection|bool False on failure
970 * @throws CloudFilesException
972 protected function getConnection() {
973 if ( $this->connException
instanceof Exception
) {
974 throw $this->connException
; // failed last attempt
976 // Session keys expire after a while, so we renew them periodically
977 if ( $this->conn
&& ( time() - $this->connStarted
) > $this->authTTL
) {
978 $this->conn
->close(); // close active cURL connections
981 // Authenticate with proxy and get a session key...
982 if ( !$this->conn
) {
983 $this->connStarted
= 0;
984 $this->connContainers
= array();
986 $this->auth
->authenticate();
987 $this->conn
= new CF_Connection( $this->auth
);
988 $this->connStarted
= time();
989 } catch ( CloudFilesException
$e ) {
990 $this->connException
= $e; // don't keep re-trying
991 throw $e; // throw it back
998 * @see FileBackendStore::doClearCache()
1000 protected function doClearCache( array $paths = null ) {
1001 $this->connContainers
= array(); // clear container object cache
1005 * Get a Swift container object, possibly from process cache.
1006 * Use $reCache if the file count or byte count is needed.
1008 * @param $container string Container name
1009 * @param $bypassCache bool Bypass all caches and load from Swift
1010 * @return CF_Container
1011 * @throws CloudFilesException
1013 protected function getContainer( $container, $bypassCache = false ) {
1014 $conn = $this->getConnection(); // Swift proxy connection
1015 if ( $bypassCache ) { // purge cache
1016 unset( $this->connContainers
[$container] );
1017 } elseif ( !isset( $this->connContainers
[$container] ) ) {
1018 $this->primeContainerCache( array( $container ) ); // check persistent cache
1020 if ( !isset( $this->connContainers
[$container] ) ) {
1021 $contObj = $conn->get_container( $container );
1022 // NoSuchContainerException not thrown: container must exist
1023 if ( count( $this->connContainers
) >= $this->maxContCacheSize
) { // trim cache?
1024 reset( $this->connContainers
);
1025 unset( $this->connContainers
[key( $this->connContainers
)] );
1027 $this->connContainers
[$container] = $contObj; // cache it
1028 if ( !$bypassCache ) {
1029 $this->setContainerCache( $container, // update persistent cache
1030 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1034 return $this->connContainers
[$container];
1038 * Create a Swift container
1040 * @param $container string Container name
1041 * @return CF_Container
1042 * @throws InvalidResponseException
1044 protected function createContainer( $container ) {
1045 $conn = $this->getConnection(); // Swift proxy connection
1046 $contObj = $conn->create_container( $container );
1047 $this->connContainers
[$container] = $contObj; // cache it
1052 * Delete a Swift container
1054 * @param $container string Container name
1056 * @throws InvalidResponseException
1058 protected function deleteContainer( $container ) {
1059 $conn = $this->getConnection(); // Swift proxy connection
1060 $conn->delete_container( $container );
1061 unset( $this->connContainers
[$container] ); // purge cache
1065 * @see FileBackendStore::doPrimeContainerCache()
1068 protected function doPrimeContainerCache( array $containerInfo ) {
1070 $conn = $this->getConnection(); // Swift proxy connection
1071 foreach ( $containerInfo as $container => $info ) {
1072 $this->connContainers
[$container] = new CF_Container(
1080 } catch ( CloudFilesException
$e ) { // some other exception?
1081 $this->handleException( $e, null, __METHOD__
, array() );
1086 * Log an unexpected exception for this backend.
1087 * This also sets the Status object to have a fatal error.
1089 * @param $e Exception
1090 * @param $status Status|null
1091 * @param $func string
1092 * @param $params Array
1095 protected function handleException( Exception
$e, $status, $func, array $params ) {
1096 if ( $status instanceof Status
) {
1097 if ( $e instanceof AuthenticationException
) {
1098 $status->fatal( 'backend-fail-connect', $this->name
);
1100 $status->fatal( 'backend-fail-internal', $this->name
);
1103 if ( $e->getMessage() ) {
1104 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1106 wfDebugLog( 'SwiftBackend',
1107 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1108 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1114 * @see FileBackendStoreOpHandle
1116 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1117 /** @var CF_Async_Op */
1120 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1121 $this->backend
= $backend;
1122 $this->params
= $params;
1123 $this->call
= $call;
1124 $this->cfOp
= $cfOp;
1129 * SwiftFileBackend helper class to page through listings.
1130 * Swift also has a listing limit of 10,000 objects for sanity.
1131 * Do not use this class from places outside SwiftFileBackend.
1133 * @ingroup FileBackend
1135 abstract class SwiftFileBackendList
implements Iterator
{
1137 protected $bufferIter = array();
1138 protected $bufferAfter = null; // string; list items *after* this path
1139 protected $pos = 0; // integer
1141 protected $params = array();
1143 /** @var SwiftFileBackend */
1145 protected $container; // string; container name
1146 protected $dir; // string; storage directory
1147 protected $suffixStart; // integer
1149 const PAGE_SIZE
= 5000; // file listing buffer size
1152 * @param $backend SwiftFileBackend
1153 * @param $fullCont string Resolved container name
1154 * @param $dir string Resolved directory relative to container
1155 * @param $params Array
1157 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1158 $this->backend
= $backend;
1159 $this->container
= $fullCont;
1161 if ( substr( $this->dir
, -1 ) === '/' ) {
1162 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1164 if ( $this->dir
== '' ) { // whole container
1165 $this->suffixStart
= 0;
1166 } else { // dir within container
1167 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1169 $this->params
= $params;
1173 * @see Iterator::key()
1176 public function key() {
1181 * @see Iterator::next()
1184 public function next() {
1185 // Advance to the next file in the page
1186 next( $this->bufferIter
);
1188 // Check if there are no files left in this page and
1189 // advance to the next page if this page was not empty.
1190 if ( !$this->valid() && count( $this->bufferIter
) ) {
1191 $this->bufferIter
= $this->pageFromList(
1192 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1193 ); // updates $this->bufferAfter
1198 * @see Iterator::rewind()
1201 public function rewind() {
1203 $this->bufferAfter
= null;
1204 $this->bufferIter
= $this->pageFromList(
1205 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1206 ); // updates $this->bufferAfter
1210 * @see Iterator::valid()
1213 public function valid() {
1214 if ( $this->bufferIter
=== null ) {
1215 return false; // some failure?
1217 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1222 * Get the given list portion (page)
1224 * @param $container string Resolved container name
1225 * @param $dir string Resolved path relative to container
1226 * @param $after string|null
1227 * @param $limit integer
1228 * @param $params Array
1229 * @return Traversable|Array|null Returns null on failure
1231 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1235 * Iterator for listing directories
1237 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1239 * @see Iterator::current()
1240 * @return string|bool String (relative path) or false
1242 public function current() {
1243 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1247 * @see SwiftFileBackendList::pageFromList()
1248 * @return Array|null
1250 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1251 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1256 * Iterator for listing regular files
1258 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1260 * @see Iterator::current()
1261 * @return string|bool String (relative path) or false
1263 public function current() {
1264 return substr( current( $this->bufferIter
), $this->suffixStart
);
1268 * @see SwiftFileBackendList::pageFromList()
1269 * @return Array|null
1271 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1272 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );