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 ( !empty( $params['async'] ) ) { // deferred
192 $handle = $obj->write_async( $params['content'] );
193 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $handle );
194 $status->value
->affectedObjects
[] = $obj;
195 } else { // actually write the object in Swift
196 $obj->write( $params['content'] );
197 $this->purgeCDNCache( array( $obj ) );
199 } catch ( CDNNotEnabledException
$e ) {
200 // CDN not enabled; nothing to see here
201 } catch ( BadContentTypeException
$e ) {
202 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
203 } catch ( CloudFilesException
$e ) { // some other exception?
204 $this->handleException( $e, $status, __METHOD__
, $params );
211 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
213 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
215 $cfOp->getLastResponse();
216 } catch ( BadContentTypeException
$e ) {
217 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
222 * @see FileBackendStore::doStoreInternal()
225 protected function doStoreInternal( array $params ) {
226 $status = Status
::newGood();
228 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
229 if ( $dstRel === null ) {
230 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
234 // (a) Check the destination container and object
236 $dContObj = $this->getContainer( $dstCont );
237 if ( empty( $params['overwrite'] ) &&
238 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
240 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
243 } catch ( NoSuchContainerException
$e ) {
244 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
246 } catch ( CloudFilesException
$e ) { // some other exception?
247 $this->handleException( $e, $status, __METHOD__
, $params );
251 // (b) Get a SHA-1 hash of the object
252 $sha1Hash = sha1_file( $params['src'] );
253 if ( $sha1Hash === false ) { // source doesn't exist?
254 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
257 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
259 // (c) Actually store the object
261 // Create a fresh CF_Object with no fields preloaded.
262 // We don't want to preserve headers, metadata, and such.
263 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
264 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
265 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
266 // The MD5 here will be checked within Swift against its own MD5.
267 $obj->set_etag( md5_file( $params['src'] ) );
268 // Use the same content type as StreamFile for security
269 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
270 if ( !empty( $params['async'] ) ) { // deferred
271 wfSuppressWarnings();
272 $fp = fopen( $params['src'], 'rb' );
275 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
277 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
278 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $handle );
279 $status->value
->resourcesToClose
[] = $fp;
280 $status->value
->affectedObjects
[] = $obj;
282 } else { // actually write the object in Swift
283 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
284 $this->purgeCDNCache( array( $obj ) );
286 } catch ( CDNNotEnabledException
$e ) {
287 // CDN not enabled; nothing to see here
288 } catch ( BadContentTypeException
$e ) {
289 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
290 } catch ( IOException
$e ) {
291 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
292 } catch ( CloudFilesException
$e ) { // some other exception?
293 $this->handleException( $e, $status, __METHOD__
, $params );
300 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
302 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
304 $cfOp->getLastResponse();
305 } catch ( BadContentTypeException
$e ) {
306 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
307 } catch ( IOException
$e ) {
308 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
313 * @see FileBackendStore::doCopyInternal()
316 protected function doCopyInternal( array $params ) {
317 $status = Status
::newGood();
319 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
320 if ( $srcRel === null ) {
321 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
325 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
326 if ( $dstRel === null ) {
327 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
331 // (a) Check the source/destination containers and destination object
333 $sContObj = $this->getContainer( $srcCont );
334 $dContObj = $this->getContainer( $dstCont );
335 if ( empty( $params['overwrite'] ) &&
336 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
338 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
341 } catch ( NoSuchContainerException
$e ) {
342 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
344 } catch ( CloudFilesException
$e ) { // some other exception?
345 $this->handleException( $e, $status, __METHOD__
, $params );
349 // (b) Actually copy the file to the destination
351 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
352 if ( !empty( $params['async'] ) ) { // deferred
353 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
354 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
355 $status->value
->affectedObjects
[] = $dstObj;
356 } else { // actually write the object in Swift
357 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
358 $this->purgeCDNCache( array( $dstObj ) );
360 } catch ( CDNNotEnabledException
$e ) {
361 // CDN not enabled; nothing to see here
362 } catch ( NoSuchObjectException
$e ) { // source object does not exist
363 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
364 } catch ( CloudFilesException
$e ) { // some other exception?
365 $this->handleException( $e, $status, __METHOD__
, $params );
372 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
374 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
376 $cfOp->getLastResponse();
377 } catch ( NoSuchObjectException
$e ) { // source object does not exist
378 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
383 * @see FileBackendStore::doMoveInternal()
386 protected function doMoveInternal( array $params ) {
387 $status = Status
::newGood();
389 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
390 if ( $srcRel === null ) {
391 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
395 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
396 if ( $dstRel === null ) {
397 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
401 // (a) Check the source/destination containers and destination object
403 $sContObj = $this->getContainer( $srcCont );
404 $dContObj = $this->getContainer( $dstCont );
405 if ( empty( $params['overwrite'] ) &&
406 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
408 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
411 } catch ( NoSuchContainerException
$e ) {
412 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
414 } catch ( CloudFilesException
$e ) { // some other exception?
415 $this->handleException( $e, $status, __METHOD__
, $params );
419 // (b) Actually move the file to the destination
421 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
422 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
423 if ( !empty( $params['async'] ) ) { // deferred
424 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
425 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $handle );
426 $status->value
->affectedObjects
[] = $srcObj;
427 $status->value
->affectedObjects
[] = $dstObj;
428 } else { // actually write the object in Swift
429 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
430 $this->purgeCDNCache( array( $srcObj, $dstObj ) );
432 } catch ( CDNNotEnabledException
$e ) {
433 // CDN not enabled; nothing to see here
434 } catch ( NoSuchObjectException
$e ) { // source object does not exist
435 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
436 } catch ( CloudFilesException
$e ) { // some other exception?
437 $this->handleException( $e, $status, __METHOD__
, $params );
444 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
446 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
448 $cfOp->getLastResponse();
449 } catch ( NoSuchObjectException
$e ) { // source object does not exist
450 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
455 * @see FileBackendStore::doDeleteInternal()
458 protected function doDeleteInternal( array $params ) {
459 $status = Status
::newGood();
461 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
462 if ( $srcRel === null ) {
463 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
468 $sContObj = $this->getContainer( $srcCont );
469 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
470 if ( !empty( $params['async'] ) ) { // deferred
471 $handle = $sContObj->delete_object_async( $srcRel );
472 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
473 $status->value
->affectedObjects
[] = $srcObj;
474 } else { // actually write the object in Swift
475 $sContObj->delete_object( $srcRel );
476 $this->purgeCDNCache( array( $srcObj ) );
478 } catch ( CDNNotEnabledException
$e ) {
479 // CDN not enabled; nothing to see here
480 } catch ( NoSuchContainerException
$e ) {
481 $status->fatal( 'backend-fail-delete', $params['src'] );
482 } catch ( NoSuchObjectException
$e ) {
483 if ( empty( $params['ignoreMissingSource'] ) ) {
484 $status->fatal( 'backend-fail-delete', $params['src'] );
486 } catch ( CloudFilesException
$e ) { // some other exception?
487 $this->handleException( $e, $status, __METHOD__
, $params );
494 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
496 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
498 $cfOp->getLastResponse();
499 } catch ( NoSuchContainerException
$e ) {
500 $status->fatal( 'backend-fail-delete', $params['src'] );
501 } catch ( NoSuchObjectException
$e ) {
502 if ( empty( $params['ignoreMissingSource'] ) ) {
503 $status->fatal( 'backend-fail-delete', $params['src'] );
509 * @see FileBackendStore::doPrepareInternal()
512 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
513 $status = Status
::newGood();
515 // (a) Check if container already exists
517 $contObj = $this->getContainer( $fullCont );
518 // NoSuchContainerException not thrown: container must exist
519 return $status; // already exists
520 } catch ( NoSuchContainerException
$e ) {
521 // NoSuchContainerException thrown: container does not exist
522 } catch ( CloudFilesException
$e ) { // some other exception?
523 $this->handleException( $e, $status, __METHOD__
, $params );
527 // (b) Create container as needed
529 $contObj = $this->createContainer( $fullCont );
530 if ( !empty( $params['noAccess'] ) ) {
531 // Make container private to end-users...
532 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
534 // Make container public to end-users...
535 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
537 if ( $this->swiftUseCDN
) { // Rackspace style CDN
538 $contObj->make_public( $this->swiftCDNExpiry
);
540 } catch ( CDNNotEnabledException
$e ) {
541 // CDN not enabled; nothing to see here
542 } catch ( CloudFilesException
$e ) { // some other exception?
543 $this->handleException( $e, $status, __METHOD__
, $params );
551 * @see FileBackendStore::doSecureInternal()
554 protected function doSecureInternal( $fullCont, $dir, array $params ) {
555 $status = Status
::newGood();
556 if ( empty( $params['noAccess'] ) ) {
557 return $status; // nothing to do
560 // Restrict container from end-users...
562 // doPrepareInternal() should have been called,
563 // so the Swift container should already exist...
564 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
565 // NoSuchContainerException not thrown: container must exist
567 // Make container private to end-users...
568 $status->merge( $this->setContainerAccess(
570 array( $this->auth
->username
), // read
571 array( $this->auth
->username
) // write
573 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
574 $contObj->make_private();
576 } catch ( CDNNotEnabledException
$e ) {
577 // CDN not enabled; nothing to see here
578 } catch ( CloudFilesException
$e ) { // some other exception?
579 $this->handleException( $e, $status, __METHOD__
, $params );
586 * @see FileBackendStore::doPublishInternal()
589 protected function doPublishInternal( $fullCont, $dir, array $params ) {
590 $status = Status
::newGood();
592 // Unrestrict container from end-users...
594 // doPrepareInternal() should have been called,
595 // so the Swift container should already exist...
596 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
597 // NoSuchContainerException not thrown: container must exist
599 // Make container public to end-users...
600 if ( $this->swiftAnonUser
!= '' ) {
601 $status->merge( $this->setContainerAccess(
603 array( $this->auth
->username
, $this->swiftAnonUser
), // read
604 array( $this->auth
->username
, $this->swiftAnonUser
) // write
607 $status->merge( $this->setContainerAccess(
609 array( $this->auth
->username
, '.r:*' ), // read
610 array( $this->auth
->username
) // write
613 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
614 $contObj->make_public();
616 } catch ( CDNNotEnabledException
$e ) {
617 // CDN not enabled; nothing to see here
618 } catch ( CloudFilesException
$e ) { // some other exception?
619 $this->handleException( $e, $status, __METHOD__
, $params );
626 * @see FileBackendStore::doCleanInternal()
629 protected function doCleanInternal( $fullCont, $dir, array $params ) {
630 $status = Status
::newGood();
632 // Only containers themselves can be removed, all else is virtual
634 return $status; // nothing to do
637 // (a) Check the container
639 $contObj = $this->getContainer( $fullCont, true );
640 } catch ( NoSuchContainerException
$e ) {
641 return $status; // ok, nothing to do
642 } catch ( CloudFilesException
$e ) { // some other exception?
643 $this->handleException( $e, $status, __METHOD__
, $params );
647 // (b) Delete the container if empty
648 if ( $contObj->object_count
== 0 ) {
650 $this->deleteContainer( $fullCont );
651 } catch ( NoSuchContainerException
$e ) {
652 return $status; // race?
653 } catch ( NonEmptyContainerException
$e ) {
654 return $status; // race? consistency delay?
655 } catch ( CloudFilesException
$e ) { // some other exception?
656 $this->handleException( $e, $status, __METHOD__
, $params );
665 * @see FileBackendStore::doFileExists()
666 * @return array|bool|null
668 protected function doGetFileStat( array $params ) {
669 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
670 if ( $srcRel === null ) {
671 return false; // invalid storage path
676 $contObj = $this->getContainer( $srcCont );
677 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
678 $this->addMissingMetadata( $srcObj, $params['src'] );
680 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
681 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
682 'size' => (int)$srcObj->content_length
,
683 'sha1' => $srcObj->metadata
['Sha1base36']
685 } catch ( NoSuchContainerException
$e ) {
686 } catch ( NoSuchObjectException
$e ) {
687 } catch ( CloudFilesException
$e ) { // some other exception?
689 $this->handleException( $e, null, __METHOD__
, $params );
696 * Fill in any missing object metadata and save it to Swift
698 * @param $obj CF_Object
699 * @param $path string Storage path to object
700 * @return bool Success
701 * @throws Exception cloudfiles exceptions
703 protected function addMissingMetadata( CF_Object
$obj, $path ) {
704 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
705 return true; // nothing to do
707 $status = Status
::newGood();
708 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
709 if ( $status->isOK() ) {
710 # Do not stat the file in getLocalCopy() to avoid infinite loops
711 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
713 $hash = $tmpFile->getSha1Base36();
714 if ( $hash !== false ) {
715 $obj->metadata
['Sha1base36'] = $hash;
716 $obj->sync_metadata(); // save to Swift
717 return true; // success
721 $obj->metadata
['Sha1base36'] = false;
722 return false; // failed
726 * @see FileBackend::getFileContents()
727 * @return bool|null|string
729 public function getFileContents( array $params ) {
730 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
731 if ( $srcRel === null ) {
732 return false; // invalid storage path
735 if ( !$this->fileExists( $params ) ) {
741 $sContObj = $this->getContainer( $srcCont );
742 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
743 $data = $obj->read( $this->headersFromParams( $params ) );
744 } catch ( NoSuchContainerException
$e ) {
745 } catch ( CloudFilesException
$e ) { // some other exception?
746 $this->handleException( $e, null, __METHOD__
, $params );
753 * @see FileBackendStore::doDirectoryExists()
756 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
758 $container = $this->getContainer( $fullCont );
759 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
760 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
761 } catch ( NoSuchContainerException
$e ) {
763 } catch ( CloudFilesException
$e ) { // some other exception?
764 $this->handleException( $e, null, __METHOD__
,
765 array( 'cont' => $fullCont, 'dir' => $dir ) );
768 return null; // error
772 * @see FileBackendStore::getDirectoryListInternal()
773 * @return SwiftFileBackendDirList
775 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
776 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
780 * @see FileBackendStore::getFileListInternal()
781 * @return SwiftFileBackendFileList
783 public function getFileListInternal( $fullCont, $dir, array $params ) {
784 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
788 * Do not call this function outside of SwiftFileBackendFileList
790 * @param $fullCont string Resolved container name
791 * @param $dir string Resolved storage directory with no trailing slash
792 * @param $after string|null Storage path of file to list items after
793 * @param $limit integer Max number of items to list
794 * @param $params Array Includes flag for 'topOnly'
795 * @return Array List of relative paths of dirs directly under $dir
797 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
799 if ( $after === INF
) {
800 return $dirs; // nothing more
802 wfProfileIn( __METHOD__
. '-' . $this->name
);
805 $container = $this->getContainer( $fullCont );
806 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
807 // Non-recursive: only list dirs right under $dir
808 if ( !empty( $params['topOnly'] ) ) {
809 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
810 foreach ( $objects as $object ) { // files and dirs
811 if ( substr( $object, -1 ) === '/' ) {
812 $dirs[] = $object; // directories end in '/'
815 // Recursive: list all dirs under $dir and its subdirs
817 // Get directory from last item of prior page
818 $lastDir = $this->getParentDir( $after ); // must be first page
819 $objects = $container->list_objects( $limit, $after, $prefix );
820 foreach ( $objects as $object ) { // files
821 $objectDir = $this->getParentDir( $object ); // directory of object
822 if ( $objectDir !== false ) { // file has a parent dir
823 // Swift stores paths in UTF-8, using binary sorting.
824 // See function "create_container_table" in common/db.py.
825 // If a directory is not "greater" than the last one,
826 // then it was already listed by the calling iterator.
827 if ( $objectDir > $lastDir ) {
829 do { // add dir and all its parent dirs
830 $dirs[] = "{$pDir}/";
831 $pDir = $this->getParentDir( $pDir );
832 } while ( $pDir !== false // sanity
833 && $pDir > $lastDir // not done already
834 && strlen( $pDir ) > strlen( $dir ) // within $dir
837 $lastDir = $objectDir;
841 if ( count( $objects ) < $limit ) {
842 $after = INF
; // avoid a second RTT
844 $after = end( $objects ); // update last item
846 } catch ( NoSuchContainerException
$e ) {
847 } catch ( CloudFilesException
$e ) { // some other exception?
848 $this->handleException( $e, null, __METHOD__
,
849 array( 'cont' => $fullCont, 'dir' => $dir ) );
852 wfProfileOut( __METHOD__
. '-' . $this->name
);
856 protected function getParentDir( $path ) {
857 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
861 * Do not call this function outside of SwiftFileBackendFileList
863 * @param $fullCont string Resolved container name
864 * @param $dir string Resolved storage directory with no trailing slash
865 * @param $after string|null Storage path of file to list items after
866 * @param $limit integer Max number of items to list
867 * @param $params Array Includes flag for 'topOnly'
868 * @return Array List of relative paths of files under $dir
870 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
872 if ( $after === INF
) {
873 return $files; // nothing more
875 wfProfileIn( __METHOD__
. '-' . $this->name
);
878 $container = $this->getContainer( $fullCont );
879 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
880 // Non-recursive: only list files right under $dir
881 if ( !empty( $params['topOnly'] ) ) { // files and dirs
882 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
883 foreach ( $objects as $object ) {
884 if ( substr( $object, -1 ) !== '/' ) {
885 $files[] = $object; // directories end in '/'
888 // Recursive: list all files under $dir and its subdirs
890 $objects = $container->list_objects( $limit, $after, $prefix );
893 if ( count( $objects ) < $limit ) {
894 $after = INF
; // avoid a second RTT
896 $after = end( $objects ); // update last item
898 } catch ( NoSuchContainerException
$e ) {
899 } catch ( CloudFilesException
$e ) { // some other exception?
900 $this->handleException( $e, null, __METHOD__
,
901 array( 'cont' => $fullCont, 'dir' => $dir ) );
904 wfProfileOut( __METHOD__
. '-' . $this->name
);
909 * @see FileBackendStore::doGetFileSha1base36()
912 protected function doGetFileSha1base36( array $params ) {
913 $stat = $this->getFileStat( $params );
915 return $stat['sha1'];
922 * @see FileBackendStore::doStreamFile()
925 protected function doStreamFile( array $params ) {
926 $status = Status
::newGood();
928 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
929 if ( $srcRel === null ) {
930 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
934 $cont = $this->getContainer( $srcCont );
935 } catch ( NoSuchContainerException
$e ) {
936 $status->fatal( 'backend-fail-stream', $params['src'] );
938 } catch ( CloudFilesException
$e ) { // some other exception?
939 $this->handleException( $e, $status, __METHOD__
, $params );
944 $output = fopen( 'php://output', 'wb' );
945 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
946 $obj->stream( $output, $this->headersFromParams( $params ) );
947 } catch ( CloudFilesException
$e ) { // some other exception?
948 $this->handleException( $e, $status, __METHOD__
, $params );
955 * @see FileBackendStore::getLocalCopy()
956 * @return null|TempFSFile
958 public function getLocalCopy( array $params ) {
959 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
960 if ( $srcRel === null ) {
964 # Check the recursion guard to avoid loops when filling metadata
965 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
971 $sContObj = $this->getContainer( $srcCont );
972 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
973 // Get source file extension
974 $ext = FileBackend
::extensionFromPath( $srcRel );
975 // Create a new temporary file...
976 $tmpFile = TempFSFile
::factory( wfBaseName( $srcRel ) . '_', $ext );
978 $handle = fopen( $tmpFile->getPath(), 'wb' );
980 $obj->stream( $handle, $this->headersFromParams( $params ) );
983 $tmpFile = null; // couldn't open temp file
986 } catch ( NoSuchContainerException
$e ) {
988 } catch ( CloudFilesException
$e ) { // some other exception?
990 $this->handleException( $e, null, __METHOD__
, $params );
997 * @see FileBackendStore::directoriesAreVirtual()
1000 protected function directoriesAreVirtual() {
1005 * Get headers to send to Swift when reading a file based
1006 * on a FileBackend params array, e.g. that of getLocalCopy().
1007 * $params is currently only checked for a 'latest' flag.
1009 * @param $params Array
1012 protected function headersFromParams( array $params ) {
1014 if ( !empty( $params['latest'] ) ) {
1015 $hdrs[] = 'X-Newest: true';
1021 * @see FileBackendStore::doExecuteOpHandlesInternal()
1022 * @return Array List of corresponding Status objects
1024 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1025 $statuses = array();
1027 $cfOps = array(); // list of CF_Async_Op objects
1028 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1029 $cfOps[$index] = $fileOpHandle->cfOp
;
1031 $batch = new CF_Async_Op_Batch( $cfOps );
1033 $cfOps = $batch->execute();
1034 foreach ( $cfOps as $index => $cfOp ) {
1035 $status = Status
::newGood();
1036 try { // catch exceptions; update status
1037 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1038 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1039 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1040 } catch ( CloudFilesException
$e ) { // some other exception?
1041 $this->handleException( $e, $status,
1042 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1044 $statuses[$index] = $status;
1051 * Set read/write permissions for a Swift container.
1053 * $readGrps is a list of the possible criteria for a request to have
1054 * access to read a container. Each item is one of the following formats:
1055 * - account:user : Grants access if the request is by the given user
1056 * - .r:<regex> : Grants access if the request is from a referrer host that
1057 * matches the expression and the request is not for a listing.
1058 * Setting this to '*' effectively makes a container public.
1059 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1060 * matches the expression and the request for a listing.
1062 * $writeGrps is a list of the possible criteria for a request to have
1063 * access to write to a container. Each item is of the following format:
1064 * - account:user : Grants access if the request is by the given user
1066 * @see http://swift.openstack.org/misc.html#acls
1068 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1069 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1071 * @param $contObj CF_Container Swift container
1072 * @param $readGrps Array List of read access routes
1073 * @param $writeGrps Array List of write access routes
1076 protected function setContainerAccess(
1077 CF_Container
$contObj, array $readGrps, array $writeGrps
1079 $creds = $contObj->cfs_auth
->export_credentials();
1081 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1083 // Note: 10 second timeout consistent with php-cloudfiles
1084 $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1085 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1086 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1087 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1089 return $req->execute(); // should return 204
1093 * Purge the CDN cache of affected objects if CDN caching is enabled.
1094 * This is for Rackspace/Akamai CDNs.
1096 * @param $objects Array List of CF_Object items
1099 public function purgeCDNCache( array $objects ) {
1100 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1101 foreach ( $objects as $object ) {
1103 $object->purge_from_cdn();
1104 } catch ( CDNNotEnabledException
$e ) {
1105 // CDN not enabled; nothing to see here
1106 } catch ( CloudFilesException
$e ) {
1107 $this->handleException( $e, null, __METHOD__
,
1108 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1115 * Get a connection to the Swift proxy
1117 * @return CF_Connection|bool False on failure
1118 * @throws CloudFilesException
1120 protected function getConnection() {
1121 if ( $this->connException
instanceof Exception
) {
1122 throw $this->connException
; // failed last attempt
1124 // Session keys expire after a while, so we renew them periodically
1125 if ( $this->conn
&& ( time() - $this->connStarted
) > $this->authTTL
) {
1126 $this->conn
->close(); // close active cURL connections
1129 // Authenticate with proxy and get a session key...
1130 if ( !$this->conn
) {
1131 $this->connStarted
= 0;
1132 $this->connContainers
= array();
1134 $this->auth
->authenticate();
1135 $this->conn
= new CF_Connection( $this->auth
);
1136 $this->connStarted
= time();
1137 } catch ( CloudFilesException
$e ) {
1138 $this->connException
= $e; // don't keep re-trying
1139 throw $e; // throw it back
1146 * @see FileBackendStore::doClearCache()
1148 protected function doClearCache( array $paths = null ) {
1149 $this->connContainers
= array(); // clear container object cache
1153 * Get a Swift container object, possibly from process cache.
1154 * Use $reCache if the file count or byte count is needed.
1156 * @param $container string Container name
1157 * @param $bypassCache bool Bypass all caches and load from Swift
1158 * @return CF_Container
1159 * @throws CloudFilesException
1161 protected function getContainer( $container, $bypassCache = false ) {
1162 $conn = $this->getConnection(); // Swift proxy connection
1163 if ( $bypassCache ) { // purge cache
1164 unset( $this->connContainers
[$container] );
1165 } elseif ( !isset( $this->connContainers
[$container] ) ) {
1166 $this->primeContainerCache( array( $container ) ); // check persistent cache
1168 if ( !isset( $this->connContainers
[$container] ) ) {
1169 $contObj = $conn->get_container( $container );
1170 // NoSuchContainerException not thrown: container must exist
1171 if ( count( $this->connContainers
) >= $this->maxContCacheSize
) { // trim cache?
1172 reset( $this->connContainers
);
1173 unset( $this->connContainers
[key( $this->connContainers
)] );
1175 $this->connContainers
[$container] = $contObj; // cache it
1176 if ( !$bypassCache ) {
1177 $this->setContainerCache( $container, // update persistent cache
1178 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1182 return $this->connContainers
[$container];
1186 * Create a Swift container
1188 * @param $container string Container name
1189 * @return CF_Container
1190 * @throws CloudFilesException
1192 protected function createContainer( $container ) {
1193 $conn = $this->getConnection(); // Swift proxy connection
1194 $contObj = $conn->create_container( $container );
1195 $this->connContainers
[$container] = $contObj; // cache it
1200 * Delete a Swift container
1202 * @param $container string Container name
1204 * @throws CloudFilesException
1206 protected function deleteContainer( $container ) {
1207 $conn = $this->getConnection(); // Swift proxy connection
1208 unset( $this->connContainers
[$container] ); // purge cache
1209 $conn->delete_container( $container );
1213 * @see FileBackendStore::doPrimeContainerCache()
1216 protected function doPrimeContainerCache( array $containerInfo ) {
1218 $conn = $this->getConnection(); // Swift proxy connection
1219 foreach ( $containerInfo as $container => $info ) {
1220 $this->connContainers
[$container] = new CF_Container(
1228 } catch ( CloudFilesException
$e ) { // some other exception?
1229 $this->handleException( $e, null, __METHOD__
, array() );
1234 * Log an unexpected exception for this backend.
1235 * This also sets the Status object to have a fatal error.
1237 * @param $e Exception
1238 * @param $status Status|null
1239 * @param $func string
1240 * @param $params Array
1243 protected function handleException( Exception
$e, $status, $func, array $params ) {
1244 if ( $status instanceof Status
) {
1245 if ( $e instanceof AuthenticationException
) {
1246 $status->fatal( 'backend-fail-connect', $this->name
);
1248 $status->fatal( 'backend-fail-internal', $this->name
);
1251 if ( $e->getMessage() ) {
1252 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1254 wfDebugLog( 'SwiftBackend',
1255 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1256 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1262 * @see FileBackendStoreOpHandle
1264 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1265 /** @var CF_Async_Op */
1268 public $affectedObjects = array();
1270 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1271 $this->backend
= $backend;
1272 $this->params
= $params;
1273 $this->call
= $call;
1274 $this->cfOp
= $cfOp;
1279 * SwiftFileBackend helper class to page through listings.
1280 * Swift also has a listing limit of 10,000 objects for sanity.
1281 * Do not use this class from places outside SwiftFileBackend.
1283 * @ingroup FileBackend
1285 abstract class SwiftFileBackendList
implements Iterator
{
1287 protected $bufferIter = array();
1288 protected $bufferAfter = null; // string; list items *after* this path
1289 protected $pos = 0; // integer
1291 protected $params = array();
1293 /** @var SwiftFileBackend */
1295 protected $container; // string; container name
1296 protected $dir; // string; storage directory
1297 protected $suffixStart; // integer
1299 const PAGE_SIZE
= 5000; // file listing buffer size
1302 * @param $backend SwiftFileBackend
1303 * @param $fullCont string Resolved container name
1304 * @param $dir string Resolved directory relative to container
1305 * @param $params Array
1307 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1308 $this->backend
= $backend;
1309 $this->container
= $fullCont;
1311 if ( substr( $this->dir
, -1 ) === '/' ) {
1312 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1314 if ( $this->dir
== '' ) { // whole container
1315 $this->suffixStart
= 0;
1316 } else { // dir within container
1317 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1319 $this->params
= $params;
1323 * @see Iterator::key()
1326 public function key() {
1331 * @see Iterator::next()
1334 public function next() {
1335 // Advance to the next file in the page
1336 next( $this->bufferIter
);
1338 // Check if there are no files left in this page and
1339 // advance to the next page if this page was not empty.
1340 if ( !$this->valid() && count( $this->bufferIter
) ) {
1341 $this->bufferIter
= $this->pageFromList(
1342 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1343 ); // updates $this->bufferAfter
1348 * @see Iterator::rewind()
1351 public function rewind() {
1353 $this->bufferAfter
= null;
1354 $this->bufferIter
= $this->pageFromList(
1355 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1356 ); // updates $this->bufferAfter
1360 * @see Iterator::valid()
1363 public function valid() {
1364 if ( $this->bufferIter
=== null ) {
1365 return false; // some failure?
1367 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1372 * Get the given list portion (page)
1374 * @param $container string Resolved container name
1375 * @param $dir string Resolved path relative to container
1376 * @param $after string|null
1377 * @param $limit integer
1378 * @param $params Array
1379 * @return Traversable|Array|null Returns null on failure
1381 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1385 * Iterator for listing directories
1387 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1389 * @see Iterator::current()
1390 * @return string|bool String (relative path) or false
1392 public function current() {
1393 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1397 * @see SwiftFileBackendList::pageFromList()
1398 * @return Array|null
1400 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1401 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1406 * Iterator for listing regular files
1408 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1410 * @see Iterator::current()
1411 * @return string|bool String (relative path) or false
1413 public function current() {
1414 return substr( current( $this->bufferIter
), $this->suffixStart
);
1418 * @see SwiftFileBackendList::pageFromList()
1419 * @return Array|null
1421 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1422 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );