3 * OpenStack Swift based file backend.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
23 * @author Aaron Schulz
27 * @brief Class for an OpenStack Swift based file backend.
29 * This requires the SwiftCloudFiles MediaWiki extension, which includes
30 * the php-cloudfiles library (https://github.com/rackspace/php-cloudfiles).
31 * php-cloudfiles requires the curl, fileinfo, and mb_string PHP extensions.
33 * Status messages should avoid mentioning the Swift account name.
34 * Likewise, error suppression should be used to avoid path disclosure.
36 * @ingroup FileBackend
39 class SwiftFileBackend
extends FileBackendStore
{
40 /** @var CF_Authentication */
41 protected $auth; // Swift authentication handler
42 protected $authTTL; // integer seconds
43 protected $swiftAnonUser; // string; username to handle unauthenticated requests
44 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
45 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
46 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
48 protected $maxContCacheSize = 300; // integer; max containers with entries
50 /** @var CF_Connection */
51 protected $conn; // Swift connection handle
52 protected $connStarted = 0; // integer UNIX timestamp
53 protected $connContainers = array(); // container object cache
54 protected $connException; // CloudFiles exception
57 * @see FileBackendStore::__construct()
58 * Additional $config params include:
59 * - swiftAuthUrl : Swift authentication server URL
60 * - swiftUser : Swift user used by MediaWiki (account:username)
61 * - swiftKey : Swift authentication key for the above user
62 * - swiftAuthTTL : Swift authentication TTL (seconds)
63 * - swiftAnonUser : Swift user used for end-user requests (account:username).
64 * If set, then views of public containers are assumed to go
65 * through this user. If not set, then public containers are
66 * accessible to unauthenticated requests via ".r:*" in the ACL.
67 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
68 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
69 * If files may likely change, this should probably not exceed
70 * a few days. For example, deletions may take this long to apply.
71 * If object purging is enabled, however, this is not an issue.
72 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
73 * - shardViaHashLevels : Map of container names to sharding config with:
74 * - base : base of hash characters, 16 or 36
75 * - levels : the number of hash levels (and digits)
76 * - repeat : hash subdirectories are prefixed with all the
77 * parent hash directory names (e.g. "a/ab/abc")
79 public function __construct( array $config ) {
80 parent
::__construct( $config );
81 if ( !MWInit
::classExists( 'CF_Constants' ) ) {
82 throw new MWException( 'SwiftCloudFiles extension not installed.' );
85 $this->auth
= new CF_Authentication(
88 null, // account; unused
89 $config['swiftAuthUrl']
92 $this->authTTL
= isset( $config['swiftAuthTTL'] )
93 ?
$config['swiftAuthTTL']
94 : 5 * 60; // some sane number
95 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
96 ?
$config['swiftAnonUser']
98 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
99 ?
$config['shardViaHashLevels']
101 $this->swiftUseCDN
= isset( $config['swiftUseCDN'] )
102 ?
$config['swiftUseCDN']
104 $this->swiftCDNExpiry
= isset( $config['swiftCDNExpiry'] )
105 ?
$config['swiftCDNExpiry']
107 $this->swiftCDNPurgable
= isset( $config['swiftCDNPurgable'] )
108 ?
$config['swiftCDNPurgable']
110 // Cache container info to mask latency
111 $this->memCache
= wfGetMainCache();
115 * @see FileBackendStore::resolveContainerPath()
118 protected function resolveContainerPath( $container, $relStoragePath ) {
119 if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
120 return null; // too long for Swift
122 return $relStoragePath;
126 * @see FileBackendStore::isPathUsableInternal()
129 public function isPathUsableInternal( $storagePath ) {
130 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
131 if ( $rel === null ) {
132 return false; // invalid
136 $this->getContainer( $container );
137 return true; // container exists
138 } catch ( NoSuchContainerException
$e ) {
139 } catch ( CloudFilesException
$e ) { // some other exception?
140 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
147 * @see FileBackendStore::doCreateInternal()
150 protected function doCreateInternal( array $params ) {
151 $status = Status
::newGood();
153 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
154 if ( $dstRel === null ) {
155 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
159 // (a) Check the destination container and object
161 $dContObj = $this->getContainer( $dstCont );
162 if ( empty( $params['overwrite'] ) &&
163 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
165 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
168 } catch ( NoSuchContainerException
$e ) {
169 $status->fatal( 'backend-fail-create', $params['dst'] );
171 } catch ( CloudFilesException
$e ) { // some other exception?
172 $this->handleException( $e, $status, __METHOD__
, $params );
176 // (b) Get a SHA-1 hash of the object
177 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
179 // (c) Actually create the object
181 // Create a fresh CF_Object with no fields preloaded.
182 // We don't want to preserve headers, metadata, and such.
183 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
184 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
185 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
186 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
187 // The MD5 here will be checked within Swift against its own MD5.
188 $obj->set_etag( md5( $params['content'] ) );
189 // Use the same content type as StreamFile for security
190 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
191 if ( !strlen( $obj->content_type
) ) { // special case
192 $obj->content_type
= 'unknown/unknown';
194 if ( !empty( $params['async'] ) ) { // deferred
195 $handle = $obj->write_async( $params['content'] );
196 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $handle );
197 $status->value
->affectedObjects
[] = $obj;
198 } else { // actually write the object in Swift
199 $obj->write( $params['content'] );
200 $this->purgeCDNCache( array( $obj ) );
202 } catch ( CDNNotEnabledException
$e ) {
203 // CDN not enabled; nothing to see here
204 } catch ( BadContentTypeException
$e ) {
205 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
206 } catch ( CloudFilesException
$e ) { // some other exception?
207 $this->handleException( $e, $status, __METHOD__
, $params );
214 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
216 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
218 $cfOp->getLastResponse();
219 } catch ( BadContentTypeException
$e ) {
220 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
225 * @see FileBackendStore::doStoreInternal()
228 protected function doStoreInternal( array $params ) {
229 $status = Status
::newGood();
231 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
232 if ( $dstRel === null ) {
233 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
237 // (a) Check the destination container and object
239 $dContObj = $this->getContainer( $dstCont );
240 if ( empty( $params['overwrite'] ) &&
241 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
243 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
246 } catch ( NoSuchContainerException
$e ) {
247 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
249 } catch ( CloudFilesException
$e ) { // some other exception?
250 $this->handleException( $e, $status, __METHOD__
, $params );
254 // (b) Get a SHA-1 hash of the object
255 $sha1Hash = sha1_file( $params['src'] );
256 if ( $sha1Hash === false ) { // source doesn't exist?
257 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
260 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
262 // (c) Actually store the object
264 // Create a fresh CF_Object with no fields preloaded.
265 // We don't want to preserve headers, metadata, and such.
266 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
267 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
268 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
269 // The MD5 here will be checked within Swift against its own MD5.
270 $obj->set_etag( md5_file( $params['src'] ) );
271 // Use the same content type as StreamFile for security
272 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
273 if ( !strlen( $obj->content_type
) ) { // special case
274 $obj->content_type
= 'unknown/unknown';
276 if ( !empty( $params['async'] ) ) { // deferred
277 wfSuppressWarnings();
278 $fp = fopen( $params['src'], 'rb' );
281 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
283 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
284 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $handle );
285 $status->value
->resourcesToClose
[] = $fp;
286 $status->value
->affectedObjects
[] = $obj;
288 } else { // actually write the object in Swift
289 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
290 $this->purgeCDNCache( array( $obj ) );
292 } catch ( CDNNotEnabledException
$e ) {
293 // CDN not enabled; nothing to see here
294 } catch ( BadContentTypeException
$e ) {
295 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
296 } catch ( IOException
$e ) {
297 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
298 } catch ( CloudFilesException
$e ) { // some other exception?
299 $this->handleException( $e, $status, __METHOD__
, $params );
306 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
308 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
310 $cfOp->getLastResponse();
311 } catch ( BadContentTypeException
$e ) {
312 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
313 } catch ( IOException
$e ) {
314 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
319 * @see FileBackendStore::doCopyInternal()
322 protected function doCopyInternal( array $params ) {
323 $status = Status
::newGood();
325 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
326 if ( $srcRel === null ) {
327 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
331 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
332 if ( $dstRel === null ) {
333 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
337 // (a) Check the source/destination containers and destination object
339 $sContObj = $this->getContainer( $srcCont );
340 $dContObj = $this->getContainer( $dstCont );
341 if ( empty( $params['overwrite'] ) &&
342 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
344 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
347 } catch ( NoSuchContainerException
$e ) {
348 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
350 } catch ( CloudFilesException
$e ) { // some other exception?
351 $this->handleException( $e, $status, __METHOD__
, $params );
355 // (b) Actually copy the file to the destination
357 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
358 if ( !empty( $params['async'] ) ) { // deferred
359 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
360 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
361 $status->value
->affectedObjects
[] = $dstObj;
362 } else { // actually write the object in Swift
363 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
364 $this->purgeCDNCache( array( $dstObj ) );
366 } catch ( CDNNotEnabledException
$e ) {
367 // CDN not enabled; nothing to see here
368 } catch ( NoSuchObjectException
$e ) { // source object does not exist
369 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
370 } catch ( CloudFilesException
$e ) { // some other exception?
371 $this->handleException( $e, $status, __METHOD__
, $params );
378 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
380 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
382 $cfOp->getLastResponse();
383 } catch ( NoSuchObjectException
$e ) { // source object does not exist
384 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
389 * @see FileBackendStore::doMoveInternal()
392 protected function doMoveInternal( array $params ) {
393 $status = Status
::newGood();
395 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
396 if ( $srcRel === null ) {
397 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
401 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
402 if ( $dstRel === null ) {
403 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
407 // (a) Check the source/destination containers and destination object
409 $sContObj = $this->getContainer( $srcCont );
410 $dContObj = $this->getContainer( $dstCont );
411 if ( empty( $params['overwrite'] ) &&
412 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
414 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
417 } catch ( NoSuchContainerException
$e ) {
418 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
420 } catch ( CloudFilesException
$e ) { // some other exception?
421 $this->handleException( $e, $status, __METHOD__
, $params );
425 // (b) Actually move the file to the destination
427 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
428 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
429 if ( !empty( $params['async'] ) ) { // deferred
430 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
431 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $handle );
432 $status->value
->affectedObjects
[] = $srcObj;
433 $status->value
->affectedObjects
[] = $dstObj;
434 } else { // actually write the object in Swift
435 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
436 $this->purgeCDNCache( array( $srcObj, $dstObj ) );
438 } catch ( CDNNotEnabledException
$e ) {
439 // CDN not enabled; nothing to see here
440 } catch ( NoSuchObjectException
$e ) { // source object does not exist
441 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
442 } catch ( CloudFilesException
$e ) { // some other exception?
443 $this->handleException( $e, $status, __METHOD__
, $params );
450 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
452 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
454 $cfOp->getLastResponse();
455 } catch ( NoSuchObjectException
$e ) { // source object does not exist
456 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
461 * @see FileBackendStore::doDeleteInternal()
464 protected function doDeleteInternal( array $params ) {
465 $status = Status
::newGood();
467 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
468 if ( $srcRel === null ) {
469 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
474 $sContObj = $this->getContainer( $srcCont );
475 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
476 if ( !empty( $params['async'] ) ) { // deferred
477 $handle = $sContObj->delete_object_async( $srcRel );
478 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
479 $status->value
->affectedObjects
[] = $srcObj;
480 } else { // actually write the object in Swift
481 $sContObj->delete_object( $srcRel );
482 $this->purgeCDNCache( array( $srcObj ) );
484 } catch ( CDNNotEnabledException
$e ) {
485 // CDN not enabled; nothing to see here
486 } catch ( NoSuchContainerException
$e ) {
487 $status->fatal( 'backend-fail-delete', $params['src'] );
488 } catch ( NoSuchObjectException
$e ) {
489 if ( empty( $params['ignoreMissingSource'] ) ) {
490 $status->fatal( 'backend-fail-delete', $params['src'] );
492 } catch ( CloudFilesException
$e ) { // some other exception?
493 $this->handleException( $e, $status, __METHOD__
, $params );
500 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
502 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
504 $cfOp->getLastResponse();
505 } catch ( NoSuchContainerException
$e ) {
506 $status->fatal( 'backend-fail-delete', $params['src'] );
507 } catch ( NoSuchObjectException
$e ) {
508 if ( empty( $params['ignoreMissingSource'] ) ) {
509 $status->fatal( 'backend-fail-delete', $params['src'] );
515 * @see FileBackendStore::doPrepareInternal()
518 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
519 $status = Status
::newGood();
521 // (a) Check if container already exists
523 $contObj = $this->getContainer( $fullCont );
524 // NoSuchContainerException not thrown: container must exist
525 return $status; // already exists
526 } catch ( NoSuchContainerException
$e ) {
527 // NoSuchContainerException thrown: container does not exist
528 } catch ( CloudFilesException
$e ) { // some other exception?
529 $this->handleException( $e, $status, __METHOD__
, $params );
533 // (b) Create container as needed
535 $contObj = $this->createContainer( $fullCont );
536 if ( !empty( $params['noAccess'] ) ) {
537 // Make container private to end-users...
538 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
540 // Make container public to end-users...
541 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
543 if ( $this->swiftUseCDN
) { // Rackspace style CDN
544 $contObj->make_public( $this->swiftCDNExpiry
);
546 } catch ( CDNNotEnabledException
$e ) {
547 // CDN not enabled; nothing to see here
548 } catch ( CloudFilesException
$e ) { // some other exception?
549 $this->handleException( $e, $status, __METHOD__
, $params );
557 * @see FileBackendStore::doSecureInternal()
560 protected function doSecureInternal( $fullCont, $dir, array $params ) {
561 $status = Status
::newGood();
562 if ( empty( $params['noAccess'] ) ) {
563 return $status; // nothing to do
566 // Restrict container from end-users...
568 // doPrepareInternal() should have been called,
569 // so the Swift container should already exist...
570 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
571 // NoSuchContainerException not thrown: container must exist
573 // Make container private to end-users...
574 $status->merge( $this->setContainerAccess(
576 array( $this->auth
->username
), // read
577 array( $this->auth
->username
) // write
579 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
580 $contObj->make_private();
582 } catch ( CDNNotEnabledException
$e ) {
583 // CDN not enabled; nothing to see here
584 } catch ( CloudFilesException
$e ) { // some other exception?
585 $this->handleException( $e, $status, __METHOD__
, $params );
592 * @see FileBackendStore::doPublishInternal()
595 protected function doPublishInternal( $fullCont, $dir, array $params ) {
596 $status = Status
::newGood();
598 // Unrestrict container from end-users...
600 // doPrepareInternal() should have been called,
601 // so the Swift container should already exist...
602 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
603 // NoSuchContainerException not thrown: container must exist
605 // Make container public to end-users...
606 if ( $this->swiftAnonUser
!= '' ) {
607 $status->merge( $this->setContainerAccess(
609 array( $this->auth
->username
, $this->swiftAnonUser
), // read
610 array( $this->auth
->username
, $this->swiftAnonUser
) // write
613 $status->merge( $this->setContainerAccess(
615 array( $this->auth
->username
, '.r:*' ), // read
616 array( $this->auth
->username
) // write
619 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
620 $contObj->make_public();
622 } catch ( CDNNotEnabledException
$e ) {
623 // CDN not enabled; nothing to see here
624 } catch ( CloudFilesException
$e ) { // some other exception?
625 $this->handleException( $e, $status, __METHOD__
, $params );
632 * @see FileBackendStore::doCleanInternal()
635 protected function doCleanInternal( $fullCont, $dir, array $params ) {
636 $status = Status
::newGood();
638 // Only containers themselves can be removed, all else is virtual
640 return $status; // nothing to do
643 // (a) Check the container
645 $contObj = $this->getContainer( $fullCont, true );
646 } catch ( NoSuchContainerException
$e ) {
647 return $status; // ok, nothing to do
648 } catch ( CloudFilesException
$e ) { // some other exception?
649 $this->handleException( $e, $status, __METHOD__
, $params );
653 // (b) Delete the container if empty
654 if ( $contObj->object_count
== 0 ) {
656 $this->deleteContainer( $fullCont );
657 } catch ( NoSuchContainerException
$e ) {
658 return $status; // race?
659 } catch ( NonEmptyContainerException
$e ) {
660 return $status; // race? consistency delay?
661 } catch ( CloudFilesException
$e ) { // some other exception?
662 $this->handleException( $e, $status, __METHOD__
, $params );
671 * @see FileBackendStore::doFileExists()
672 * @return array|bool|null
674 protected function doGetFileStat( array $params ) {
675 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
676 if ( $srcRel === null ) {
677 return false; // invalid storage path
682 $contObj = $this->getContainer( $srcCont );
683 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
684 $this->addMissingMetadata( $srcObj, $params['src'] );
686 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
687 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
688 'size' => (int)$srcObj->content_length
,
689 'sha1' => $srcObj->metadata
['Sha1base36']
691 } catch ( NoSuchContainerException
$e ) {
692 } catch ( NoSuchObjectException
$e ) {
693 } catch ( CloudFilesException
$e ) { // some other exception?
695 $this->handleException( $e, null, __METHOD__
, $params );
702 * Fill in any missing object metadata and save it to Swift
704 * @param $obj CF_Object
705 * @param $path string Storage path to object
706 * @return bool Success
707 * @throws Exception cloudfiles exceptions
709 protected function addMissingMetadata( CF_Object
$obj, $path ) {
710 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
711 return true; // nothing to do
713 $status = Status
::newGood();
714 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
715 if ( $status->isOK() ) {
716 # Do not stat the file in getLocalCopy() to avoid infinite loops
717 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
719 $hash = $tmpFile->getSha1Base36();
720 if ( $hash !== false ) {
721 $obj->metadata
['Sha1base36'] = $hash;
722 $obj->sync_metadata(); // save to Swift
723 return true; // success
727 $obj->metadata
['Sha1base36'] = false;
728 return false; // failed
732 * @see FileBackend::getFileContents()
733 * @return bool|null|string
735 public function getFileContents( array $params ) {
736 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
737 if ( $srcRel === null ) {
738 return false; // invalid storage path
741 if ( !$this->fileExists( $params ) ) {
747 $sContObj = $this->getContainer( $srcCont );
748 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
749 $data = $obj->read( $this->headersFromParams( $params ) );
750 } catch ( NoSuchContainerException
$e ) {
751 } catch ( CloudFilesException
$e ) { // some other exception?
752 $this->handleException( $e, null, __METHOD__
, $params );
759 * @see FileBackendStore::doDirectoryExists()
762 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
764 $container = $this->getContainer( $fullCont );
765 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
766 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
767 } catch ( NoSuchContainerException
$e ) {
769 } catch ( CloudFilesException
$e ) { // some other exception?
770 $this->handleException( $e, null, __METHOD__
,
771 array( 'cont' => $fullCont, 'dir' => $dir ) );
774 return null; // error
778 * @see FileBackendStore::getDirectoryListInternal()
779 * @return SwiftFileBackendDirList
781 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
782 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
786 * @see FileBackendStore::getFileListInternal()
787 * @return SwiftFileBackendFileList
789 public function getFileListInternal( $fullCont, $dir, array $params ) {
790 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
794 * Do not call this function outside of SwiftFileBackendFileList
796 * @param $fullCont string Resolved container name
797 * @param $dir string Resolved storage directory with no trailing slash
798 * @param $after string|null Storage path of file to list items after
799 * @param $limit integer Max number of items to list
800 * @param $params Array Includes flag for 'topOnly'
801 * @return Array List of relative paths of dirs directly under $dir
803 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
805 if ( $after === INF
) {
806 return $dirs; // nothing more
808 wfProfileIn( __METHOD__
. '-' . $this->name
);
811 $container = $this->getContainer( $fullCont );
812 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
813 // Non-recursive: only list dirs right under $dir
814 if ( !empty( $params['topOnly'] ) ) {
815 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
816 foreach ( $objects as $object ) { // files and dirs
817 if ( substr( $object, -1 ) === '/' ) {
818 $dirs[] = $object; // directories end in '/'
821 // Recursive: list all dirs under $dir and its subdirs
823 // Get directory from last item of prior page
824 $lastDir = $this->getParentDir( $after ); // must be first page
825 $objects = $container->list_objects( $limit, $after, $prefix );
826 foreach ( $objects as $object ) { // files
827 $objectDir = $this->getParentDir( $object ); // directory of object
828 if ( $objectDir !== false ) { // file has a parent dir
829 // Swift stores paths in UTF-8, using binary sorting.
830 // See function "create_container_table" in common/db.py.
831 // If a directory is not "greater" than the last one,
832 // then it was already listed by the calling iterator.
833 if ( $objectDir > $lastDir ) {
835 do { // add dir and all its parent dirs
836 $dirs[] = "{$pDir}/";
837 $pDir = $this->getParentDir( $pDir );
838 } while ( $pDir !== false // sanity
839 && $pDir > $lastDir // not done already
840 && strlen( $pDir ) > strlen( $dir ) // within $dir
843 $lastDir = $objectDir;
847 if ( count( $objects ) < $limit ) {
848 $after = INF
; // avoid a second RTT
850 $after = end( $objects ); // update last item
852 } catch ( NoSuchContainerException
$e ) {
853 } catch ( CloudFilesException
$e ) { // some other exception?
854 $this->handleException( $e, null, __METHOD__
,
855 array( 'cont' => $fullCont, 'dir' => $dir ) );
858 wfProfileOut( __METHOD__
. '-' . $this->name
);
862 protected function getParentDir( $path ) {
863 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
867 * Do not call this function outside of SwiftFileBackendFileList
869 * @param $fullCont string Resolved container name
870 * @param $dir string Resolved storage directory with no trailing slash
871 * @param $after string|null Storage path of file to list items after
872 * @param $limit integer Max number of items to list
873 * @param $params Array Includes flag for 'topOnly'
874 * @return Array List of relative paths of files under $dir
876 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
878 if ( $after === INF
) {
879 return $files; // nothing more
881 wfProfileIn( __METHOD__
. '-' . $this->name
);
884 $container = $this->getContainer( $fullCont );
885 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
886 // Non-recursive: only list files right under $dir
887 if ( !empty( $params['topOnly'] ) ) { // files and dirs
888 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
889 foreach ( $objects as $object ) {
890 if ( substr( $object, -1 ) !== '/' ) {
891 $files[] = $object; // directories end in '/'
894 // Recursive: list all files under $dir and its subdirs
896 $objects = $container->list_objects( $limit, $after, $prefix );
899 if ( count( $objects ) < $limit ) {
900 $after = INF
; // avoid a second RTT
902 $after = end( $objects ); // update last item
904 } catch ( NoSuchContainerException
$e ) {
905 } catch ( CloudFilesException
$e ) { // some other exception?
906 $this->handleException( $e, null, __METHOD__
,
907 array( 'cont' => $fullCont, 'dir' => $dir ) );
910 wfProfileOut( __METHOD__
. '-' . $this->name
);
915 * @see FileBackendStore::doGetFileSha1base36()
918 protected function doGetFileSha1base36( array $params ) {
919 $stat = $this->getFileStat( $params );
921 return $stat['sha1'];
928 * @see FileBackendStore::doStreamFile()
931 protected function doStreamFile( array $params ) {
932 $status = Status
::newGood();
934 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
935 if ( $srcRel === null ) {
936 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
940 $cont = $this->getContainer( $srcCont );
941 } catch ( NoSuchContainerException
$e ) {
942 $status->fatal( 'backend-fail-stream', $params['src'] );
944 } catch ( CloudFilesException
$e ) { // some other exception?
945 $this->handleException( $e, $status, __METHOD__
, $params );
950 $output = fopen( 'php://output', 'wb' );
951 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
952 $obj->stream( $output, $this->headersFromParams( $params ) );
953 } catch ( CloudFilesException
$e ) { // some other exception?
954 $this->handleException( $e, $status, __METHOD__
, $params );
961 * @see FileBackendStore::getLocalCopy()
962 * @return null|TempFSFile
964 public function getLocalCopy( array $params ) {
965 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
966 if ( $srcRel === null ) {
970 # Check the recursion guard to avoid loops when filling metadata
971 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
977 $sContObj = $this->getContainer( $srcCont );
978 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
979 // Get source file extension
980 $ext = FileBackend
::extensionFromPath( $srcRel );
981 // Create a new temporary file...
982 $tmpFile = TempFSFile
::factory( wfBaseName( $srcRel ) . '_', $ext );
984 $handle = fopen( $tmpFile->getPath(), 'wb' );
986 $obj->stream( $handle, $this->headersFromParams( $params ) );
989 $tmpFile = null; // couldn't open temp file
992 } catch ( NoSuchContainerException
$e ) {
994 } catch ( CloudFilesException
$e ) { // some other exception?
996 $this->handleException( $e, null, __METHOD__
, $params );
1003 * @see FileBackendStore::directoriesAreVirtual()
1006 protected function directoriesAreVirtual() {
1011 * Get headers to send to Swift when reading a file based
1012 * on a FileBackend params array, e.g. that of getLocalCopy().
1013 * $params is currently only checked for a 'latest' flag.
1015 * @param $params Array
1018 protected function headersFromParams( array $params ) {
1020 if ( !empty( $params['latest'] ) ) {
1021 $hdrs[] = 'X-Newest: true';
1027 * @see FileBackendStore::doExecuteOpHandlesInternal()
1028 * @return Array List of corresponding Status objects
1030 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1031 $statuses = array();
1033 $cfOps = array(); // list of CF_Async_Op objects
1034 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1035 $cfOps[$index] = $fileOpHandle->cfOp
;
1037 $batch = new CF_Async_Op_Batch( $cfOps );
1039 $cfOps = $batch->execute();
1040 foreach ( $cfOps as $index => $cfOp ) {
1041 $status = Status
::newGood();
1042 try { // catch exceptions; update status
1043 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1044 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1045 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1046 } catch ( CloudFilesException
$e ) { // some other exception?
1047 $this->handleException( $e, $status,
1048 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1050 $statuses[$index] = $status;
1057 * Set read/write permissions for a Swift container.
1059 * $readGrps is a list of the possible criteria for a request to have
1060 * access to read a container. Each item is one of the following formats:
1061 * - account:user : Grants access if the request is by the given user
1062 * - .r:<regex> : Grants access if the request is from a referrer host that
1063 * matches the expression and the request is not for a listing.
1064 * Setting this to '*' effectively makes a container public.
1065 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1066 * matches the expression and the request for a listing.
1068 * $writeGrps is a list of the possible criteria for a request to have
1069 * access to write to a container. Each item is of the following format:
1070 * - account:user : Grants access if the request is by the given user
1072 * @see http://swift.openstack.org/misc.html#acls
1074 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1075 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1077 * @param $contObj CF_Container Swift container
1078 * @param $readGrps Array List of read access routes
1079 * @param $writeGrps Array List of write access routes
1082 protected function setContainerAccess(
1083 CF_Container
$contObj, array $readGrps, array $writeGrps
1085 $creds = $contObj->cfs_auth
->export_credentials();
1087 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1089 // Note: 10 second timeout consistent with php-cloudfiles
1090 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1091 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1092 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1093 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1095 return $req->execute(); // should return 204
1099 * Purge the CDN cache of affected objects if CDN caching is enabled.
1100 * This is for Rackspace/Akamai CDNs.
1102 * @param $objects Array List of CF_Object items
1105 public function purgeCDNCache( array $objects ) {
1106 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1107 foreach ( $objects as $object ) {
1109 $object->purge_from_cdn();
1110 } catch ( CDNNotEnabledException
$e ) {
1111 // CDN not enabled; nothing to see here
1112 } catch ( CloudFilesException
$e ) {
1113 $this->handleException( $e, null, __METHOD__
,
1114 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1121 * Get a connection to the Swift proxy
1123 * @return CF_Connection|bool False on failure
1124 * @throws CloudFilesException
1126 protected function getConnection() {
1127 if ( $this->connException
instanceof Exception
) {
1128 throw $this->connException
; // failed last attempt
1130 // Session keys expire after a while, so we renew them periodically
1131 if ( $this->conn
&& ( time() - $this->connStarted
) > $this->authTTL
) {
1132 $this->conn
->close(); // close active cURL connections
1135 // Authenticate with proxy and get a session key...
1136 if ( !$this->conn
) {
1137 $this->connStarted
= 0;
1138 $this->connContainers
= array();
1140 $this->auth
->authenticate();
1141 $this->conn
= new CF_Connection( $this->auth
);
1142 $this->connStarted
= time();
1143 } catch ( CloudFilesException
$e ) {
1144 $this->connException
= $e; // don't keep re-trying
1145 throw $e; // throw it back
1152 * @see FileBackendStore::doClearCache()
1154 protected function doClearCache( array $paths = null ) {
1155 $this->connContainers
= array(); // clear container object cache
1159 * Get a Swift container object, possibly from process cache.
1160 * Use $reCache if the file count or byte count is needed.
1162 * @param $container string Container name
1163 * @param $bypassCache bool Bypass all caches and load from Swift
1164 * @return CF_Container
1165 * @throws CloudFilesException
1167 protected function getContainer( $container, $bypassCache = false ) {
1168 $conn = $this->getConnection(); // Swift proxy connection
1169 if ( $bypassCache ) { // purge cache
1170 unset( $this->connContainers
[$container] );
1171 } elseif ( !isset( $this->connContainers
[$container] ) ) {
1172 $this->primeContainerCache( array( $container ) ); // check persistent cache
1174 if ( !isset( $this->connContainers
[$container] ) ) {
1175 $contObj = $conn->get_container( $container );
1176 // NoSuchContainerException not thrown: container must exist
1177 if ( count( $this->connContainers
) >= $this->maxContCacheSize
) { // trim cache?
1178 reset( $this->connContainers
);
1179 unset( $this->connContainers
[key( $this->connContainers
)] );
1181 $this->connContainers
[$container] = $contObj; // cache it
1182 if ( !$bypassCache ) {
1183 $this->setContainerCache( $container, // update persistent cache
1184 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1188 return $this->connContainers
[$container];
1192 * Create a Swift container
1194 * @param $container string Container name
1195 * @return CF_Container
1196 * @throws CloudFilesException
1198 protected function createContainer( $container ) {
1199 $conn = $this->getConnection(); // Swift proxy connection
1200 $contObj = $conn->create_container( $container );
1201 $this->connContainers
[$container] = $contObj; // cache it
1206 * Delete a Swift container
1208 * @param $container string Container name
1210 * @throws CloudFilesException
1212 protected function deleteContainer( $container ) {
1213 $conn = $this->getConnection(); // Swift proxy connection
1214 unset( $this->connContainers
[$container] ); // purge cache
1215 $conn->delete_container( $container );
1219 * @see FileBackendStore::doPrimeContainerCache()
1222 protected function doPrimeContainerCache( array $containerInfo ) {
1224 $conn = $this->getConnection(); // Swift proxy connection
1225 foreach ( $containerInfo as $container => $info ) {
1226 $this->connContainers
[$container] = new CF_Container(
1234 } catch ( CloudFilesException
$e ) { // some other exception?
1235 $this->handleException( $e, null, __METHOD__
, array() );
1240 * Log an unexpected exception for this backend.
1241 * This also sets the Status object to have a fatal error.
1243 * @param $e Exception
1244 * @param $status Status|null
1245 * @param $func string
1246 * @param $params Array
1249 protected function handleException( Exception
$e, $status, $func, array $params ) {
1250 if ( $status instanceof Status
) {
1251 if ( $e instanceof AuthenticationException
) {
1252 $status->fatal( 'backend-fail-connect', $this->name
);
1254 $status->fatal( 'backend-fail-internal', $this->name
);
1257 if ( $e->getMessage() ) {
1258 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1260 wfDebugLog( 'SwiftBackend',
1261 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1262 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1268 * @see FileBackendStoreOpHandle
1270 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1271 /** @var CF_Async_Op */
1274 public $affectedObjects = array();
1276 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1277 $this->backend
= $backend;
1278 $this->params
= $params;
1279 $this->call
= $call;
1280 $this->cfOp
= $cfOp;
1285 * SwiftFileBackend helper class to page through listings.
1286 * Swift also has a listing limit of 10,000 objects for sanity.
1287 * Do not use this class from places outside SwiftFileBackend.
1289 * @ingroup FileBackend
1291 abstract class SwiftFileBackendList
implements Iterator
{
1293 protected $bufferIter = array();
1294 protected $bufferAfter = null; // string; list items *after* this path
1295 protected $pos = 0; // integer
1297 protected $params = array();
1299 /** @var SwiftFileBackend */
1301 protected $container; // string; container name
1302 protected $dir; // string; storage directory
1303 protected $suffixStart; // integer
1305 const PAGE_SIZE
= 9000; // file listing buffer size
1308 * @param $backend SwiftFileBackend
1309 * @param $fullCont string Resolved container name
1310 * @param $dir string Resolved directory relative to container
1311 * @param $params Array
1313 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1314 $this->backend
= $backend;
1315 $this->container
= $fullCont;
1317 if ( substr( $this->dir
, -1 ) === '/' ) {
1318 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1320 if ( $this->dir
== '' ) { // whole container
1321 $this->suffixStart
= 0;
1322 } else { // dir within container
1323 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1325 $this->params
= $params;
1329 * @see Iterator::key()
1332 public function key() {
1337 * @see Iterator::next()
1340 public function next() {
1341 // Advance to the next file in the page
1342 next( $this->bufferIter
);
1344 // Check if there are no files left in this page and
1345 // advance to the next page if this page was not empty.
1346 if ( !$this->valid() && count( $this->bufferIter
) ) {
1347 $this->bufferIter
= $this->pageFromList(
1348 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1349 ); // updates $this->bufferAfter
1354 * @see Iterator::rewind()
1357 public function rewind() {
1359 $this->bufferAfter
= null;
1360 $this->bufferIter
= $this->pageFromList(
1361 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1362 ); // updates $this->bufferAfter
1366 * @see Iterator::valid()
1369 public function valid() {
1370 if ( $this->bufferIter
=== null ) {
1371 return false; // some failure?
1373 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1378 * Get the given list portion (page)
1380 * @param $container string Resolved container name
1381 * @param $dir string Resolved path relative to container
1382 * @param $after string|null
1383 * @param $limit integer
1384 * @param $params Array
1385 * @return Traversable|Array|null Returns null on failure
1387 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1391 * Iterator for listing directories
1393 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1395 * @see Iterator::current()
1396 * @return string|bool String (relative path) or false
1398 public function current() {
1399 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1403 * @see SwiftFileBackendList::pageFromList()
1404 * @return Array|null
1406 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1407 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1412 * Iterator for listing regular files
1414 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1416 * @see Iterator::current()
1417 * @return string|bool String (relative path) or false
1419 public function current() {
1420 return substr( current( $this->bufferIter
), $this->suffixStart
);
1424 * @see SwiftFileBackendList::pageFromList()
1425 * @return Array|null
1427 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1428 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );