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
52 * @see FileBackendStore::__construct()
53 * Additional $config params include:
54 * swiftAuthUrl : Swift authentication server URL
55 * swiftUser : Swift user used by MediaWiki (account:username)
56 * swiftKey : Swift authentication key for the above user
57 * swiftAuthTTL : Swift authentication TTL (seconds)
58 * swiftAnonUser : Swift user used for end-user requests (account:username)
59 * shardViaHashLevels : Map of container names to sharding config with:
60 * 'base' : base of hash characters, 16 or 36
61 * 'levels' : the number of hash levels (and digits)
62 * 'repeat' : hash subdirectories are prefixed with all the
63 * parent hash directory names (e.g. "a/ab/abc")
65 public function __construct( array $config ) {
66 parent
::__construct( $config );
67 if ( !MWInit
::classExists( 'CF_Constants' ) ) {
68 throw new MWException( 'SwiftCloudFiles extension not installed.' );
71 $this->auth
= new CF_Authentication(
74 null, // account; unused
75 $config['swiftAuthUrl']
78 $this->authTTL
= isset( $config['swiftAuthTTL'] )
79 ?
$config['swiftAuthTTL']
80 : 5 * 60; // some sane number
81 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
82 ?
$config['swiftAnonUser']
84 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
85 ?
$config['shardViaHashLevels']
87 // Cache container info to mask latency
88 $this->memCache
= wfGetMainCache();
92 * @see FileBackendStore::resolveContainerPath()
95 protected function resolveContainerPath( $container, $relStoragePath ) {
96 if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
97 return null; // too long for Swift
99 return $relStoragePath;
103 * @see FileBackendStore::isPathUsableInternal()
106 public function isPathUsableInternal( $storagePath ) {
107 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
108 if ( $rel === null ) {
109 return false; // invalid
113 $this->getContainer( $container );
114 return true; // container exists
115 } catch ( NoSuchContainerException
$e ) {
116 } catch ( CloudFilesException
$e ) { // some other exception?
117 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
124 * @see FileBackendStore::doCreateInternal()
127 protected function doCreateInternal( array $params ) {
128 $status = Status
::newGood();
130 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
131 if ( $dstRel === null ) {
132 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
136 // (a) Check the destination container and object
138 $dContObj = $this->getContainer( $dstCont );
139 if ( empty( $params['overwrite'] ) &&
140 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
142 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
145 } catch ( NoSuchContainerException
$e ) {
146 $status->fatal( 'backend-fail-create', $params['dst'] );
148 } catch ( CloudFilesException
$e ) { // some other exception?
149 $this->handleException( $e, $status, __METHOD__
, $params );
153 // (b) Get a SHA-1 hash of the object
154 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
156 // (c) Actually create the object
158 // Create a fresh CF_Object with no fields preloaded.
159 // We don't want to preserve headers, metadata, and such.
160 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
161 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
162 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
163 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
164 // The MD5 here will be checked within Swift against its own MD5.
165 $obj->set_etag( md5( $params['content'] ) );
166 // Use the same content type as StreamFile for security
167 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
168 if ( !empty( $params['async'] ) ) { // deferred
169 $handle = $obj->write_async( $params['content'] );
170 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $handle );
171 } else { // actually write the object in Swift
172 $obj->write( $params['content'] );
174 } catch ( BadContentTypeException
$e ) {
175 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
176 } catch ( CloudFilesException
$e ) { // some other exception?
177 $this->handleException( $e, $status, __METHOD__
, $params );
184 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
186 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
188 $cfOp->getLastResponse();
189 } catch ( BadContentTypeException
$e ) {
190 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
195 * @see FileBackendStore::doStoreInternal()
198 protected function doStoreInternal( array $params ) {
199 $status = Status
::newGood();
201 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
202 if ( $dstRel === null ) {
203 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
207 // (a) Check the destination container and object
209 $dContObj = $this->getContainer( $dstCont );
210 if ( empty( $params['overwrite'] ) &&
211 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
213 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
216 } catch ( NoSuchContainerException
$e ) {
217 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
219 } catch ( CloudFilesException
$e ) { // some other exception?
220 $this->handleException( $e, $status, __METHOD__
, $params );
224 // (b) Get a SHA-1 hash of the object
225 $sha1Hash = sha1_file( $params['src'] );
226 if ( $sha1Hash === false ) { // source doesn't exist?
227 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
230 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
232 // (c) Actually store the object
234 // Create a fresh CF_Object with no fields preloaded.
235 // We don't want to preserve headers, metadata, and such.
236 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
237 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
238 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
239 // The MD5 here will be checked within Swift against its own MD5.
240 $obj->set_etag( md5_file( $params['src'] ) );
241 // Use the same content type as StreamFile for security
242 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
243 if ( !empty( $params['async'] ) ) { // deferred
244 wfSuppressWarnings();
245 $fp = fopen( $params['src'], 'rb' );
248 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
250 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
251 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $handle );
252 $status->value
->resourcesToClose
[] = $fp;
254 } else { // actually write the object in Swift
255 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
257 } catch ( BadContentTypeException
$e ) {
258 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
259 } catch ( IOException
$e ) {
260 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
261 } catch ( CloudFilesException
$e ) { // some other exception?
262 $this->handleException( $e, $status, __METHOD__
, $params );
269 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
271 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
273 $cfOp->getLastResponse();
274 } catch ( BadContentTypeException
$e ) {
275 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
276 } catch ( IOException
$e ) {
277 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
282 * @see FileBackendStore::doCopyInternal()
285 protected function doCopyInternal( array $params ) {
286 $status = Status
::newGood();
288 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
289 if ( $srcRel === null ) {
290 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
294 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
295 if ( $dstRel === null ) {
296 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
300 // (a) Check the source/destination containers and destination object
302 $sContObj = $this->getContainer( $srcCont );
303 $dContObj = $this->getContainer( $dstCont );
304 if ( empty( $params['overwrite'] ) &&
305 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
307 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
310 } catch ( NoSuchContainerException
$e ) {
311 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
313 } catch ( CloudFilesException
$e ) { // some other exception?
314 $this->handleException( $e, $status, __METHOD__
, $params );
318 // (b) Actually copy the file to the destination
320 if ( !empty( $params['async'] ) ) { // deferred
321 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
322 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
323 } else { // actually write the object in Swift
324 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
326 } catch ( NoSuchObjectException
$e ) { // source object does not exist
327 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
328 } catch ( CloudFilesException
$e ) { // some other exception?
329 $this->handleException( $e, $status, __METHOD__
, $params );
336 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
338 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
340 $cfOp->getLastResponse();
341 } catch ( NoSuchObjectException
$e ) { // source object does not exist
342 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
347 * @see FileBackendStore::doMoveInternal()
350 protected function doMoveInternal( array $params ) {
351 $status = Status
::newGood();
353 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
354 if ( $srcRel === null ) {
355 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
359 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
360 if ( $dstRel === null ) {
361 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
365 // (a) Check the source/destination containers and destination object
367 $sContObj = $this->getContainer( $srcCont );
368 $dContObj = $this->getContainer( $dstCont );
369 if ( empty( $params['overwrite'] ) &&
370 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
372 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
375 } catch ( NoSuchContainerException
$e ) {
376 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
378 } catch ( CloudFilesException
$e ) { // some other exception?
379 $this->handleException( $e, $status, __METHOD__
, $params );
383 // (b) Actually move the file to the destination
385 if ( !empty( $params['async'] ) ) { // deferred
386 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
387 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $handle );
388 } else { // actually write the object in Swift
389 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
391 } catch ( NoSuchObjectException
$e ) { // source object does not exist
392 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
393 } catch ( CloudFilesException
$e ) { // some other exception?
394 $this->handleException( $e, $status, __METHOD__
, $params );
401 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
403 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
405 $cfOp->getLastResponse();
406 } catch ( NoSuchObjectException
$e ) { // source object does not exist
407 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
412 * @see FileBackendStore::doDeleteInternal()
415 protected function doDeleteInternal( array $params ) {
416 $status = Status
::newGood();
418 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
419 if ( $srcRel === null ) {
420 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
425 $sContObj = $this->getContainer( $srcCont );
426 if ( !empty( $params['async'] ) ) { // deferred
427 $handle = $sContObj->delete_object_async( $srcRel );
428 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
429 } else { // actually write the object in Swift
430 $sContObj->delete_object( $srcRel );
432 } catch ( NoSuchContainerException
$e ) {
433 $status->fatal( 'backend-fail-delete', $params['src'] );
434 } catch ( NoSuchObjectException
$e ) {
435 if ( empty( $params['ignoreMissingSource'] ) ) {
436 $status->fatal( 'backend-fail-delete', $params['src'] );
438 } catch ( CloudFilesException
$e ) { // some other exception?
439 $this->handleException( $e, $status, __METHOD__
, $params );
446 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
448 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
450 $cfOp->getLastResponse();
451 } catch ( NoSuchContainerException
$e ) {
452 $status->fatal( 'backend-fail-delete', $params['src'] );
453 } catch ( NoSuchObjectException
$e ) {
454 if ( empty( $params['ignoreMissingSource'] ) ) {
455 $status->fatal( 'backend-fail-delete', $params['src'] );
461 * @see FileBackendStore::doPrepareInternal()
464 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
465 $status = Status
::newGood();
467 // (a) Check if container already exists
469 $contObj = $this->getContainer( $fullCont );
470 // NoSuchContainerException not thrown: container must exist
471 return $status; // already exists
472 } catch ( NoSuchContainerException
$e ) {
473 // NoSuchContainerException thrown: container does not exist
474 } catch ( CloudFilesException
$e ) { // some other exception?
475 $this->handleException( $e, $status, __METHOD__
, $params );
479 // (b) Create container as needed
481 $contObj = $this->createContainer( $fullCont );
482 if ( $this->swiftAnonUser
!= '' ) {
483 // Make container public to end-users...
484 $status->merge( $this->setContainerAccess(
486 array( $this->auth
->username
, $this->swiftAnonUser
), // read
487 array( $this->auth
->username
) // write
490 } catch ( CloudFilesException
$e ) { // some other exception?
491 $this->handleException( $e, $status, __METHOD__
, $params );
499 * @see FileBackendStore::doSecureInternal()
502 protected function doSecureInternal( $fullCont, $dir, array $params ) {
503 $status = Status
::newGood();
505 if ( $this->swiftAnonUser
!= '' ) {
506 // Restrict container from end-users...
508 // doPrepareInternal() should have been called,
509 // so the Swift container should already exist...
510 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
511 // NoSuchContainerException not thrown: container must exist
512 if ( !isset( $contObj->mw_wasSecured
) ) {
513 $status->merge( $this->setContainerAccess(
515 array( $this->auth
->username
), // read
516 array( $this->auth
->username
) // write
518 // @TODO: when php-cloudfiles supports container
519 // metadata, we can make use of that to avoid RTTs
520 $contObj->mw_wasSecured
= true; // avoid useless RTTs
522 } catch ( CloudFilesException
$e ) { // some other exception?
523 $this->handleException( $e, $status, __METHOD__
, $params );
531 * @see FileBackendStore::doCleanInternal()
534 protected function doCleanInternal( $fullCont, $dir, array $params ) {
535 $status = Status
::newGood();
537 // Only containers themselves can be removed, all else is virtual
539 return $status; // nothing to do
542 // (a) Check the container
544 $contObj = $this->getContainer( $fullCont, true );
545 } catch ( NoSuchContainerException
$e ) {
546 return $status; // ok, nothing to do
547 } catch ( CloudFilesException
$e ) { // some other exception?
548 $this->handleException( $e, $status, __METHOD__
, $params );
552 // (b) Delete the container if empty
553 if ( $contObj->object_count
== 0 ) {
555 $this->deleteContainer( $fullCont );
556 } catch ( NoSuchContainerException
$e ) {
557 return $status; // race?
558 } catch ( NonEmptyContainerException
$e ) {
559 return $status; // race? consistency delay?
560 } catch ( CloudFilesException
$e ) { // some other exception?
561 $this->handleException( $e, $status, __METHOD__
, $params );
570 * @see FileBackendStore::doFileExists()
571 * @return array|bool|null
573 protected function doGetFileStat( array $params ) {
574 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
575 if ( $srcRel === null ) {
576 return false; // invalid storage path
581 $contObj = $this->getContainer( $srcCont );
582 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
583 $this->addMissingMetadata( $srcObj, $params['src'] );
585 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
586 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
587 'size' => $srcObj->content_length
,
588 'sha1' => $srcObj->metadata
['Sha1base36']
590 } catch ( NoSuchContainerException
$e ) {
591 } catch ( NoSuchObjectException
$e ) {
592 } catch ( CloudFilesException
$e ) { // some other exception?
594 $this->handleException( $e, null, __METHOD__
, $params );
601 * Fill in any missing object metadata and save it to Swift
603 * @param $obj CF_Object
604 * @param $path string Storage path to object
605 * @return bool Success
606 * @throws Exception cloudfiles exceptions
608 protected function addMissingMetadata( CF_Object
$obj, $path ) {
609 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
610 return true; // nothing to do
612 $status = Status
::newGood();
613 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
614 if ( $status->isOK() ) {
615 # Do not stat the file in getLocalCopy() to avoid infinite loops
616 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
618 $hash = $tmpFile->getSha1Base36();
619 if ( $hash !== false ) {
620 $obj->metadata
['Sha1base36'] = $hash;
621 $obj->sync_metadata(); // save to Swift
622 return true; // success
626 $obj->metadata
['Sha1base36'] = false;
627 return false; // failed
631 * @see FileBackend::getFileContents()
632 * @return bool|null|string
634 public function getFileContents( array $params ) {
635 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
636 if ( $srcRel === null ) {
637 return false; // invalid storage path
640 if ( !$this->fileExists( $params ) ) {
646 $sContObj = $this->getContainer( $srcCont );
647 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD request
648 $data = $obj->read( $this->headersFromParams( $params ) );
649 } catch ( NoSuchContainerException
$e ) {
650 } catch ( CloudFilesException
$e ) { // some other exception?
651 $this->handleException( $e, null, __METHOD__
, $params );
658 * @see FileBackendStore::doDirectoryExists()
661 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
663 $container = $this->getContainer( $fullCont );
664 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
665 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
666 } catch ( NoSuchContainerException
$e ) {
668 } catch ( CloudFilesException
$e ) { // some other exception?
669 $this->handleException( $e, null, __METHOD__
,
670 array( 'cont' => $fullCont, 'dir' => $dir ) );
673 return null; // error
677 * @see FileBackendStore::getDirectoryListInternal()
678 * @return SwiftFileBackendDirList
680 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
681 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
685 * @see FileBackendStore::getFileListInternal()
686 * @return SwiftFileBackendFileList
688 public function getFileListInternal( $fullCont, $dir, array $params ) {
689 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
693 * Do not call this function outside of SwiftFileBackendFileList
695 * @param $fullCont string Resolved container name
696 * @param $dir string Resolved storage directory with no trailing slash
697 * @param $after string|null Storage path of file to list items after
698 * @param $limit integer Max number of items to list
699 * @param $params Array Includes flag for 'topOnly'
700 * @return Array List of relative paths of dirs directly under $dir
702 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
706 $container = $this->getContainer( $fullCont );
707 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
708 // Non-recursive: only list dirs right under $dir
709 if ( !empty( $params['topOnly'] ) ) {
710 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
711 foreach ( $objects as $object ) { // files and dirs
712 if ( substr( $object, -1 ) === '/' ) {
713 $dirs[] = $object; // directories end in '/'
715 $after = $object; // update last item
717 // Recursive: list all dirs under $dir and its subdirs
719 // Get directory from last item of prior page
720 $lastDir = $this->getParentDir( $after ); // must be first page
721 $objects = $container->list_objects( $limit, $after, $prefix );
722 foreach ( $objects as $object ) { // files
723 $objectDir = $this->getParentDir( $object ); // directory of object
724 if ( $objectDir !== false ) { // file has a parent dir
725 // Swift stores paths in UTF-8, using binary sorting.
726 // See function "create_container_table" in common/db.py.
727 // If a directory is not "greater" than the last one,
728 // then it was already listed by the calling iterator.
729 if ( $objectDir > $lastDir ) {
731 do { // add dir and all its parent dirs
732 $dirs[] = "{$pDir}/";
733 $pDir = $this->getParentDir( $pDir );
734 } while ( $pDir !== false // sanity
735 && $pDir > $lastDir // not done already
736 && strlen( $pDir ) > strlen( $dir ) // within $dir
739 $lastDir = $objectDir;
741 $after = $object; // update last item
744 } catch ( NoSuchContainerException
$e ) {
745 } catch ( CloudFilesException
$e ) { // some other exception?
746 $this->handleException( $e, null, __METHOD__
,
747 array( 'cont' => $fullCont, 'dir' => $dir ) );
753 protected function getParentDir( $path ) {
754 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
758 * Do not call this function outside of SwiftFileBackendFileList
760 * @param $fullCont string Resolved container name
761 * @param $dir string Resolved storage directory with no trailing slash
762 * @param $after string|null Storage path of file to list items after
763 * @param $limit integer Max number of items to list
764 * @param $params Array Includes flag for 'topOnly'
765 * @return Array List of relative paths of files under $dir
767 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
771 $container = $this->getContainer( $fullCont );
772 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
773 // Non-recursive: only list files right under $dir
774 if ( !empty( $params['topOnly'] ) ) { // files and dirs
775 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
776 foreach ( $objects as $object ) {
777 if ( substr( $object, -1 ) !== '/' ) {
778 $files[] = $object; // directories end in '/'
781 // Recursive: list all files under $dir and its subdirs
783 $files = $container->list_objects( $limit, $after, $prefix );
785 $after = end( $files ); // update last item
786 reset( $files ); // reset pointer
787 } catch ( NoSuchContainerException
$e ) {
788 } catch ( CloudFilesException
$e ) { // some other exception?
789 $this->handleException( $e, null, __METHOD__
,
790 array( 'cont' => $fullCont, 'dir' => $dir ) );
797 * @see FileBackendStore::doGetFileSha1base36()
800 protected function doGetFileSha1base36( array $params ) {
801 $stat = $this->getFileStat( $params );
803 return $stat['sha1'];
810 * @see FileBackendStore::doStreamFile()
813 protected function doStreamFile( array $params ) {
814 $status = Status
::newGood();
816 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
817 if ( $srcRel === null ) {
818 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
822 $cont = $this->getContainer( $srcCont );
823 } catch ( NoSuchContainerException
$e ) {
824 $status->fatal( 'backend-fail-stream', $params['src'] );
826 } catch ( CloudFilesException
$e ) { // some other exception?
827 $this->handleException( $e, $status, __METHOD__
, $params );
832 $output = fopen( 'php://output', 'wb' );
833 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD request
834 $obj->stream( $output, $this->headersFromParams( $params ) );
835 } catch ( CloudFilesException
$e ) { // some other exception?
836 $this->handleException( $e, $status, __METHOD__
, $params );
843 * @see FileBackendStore::getLocalCopy()
844 * @return null|TempFSFile
846 public function getLocalCopy( array $params ) {
847 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
848 if ( $srcRel === null ) {
852 # Check the recursion guard to avoid loops when filling metadata
853 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
859 $sContObj = $this->getContainer( $srcCont );
860 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
861 // Get source file extension
862 $ext = FileBackend
::extensionFromPath( $srcRel );
863 // Create a new temporary file...
864 $tmpFile = TempFSFile
::factory( wfBaseName( $srcRel ) . '_', $ext );
866 $handle = fopen( $tmpFile->getPath(), 'wb' );
868 $obj->stream( $handle, $this->headersFromParams( $params ) );
871 $tmpFile = null; // couldn't open temp file
874 } catch ( NoSuchContainerException
$e ) {
876 } catch ( CloudFilesException
$e ) { // some other exception?
878 $this->handleException( $e, null, __METHOD__
, $params );
885 * @see FileBackendStore::directoriesAreVirtual()
888 protected function directoriesAreVirtual() {
893 * Get headers to send to Swift when reading a file based
894 * on a FileBackend params array, e.g. that of getLocalCopy().
895 * $params is currently only checked for a 'latest' flag.
897 * @param $params Array
900 protected function headersFromParams( array $params ) {
902 if ( !empty( $params['latest'] ) ) {
903 $hdrs[] = 'X-Newest: true';
909 * @see FileBackendStore::doExecuteOpHandlesInternal()
910 * @return Array List of corresponding Status objects
912 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
915 $cfOps = array(); // list of CF_Async_Op objects
916 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
917 $cfOps[$index] = $fileOpHandle->cfOp
;
919 $batch = new CF_Async_Op_Batch( $cfOps );
921 $cfOps = $batch->execute();
922 foreach ( $cfOps as $index => $cfOp ) {
923 $status = Status
::newGood();
924 try { // catch exceptions; update status
925 $function = '_getResponse' . $fileOpHandles[$index]->call
;
926 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
927 } catch ( CloudFilesException
$e ) { // some other exception?
928 $this->handleException( $e, $status,
929 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
931 $statuses[$index] = $status;
934 foreach ( $fileOpHandles as $fileOpHandle ) {
935 $fileOpHandle->closeResources();
942 * Set read/write permissions for a Swift container
944 * @param $contObj CF_Container Swift container
945 * @param $readGrps Array Swift users who can read (account:user)
946 * @param $writeGrps Array Swift users who can write (account:user)
949 protected function setContainerAccess(
950 CF_Container
$contObj, array $readGrps, array $writeGrps
952 $creds = $contObj->cfs_auth
->export_credentials();
954 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
956 // Note: 10 second timeout consistent with php-cloudfiles
957 $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
958 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
959 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
960 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
962 return $req->execute(); // should return 204
966 * Get a connection to the Swift proxy
968 * @return CF_Connection|bool False on failure
969 * @throws InvalidResponseException
971 protected function getConnection() {
972 if ( $this->conn
=== false ) {
973 throw new InvalidResponseException
; // failed last attempt
975 // Session keys expire after a while, so we renew them periodically
976 if ( $this->conn
&& ( time() - $this->connStarted
) > $this->authTTL
) {
977 $this->conn
->close(); // close active cURL connections
980 // Authenticate with proxy and get a session key...
981 if ( $this->conn
=== null ) {
982 $this->connContainers
= array();
984 $this->auth
->authenticate();
985 $this->conn
= new CF_Connection( $this->auth
);
986 $this->connStarted
= time();
987 } catch ( AuthenticationException
$e ) {
988 $this->conn
= false; // don't keep re-trying
989 } catch ( InvalidResponseException
$e ) {
990 $this->conn
= false; // don't keep re-trying
993 if ( !$this->conn
) {
994 throw new InvalidResponseException
; // auth/connection problem
1000 * @see FileBackendStore::doClearCache()
1002 protected function doClearCache( array $paths = null ) {
1003 $this->connContainers
= array(); // clear container object cache
1007 * Get a Swift container object, possibly from process cache.
1008 * Use $reCache if the file count or byte count is needed.
1010 * @param $container string Container name
1011 * @param $bypassCache bool Bypass all caches and load from Swift
1012 * @return CF_Container
1013 * @throws NoSuchContainerException
1014 * @throws InvalidResponseException
1016 protected function getContainer( $container, $bypassCache = false ) {
1017 $conn = $this->getConnection(); // Swift proxy connection
1018 if ( $bypassCache ) { // purge cache
1019 unset( $this->connContainers
[$container] );
1020 } elseif ( !isset( $this->connContainers
[$container] ) ) {
1021 $this->primeContainerCache( array( $container ) ); // check persistent cache
1023 if ( !isset( $this->connContainers
[$container] ) ) {
1024 $contObj = $conn->get_container( $container );
1025 // NoSuchContainerException not thrown: container must exist
1026 if ( count( $this->connContainers
) >= $this->maxContCacheSize
) { // trim cache?
1027 reset( $this->connContainers
);
1028 unset( $this->connContainers
[key( $this->connContainers
)] );
1030 $this->connContainers
[$container] = $contObj; // cache it
1031 if ( !$bypassCache ) {
1032 $this->setContainerCache( $container, // update persistent cache
1033 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1037 return $this->connContainers
[$container];
1041 * Create a Swift container
1043 * @param $container string Container name
1044 * @return CF_Container
1045 * @throws InvalidResponseException
1047 protected function createContainer( $container ) {
1048 $conn = $this->getConnection(); // Swift proxy connection
1049 $contObj = $conn->create_container( $container );
1050 $this->connContainers
[$container] = $contObj; // cache it
1055 * Delete a Swift container
1057 * @param $container string Container name
1059 * @throws InvalidResponseException
1061 protected function deleteContainer( $container ) {
1062 $conn = $this->getConnection(); // Swift proxy connection
1063 $conn->delete_container( $container );
1064 unset( $this->connContainers
[$container] ); // purge cache
1068 * @see FileBackendStore::doPrimeContainerCache()
1071 protected function doPrimeContainerCache( array $containerInfo ) {
1073 $conn = $this->getConnection(); // Swift proxy connection
1074 foreach ( $containerInfo as $container => $info ) {
1075 $this->connContainers
[$container] = new CF_Container(
1083 } catch ( CloudFilesException
$e ) { // some other exception?
1084 $this->handleException( $e, null, __METHOD__
, array() );
1089 * Log an unexpected exception for this backend.
1090 * This also sets the Status object to have a fatal error.
1092 * @param $e Exception
1093 * @param $status Status|null
1094 * @param $func string
1095 * @param $params Array
1098 protected function handleException( Exception
$e, $status, $func, array $params ) {
1099 if ( $status instanceof Status
) {
1100 if ( $e instanceof AuthenticationException
) {
1101 $status->fatal( 'backend-fail-connect', $this->name
);
1103 $status->fatal( 'backend-fail-internal', $this->name
);
1106 if ( $e->getMessage() ) {
1107 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1109 wfDebugLog( 'SwiftBackend',
1110 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1111 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1117 * @see FileBackendStoreOpHandle
1119 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1120 /** @var CF_Async_Op */
1123 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1124 $this->backend
= $backend;
1125 $this->params
= $params;
1126 $this->call
= $call;
1127 $this->cfOp
= $cfOp;
1132 * SwiftFileBackend helper class to page through listings.
1133 * Swift also has a listing limit of 10,000 objects for sanity.
1134 * Do not use this class from places outside SwiftFileBackend.
1136 * @ingroup FileBackend
1138 abstract class SwiftFileBackendList
implements Iterator
{
1140 protected $bufferIter = array();
1141 protected $bufferAfter = null; // string; list items *after* this path
1142 protected $pos = 0; // integer
1144 protected $params = array();
1146 /** @var SwiftFileBackend */
1148 protected $container; // string; container name
1149 protected $dir; // string; storage directory
1150 protected $suffixStart; // integer
1152 const PAGE_SIZE
= 5000; // file listing buffer size
1155 * @param $backend SwiftFileBackend
1156 * @param $fullCont string Resolved container name
1157 * @param $dir string Resolved directory relative to container
1158 * @param $params Array
1160 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1161 $this->backend
= $backend;
1162 $this->container
= $fullCont;
1164 if ( substr( $this->dir
, -1 ) === '/' ) {
1165 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1167 if ( $this->dir
== '' ) { // whole container
1168 $this->suffixStart
= 0;
1169 } else { // dir within container
1170 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1172 $this->params
= $params;
1176 * @see Iterator::key()
1179 public function key() {
1184 * @see Iterator::next()
1187 public function next() {
1188 // Advance to the next file in the page
1189 next( $this->bufferIter
);
1191 // Check if there are no files left in this page and
1192 // advance to the next page if this page was not empty.
1193 if ( !$this->valid() && count( $this->bufferIter
) ) {
1194 $this->bufferIter
= $this->pageFromList(
1195 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1196 ); // updates $this->bufferAfter
1201 * @see Iterator::rewind()
1204 public function rewind() {
1206 $this->bufferAfter
= null;
1207 $this->bufferIter
= $this->pageFromList(
1208 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1209 ); // updates $this->bufferAfter
1213 * @see Iterator::valid()
1216 public function valid() {
1217 if ( $this->bufferIter
=== null ) {
1218 return false; // some failure?
1220 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1225 * Get the given list portion (page)
1227 * @param $container string Resolved container name
1228 * @param $dir string Resolved path relative to container
1229 * @param $after string|null
1230 * @param $limit integer
1231 * @param $params Array
1232 * @return Traversable|Array|null Returns null on failure
1234 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1238 * Iterator for listing directories
1240 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1242 * @see Iterator::current()
1243 * @return string|bool String (relative path) or false
1245 public function current() {
1246 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1250 * @see SwiftFileBackendList::pageFromList()
1251 * @return Array|null
1253 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1254 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1259 * Iterator for listing regular files
1261 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1263 * @see Iterator::current()
1264 * @return string|bool String (relative path) or false
1266 public function current() {
1267 return substr( current( $this->bufferIter
), $this->suffixStart
);
1271 * @see SwiftFileBackendList::pageFromList()
1272 * @return Array|null
1274 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1275 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );