10 * @brief Class for an OpenStack Swift based file backend.
12 * This requires the SwiftCloudFiles MediaWiki extension, which includes
13 * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
14 * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
16 * Status messages should avoid mentioning the Swift account name.
17 * Likewise, error suppression should be used to avoid path disclosure.
19 * @ingroup FileBackend
22 class SwiftFileBackend
extends FileBackendStore
{
23 /** @var CF_Authentication */
24 protected $auth; // Swift authentication handler
25 protected $authTTL; // integer seconds
26 protected $swiftAnonUser; // string; username to handle unauthenticated requests
27 protected $maxContCacheSize = 100; // integer; max containers with entries
29 /** @var CF_Connection */
30 protected $conn; // Swift connection handle
31 protected $connStarted = 0; // integer UNIX timestamp
32 protected $connContainers = array(); // container object cache
35 * @see FileBackendStore::__construct()
36 * Additional $config params include:
37 * swiftAuthUrl : Swift authentication server URL
38 * swiftUser : Swift user used by MediaWiki (account:username)
39 * swiftKey : Swift authentication key for the above user
40 * swiftAuthTTL : Swift authentication TTL (seconds)
41 * swiftAnonUser : Swift user used for end-user requests (account:username)
42 * shardViaHashLevels : Map of container names to sharding config with:
43 * 'base' : base of hash characters, 16 or 36
44 * 'levels' : the number of hash levels (and digits)
45 * 'repeat' : hash subdirectories are prefixed with all the
46 * parent hash directory names (e.g. "a/ab/abc")
48 public function __construct( array $config ) {
49 parent
::__construct( $config );
51 $this->auth
= new CF_Authentication(
54 null, // account; unused
55 $config['swiftAuthUrl']
58 $this->authTTL
= isset( $config['swiftAuthTTL'] )
59 ?
$config['swiftAuthTTL']
60 : 120; // some sane number
61 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
62 ?
$config['swiftAnonUser']
64 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
65 ?
$config['shardViaHashLevels']
70 * @see FileBackendStore::resolveContainerPath()
73 protected function resolveContainerPath( $container, $relStoragePath ) {
74 if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
75 return null; // too long for Swift
77 return $relStoragePath;
81 * @see FileBackendStore::isPathUsableInternal()
84 public function isPathUsableInternal( $storagePath ) {
85 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
86 if ( $rel === null ) {
87 return false; // invalid
91 $this->getContainer( $container );
92 return true; // container exists
93 } catch ( NoSuchContainerException
$e ) {
94 } catch ( InvalidResponseException
$e ) {
95 } catch ( Exception
$e ) { // some other exception?
96 $this->logException( $e, __METHOD__
, array( 'path' => $storagePath ) );
103 * @see FileBackendStore::doCreateInternal()
106 protected function doCreateInternal( array $params ) {
107 $status = Status
::newGood();
109 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
110 if ( $dstRel === null ) {
111 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
115 // (a) Check the destination container and object
117 $dContObj = $this->getContainer( $dstCont );
118 if ( empty( $params['overwrite'] ) &&
119 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
121 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
124 } catch ( NoSuchContainerException
$e ) {
125 $status->fatal( 'backend-fail-create', $params['dst'] );
127 } catch ( InvalidResponseException
$e ) {
128 $status->fatal( 'backend-fail-connect', $this->name
);
130 } catch ( Exception
$e ) { // some other exception?
131 $status->fatal( 'backend-fail-internal', $this->name
);
132 $this->logException( $e, __METHOD__
, $params );
136 // (b) Get a SHA-1 hash of the object
137 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
139 // (c) Actually create the object
141 // Create a fresh CF_Object with no fields preloaded.
142 // We don't want to preserve headers, metadata, and such.
143 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
144 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
145 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
146 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
147 // The MD5 here will be checked within Swift against its own MD5.
148 $obj->set_etag( md5( $params['content'] ) );
149 // Use the same content type as StreamFile for security
150 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
151 // Actually write the object in Swift
152 $obj->write( $params['content'] );
153 } catch ( BadContentTypeException
$e ) {
154 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
155 } catch ( InvalidResponseException
$e ) {
156 $status->fatal( 'backend-fail-connect', $this->name
);
157 } catch ( Exception
$e ) { // some other exception?
158 $status->fatal( 'backend-fail-internal', $this->name
);
159 $this->logException( $e, __METHOD__
, $params );
166 * @see FileBackendStore::doStoreInternal()
169 protected function doStoreInternal( array $params ) {
170 $status = Status
::newGood();
172 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
173 if ( $dstRel === null ) {
174 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
178 // (a) Check the destination container and object
180 $dContObj = $this->getContainer( $dstCont );
181 if ( empty( $params['overwrite'] ) &&
182 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
184 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
187 } catch ( NoSuchContainerException
$e ) {
188 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
190 } catch ( InvalidResponseException
$e ) {
191 $status->fatal( 'backend-fail-connect', $this->name
);
193 } catch ( Exception
$e ) { // some other exception?
194 $status->fatal( 'backend-fail-internal', $this->name
);
195 $this->logException( $e, __METHOD__
, $params );
199 // (b) Get a SHA-1 hash of the object
200 $sha1Hash = sha1_file( $params['src'] );
201 if ( $sha1Hash === false ) { // source doesn't exist?
202 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
205 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
207 // (c) Actually store the object
209 // Create a fresh CF_Object with no fields preloaded.
210 // We don't want to preserve headers, metadata, and such.
211 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
212 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
213 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
214 // The MD5 here will be checked within Swift against its own MD5.
215 $obj->set_etag( md5_file( $params['src'] ) );
216 // Use the same content type as StreamFile for security
217 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
218 // Actually write the object in Swift
219 $obj->load_from_filename( $params['src'], True ); // calls $obj->write()
220 } catch ( BadContentTypeException
$e ) {
221 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
222 } catch ( IOException
$e ) {
223 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
224 } catch ( InvalidResponseException
$e ) {
225 $status->fatal( 'backend-fail-connect', $this->name
);
226 } catch ( Exception
$e ) { // some other exception?
227 $status->fatal( 'backend-fail-internal', $this->name
);
228 $this->logException( $e, __METHOD__
, $params );
235 * @see FileBackendStore::doCopyInternal()
238 protected function doCopyInternal( array $params ) {
239 $status = Status
::newGood();
241 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
242 if ( $srcRel === null ) {
243 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
247 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
248 if ( $dstRel === null ) {
249 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
253 // (a) Check the source/destination containers and destination object
255 $sContObj = $this->getContainer( $srcCont );
256 $dContObj = $this->getContainer( $dstCont );
257 if ( empty( $params['overwrite'] ) &&
258 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
260 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
263 } catch ( NoSuchContainerException
$e ) {
264 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
266 } catch ( InvalidResponseException
$e ) {
267 $status->fatal( 'backend-fail-connect', $this->name
);
269 } catch ( Exception
$e ) { // some other exception?
270 $status->fatal( 'backend-fail-internal', $this->name
);
271 $this->logException( $e, __METHOD__
, $params );
275 // (b) Actually copy the file to the destination
277 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
278 } catch ( NoSuchObjectException
$e ) { // source object does not exist
279 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
280 } catch ( InvalidResponseException
$e ) {
281 $status->fatal( 'backend-fail-connect', $this->name
);
282 } catch ( Exception
$e ) { // some other exception?
283 $status->fatal( 'backend-fail-internal', $this->name
);
284 $this->logException( $e, __METHOD__
, $params );
291 * @see FileBackendStore::doDeleteInternal()
294 protected function doDeleteInternal( array $params ) {
295 $status = Status
::newGood();
297 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
298 if ( $srcRel === null ) {
299 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
304 $sContObj = $this->getContainer( $srcCont );
305 $sContObj->delete_object( $srcRel );
306 } catch ( NoSuchContainerException
$e ) {
307 $status->fatal( 'backend-fail-delete', $params['src'] );
308 } catch ( NoSuchObjectException
$e ) {
309 if ( empty( $params['ignoreMissingSource'] ) ) {
310 $status->fatal( 'backend-fail-delete', $params['src'] );
312 } catch ( InvalidResponseException
$e ) {
313 $status->fatal( 'backend-fail-connect', $this->name
);
314 } catch ( Exception
$e ) { // some other exception?
315 $status->fatal( 'backend-fail-internal', $this->name
);
316 $this->logException( $e, __METHOD__
, $params );
323 * @see FileBackendStore::doPrepareInternal()
326 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
327 $status = Status
::newGood();
329 // (a) Check if container already exists
331 $contObj = $this->getContainer( $fullCont );
332 // NoSuchContainerException not thrown: container must exist
333 return $status; // already exists
334 } catch ( NoSuchContainerException
$e ) {
335 // NoSuchContainerException thrown: container does not exist
336 } catch ( InvalidResponseException
$e ) {
337 $status->fatal( 'backend-fail-connect', $this->name
);
339 } catch ( Exception
$e ) { // some other exception?
340 $status->fatal( 'backend-fail-internal', $this->name
);
341 $this->logException( $e, __METHOD__
, $params );
345 // (b) Create container as needed
347 $contObj = $this->createContainer( $fullCont );
348 if ( $this->swiftAnonUser
!= '' ) {
349 // Make container public to end-users...
350 $status->merge( $this->setContainerAccess(
352 array( $this->auth
->username
, $this->swiftAnonUser
), // read
353 array( $this->auth
->username
) // write
356 } catch ( InvalidResponseException
$e ) {
357 $status->fatal( 'backend-fail-connect', $this->name
);
359 } catch ( Exception
$e ) { // some other exception?
360 $status->fatal( 'backend-fail-internal', $this->name
);
361 $this->logException( $e, __METHOD__
, $params );
369 * @see FileBackendStore::doSecureInternal()
372 protected function doSecureInternal( $fullCont, $dir, array $params ) {
373 $status = Status
::newGood();
375 if ( $this->swiftAnonUser
!= '' ) {
376 // Restrict container from end-users...
378 // doPrepareInternal() should have been called,
379 // so the Swift container should already exist...
380 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
381 // NoSuchContainerException not thrown: container must exist
382 if ( !isset( $contObj->mw_wasSecured
) ) {
383 $status->merge( $this->setContainerAccess(
385 array( $this->auth
->username
), // read
386 array( $this->auth
->username
) // write
388 // @TODO: when php-cloudfiles supports container
389 // metadata, we can make use of that to avoid RTTs
390 $contObj->mw_wasSecured
= true; // avoid useless RTTs
392 } catch ( InvalidResponseException
$e ) {
393 $status->fatal( 'backend-fail-connect', $this->name
);
394 } catch ( Exception
$e ) { // some other exception?
395 $status->fatal( 'backend-fail-internal', $this->name
);
396 $this->logException( $e, __METHOD__
, $params );
404 * @see FileBackendStore::doCleanInternal()
407 protected function doCleanInternal( $fullCont, $dir, array $params ) {
408 $status = Status
::newGood();
410 // Only containers themselves can be removed, all else is virtual
412 return $status; // nothing to do
415 // (a) Check the container
417 $contObj = $this->getContainer( $fullCont, true );
418 } catch ( NoSuchContainerException
$e ) {
419 return $status; // ok, nothing to do
420 } catch ( InvalidResponseException
$e ) {
421 $status->fatal( 'backend-fail-connect', $this->name
);
423 } catch ( Exception
$e ) { // some other exception?
424 $status->fatal( 'backend-fail-internal', $this->name
);
425 $this->logException( $e, __METHOD__
, $params );
429 // (b) Delete the container if empty
430 if ( $contObj->object_count
== 0 ) {
432 $this->deleteContainer( $fullCont );
433 } catch ( NoSuchContainerException
$e ) {
434 return $status; // race?
435 } catch ( InvalidResponseException
$e ) {
436 $status->fatal( 'backend-fail-connect', $this->name
);
438 } catch ( Exception
$e ) { // some other exception?
439 $status->fatal( 'backend-fail-internal', $this->name
);
440 $this->logException( $e, __METHOD__
, $params );
449 * @see FileBackendStore::doFileExists()
450 * @return array|bool|null
452 protected function doGetFileStat( array $params ) {
453 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
454 if ( $srcRel === null ) {
455 return false; // invalid storage path
460 $contObj = $this->getContainer( $srcCont );
461 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
462 $this->addMissingMetadata( $srcObj, $params['src'] );
464 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
465 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
466 'size' => $srcObj->content_length
,
467 'sha1' => $srcObj->metadata
['Sha1base36']
469 } catch ( NoSuchContainerException
$e ) {
470 } catch ( NoSuchObjectException
$e ) {
471 } catch ( InvalidResponseException
$e ) {
473 } catch ( Exception
$e ) { // some other exception?
475 $this->logException( $e, __METHOD__
, $params );
482 * Fill in any missing object metadata and save it to Swift
484 * @param $obj CF_Object
485 * @param $path string Storage path to object
486 * @return bool Success
487 * @throws Exception cloudfiles exceptions
489 protected function addMissingMetadata( CF_Object
$obj, $path ) {
490 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
491 return true; // nothing to do
493 $status = Status
::newGood();
494 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
495 if ( $status->isOK() ) {
496 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
498 $hash = $tmpFile->getSha1Base36();
499 if ( $hash !== false ) {
500 $obj->metadata
['Sha1base36'] = $hash;
501 $obj->sync_metadata(); // save to Swift
502 return true; // success
506 $obj->metadata
['Sha1base36'] = false;
507 return false; // failed
511 * @see FileBackend::getFileContents()
512 * @return bool|null|string
514 public function getFileContents( array $params ) {
515 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
516 if ( $srcRel === null ) {
517 return false; // invalid storage path
520 if ( !$this->fileExists( $params ) ) {
526 $sContObj = $this->getContainer( $srcCont );
527 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD request
528 $data = $obj->read( $this->headersFromParams( $params ) );
529 } catch ( NoSuchContainerException
$e ) {
530 } catch ( InvalidResponseException
$e ) {
531 } catch ( Exception
$e ) { // some other exception?
532 $this->logException( $e, __METHOD__
, $params );
539 * @see FileBackendStore::getFileListInternal()
540 * @return SwiftFileBackendFileList
542 public function getFileListInternal( $fullCont, $dir, array $params ) {
543 return new SwiftFileBackendFileList( $this, $fullCont, $dir );
547 * Do not call this function outside of SwiftFileBackendFileList
549 * @param $fullCont string Resolved container name
550 * @param $dir string Resolved storage directory with no trailing slash
551 * @param $after string Storage path of file to list items after
552 * @param $limit integer Max number of items to list
555 public function getFileListPageInternal( $fullCont, $dir, $after, $limit ) {
559 $container = $this->getContainer( $fullCont );
560 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
561 $files = $container->list_objects( $limit, $after, $prefix );
562 } catch ( NoSuchContainerException
$e ) {
563 } catch ( NoSuchObjectException
$e ) {
564 } catch ( InvalidResponseException
$e ) {
565 } catch ( Exception
$e ) { // some other exception?
566 $this->logException( $e, __METHOD__
, array( 'cont' => $fullCont, 'dir' => $dir ) );
573 * @see FileBackendStore::doGetFileSha1base36()
576 public function doGetFileSha1base36( array $params ) {
577 $stat = $this->getFileStat( $params );
579 return $stat['sha1'];
586 * @see FileBackendStore::doStreamFile()
589 protected function doStreamFile( array $params ) {
590 $status = Status
::newGood();
592 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
593 if ( $srcRel === null ) {
594 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
598 $cont = $this->getContainer( $srcCont );
599 } catch ( NoSuchContainerException
$e ) {
600 $status->fatal( 'backend-fail-stream', $params['src'] );
602 } catch ( InvalidResponseException
$e ) {
603 $status->fatal( 'backend-fail-connect', $this->name
);
605 } catch ( Exception
$e ) { // some other exception?
606 $status->fatal( 'backend-fail-stream', $params['src'] );
607 $this->logException( $e, __METHOD__
, $params );
612 $output = fopen( 'php://output', 'wb' );
613 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD request
614 $obj->stream( $output, $this->headersFromParams( $params ) );
615 } catch ( InvalidResponseException
$e ) { // 404? connection problem?
616 $status->fatal( 'backend-fail-stream', $params['src'] );
617 } catch ( Exception
$e ) { // some other exception?
618 $status->fatal( 'backend-fail-stream', $params['src'] );
619 $this->logException( $e, __METHOD__
, $params );
626 * @see FileBackendStore::getLocalCopy()
627 * @return null|TempFSFile
629 public function getLocalCopy( array $params ) {
630 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
631 if ( $srcRel === null ) {
635 if ( !$this->fileExists( $params ) ) {
641 $sContObj = $this->getContainer( $srcCont );
642 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
643 // Get source file extension
644 $ext = FileBackend
::extensionFromPath( $srcRel );
645 // Create a new temporary file...
646 $tmpFile = TempFSFile
::factory( wfBaseName( $srcRel ) . '_', $ext );
648 $handle = fopen( $tmpFile->getPath(), 'wb' );
650 $obj->stream( $handle, $this->headersFromParams( $params ) );
653 $tmpFile = null; // couldn't open temp file
656 } catch ( NoSuchContainerException
$e ) {
658 } catch ( InvalidResponseException
$e ) {
660 } catch ( Exception
$e ) { // some other exception?
662 $this->logException( $e, __METHOD__
, $params );
669 * Get headers to send to Swift when reading a file based
670 * on a FileBackend params array, e.g. that of getLocalCopy().
671 * $params is currently only checked for a 'latest' flag.
673 * @param $params Array
676 protected function headersFromParams( array $params ) {
678 if ( !empty( $params['latest'] ) ) {
679 $hdrs[] = 'X-Newest: true';
685 * Set read/write permissions for a Swift container
687 * @param $contObj CF_Container Swift container
688 * @param $readGrps Array Swift users who can read (account:user)
689 * @param $writeGrps Array Swift users who can write (account:user)
692 protected function setContainerAccess(
693 CF_Container
$contObj, array $readGrps, array $writeGrps
695 $creds = $contObj->cfs_auth
->export_credentials();
697 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
699 // Note: 10 second timeout consistent with php-cloudfiles
700 $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
701 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
702 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
703 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
705 return $req->execute(); // should return 204
709 * Get a connection to the Swift proxy
711 * @return CF_Connection|bool False on failure
712 * @throws InvalidResponseException
714 protected function getConnection() {
715 if ( $this->conn
=== false ) {
716 throw new InvalidResponseException
; // failed last attempt
718 // Session keys expire after a while, so we renew them periodically
719 if ( $this->conn
&& ( time() - $this->connStarted
) > $this->authTTL
) {
720 $this->conn
->close(); // close active cURL connections
723 // Authenticate with proxy and get a session key...
724 if ( $this->conn
=== null ) {
725 $this->connContainers
= array();
727 $this->auth
->authenticate();
728 $this->conn
= new CF_Connection( $this->auth
);
729 $this->connStarted
= time();
730 } catch ( AuthenticationException
$e ) {
731 $this->conn
= false; // don't keep re-trying
732 } catch ( InvalidResponseException
$e ) {
733 $this->conn
= false; // don't keep re-trying
736 if ( !$this->conn
) {
737 throw new InvalidResponseException
; // auth/connection problem
743 * @see FileBackendStore::doClearCache()
745 protected function doClearCache( array $paths = null ) {
746 $this->connContainers
= array(); // clear container object cache
750 * Get a Swift container object, possibly from process cache.
751 * Use $reCache if the file count or byte count is needed.
753 * @param $container string Container name
754 * @param $reCache bool Refresh the process cache
755 * @return CF_Container
757 protected function getContainer( $container, $reCache = false ) {
758 $conn = $this->getConnection(); // Swift proxy connection
760 unset( $this->connContainers
[$container] ); // purge cache
762 if ( !isset( $this->connContainers
[$container] ) ) {
763 $contObj = $conn->get_container( $container );
764 // NoSuchContainerException not thrown: container must exist
765 if ( count( $this->connContainers
) >= $this->maxContCacheSize
) { // trim cache?
766 reset( $this->connContainers
);
767 $key = key( $this->connContainers
);
768 unset( $this->connContainers
[$key] );
770 $this->connContainers
[$container] = $contObj; // cache it
772 return $this->connContainers
[$container];
776 * Create a Swift container
778 * @param $container string Container name
779 * @return CF_Container
781 protected function createContainer( $container ) {
782 $conn = $this->getConnection(); // Swift proxy connection
783 $contObj = $conn->create_container( $container );
784 $this->connContainers
[$container] = $contObj; // cache it
789 * Delete a Swift container
791 * @param $container string Container name
794 protected function deleteContainer( $container ) {
795 $conn = $this->getConnection(); // Swift proxy connection
796 $conn->delete_container( $container );
797 unset( $this->connContainers
[$container] ); // purge cache
801 * Log an unexpected exception for this backend
803 * @param $e Exception
804 * @param $func string
805 * @param $params Array
808 protected function logException( Exception
$e, $func, array $params ) {
809 wfDebugLog( 'SwiftBackend',
810 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
811 ( $e instanceof InvalidResponseException
812 ?
": {$e->getMessage()}"
820 * SwiftFileBackend helper class to page through object listings.
821 * Swift also has a listing limit of 10,000 objects for sanity.
822 * Do not use this class from places outside SwiftFileBackend.
824 * @ingroup FileBackend
826 class SwiftFileBackendFileList
implements Iterator
{
828 protected $bufferIter = array();
829 protected $bufferAfter = null; // string; list items *after* this path
830 protected $pos = 0; // integer
832 /** @var SwiftFileBackend */
834 protected $container; //
835 protected $dir; // string storage directory
836 protected $suffixStart; // integer
838 const PAGE_SIZE
= 5000; // file listing buffer size
841 * @param $backend SwiftFileBackend
842 * @param $fullCont string Resolved container name
843 * @param $dir string Resolved directory relative to container
845 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir ) {
846 $this->backend
= $backend;
847 $this->container
= $fullCont;
849 if ( substr( $this->dir
, -1 ) === '/' ) {
850 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
852 if ( $this->dir
== '' ) { // whole container
853 $this->suffixStart
= 0;
854 } else { // dir within container
855 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
860 * @see Iterator::current()
861 * @return string|bool String or false
863 public function current() {
864 return substr( current( $this->bufferIter
), $this->suffixStart
);
868 * @see Iterator::key()
871 public function key() {
876 * @see Iterator::next()
879 public function next() {
880 // Advance to the next file in the page
881 next( $this->bufferIter
);
883 // Check if there are no files left in this page and
884 // advance to the next page if this page was not empty.
885 if ( !$this->valid() && count( $this->bufferIter
) ) {
886 $this->bufferAfter
= end( $this->bufferIter
);
887 $this->bufferIter
= $this->backend
->getFileListPageInternal(
888 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
894 * @see Iterator::rewind()
897 public function rewind() {
899 $this->bufferAfter
= null;
900 $this->bufferIter
= $this->backend
->getFileListPageInternal(
901 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
906 * @see Iterator::valid()
909 public function valid() {
910 return ( current( $this->bufferIter
) !== false ); // no paths can have this value