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 /** @var CF_Connection */
49 protected $conn; // Swift connection handle
50 protected $connStarted = 0; // integer UNIX timestamp
51 protected $connException; // CloudFiles exception
53 /** @var ProcessCacheLRU */
54 protected $connContainerCache; // container object cache
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();
112 // Process cache for container info
113 $this->connContainerCache
= new ProcessCacheLRU( 300 );
117 * @see FileBackendStore::resolveContainerPath()
120 protected function resolveContainerPath( $container, $relStoragePath ) {
121 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
122 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
123 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
124 return null; // too long for Swift
126 return $relStoragePath;
130 * @see FileBackendStore::isPathUsableInternal()
133 public function isPathUsableInternal( $storagePath ) {
134 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
135 if ( $rel === null ) {
136 return false; // invalid
140 $this->getContainer( $container );
141 return true; // container exists
142 } catch ( NoSuchContainerException
$e ) {
143 } catch ( CloudFilesException
$e ) { // some other exception?
144 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
151 * @see FileBackendStore::doCreateInternal()
154 protected function doCreateInternal( array $params ) {
155 $status = Status
::newGood();
157 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
158 if ( $dstRel === null ) {
159 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
163 // (a) Check the destination container and object
165 $dContObj = $this->getContainer( $dstCont );
166 if ( empty( $params['overwrite'] ) &&
167 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
169 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
172 } catch ( NoSuchContainerException
$e ) {
173 $status->fatal( 'backend-fail-create', $params['dst'] );
175 } catch ( CloudFilesException
$e ) { // some other exception?
176 $this->handleException( $e, $status, __METHOD__
, $params );
180 // (b) Get a SHA-1 hash of the object
181 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
183 // (c) Actually create the object
185 // Create a fresh CF_Object with no fields preloaded.
186 // We don't want to preserve headers, metadata, and such.
187 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
188 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
189 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
190 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
191 // The MD5 here will be checked within Swift against its own MD5.
192 $obj->set_etag( md5( $params['content'] ) );
193 // Use the same content type as StreamFile for security
194 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
195 if ( !strlen( $obj->content_type
) ) { // special case
196 $obj->content_type
= 'unknown/unknown';
198 if ( !empty( $params['async'] ) ) { // deferred
199 $handle = $obj->write_async( $params['content'] );
200 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $handle );
201 $status->value
->affectedObjects
[] = $obj;
202 } else { // actually write the object in Swift
203 $obj->write( $params['content'] );
204 $this->purgeCDNCache( array( $obj ) );
206 } catch ( CDNNotEnabledException
$e ) {
207 // CDN not enabled; nothing to see here
208 } catch ( BadContentTypeException
$e ) {
209 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
210 } catch ( CloudFilesException
$e ) { // some other exception?
211 $this->handleException( $e, $status, __METHOD__
, $params );
218 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
220 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
222 $cfOp->getLastResponse();
223 } catch ( BadContentTypeException
$e ) {
224 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
229 * @see FileBackendStore::doStoreInternal()
232 protected function doStoreInternal( array $params ) {
233 $status = Status
::newGood();
235 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
236 if ( $dstRel === null ) {
237 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
241 // (a) Check the destination container and object
243 $dContObj = $this->getContainer( $dstCont );
244 if ( empty( $params['overwrite'] ) &&
245 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
247 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
250 } catch ( NoSuchContainerException
$e ) {
251 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
253 } catch ( CloudFilesException
$e ) { // some other exception?
254 $this->handleException( $e, $status, __METHOD__
, $params );
258 // (b) Get a SHA-1 hash of the object
259 $sha1Hash = sha1_file( $params['src'] );
260 if ( $sha1Hash === false ) { // source doesn't exist?
261 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
264 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
266 // (c) Actually store the object
268 // Create a fresh CF_Object with no fields preloaded.
269 // We don't want to preserve headers, metadata, and such.
270 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
271 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
272 $obj->metadata
= array( 'Sha1base36' => $sha1Hash );
273 // The MD5 here will be checked within Swift against its own MD5.
274 $obj->set_etag( md5_file( $params['src'] ) );
275 // Use the same content type as StreamFile for security
276 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
277 if ( !strlen( $obj->content_type
) ) { // special case
278 $obj->content_type
= 'unknown/unknown';
280 if ( !empty( $params['async'] ) ) { // deferred
281 wfSuppressWarnings();
282 $fp = fopen( $params['src'], 'rb' );
285 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
287 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
288 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $handle );
289 $status->value
->resourcesToClose
[] = $fp;
290 $status->value
->affectedObjects
[] = $obj;
292 } else { // actually write the object in Swift
293 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
294 $this->purgeCDNCache( array( $obj ) );
296 } catch ( CDNNotEnabledException
$e ) {
297 // CDN not enabled; nothing to see here
298 } catch ( BadContentTypeException
$e ) {
299 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
300 } catch ( IOException
$e ) {
301 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
302 } catch ( CloudFilesException
$e ) { // some other exception?
303 $this->handleException( $e, $status, __METHOD__
, $params );
310 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
312 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
314 $cfOp->getLastResponse();
315 } catch ( BadContentTypeException
$e ) {
316 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
317 } catch ( IOException
$e ) {
318 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
323 * @see FileBackendStore::doCopyInternal()
326 protected function doCopyInternal( array $params ) {
327 $status = Status
::newGood();
329 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
330 if ( $srcRel === null ) {
331 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
335 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
336 if ( $dstRel === null ) {
337 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
341 // (a) Check the source/destination containers and destination object
343 $sContObj = $this->getContainer( $srcCont );
344 $dContObj = $this->getContainer( $dstCont );
345 if ( empty( $params['overwrite'] ) &&
346 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
348 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
351 } catch ( NoSuchContainerException
$e ) {
352 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
354 } catch ( CloudFilesException
$e ) { // some other exception?
355 $this->handleException( $e, $status, __METHOD__
, $params );
359 // (b) Actually copy the file to the destination
361 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
362 if ( !empty( $params['async'] ) ) { // deferred
363 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
364 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
365 $status->value
->affectedObjects
[] = $dstObj;
366 } else { // actually write the object in Swift
367 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
368 $this->purgeCDNCache( array( $dstObj ) );
370 } catch ( CDNNotEnabledException
$e ) {
371 // CDN not enabled; nothing to see here
372 } catch ( NoSuchObjectException
$e ) { // source object does not exist
373 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
374 } catch ( CloudFilesException
$e ) { // some other exception?
375 $this->handleException( $e, $status, __METHOD__
, $params );
382 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
384 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
386 $cfOp->getLastResponse();
387 } catch ( NoSuchObjectException
$e ) { // source object does not exist
388 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
393 * @see FileBackendStore::doMoveInternal()
396 protected function doMoveInternal( array $params ) {
397 $status = Status
::newGood();
399 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
400 if ( $srcRel === null ) {
401 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
405 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
406 if ( $dstRel === null ) {
407 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
411 // (a) Check the source/destination containers and destination object
413 $sContObj = $this->getContainer( $srcCont );
414 $dContObj = $this->getContainer( $dstCont );
415 if ( empty( $params['overwrite'] ) &&
416 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
418 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
421 } catch ( NoSuchContainerException
$e ) {
422 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
424 } catch ( CloudFilesException
$e ) { // some other exception?
425 $this->handleException( $e, $status, __METHOD__
, $params );
429 // (b) Actually move the file to the destination
431 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
432 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
433 if ( !empty( $params['async'] ) ) { // deferred
434 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
435 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $handle );
436 $status->value
->affectedObjects
[] = $srcObj;
437 $status->value
->affectedObjects
[] = $dstObj;
438 } else { // actually write the object in Swift
439 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
440 $this->purgeCDNCache( array( $srcObj, $dstObj ) );
442 } catch ( CDNNotEnabledException
$e ) {
443 // CDN not enabled; nothing to see here
444 } catch ( NoSuchObjectException
$e ) { // source object does not exist
445 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
446 } catch ( CloudFilesException
$e ) { // some other exception?
447 $this->handleException( $e, $status, __METHOD__
, $params );
454 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
456 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
458 $cfOp->getLastResponse();
459 } catch ( NoSuchObjectException
$e ) { // source object does not exist
460 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
465 * @see FileBackendStore::doDeleteInternal()
468 protected function doDeleteInternal( array $params ) {
469 $status = Status
::newGood();
471 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
472 if ( $srcRel === null ) {
473 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
478 $sContObj = $this->getContainer( $srcCont );
479 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
480 if ( !empty( $params['async'] ) ) { // deferred
481 $handle = $sContObj->delete_object_async( $srcRel );
482 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
483 $status->value
->affectedObjects
[] = $srcObj;
484 } else { // actually write the object in Swift
485 $sContObj->delete_object( $srcRel );
486 $this->purgeCDNCache( array( $srcObj ) );
488 } catch ( CDNNotEnabledException
$e ) {
489 // CDN not enabled; nothing to see here
490 } catch ( NoSuchContainerException
$e ) {
491 $status->fatal( 'backend-fail-delete', $params['src'] );
492 } catch ( NoSuchObjectException
$e ) {
493 if ( empty( $params['ignoreMissingSource'] ) ) {
494 $status->fatal( 'backend-fail-delete', $params['src'] );
496 } catch ( CloudFilesException
$e ) { // some other exception?
497 $this->handleException( $e, $status, __METHOD__
, $params );
504 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
506 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
508 $cfOp->getLastResponse();
509 } catch ( NoSuchContainerException
$e ) {
510 $status->fatal( 'backend-fail-delete', $params['src'] );
511 } catch ( NoSuchObjectException
$e ) {
512 if ( empty( $params['ignoreMissingSource'] ) ) {
513 $status->fatal( 'backend-fail-delete', $params['src'] );
519 * @see FileBackendStore::doPrepareInternal()
522 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
523 $status = Status
::newGood();
525 // (a) Check if container already exists
527 $contObj = $this->getContainer( $fullCont );
528 // NoSuchContainerException not thrown: container must exist
529 return $status; // already exists
530 } catch ( NoSuchContainerException
$e ) {
531 // NoSuchContainerException thrown: container does not exist
532 } catch ( CloudFilesException
$e ) { // some other exception?
533 $this->handleException( $e, $status, __METHOD__
, $params );
537 // (b) Create container as needed
539 $contObj = $this->createContainer( $fullCont );
540 if ( !empty( $params['noAccess'] ) ) {
541 // Make container private to end-users...
542 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
544 // Make container public to end-users...
545 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
547 if ( $this->swiftUseCDN
) { // Rackspace style CDN
548 $contObj->make_public( $this->swiftCDNExpiry
);
550 } catch ( CDNNotEnabledException
$e ) {
551 // CDN not enabled; nothing to see here
552 } catch ( CloudFilesException
$e ) { // some other exception?
553 $this->handleException( $e, $status, __METHOD__
, $params );
561 * @see FileBackendStore::doSecureInternal()
564 protected function doSecureInternal( $fullCont, $dir, array $params ) {
565 $status = Status
::newGood();
566 if ( empty( $params['noAccess'] ) ) {
567 return $status; // nothing to do
570 // Restrict container from end-users...
572 // doPrepareInternal() should have been called,
573 // so the Swift container should already exist...
574 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
575 // NoSuchContainerException not thrown: container must exist
577 // Make container private to end-users...
578 $status->merge( $this->setContainerAccess(
580 array( $this->auth
->username
), // read
581 array( $this->auth
->username
) // write
583 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
584 $contObj->make_private();
586 } catch ( CDNNotEnabledException
$e ) {
587 // CDN not enabled; nothing to see here
588 } catch ( CloudFilesException
$e ) { // some other exception?
589 $this->handleException( $e, $status, __METHOD__
, $params );
596 * @see FileBackendStore::doPublishInternal()
599 protected function doPublishInternal( $fullCont, $dir, array $params ) {
600 $status = Status
::newGood();
602 // Unrestrict container from end-users...
604 // doPrepareInternal() should have been called,
605 // so the Swift container should already exist...
606 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
607 // NoSuchContainerException not thrown: container must exist
609 // Make container public to end-users...
610 if ( $this->swiftAnonUser
!= '' ) {
611 $status->merge( $this->setContainerAccess(
613 array( $this->auth
->username
, $this->swiftAnonUser
), // read
614 array( $this->auth
->username
, $this->swiftAnonUser
) // write
617 $status->merge( $this->setContainerAccess(
619 array( $this->auth
->username
, '.r:*' ), // read
620 array( $this->auth
->username
) // write
623 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
624 $contObj->make_public();
626 } catch ( CDNNotEnabledException
$e ) {
627 // CDN not enabled; nothing to see here
628 } catch ( CloudFilesException
$e ) { // some other exception?
629 $this->handleException( $e, $status, __METHOD__
, $params );
636 * @see FileBackendStore::doCleanInternal()
639 protected function doCleanInternal( $fullCont, $dir, array $params ) {
640 $status = Status
::newGood();
642 // Only containers themselves can be removed, all else is virtual
644 return $status; // nothing to do
647 // (a) Check the container
649 $contObj = $this->getContainer( $fullCont, true );
650 } catch ( NoSuchContainerException
$e ) {
651 return $status; // ok, nothing to do
652 } catch ( CloudFilesException
$e ) { // some other exception?
653 $this->handleException( $e, $status, __METHOD__
, $params );
657 // (b) Delete the container if empty
658 if ( $contObj->object_count
== 0 ) {
660 $this->deleteContainer( $fullCont );
661 } catch ( NoSuchContainerException
$e ) {
662 return $status; // race?
663 } catch ( NonEmptyContainerException
$e ) {
664 return $status; // race? consistency delay?
665 } catch ( CloudFilesException
$e ) { // some other exception?
666 $this->handleException( $e, $status, __METHOD__
, $params );
675 * @see FileBackendStore::doFileExists()
676 * @return array|bool|null
678 protected function doGetFileStat( array $params ) {
679 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
680 if ( $srcRel === null ) {
681 return false; // invalid storage path
686 $contObj = $this->getContainer( $srcCont );
687 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
688 $this->addMissingMetadata( $srcObj, $params['src'] );
690 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
691 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
692 'size' => (int)$srcObj->content_length
,
693 'sha1' => $srcObj->metadata
['Sha1base36']
695 } catch ( NoSuchContainerException
$e ) {
696 } catch ( NoSuchObjectException
$e ) {
697 } catch ( CloudFilesException
$e ) { // some other exception?
699 $this->handleException( $e, null, __METHOD__
, $params );
706 * Fill in any missing object metadata and save it to Swift
708 * @param $obj CF_Object
709 * @param $path string Storage path to object
710 * @return bool Success
711 * @throws Exception cloudfiles exceptions
713 protected function addMissingMetadata( CF_Object
$obj, $path ) {
714 if ( isset( $obj->metadata
['Sha1base36'] ) ) {
715 return true; // nothing to do
717 wfProfileIn( __METHOD__
);
718 $status = Status
::newGood();
719 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
720 if ( $status->isOK() ) {
721 # Do not stat the file in getLocalCopy() to avoid infinite loops
722 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
724 $hash = $tmpFile->getSha1Base36();
725 if ( $hash !== false ) {
726 $obj->metadata
['Sha1base36'] = $hash;
727 $obj->sync_metadata(); // save to Swift
728 wfProfileOut( __METHOD__
);
729 return true; // success
733 $obj->metadata
['Sha1base36'] = false;
734 wfProfileOut( __METHOD__
);
735 return false; // failed
739 * @see FileBackend::getFileContents()
740 * @return bool|null|string
742 public function getFileContents( array $params ) {
743 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
744 if ( $srcRel === null ) {
745 return false; // invalid storage path
748 if ( !$this->fileExists( $params ) ) {
754 $sContObj = $this->getContainer( $srcCont );
755 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
756 $data = $obj->read( $this->headersFromParams( $params ) );
757 } catch ( NoSuchContainerException
$e ) {
758 } catch ( CloudFilesException
$e ) { // some other exception?
759 $this->handleException( $e, null, __METHOD__
, $params );
766 * @see FileBackendStore::doDirectoryExists()
769 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
771 $container = $this->getContainer( $fullCont );
772 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
773 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
774 } catch ( NoSuchContainerException
$e ) {
776 } catch ( CloudFilesException
$e ) { // some other exception?
777 $this->handleException( $e, null, __METHOD__
,
778 array( 'cont' => $fullCont, 'dir' => $dir ) );
781 return null; // error
785 * @see FileBackendStore::getDirectoryListInternal()
786 * @return SwiftFileBackendDirList
788 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
789 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
793 * @see FileBackendStore::getFileListInternal()
794 * @return SwiftFileBackendFileList
796 public function getFileListInternal( $fullCont, $dir, array $params ) {
797 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
801 * Do not call this function outside of SwiftFileBackendFileList
803 * @param $fullCont string Resolved container name
804 * @param $dir string Resolved storage directory with no trailing slash
805 * @param $after string|null Storage path of file to list items after
806 * @param $limit integer Max number of items to list
807 * @param $params Array Includes flag for 'topOnly'
808 * @return Array List of relative paths of dirs directly under $dir
810 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
812 if ( $after === INF
) {
813 return $dirs; // nothing more
815 wfProfileIn( __METHOD__
. '-' . $this->name
);
818 $container = $this->getContainer( $fullCont );
819 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
820 // Non-recursive: only list dirs right under $dir
821 if ( !empty( $params['topOnly'] ) ) {
822 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
823 foreach ( $objects as $object ) { // files and dirs
824 if ( substr( $object, -1 ) === '/' ) {
825 $dirs[] = $object; // directories end in '/'
828 // Recursive: list all dirs under $dir and its subdirs
830 // Get directory from last item of prior page
831 $lastDir = $this->getParentDir( $after ); // must be first page
832 $objects = $container->list_objects( $limit, $after, $prefix );
833 foreach ( $objects as $object ) { // files
834 $objectDir = $this->getParentDir( $object ); // directory of object
835 if ( $objectDir !== false ) { // file has a parent dir
836 // Swift stores paths in UTF-8, using binary sorting.
837 // See function "create_container_table" in common/db.py.
838 // If a directory is not "greater" than the last one,
839 // then it was already listed by the calling iterator.
840 if ( $objectDir > $lastDir ) {
842 do { // add dir and all its parent dirs
843 $dirs[] = "{$pDir}/";
844 $pDir = $this->getParentDir( $pDir );
845 } while ( $pDir !== false // sanity
846 && $pDir > $lastDir // not done already
847 && strlen( $pDir ) > strlen( $dir ) // within $dir
850 $lastDir = $objectDir;
854 if ( count( $objects ) < $limit ) {
855 $after = INF
; // avoid a second RTT
857 $after = end( $objects ); // update last item
859 } catch ( NoSuchContainerException
$e ) {
860 } catch ( CloudFilesException
$e ) { // some other exception?
861 $this->handleException( $e, null, __METHOD__
,
862 array( 'cont' => $fullCont, 'dir' => $dir ) );
865 wfProfileOut( __METHOD__
. '-' . $this->name
);
869 protected function getParentDir( $path ) {
870 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
874 * Do not call this function outside of SwiftFileBackendFileList
876 * @param $fullCont string Resolved container name
877 * @param $dir string Resolved storage directory with no trailing slash
878 * @param $after string|null Storage path of file to list items after
879 * @param $limit integer Max number of items to list
880 * @param $params Array Includes flag for 'topOnly'
881 * @return Array List of relative paths of files under $dir
883 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
885 if ( $after === INF
) {
886 return $files; // nothing more
888 wfProfileIn( __METHOD__
. '-' . $this->name
);
891 $container = $this->getContainer( $fullCont );
892 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
893 // Non-recursive: only list files right under $dir
894 if ( !empty( $params['topOnly'] ) ) { // files and dirs
895 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
896 foreach ( $objects as $object ) {
897 if ( substr( $object, -1 ) !== '/' ) {
898 $files[] = $object; // directories end in '/'
901 // Recursive: list all files under $dir and its subdirs
903 $objects = $container->list_objects( $limit, $after, $prefix );
906 if ( count( $objects ) < $limit ) {
907 $after = INF
; // avoid a second RTT
909 $after = end( $objects ); // update last item
911 } catch ( NoSuchContainerException
$e ) {
912 } catch ( CloudFilesException
$e ) { // some other exception?
913 $this->handleException( $e, null, __METHOD__
,
914 array( 'cont' => $fullCont, 'dir' => $dir ) );
917 wfProfileOut( __METHOD__
. '-' . $this->name
);
922 * @see FileBackendStore::doGetFileSha1base36()
925 protected function doGetFileSha1base36( array $params ) {
926 $stat = $this->getFileStat( $params );
928 return $stat['sha1'];
935 * @see FileBackendStore::doStreamFile()
938 protected function doStreamFile( array $params ) {
939 $status = Status
::newGood();
941 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
942 if ( $srcRel === null ) {
943 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
947 $cont = $this->getContainer( $srcCont );
948 } catch ( NoSuchContainerException
$e ) {
949 $status->fatal( 'backend-fail-stream', $params['src'] );
951 } catch ( CloudFilesException
$e ) { // some other exception?
952 $this->handleException( $e, $status, __METHOD__
, $params );
957 $output = fopen( 'php://output', 'wb' );
958 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
959 $obj->stream( $output, $this->headersFromParams( $params ) );
960 } catch ( CloudFilesException
$e ) { // some other exception?
961 $this->handleException( $e, $status, __METHOD__
, $params );
968 * @see FileBackendStore::getLocalCopy()
969 * @return null|TempFSFile
971 public function getLocalCopy( array $params ) {
972 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
973 if ( $srcRel === null ) {
977 # Check the recursion guard to avoid loops when filling metadata
978 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
984 $sContObj = $this->getContainer( $srcCont );
985 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
986 // Get source file extension
987 $ext = FileBackend
::extensionFromPath( $srcRel );
988 // Create a new temporary file...
989 $tmpFile = TempFSFile
::factory( wfBaseName( $srcRel ) . '_', $ext );
991 $handle = fopen( $tmpFile->getPath(), 'wb' );
993 $obj->stream( $handle, $this->headersFromParams( $params ) );
996 $tmpFile = null; // couldn't open temp file
999 } catch ( NoSuchContainerException
$e ) {
1001 } catch ( CloudFilesException
$e ) { // some other exception?
1003 $this->handleException( $e, null, __METHOD__
, $params );
1010 * @see FileBackendStore::directoriesAreVirtual()
1013 protected function directoriesAreVirtual() {
1018 * Get headers to send to Swift when reading a file based
1019 * on a FileBackend params array, e.g. that of getLocalCopy().
1020 * $params is currently only checked for a 'latest' flag.
1022 * @param $params Array
1025 protected function headersFromParams( array $params ) {
1027 if ( !empty( $params['latest'] ) ) {
1028 $hdrs[] = 'X-Newest: true';
1034 * @see FileBackendStore::doExecuteOpHandlesInternal()
1035 * @return Array List of corresponding Status objects
1037 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1038 $statuses = array();
1040 $cfOps = array(); // list of CF_Async_Op objects
1041 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1042 $cfOps[$index] = $fileOpHandle->cfOp
;
1044 $batch = new CF_Async_Op_Batch( $cfOps );
1046 $cfOps = $batch->execute();
1047 foreach ( $cfOps as $index => $cfOp ) {
1048 $status = Status
::newGood();
1049 try { // catch exceptions; update status
1050 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1051 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1052 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1053 } catch ( CloudFilesException
$e ) { // some other exception?
1054 $this->handleException( $e, $status,
1055 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1057 $statuses[$index] = $status;
1064 * Set read/write permissions for a Swift container.
1066 * $readGrps is a list of the possible criteria for a request to have
1067 * access to read a container. Each item is one of the following formats:
1068 * - account:user : Grants access if the request is by the given user
1069 * - .r:<regex> : Grants access if the request is from a referrer host that
1070 * matches the expression and the request is not for a listing.
1071 * Setting this to '*' effectively makes a container public.
1072 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1073 * matches the expression and the request for a listing.
1075 * $writeGrps is a list of the possible criteria for a request to have
1076 * access to write to a container. Each item is of the following format:
1077 * - account:user : Grants access if the request is by the given user
1079 * @see http://swift.openstack.org/misc.html#acls
1081 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1082 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1084 * @param $contObj CF_Container Swift container
1085 * @param $readGrps Array List of read access routes
1086 * @param $writeGrps Array List of write access routes
1089 protected function setContainerAccess(
1090 CF_Container
$contObj, array $readGrps, array $writeGrps
1092 $creds = $contObj->cfs_auth
->export_credentials();
1094 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1096 // Note: 10 second timeout consistent with php-cloudfiles
1097 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1098 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1099 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1100 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1102 return $req->execute(); // should return 204
1106 * Purge the CDN cache of affected objects if CDN caching is enabled.
1107 * This is for Rackspace/Akamai CDNs.
1109 * @param $objects Array List of CF_Object items
1112 public function purgeCDNCache( array $objects ) {
1113 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1114 foreach ( $objects as $object ) {
1116 $object->purge_from_cdn();
1117 } catch ( CDNNotEnabledException
$e ) {
1118 // CDN not enabled; nothing to see here
1119 } catch ( CloudFilesException
$e ) {
1120 $this->handleException( $e, null, __METHOD__
,
1121 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1128 * Get a connection to the Swift proxy
1130 * @return CF_Connection|bool False on failure
1131 * @throws CloudFilesException
1133 protected function getConnection() {
1134 if ( $this->connException
instanceof Exception
) {
1135 throw $this->connException
; // failed last attempt
1137 // Session keys expire after a while, so we renew them periodically
1138 if ( $this->conn
&& ( time() - $this->connStarted
) > $this->authTTL
) {
1139 $this->conn
->close(); // close active cURL connections
1142 // Authenticate with proxy and get a session key...
1143 if ( !$this->conn
) {
1144 $this->connStarted
= 0;
1145 $this->connContainerCache
->clear();
1147 $this->auth
->authenticate();
1148 $this->conn
= new CF_Connection( $this->auth
);
1149 $this->connStarted
= time();
1150 } catch ( CloudFilesException
$e ) {
1151 $this->connException
= $e; // don't keep re-trying
1152 throw $e; // throw it back
1159 * @see FileBackendStore::doClearCache()
1161 protected function doClearCache( array $paths = null ) {
1162 $this->connContainerCache
->clear(); // clear container object cache
1166 * Get a Swift container object, possibly from process cache.
1167 * Use $reCache if the file count or byte count is needed.
1169 * @param $container string Container name
1170 * @param $bypassCache bool Bypass all caches and load from Swift
1171 * @return CF_Container
1172 * @throws CloudFilesException
1174 protected function getContainer( $container, $bypassCache = false ) {
1175 $conn = $this->getConnection(); // Swift proxy connection
1176 if ( $bypassCache ) { // purge cache
1177 $this->connContainerCache
->clear( $container );
1178 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1179 $this->primeContainerCache( array( $container ) ); // check persistent cache
1181 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1182 $contObj = $conn->get_container( $container );
1183 // NoSuchContainerException not thrown: container must exist
1184 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1185 if ( !$bypassCache ) {
1186 $this->setContainerCache( $container, // update persistent cache
1187 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1191 return $this->connContainerCache
->get( $container, 'obj' );
1195 * Create a Swift container
1197 * @param $container string Container name
1198 * @return CF_Container
1199 * @throws CloudFilesException
1201 protected function createContainer( $container ) {
1202 $conn = $this->getConnection(); // Swift proxy connection
1203 $contObj = $conn->create_container( $container );
1204 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1209 * Delete a Swift container
1211 * @param $container string Container name
1213 * @throws CloudFilesException
1215 protected function deleteContainer( $container ) {
1216 $conn = $this->getConnection(); // Swift proxy connection
1217 $this->connContainerCache
->clear( $container ); // purge
1218 $conn->delete_container( $container );
1222 * @see FileBackendStore::doPrimeContainerCache()
1225 protected function doPrimeContainerCache( array $containerInfo ) {
1227 $conn = $this->getConnection(); // Swift proxy connection
1228 foreach ( $containerInfo as $container => $info ) {
1229 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1230 $container, $info['count'], $info['bytes'] );
1231 $this->connContainerCache
->set( $container, 'obj', $contObj );
1233 } catch ( CloudFilesException
$e ) { // some other exception?
1234 $this->handleException( $e, null, __METHOD__
, array() );
1239 * Log an unexpected exception for this backend.
1240 * This also sets the Status object to have a fatal error.
1242 * @param $e Exception
1243 * @param $status Status|null
1244 * @param $func string
1245 * @param $params Array
1248 protected function handleException( Exception
$e, $status, $func, array $params ) {
1249 if ( $status instanceof Status
) {
1250 if ( $e instanceof AuthenticationException
) {
1251 $status->fatal( 'backend-fail-connect', $this->name
);
1253 $status->fatal( 'backend-fail-internal', $this->name
);
1256 if ( $e->getMessage() ) {
1257 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1259 wfDebugLog( 'SwiftBackend',
1260 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1261 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1267 * @see FileBackendStoreOpHandle
1269 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1270 /** @var CF_Async_Op */
1273 public $affectedObjects = array();
1275 public function __construct( $backend, array $params, $call, CF_Async_Op
$cfOp ) {
1276 $this->backend
= $backend;
1277 $this->params
= $params;
1278 $this->call
= $call;
1279 $this->cfOp
= $cfOp;
1284 * SwiftFileBackend helper class to page through listings.
1285 * Swift also has a listing limit of 10,000 objects for sanity.
1286 * Do not use this class from places outside SwiftFileBackend.
1288 * @ingroup FileBackend
1290 abstract class SwiftFileBackendList
implements Iterator
{
1292 protected $bufferIter = array();
1293 protected $bufferAfter = null; // string; list items *after* this path
1294 protected $pos = 0; // integer
1296 protected $params = array();
1298 /** @var SwiftFileBackend */
1300 protected $container; // string; container name
1301 protected $dir; // string; storage directory
1302 protected $suffixStart; // integer
1304 const PAGE_SIZE
= 9000; // file listing buffer size
1307 * @param $backend SwiftFileBackend
1308 * @param $fullCont string Resolved container name
1309 * @param $dir string Resolved directory relative to container
1310 * @param $params Array
1312 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1313 $this->backend
= $backend;
1314 $this->container
= $fullCont;
1316 if ( substr( $this->dir
, -1 ) === '/' ) {
1317 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1319 if ( $this->dir
== '' ) { // whole container
1320 $this->suffixStart
= 0;
1321 } else { // dir within container
1322 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1324 $this->params
= $params;
1328 * @see Iterator::key()
1331 public function key() {
1336 * @see Iterator::next()
1339 public function next() {
1340 // Advance to the next file in the page
1341 next( $this->bufferIter
);
1343 // Check if there are no files left in this page and
1344 // advance to the next page if this page was not empty.
1345 if ( !$this->valid() && count( $this->bufferIter
) ) {
1346 $this->bufferIter
= $this->pageFromList(
1347 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1348 ); // updates $this->bufferAfter
1353 * @see Iterator::rewind()
1356 public function rewind() {
1358 $this->bufferAfter
= null;
1359 $this->bufferIter
= $this->pageFromList(
1360 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1361 ); // updates $this->bufferAfter
1365 * @see Iterator::valid()
1368 public function valid() {
1369 if ( $this->bufferIter
=== null ) {
1370 return false; // some failure?
1372 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1377 * Get the given list portion (page)
1379 * @param $container string Resolved container name
1380 * @param $dir string Resolved path relative to container
1381 * @param $after string|null
1382 * @param $limit integer
1383 * @param $params Array
1384 * @return Traversable|Array|null Returns null on failure
1386 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1390 * Iterator for listing directories
1392 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1394 * @see Iterator::current()
1395 * @return string|bool String (relative path) or false
1397 public function current() {
1398 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1402 * @see SwiftFileBackendList::pageFromList()
1403 * @return Array|null
1405 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1406 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1411 * Iterator for listing regular files
1413 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1415 * @see Iterator::current()
1416 * @return string|bool String (relative path) or false
1418 public function current() {
1419 return substr( current( $this->bufferIter
), $this->suffixStart
);
1423 * @see SwiftFileBackendList::pageFromList()
1424 * @return Array|null
1426 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1427 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );