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 $swiftTempUrlKey; // string; shared secret value for making temp urls
44 protected $swiftAnonUser; // string; username to handle unauthenticated requests
45 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
46 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
47 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
49 // Rados Gateway specific options
50 protected $rgwS3AccessKey; // string; S3 access key
51 protected $rgwS3SecretKey; // string; S3 authentication key
53 /** @var CF_Connection */
54 protected $conn; // Swift connection handle
55 protected $sessionStarted = 0; // integer UNIX timestamp
57 /** @var CloudFilesException */
58 protected $connException;
59 protected $connErrorTime = 0; // UNIX timestamp
64 /** @var ProcessCacheLRU */
65 protected $connContainerCache; // container object cache
68 * @see FileBackendStore::__construct()
69 * Additional $config params include:
70 * - swiftAuthUrl : Swift authentication server URL
71 * - swiftUser : Swift user used by MediaWiki (account:username)
72 * - swiftKey : Swift authentication key for the above user
73 * - swiftAuthTTL : Swift authentication TTL (seconds)
74 * - swiftTempUrlKey : Swift "X-Account-Meta-Temp-URL-Key" value on the account.
75 * Do not set this until it has been set in the backend.
76 * - swiftAnonUser : Swift user used for end-user requests (account:username).
77 * If set, then views of public containers are assumed to go
78 * through this user. If not set, then public containers are
79 * accessible to unauthenticated requests via ".r:*" in the ACL.
80 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
81 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
82 * If files may likely change, this should probably not exceed
83 * a few days. For example, deletions may take this long to apply.
84 * If object purging is enabled, however, this is not an issue.
85 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
86 * - shardViaHashLevels : Map of container names to sharding config with:
87 * - base : base of hash characters, 16 or 36
88 * - levels : the number of hash levels (and digits)
89 * - repeat : hash subdirectories are prefixed with all the
90 * parent hash directory names (e.g. "a/ab/abc")
91 * - cacheAuthInfo : Whether to cache authentication tokens in APC, XCache, ect.
92 * If those are not available, then the main cache will be used.
93 * This is probably insecure in shared hosting environments.
94 * - rgwS3AccessKey : Ragos Gateway S3 "access key" value on the account.
95 * Do not set this until it has been set in the backend.
96 * This is used for generating expiring pre-authenticated URLs.
97 * Only use this when using rgw and to work around
98 * http://tracker.newdream.net/issues/3454.
99 * - rgwS3SecretKey : Ragos Gateway S3 "secret key" value on the account.
100 * Do not set this until it has been set in the backend.
101 * This is used for generating expiring pre-authenticated URLs.
102 * Only use this when using rgw and to work around
103 * http://tracker.newdream.net/issues/3454.
105 public function __construct( array $config ) {
106 parent
::__construct( $config );
107 if ( !class_exists( 'CF_Constants' ) ) {
108 throw new MWException( 'SwiftCloudFiles extension not installed.' );
111 $this->auth
= new CF_Authentication(
112 $config['swiftUser'],
114 null, // account; unused
115 $config['swiftAuthUrl']
118 $this->authTTL
= isset( $config['swiftAuthTTL'] )
119 ?
$config['swiftAuthTTL']
120 : 5 * 60; // some sane number
121 $this->swiftAnonUser
= isset( $config['swiftAnonUser'] )
122 ?
$config['swiftAnonUser']
124 $this->swiftTempUrlKey
= isset( $config['swiftTempUrlKey'] )
125 ?
$config['swiftTempUrlKey']
127 $this->shardViaHashLevels
= isset( $config['shardViaHashLevels'] )
128 ?
$config['shardViaHashLevels']
130 $this->swiftUseCDN
= isset( $config['swiftUseCDN'] )
131 ?
$config['swiftUseCDN']
133 $this->swiftCDNExpiry
= isset( $config['swiftCDNExpiry'] )
134 ?
$config['swiftCDNExpiry']
135 : 12 * 3600; // 12 hours is safe (tokens last 24 hours per http://docs.openstack.org)
136 $this->swiftCDNPurgable
= isset( $config['swiftCDNPurgable'] )
137 ?
$config['swiftCDNPurgable']
139 $this->rgwS3AccessKey
= isset( $config['rgwS3AccessKey'] )
140 ?
$config['rgwS3AccessKey']
142 $this->rgwS3SecretKey
= isset( $config['rgwS3SecretKey'] )
143 ?
$config['rgwS3SecretKey']
145 // Cache container information to mask latency
146 $this->memCache
= wfGetMainCache();
147 // Process cache for container info
148 $this->connContainerCache
= new ProcessCacheLRU( 300 );
149 // Cache auth token information to avoid RTTs
150 if ( !empty( $config['cacheAuthInfo'] ) ) {
151 if ( PHP_SAPI
=== 'cli' ) {
152 $this->srvCache
= wfGetMainCache(); // preferrably memcached
154 try { // look for APC, XCache, WinCache, ect...
155 $this->srvCache
= ObjectCache
::newAccelerator( array() );
156 } catch ( Exception
$e ) {}
159 $this->srvCache
= $this->srvCache ?
$this->srvCache
: new EmptyBagOStuff();
163 * @see FileBackendStore::resolveContainerPath()
166 protected function resolveContainerPath( $container, $relStoragePath ) {
167 if ( !mb_check_encoding( $relStoragePath, 'UTF-8' ) ) { // mb_string required by CF
168 return null; // not UTF-8, makes it hard to use CF and the swift HTTP API
169 } elseif ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
170 return null; // too long for Swift
172 return $relStoragePath;
175 public function isPathUsableInternal( $storagePath ) {
176 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
177 if ( $rel === null ) {
178 return false; // invalid
182 $this->getContainer( $container );
183 return true; // container exists
184 } catch ( NoSuchContainerException
$e ) {
185 } catch ( CloudFilesException
$e ) { // some other exception?
186 $this->handleException( $e, null, __METHOD__
, array( 'path' => $storagePath ) );
193 * @param array $headers
196 protected function sanitizeHdrs( array $headers ) {
197 // By default, Swift has annoyingly low maximum header value limits
198 if ( isset( $headers['Content-Disposition'] ) ) {
199 $headers['Content-Disposition'] = $this->truncDisp( $headers['Content-Disposition'] );
205 * @param string $disposition Content-Disposition header value
206 * @return string Truncated Content-Disposition header value to meet Swift limits
208 protected function truncDisp( $disposition ) {
210 foreach ( explode( ';', $disposition ) as $part ) {
211 $part = trim( $part );
212 $new = ( $res === '' ) ?
$part : "{$res};{$part}";
213 if ( strlen( $new ) <= 255 ) {
216 break; // too long; sigh
222 protected function doCreateInternal( array $params ) {
223 $status = Status
::newGood();
225 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
226 if ( $dstRel === null ) {
227 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
231 // (a) Check the destination container and object
233 $dContObj = $this->getContainer( $dstCont );
234 } catch ( NoSuchContainerException
$e ) {
235 $status->fatal( 'backend-fail-create', $params['dst'] );
237 } catch ( CloudFilesException
$e ) { // some other exception?
238 $this->handleException( $e, $status, __METHOD__
, $params );
242 // (b) Get a SHA-1 hash of the object
243 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
245 // (c) Actually create the object
247 // Create a fresh CF_Object with no fields preloaded.
248 // We don't want to preserve headers, metadata, and such.
249 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
250 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
251 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
252 // The MD5 here will be checked within Swift against its own MD5.
253 $obj->set_etag( md5( $params['content'] ) );
254 // Use the same content type as StreamFile for security
255 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
256 if ( !strlen( $obj->content_type
) ) { // special case
257 $obj->content_type
= 'unknown/unknown';
259 // Set any other custom headers if requested
260 if ( isset( $params['headers'] ) ) {
261 $obj->headers +
= $this->sanitizeHdrs( $params['headers'] );
263 if ( !empty( $params['async'] ) ) { // deferred
264 $op = $obj->write_async( $params['content'] );
265 $status->value
= new SwiftFileOpHandle( $this, $params, 'Create', $op );
266 $status->value
->affectedObjects
[] = $obj;
267 } else { // actually write the object in Swift
268 $obj->write( $params['content'] );
269 $this->purgeCDNCache( array( $obj ) );
271 } catch ( CDNNotEnabledException
$e ) {
272 // CDN not enabled; nothing to see here
273 } catch ( BadContentTypeException
$e ) {
274 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
275 } catch ( CloudFilesException
$e ) { // some other exception?
276 $this->handleException( $e, $status, __METHOD__
, $params );
283 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
285 protected function _getResponseCreate( CF_Async_Op
$cfOp, Status
$status, array $params ) {
287 $cfOp->getLastResponse();
288 } catch ( BadContentTypeException
$e ) {
289 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
293 protected function doStoreInternal( array $params ) {
294 $status = Status
::newGood();
296 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
297 if ( $dstRel === null ) {
298 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
302 // (a) Check the destination container and object
304 $dContObj = $this->getContainer( $dstCont );
305 } catch ( NoSuchContainerException
$e ) {
306 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
308 } catch ( CloudFilesException
$e ) { // some other exception?
309 $this->handleException( $e, $status, __METHOD__
, $params );
313 // (b) Get a SHA-1 hash of the object
314 wfSuppressWarnings();
315 $sha1Hash = sha1_file( $params['src'] );
317 if ( $sha1Hash === false ) { // source doesn't exist?
318 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
321 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
323 // (c) Actually store the object
325 // Create a fresh CF_Object with no fields preloaded.
326 // We don't want to preserve headers, metadata, and such.
327 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
328 $obj->setMetadataValues( array( 'Sha1base36' => $sha1Hash ) );
329 // The MD5 here will be checked within Swift against its own MD5.
330 $obj->set_etag( md5_file( $params['src'] ) );
331 // Use the same content type as StreamFile for security
332 $obj->content_type
= StreamFile
::contentTypeFromPath( $params['dst'] );
333 if ( !strlen( $obj->content_type
) ) { // special case
334 $obj->content_type
= 'unknown/unknown';
336 // Set any other custom headers if requested
337 if ( isset( $params['headers'] ) ) {
338 $obj->headers +
= $this->sanitizeHdrs( $params['headers'] );
340 if ( !empty( $params['async'] ) ) { // deferred
341 wfSuppressWarnings();
342 $fp = fopen( $params['src'], 'rb' );
345 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
347 $op = $obj->write_async( $fp, filesize( $params['src'] ), true );
348 $status->value
= new SwiftFileOpHandle( $this, $params, 'Store', $op );
349 $status->value
->resourcesToClose
[] = $fp;
350 $status->value
->affectedObjects
[] = $obj;
352 } else { // actually write the object in Swift
353 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
354 $this->purgeCDNCache( array( $obj ) );
356 } catch ( CDNNotEnabledException
$e ) {
357 // CDN not enabled; nothing to see here
358 } catch ( BadContentTypeException
$e ) {
359 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
360 } catch ( IOException
$e ) {
361 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
362 } catch ( CloudFilesException
$e ) { // some other exception?
363 $this->handleException( $e, $status, __METHOD__
, $params );
370 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
372 protected function _getResponseStore( CF_Async_Op
$cfOp, Status
$status, array $params ) {
374 $cfOp->getLastResponse();
375 } catch ( BadContentTypeException
$e ) {
376 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
377 } catch ( IOException
$e ) {
378 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
382 protected function doCopyInternal( array $params ) {
383 $status = Status
::newGood();
385 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
386 if ( $srcRel === null ) {
387 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
391 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
392 if ( $dstRel === null ) {
393 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
397 // (a) Check the source/destination containers and destination object
399 $sContObj = $this->getContainer( $srcCont );
400 $dContObj = $this->getContainer( $dstCont );
401 } catch ( NoSuchContainerException
$e ) {
402 if ( empty( $params['ignoreMissingSource'] ) ||
isset( $sContObj ) ) {
403 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
406 } catch ( CloudFilesException
$e ) { // some other exception?
407 $this->handleException( $e, $status, __METHOD__
, $params );
411 // (b) Actually copy the file to the destination
413 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
414 $hdrs = array(); // source file headers to override with new values
415 // Set any other custom headers if requested
416 if ( isset( $params['headers'] ) ) {
417 $hdrs +
= $this->sanitizeHdrs( $params['headers'] );
419 if ( !empty( $params['async'] ) ) { // deferred
420 $op = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
421 $status->value
= new SwiftFileOpHandle( $this, $params, 'Copy', $op );
422 $status->value
->affectedObjects
[] = $dstObj;
423 } else { // actually write the object in Swift
424 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
425 $this->purgeCDNCache( array( $dstObj ) );
427 } catch ( CDNNotEnabledException
$e ) {
428 // CDN not enabled; nothing to see here
429 } catch ( NoSuchObjectException
$e ) { // source object does not exist
430 if ( empty( $params['ignoreMissingSource'] ) ) {
431 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
433 } catch ( CloudFilesException
$e ) { // some other exception?
434 $this->handleException( $e, $status, __METHOD__
, $params );
441 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
443 protected function _getResponseCopy( CF_Async_Op
$cfOp, Status
$status, array $params ) {
445 $cfOp->getLastResponse();
446 } catch ( NoSuchObjectException
$e ) { // source object does not exist
447 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
451 protected function doMoveInternal( array $params ) {
452 $status = Status
::newGood();
454 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
455 if ( $srcRel === null ) {
456 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
460 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
461 if ( $dstRel === null ) {
462 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
466 // (a) Check the source/destination containers and destination object
468 $sContObj = $this->getContainer( $srcCont );
469 $dContObj = $this->getContainer( $dstCont );
470 } catch ( NoSuchContainerException
$e ) {
471 if ( empty( $params['ignoreMissingSource'] ) ||
isset( $sContObj ) ) {
472 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
475 } catch ( CloudFilesException
$e ) { // some other exception?
476 $this->handleException( $e, $status, __METHOD__
, $params );
480 // (b) Actually move the file to the destination
482 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
483 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
484 $hdrs = array(); // source file headers to override with new values
485 // Set any other custom headers if requested
486 if ( isset( $params['headers'] ) ) {
487 $hdrs +
= $this->sanitizeHdrs( $params['headers'] );
489 if ( !empty( $params['async'] ) ) { // deferred
490 $op = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel, null, $hdrs );
491 $status->value
= new SwiftFileOpHandle( $this, $params, 'Move', $op );
492 $status->value
->affectedObjects
[] = $srcObj;
493 $status->value
->affectedObjects
[] = $dstObj;
494 } else { // actually write the object in Swift
495 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel, null, $hdrs );
496 $this->purgeCDNCache( array( $srcObj ) );
497 $this->purgeCDNCache( array( $dstObj ) );
499 } catch ( CDNNotEnabledException
$e ) {
500 // CDN not enabled; nothing to see here
501 } catch ( NoSuchObjectException
$e ) { // source object does not exist
502 if ( empty( $params['ignoreMissingSource'] ) ) {
503 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
505 } catch ( CloudFilesException
$e ) { // some other exception?
506 $this->handleException( $e, $status, __METHOD__
, $params );
513 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
515 protected function _getResponseMove( CF_Async_Op
$cfOp, Status
$status, array $params ) {
517 $cfOp->getLastResponse();
518 } catch ( NoSuchObjectException
$e ) { // source object does not exist
519 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
523 protected function doDeleteInternal( array $params ) {
524 $status = Status
::newGood();
526 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
527 if ( $srcRel === null ) {
528 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
533 $sContObj = $this->getContainer( $srcCont );
534 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
535 if ( !empty( $params['async'] ) ) { // deferred
536 $op = $sContObj->delete_object_async( $srcRel );
537 $status->value
= new SwiftFileOpHandle( $this, $params, 'Delete', $op );
538 $status->value
->affectedObjects
[] = $srcObj;
539 } else { // actually write the object in Swift
540 $sContObj->delete_object( $srcRel );
541 $this->purgeCDNCache( array( $srcObj ) );
543 } catch ( CDNNotEnabledException
$e ) {
544 // CDN not enabled; nothing to see here
545 } catch ( NoSuchContainerException
$e ) {
546 if ( empty( $params['ignoreMissingSource'] ) ) {
547 $status->fatal( 'backend-fail-delete', $params['src'] );
549 } catch ( NoSuchObjectException
$e ) {
550 if ( empty( $params['ignoreMissingSource'] ) ) {
551 $status->fatal( 'backend-fail-delete', $params['src'] );
553 } catch ( CloudFilesException
$e ) { // some other exception?
554 $this->handleException( $e, $status, __METHOD__
, $params );
561 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
563 protected function _getResponseDelete( CF_Async_Op
$cfOp, Status
$status, array $params ) {
565 $cfOp->getLastResponse();
566 } catch ( NoSuchContainerException
$e ) {
567 $status->fatal( 'backend-fail-delete', $params['src'] );
568 } catch ( NoSuchObjectException
$e ) {
569 if ( empty( $params['ignoreMissingSource'] ) ) {
570 $status->fatal( 'backend-fail-delete', $params['src'] );
575 protected function doDescribeInternal( array $params ) {
576 $status = Status
::newGood();
578 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
579 if ( $srcRel === null ) {
580 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
585 $sContObj = $this->getContainer( $srcCont );
586 // Get the latest version of the current metadata
587 $srcObj = $sContObj->get_object( $srcRel,
588 $this->headersFromParams( array( 'latest' => true ) ) );
589 // Merge in the metadata updates...
590 if ( isset( $params['headers'] ) ) {
591 $srcObj->headers
= $this->sanitizeHdrs( $params['headers'] ) +
$srcObj->headers
;
593 $srcObj->sync_metadata(); // save to Swift
594 $this->purgeCDNCache( array( $srcObj ) );
595 } catch ( CDNNotEnabledException
$e ) {
596 // CDN not enabled; nothing to see here
597 } catch ( NoSuchContainerException
$e ) {
598 $status->fatal( 'backend-fail-describe', $params['src'] );
599 } catch ( NoSuchObjectException
$e ) {
600 $status->fatal( 'backend-fail-describe', $params['src'] );
601 } catch ( CloudFilesException
$e ) { // some other exception?
602 $this->handleException( $e, $status, __METHOD__
, $params );
608 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
609 $status = Status
::newGood();
611 // (a) Check if container already exists
613 $this->getContainer( $fullCont );
614 // NoSuchContainerException not thrown: container must exist
615 return $status; // already exists
616 } catch ( NoSuchContainerException
$e ) {
617 // NoSuchContainerException thrown: container does not exist
618 } catch ( CloudFilesException
$e ) { // some other exception?
619 $this->handleException( $e, $status, __METHOD__
, $params );
623 // (b) Create container as needed
625 $contObj = $this->createContainer( $fullCont );
626 if ( !empty( $params['noAccess'] ) ) {
627 // Make container private to end-users...
628 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
630 // Make container public to end-users...
631 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
633 if ( $this->swiftUseCDN
) { // Rackspace style CDN
634 $contObj->make_public( $this->swiftCDNExpiry
);
636 } catch ( CDNNotEnabledException
$e ) {
637 // CDN not enabled; nothing to see here
638 } catch ( CloudFilesException
$e ) { // some other exception?
639 $this->handleException( $e, $status, __METHOD__
, $params );
647 * @see FileBackendStore::doSecureInternal()
650 protected function doSecureInternal( $fullCont, $dir, array $params ) {
651 $status = Status
::newGood();
652 if ( empty( $params['noAccess'] ) ) {
653 return $status; // nothing to do
656 // Restrict container from end-users...
658 // doPrepareInternal() should have been called,
659 // so the Swift container should already exist...
660 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
661 // NoSuchContainerException not thrown: container must exist
663 // Make container private to end-users...
664 $status->merge( $this->setContainerAccess(
666 array( $this->auth
->username
), // read
667 array( $this->auth
->username
) // write
669 if ( $this->swiftUseCDN
&& $contObj->is_public() ) { // Rackspace style CDN
670 $contObj->make_private();
672 } catch ( CDNNotEnabledException
$e ) {
673 // CDN not enabled; nothing to see here
674 } catch ( CloudFilesException
$e ) { // some other exception?
675 $this->handleException( $e, $status, __METHOD__
, $params );
682 * @see FileBackendStore::doPublishInternal()
685 protected function doPublishInternal( $fullCont, $dir, array $params ) {
686 $status = Status
::newGood();
688 // Unrestrict container from end-users...
690 // doPrepareInternal() should have been called,
691 // so the Swift container should already exist...
692 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
693 // NoSuchContainerException not thrown: container must exist
695 // Make container public to end-users...
696 if ( $this->swiftAnonUser
!= '' ) {
697 $status->merge( $this->setContainerAccess(
699 array( $this->auth
->username
, $this->swiftAnonUser
), // read
700 array( $this->auth
->username
, $this->swiftAnonUser
) // write
703 $status->merge( $this->setContainerAccess(
705 array( $this->auth
->username
, '.r:*' ), // read
706 array( $this->auth
->username
) // write
709 if ( $this->swiftUseCDN
&& !$contObj->is_public() ) { // Rackspace style CDN
710 $contObj->make_public();
712 } catch ( CDNNotEnabledException
$e ) {
713 // CDN not enabled; nothing to see here
714 } catch ( CloudFilesException
$e ) { // some other exception?
715 $this->handleException( $e, $status, __METHOD__
, $params );
721 protected function doCleanInternal( $fullCont, $dir, array $params ) {
722 $status = Status
::newGood();
724 // Only containers themselves can be removed, all else is virtual
726 return $status; // nothing to do
729 // (a) Check the container
731 $contObj = $this->getContainer( $fullCont, true );
732 } catch ( NoSuchContainerException
$e ) {
733 return $status; // ok, nothing to do
734 } catch ( CloudFilesException
$e ) { // some other exception?
735 $this->handleException( $e, $status, __METHOD__
, $params );
739 // (b) Delete the container if empty
740 if ( $contObj->object_count
== 0 ) {
742 $this->deleteContainer( $fullCont );
743 } catch ( NoSuchContainerException
$e ) {
744 return $status; // race?
745 } catch ( NonEmptyContainerException
$e ) {
746 return $status; // race? consistency delay?
747 } catch ( CloudFilesException
$e ) { // some other exception?
748 $this->handleException( $e, $status, __METHOD__
, $params );
756 protected function doGetFileStat( array $params ) {
757 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
758 if ( $srcRel === null ) {
759 return false; // invalid storage path
764 $contObj = $this->getContainer( $srcCont );
765 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
766 $this->addMissingMetadata( $srcObj, $params['src'] );
768 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
769 'mtime' => wfTimestamp( TS_MW
, $srcObj->last_modified
),
770 'size' => (int)$srcObj->content_length
,
771 'sha1' => $srcObj->getMetadataValue( 'Sha1base36' )
773 } catch ( NoSuchContainerException
$e ) {
774 } catch ( NoSuchObjectException
$e ) {
775 } catch ( CloudFilesException
$e ) { // some other exception?
777 $this->handleException( $e, null, __METHOD__
, $params );
784 * Fill in any missing object metadata and save it to Swift
786 * @param CF_Object $obj
787 * @param string $path Storage path to object
788 * @return bool Success
789 * @throws Exception cloudfiles exceptions
791 protected function addMissingMetadata( CF_Object
$obj, $path ) {
792 if ( $obj->getMetadataValue( 'Sha1base36' ) !== null ) {
793 return true; // nothing to do
795 wfProfileIn( __METHOD__
);
796 trigger_error( "$path was not stored with SHA-1 metadata.", E_USER_WARNING
);
797 $status = Status
::newGood();
798 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager
::LOCK_UW
, $status );
799 if ( $status->isOK() ) {
800 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1 ) );
802 $hash = $tmpFile->getSha1Base36();
803 if ( $hash !== false ) {
804 $obj->setMetadataValues( array( 'Sha1base36' => $hash ) );
805 $obj->sync_metadata(); // save to Swift
806 wfProfileOut( __METHOD__
);
807 return true; // success
811 trigger_error( "Unable to set SHA-1 metadata for $path", E_USER_WARNING
);
812 $obj->setMetadataValues( array( 'Sha1base36' => false ) );
813 wfProfileOut( __METHOD__
);
814 return false; // failed
817 protected function doGetFileContentsMulti( array $params ) {
820 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
821 // Blindly create tmp files and stream to them, catching any exception if the file does
822 // not exist. Doing stats here is useless and will loop infinitely in addMissingMetadata().
823 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
824 $cfOps = array(); // (path => CF_Async_Op)
826 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
827 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
828 if ( $srcRel === null ) {
829 $contents[$path] = false;
834 $sContObj = $this->getContainer( $srcCont );
835 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
836 // Create a new temporary memory file...
837 $handle = fopen( 'php://temp', 'wb' );
839 $headers = $this->headersFromParams( $params );
840 if ( count( $pathBatch ) > 1 ) {
841 $cfOps[$path] = $obj->stream_async( $handle, $headers );
842 $cfOps[$path]->_file_handle
= $handle; // close this later
844 $obj->stream( $handle, $headers );
845 rewind( $handle ); // start from the beginning
846 $data = stream_get_contents( $handle );
852 } catch ( NoSuchContainerException
$e ) {
854 } catch ( NoSuchObjectException
$e ) {
856 } catch ( CloudFilesException
$e ) { // some other exception?
858 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
860 $contents[$path] = $data;
863 $batch = new CF_Async_Op_Batch( $cfOps );
864 $cfOps = $batch->execute();
865 foreach ( $cfOps as $path => $cfOp ) {
867 $cfOp->getLastResponse();
868 rewind( $cfOp->_file_handle
); // start from the beginning
869 $contents[$path] = stream_get_contents( $cfOp->_file_handle
);
870 } catch ( NoSuchContainerException
$e ) {
871 $contents[$path] = false;
872 } catch ( NoSuchObjectException
$e ) {
873 $contents[$path] = false;
874 } catch ( CloudFilesException
$e ) { // some other exception?
875 $contents[$path] = false;
876 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
878 fclose( $cfOp->_file_handle
); // close open handle
886 * @see FileBackendStore::doDirectoryExists()
889 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
891 $container = $this->getContainer( $fullCont );
892 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
893 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
894 } catch ( NoSuchContainerException
$e ) {
896 } catch ( CloudFilesException
$e ) { // some other exception?
897 $this->handleException( $e, null, __METHOD__
,
898 array( 'cont' => $fullCont, 'dir' => $dir ) );
901 return null; // error
905 * @see FileBackendStore::getDirectoryListInternal()
906 * @return SwiftFileBackendDirList
908 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
909 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
913 * @see FileBackendStore::getFileListInternal()
914 * @return SwiftFileBackendFileList
916 public function getFileListInternal( $fullCont, $dir, array $params ) {
917 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
921 * Do not call this function outside of SwiftFileBackendFileList
923 * @param string $fullCont Resolved container name
924 * @param string $dir Resolved storage directory with no trailing slash
925 * @param string|null $after Storage path of file to list items after
926 * @param integer $limit Max number of items to list
927 * @param array $params Parameters for getDirectoryList()
928 * @return Array List of resolved paths of directories directly under $dir
929 * @throws FileBackendError
931 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
933 if ( $after === INF
) {
934 return $dirs; // nothing more
937 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
939 $container = $this->getContainer( $fullCont );
940 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
941 // Non-recursive: only list dirs right under $dir
942 if ( !empty( $params['topOnly'] ) ) {
943 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
944 foreach ( $objects as $object ) { // files and directories
945 if ( substr( $object, -1 ) === '/' ) {
946 $dirs[] = $object; // directories end in '/'
949 // Recursive: list all dirs under $dir and its subdirs
951 // Get directory from last item of prior page
952 $lastDir = $this->getParentDir( $after ); // must be first page
953 $objects = $container->list_objects( $limit, $after, $prefix );
954 foreach ( $objects as $object ) { // files
955 $objectDir = $this->getParentDir( $object ); // directory of object
956 if ( $objectDir !== false && $objectDir !== $dir ) {
957 // Swift stores paths in UTF-8, using binary sorting.
958 // See function "create_container_table" in common/db.py.
959 // If a directory is not "greater" than the last one,
960 // then it was already listed by the calling iterator.
961 if ( strcmp( $objectDir, $lastDir ) > 0 ) {
963 do { // add dir and all its parent dirs
964 $dirs[] = "{$pDir}/";
965 $pDir = $this->getParentDir( $pDir );
966 } while ( $pDir !== false // sanity
967 && strcmp( $pDir, $lastDir ) > 0 // not done already
968 && strlen( $pDir ) > strlen( $dir ) // within $dir
971 $lastDir = $objectDir;
975 // Page on the unfiltered directory listing (what is returned may be filtered)
976 if ( count( $objects ) < $limit ) {
977 $after = INF
; // avoid a second RTT
979 $after = end( $objects ); // update last item
981 } catch ( NoSuchContainerException
$e ) {
982 } catch ( CloudFilesException
$e ) { // some other exception?
983 $this->handleException( $e, null, __METHOD__
,
984 array( 'cont' => $fullCont, 'dir' => $dir ) );
985 throw new FileBackendError( "Got " . get_class( $e ) . " exception." );
991 protected function getParentDir( $path ) {
992 return ( strpos( $path, '/' ) !== false ) ?
dirname( $path ) : false;
996 * Do not call this function outside of SwiftFileBackendFileList
998 * @param string $fullCont Resolved container name
999 * @param string $dir Resolved storage directory with no trailing slash
1000 * @param string|null $after Storage path of file to list items after
1001 * @param integer $limit Max number of items to list
1002 * @param array $params Parameters for getDirectoryList()
1003 * @return Array List of resolved paths of files under $dir
1004 * @throws FileBackendError
1006 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
1008 if ( $after === INF
) {
1009 return $files; // nothing more
1012 $section = new ProfileSection( __METHOD__
. '-' . $this->name
);
1014 $container = $this->getContainer( $fullCont );
1015 $prefix = ( $dir == '' ) ?
null : "{$dir}/";
1016 // Non-recursive: only list files right under $dir
1017 if ( !empty( $params['topOnly'] ) ) { // files and dirs
1018 if ( !empty( $params['adviseStat'] ) ) {
1019 $limit = min( $limit, self
::CACHE_CHEAP_SIZE
);
1020 // Note: get_objects() does not include directories
1021 $objects = $this->loadObjectListing( $params, $dir,
1022 $container->get_objects( $limit, $after, $prefix, null, '/' ) );
1025 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
1026 foreach ( $objects as $object ) { // files and directories
1027 if ( substr( $object, -1 ) !== '/' ) {
1028 $files[] = $object; // directories end in '/'
1032 // Recursive: list all files under $dir and its subdirs
1034 if ( !empty( $params['adviseStat'] ) ) {
1035 $limit = min( $limit, self
::CACHE_CHEAP_SIZE
);
1036 $objects = $this->loadObjectListing( $params, $dir,
1037 $container->get_objects( $limit, $after, $prefix ) );
1039 $objects = $container->list_objects( $limit, $after, $prefix );
1043 // Page on the unfiltered object listing (what is returned may be filtered)
1044 if ( count( $objects ) < $limit ) {
1045 $after = INF
; // avoid a second RTT
1047 $after = end( $objects ); // update last item
1049 } catch ( NoSuchContainerException
$e ) {
1050 } catch ( CloudFilesException
$e ) { // some other exception?
1051 $this->handleException( $e, null, __METHOD__
,
1052 array( 'cont' => $fullCont, 'dir' => $dir ) );
1053 throw new FileBackendError( "Got " . get_class( $e ) . " exception." );
1060 * Load a list of objects that belong under $dir into stat cache
1061 * and return a list of the names of the objects in the same order.
1063 * @param array $params Parameters for getDirectoryList()
1064 * @param string $dir Resolved container directory path
1065 * @param array $cfObjects List of CF_Object items
1066 * @return array List of object names
1068 private function loadObjectListing( array $params, $dir, array $cfObjects ) {
1070 $storageDir = rtrim( $params['dir'], '/' );
1071 $suffixStart = ( $dir === '' ) ?
0 : strlen( $dir ) +
1; // size of "path/to/dir/"
1072 // Iterate over the list *backwards* as this primes the stat cache, which is LRU.
1073 // If this fills the cache and the caller stats an uncached file before stating
1074 // the ones on the listing, there would be zero cache hits if this went forwards.
1075 for ( end( $cfObjects ); key( $cfObjects ) !== null; prev( $cfObjects ) ) {
1076 $object = current( $cfObjects );
1077 $path = "{$storageDir}/" . substr( $object->name
, $suffixStart );
1079 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
1080 'mtime' => wfTimestamp( TS_MW
, $object->last_modified
),
1081 'size' => (int)$object->content_length
,
1082 'latest' => false // eventually consistent
1084 $this->cheapCache
->set( $path, 'stat', $val );
1085 $names[] = $object->name
;
1087 return array_reverse( $names ); // keep the paths in original order
1090 protected function doGetFileSha1base36( array $params ) {
1091 $stat = $this->getFileStat( $params );
1093 if ( !isset( $stat['sha1'] ) ) {
1094 // Stat entries filled by file listings don't include SHA1
1095 $this->clearCache( array( $params['src'] ) );
1096 $stat = $this->getFileStat( $params );
1098 return $stat['sha1'];
1104 protected function doStreamFile( array $params ) {
1105 $status = Status
::newGood();
1107 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1108 if ( $srcRel === null ) {
1109 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
1113 $cont = $this->getContainer( $srcCont );
1114 } catch ( NoSuchContainerException
$e ) {
1115 $status->fatal( 'backend-fail-stream', $params['src'] );
1117 } catch ( CloudFilesException
$e ) { // some other exception?
1118 $this->handleException( $e, $status, __METHOD__
, $params );
1123 $output = fopen( 'php://output', 'wb' );
1124 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
1125 $obj->stream( $output, $this->headersFromParams( $params ) );
1126 } catch ( NoSuchObjectException
$e ) {
1127 $status->fatal( 'backend-fail-stream', $params['src'] );
1128 } catch ( CloudFilesException
$e ) { // some other exception?
1129 $this->handleException( $e, $status, __METHOD__
, $params );
1135 protected function doGetLocalCopyMulti( array $params ) {
1136 $tmpFiles = array();
1138 $ep = array_diff_key( $params, array( 'srcs' => 1 ) ); // for error logging
1139 // Blindly create tmp files and stream to them, catching any exception if the file does
1140 // not exist. Doing a stat here is useless causes infinite loops in addMissingMetadata().
1141 foreach ( array_chunk( $params['srcs'], $params['concurrency'] ) as $pathBatch ) {
1142 $cfOps = array(); // (path => CF_Async_Op)
1144 foreach ( $pathBatch as $path ) { // each path in this concurrent batch
1145 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $path );
1146 if ( $srcRel === null ) {
1147 $tmpFiles[$path] = null;
1152 $sContObj = $this->getContainer( $srcCont );
1153 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1154 // Get source file extension
1155 $ext = FileBackend
::extensionFromPath( $path );
1156 // Create a new temporary file...
1157 $tmpFile = TempFSFile
::factory( 'localcopy_', $ext );
1159 $handle = fopen( $tmpFile->getPath(), 'wb' );
1161 $headers = $this->headersFromParams( $params );
1162 if ( count( $pathBatch ) > 1 ) {
1163 $cfOps[$path] = $obj->stream_async( $handle, $headers );
1164 $cfOps[$path]->_file_handle
= $handle; // close this later
1166 $obj->stream( $handle, $headers );
1173 } catch ( NoSuchContainerException
$e ) {
1175 } catch ( NoSuchObjectException
$e ) {
1177 } catch ( CloudFilesException
$e ) { // some other exception?
1179 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1181 $tmpFiles[$path] = $tmpFile;
1184 $batch = new CF_Async_Op_Batch( $cfOps );
1185 $cfOps = $batch->execute();
1186 foreach ( $cfOps as $path => $cfOp ) {
1188 $cfOp->getLastResponse();
1189 } catch ( NoSuchContainerException
$e ) {
1190 $tmpFiles[$path] = null;
1191 } catch ( NoSuchObjectException
$e ) {
1192 $tmpFiles[$path] = null;
1193 } catch ( CloudFilesException
$e ) { // some other exception?
1194 $tmpFiles[$path] = null;
1195 $this->handleException( $e, null, __METHOD__
, array( 'src' => $path ) +
$ep );
1197 fclose( $cfOp->_file_handle
); // close open handle
1204 public function getFileHttpUrl( array $params ) {
1205 if ( $this->swiftTempUrlKey
!= '' ||
1206 ( $this->rgwS3AccessKey
!= '' && $this->rgwS3SecretKey
!= '' ) )
1208 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
1209 if ( $srcRel === null ) {
1210 return null; // invalid path
1213 $ttl = isset( $params['ttl'] ) ?
$params['ttl'] : 86400;
1214 $sContObj = $this->getContainer( $srcCont );
1215 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
1216 if ( $this->swiftTempUrlKey
!= '' ) {
1217 return $obj->get_temp_url( $this->swiftTempUrlKey
, $ttl, "GET" );
1218 } else { // give S3 API URL for rgw
1219 $expires = time() +
$ttl;
1220 // Path for signature starts with the bucket
1221 $spath = '/' . rawurlencode( $srcCont ) . '/' .
1222 str_replace( '%2F', '/', rawurlencode( $srcRel ) );
1223 // Calculate the hash
1224 $signature = base64_encode( hash_hmac(
1226 "GET\n\n\n{$expires}\n{$spath}",
1227 $this->rgwS3SecretKey
,
1230 // See http://s3.amazonaws.com/doc/s3-developer-guide/RESTAuthentication.html.
1231 // Note: adding a newline for empty CanonicalizedAmzHeaders does not work.
1232 return wfAppendQuery(
1233 str_replace( '/swift/v1', '', // S3 API is the rgw default
1234 $sContObj->cfs_http
->getStorageUrl() . $spath ),
1236 'Signature' => $signature,
1237 'Expires' => $expires,
1238 'AWSAccessKeyId' => $this->rgwS3AccessKey
)
1241 } catch ( NoSuchContainerException
$e ) {
1242 } catch ( CloudFilesException
$e ) { // some other exception?
1243 $this->handleException( $e, null, __METHOD__
, $params );
1249 protected function directoriesAreVirtual() {
1254 * Get headers to send to Swift when reading a file based
1255 * on a FileBackend params array, e.g. that of getLocalCopy().
1256 * $params is currently only checked for a 'latest' flag.
1258 * @param array $params
1261 protected function headersFromParams( array $params ) {
1263 if ( !empty( $params['latest'] ) ) {
1264 $hdrs[] = 'X-Newest: true';
1269 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1270 $statuses = array();
1272 $cfOps = array(); // list of CF_Async_Op objects
1273 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1274 $cfOps[$index] = $fileOpHandle->cfOp
;
1276 $batch = new CF_Async_Op_Batch( $cfOps );
1278 $cfOps = $batch->execute();
1279 foreach ( $cfOps as $index => $cfOp ) {
1280 $status = Status
::newGood();
1281 $function = '_getResponse' . $fileOpHandles[$index]->call
;
1282 try { // catch exceptions; update status
1283 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params
);
1284 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects
);
1285 } catch ( CloudFilesException
$e ) { // some other exception?
1286 $this->handleException( $e, $status,
1287 __CLASS__
. ":$function", $fileOpHandles[$index]->params
);
1289 $statuses[$index] = $status;
1296 * Set read/write permissions for a Swift container.
1298 * $readGrps is a list of the possible criteria for a request to have
1299 * access to read a container. Each item is one of the following formats:
1300 * - account:user : Grants access if the request is by the given user
1301 * - ".r:<regex>" : Grants access if the request is from a referrer host that
1302 * matches the expression and the request is not for a listing.
1303 * Setting this to '*' effectively makes a container public.
1304 * -".rlistings:<regex>" : Grants access if the request is from a referrer host that
1305 * matches the expression and the request is for a listing.
1307 * $writeGrps is a list of the possible criteria for a request to have
1308 * access to write to a container. Each item is of the following format:
1309 * - account:user : Grants access if the request is by the given user
1311 * @see http://swift.openstack.org/misc.html#acls
1313 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1314 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1316 * @param CF_Container $contObj Swift container
1317 * @param array $readGrps List of read access routes
1318 * @param array $writeGrps List of write access routes
1321 protected function setContainerAccess(
1322 CF_Container
$contObj, array $readGrps, array $writeGrps
1324 $creds = $contObj->cfs_auth
->export_credentials();
1326 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name
);
1328 // Note: 10 second timeout consistent with php-cloudfiles
1329 $req = MWHttpRequest
::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1330 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1331 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1332 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1334 return $req->execute(); // should return 204
1338 * Purge the CDN cache of affected objects if CDN caching is enabled.
1339 * This is for Rackspace/Akamai CDNs.
1341 * @param array $objects List of CF_Object items
1344 public function purgeCDNCache( array $objects ) {
1345 if ( $this->swiftUseCDN
&& $this->swiftCDNPurgable
) {
1346 foreach ( $objects as $object ) {
1348 $object->purge_from_cdn();
1349 } catch ( CDNNotEnabledException
$e ) {
1350 // CDN not enabled; nothing to see here
1351 } catch ( CloudFilesException
$e ) {
1352 $this->handleException( $e, null, __METHOD__
,
1353 array( 'cont' => $object->container
->name
, 'obj' => $object->name
) );
1360 * Get an authenticated connection handle to the Swift proxy
1362 * @throws CloudFilesException
1363 * @throws CloudFilesException|Exception
1364 * @return CF_Connection|bool False on failure
1366 protected function getConnection() {
1367 if ( $this->connException
instanceof CloudFilesException
) {
1368 if ( ( time() - $this->connErrorTime
) < 60 ) {
1369 throw $this->connException
; // failed last attempt; don't bother
1370 } else { // actually retry this time
1371 $this->connException
= null;
1372 $this->connErrorTime
= 0;
1375 // Session keys expire after a while, so we renew them periodically
1376 $reAuth = ( ( time() - $this->sessionStarted
) > $this->authTTL
);
1377 // Authenticate with proxy and get a session key...
1378 if ( !$this->conn ||
$reAuth ) {
1379 $this->sessionStarted
= 0;
1380 $this->connContainerCache
->clear();
1381 $cacheKey = $this->getCredsCacheKey( $this->auth
->username
);
1382 $creds = $this->srvCache
->get( $cacheKey ); // credentials
1383 if ( is_array( $creds ) ) { // cache hit
1384 $this->auth
->load_cached_credentials(
1385 $creds['auth_token'], $creds['storage_url'], $creds['cdnm_url'] );
1386 $this->sessionStarted
= time() - ceil( $this->authTTL
/ 2 ); // skew for worst case
1387 } else { // cache miss
1389 $this->auth
->authenticate();
1390 $creds = $this->auth
->export_credentials();
1391 $this->srvCache
->add( $cacheKey, $creds, ceil( $this->authTTL
/ 2 ) ); // cache
1392 $this->sessionStarted
= time();
1393 } catch ( CloudFilesException
$e ) {
1394 $this->connException
= $e; // don't keep re-trying
1395 $this->connErrorTime
= time();
1396 throw $e; // throw it back
1399 if ( $this->conn
) { // re-authorizing?
1400 $this->conn
->close(); // close active cURL handles in CF_Http object
1402 $this->conn
= new CF_Connection( $this->auth
);
1408 * Close the connection to the Swift proxy
1412 protected function closeConnection() {
1413 if ( $this->conn
) {
1414 $this->conn
->close(); // close active cURL handles in CF_Http object
1416 $this->sessionStarted
= 0;
1417 $this->connContainerCache
->clear();
1422 * Get the cache key for a container
1424 * @param string $username
1427 private function getCredsCacheKey( $username ) {
1428 return wfMemcKey( 'backend', $this->getName(), 'usercreds', $username );
1432 * Get a Swift container object, possibly from process cache.
1433 * Use $reCache if the file count or byte count is needed.
1435 * @param string $container Container name
1436 * @param bool $bypassCache Bypass all caches and load from Swift
1437 * @return CF_Container
1438 * @throws CloudFilesException
1440 protected function getContainer( $container, $bypassCache = false ) {
1441 $conn = $this->getConnection(); // Swift proxy connection
1442 if ( $bypassCache ) { // purge cache
1443 $this->connContainerCache
->clear( $container );
1444 } elseif ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1445 $this->primeContainerCache( array( $container ) ); // check persistent cache
1447 if ( !$this->connContainerCache
->has( $container, 'obj' ) ) {
1448 $contObj = $conn->get_container( $container );
1449 // NoSuchContainerException not thrown: container must exist
1450 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache it
1451 if ( !$bypassCache ) {
1452 $this->setContainerCache( $container, // update persistent cache
1453 array( 'bytes' => $contObj->bytes_used
, 'count' => $contObj->object_count
)
1457 return $this->connContainerCache
->get( $container, 'obj' );
1461 * Create a Swift container
1463 * @param string $container Container name
1464 * @return CF_Container
1465 * @throws CloudFilesException
1467 protected function createContainer( $container ) {
1468 $conn = $this->getConnection(); // Swift proxy connection
1469 $contObj = $conn->create_container( $container );
1470 $this->connContainerCache
->set( $container, 'obj', $contObj ); // cache
1475 * Delete a Swift container
1477 * @param string $container Container name
1479 * @throws CloudFilesException
1481 protected function deleteContainer( $container ) {
1482 $conn = $this->getConnection(); // Swift proxy connection
1483 $this->connContainerCache
->clear( $container ); // purge
1484 $conn->delete_container( $container );
1487 protected function doPrimeContainerCache( array $containerInfo ) {
1489 $conn = $this->getConnection(); // Swift proxy connection
1490 foreach ( $containerInfo as $container => $info ) {
1491 $contObj = new CF_Container( $conn->cfs_auth
, $conn->cfs_http
,
1492 $container, $info['count'], $info['bytes'] );
1493 $this->connContainerCache
->set( $container, 'obj', $contObj );
1495 } catch ( CloudFilesException
$e ) { // some other exception?
1496 $this->handleException( $e, null, __METHOD__
, array() );
1501 * Log an unexpected exception for this backend.
1502 * This also sets the Status object to have a fatal error.
1504 * @param Exception $e
1505 * @param Status $status|null
1506 * @param string $func
1507 * @param array $params
1510 protected function handleException( Exception
$e, $status, $func, array $params ) {
1511 if ( $status instanceof Status
) {
1512 if ( $e instanceof AuthenticationException
) {
1513 $status->fatal( 'backend-fail-connect', $this->name
);
1515 $status->fatal( 'backend-fail-internal', $this->name
);
1518 if ( $e->getMessage() ) {
1519 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING
);
1521 if ( $e instanceof InvalidResponseException
) { // possibly a stale token
1522 $this->srvCache
->delete( $this->getCredsCacheKey( $this->auth
->username
) );
1523 $this->closeConnection(); // force a re-connect and re-auth next time
1525 wfDebugLog( 'SwiftBackend',
1526 get_class( $e ) . " in '{$func}' (given '" . FormatJson
::encode( $params ) . "')" .
1527 ( $e->getMessage() ?
": {$e->getMessage()}" : "" )
1533 * @see FileBackendStoreOpHandle
1535 class SwiftFileOpHandle
extends FileBackendStoreOpHandle
{
1536 /** @var CF_Async_Op */
1539 public $affectedObjects = array();
1542 * @param SwiftFileBackend $backend
1543 * @param array $params
1544 * @param string $call
1545 * @param CF_Async_Op $cfOp
1547 public function __construct(
1548 SwiftFileBackend
$backend, array $params, $call, CF_Async_Op
$cfOp
1550 $this->backend
= $backend;
1551 $this->params
= $params;
1552 $this->call
= $call;
1553 $this->cfOp
= $cfOp;
1558 * SwiftFileBackend helper class to page through listings.
1559 * Swift also has a listing limit of 10,000 objects for sanity.
1560 * Do not use this class from places outside SwiftFileBackend.
1562 * @ingroup FileBackend
1564 abstract class SwiftFileBackendList
implements Iterator
{
1566 protected $bufferIter = array();
1567 protected $bufferAfter = null; // string; list items *after* this path
1568 protected $pos = 0; // integer
1570 protected $params = array();
1572 /** @var SwiftFileBackend */
1574 protected $container; // string; container name
1575 protected $dir; // string; storage directory
1576 protected $suffixStart; // integer
1578 const PAGE_SIZE
= 9000; // file listing buffer size
1581 * @param SwiftFileBackend $backend
1582 * @param string $fullCont Resolved container name
1583 * @param string $dir Resolved directory relative to container
1584 * @param array $params
1586 public function __construct( SwiftFileBackend
$backend, $fullCont, $dir, array $params ) {
1587 $this->backend
= $backend;
1588 $this->container
= $fullCont;
1590 if ( substr( $this->dir
, -1 ) === '/' ) {
1591 $this->dir
= substr( $this->dir
, 0, -1 ); // remove trailing slash
1593 if ( $this->dir
== '' ) { // whole container
1594 $this->suffixStart
= 0;
1595 } else { // dir within container
1596 $this->suffixStart
= strlen( $this->dir
) +
1; // size of "path/to/dir/"
1598 $this->params
= $params;
1602 * @see Iterator::key()
1605 public function key() {
1610 * @see Iterator::next()
1613 public function next() {
1614 // Advance to the next file in the page
1615 next( $this->bufferIter
);
1617 // Check if there are no files left in this page and
1618 // advance to the next page if this page was not empty.
1619 if ( !$this->valid() && count( $this->bufferIter
) ) {
1620 $this->bufferIter
= $this->pageFromList(
1621 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1622 ); // updates $this->bufferAfter
1627 * @see Iterator::rewind()
1630 public function rewind() {
1632 $this->bufferAfter
= null;
1633 $this->bufferIter
= $this->pageFromList(
1634 $this->container
, $this->dir
, $this->bufferAfter
, self
::PAGE_SIZE
, $this->params
1635 ); // updates $this->bufferAfter
1639 * @see Iterator::valid()
1642 public function valid() {
1643 if ( $this->bufferIter
=== null ) {
1644 return false; // some failure?
1646 return ( current( $this->bufferIter
) !== false ); // no paths can have this value
1651 * Get the given list portion (page)
1653 * @param string $container Resolved container name
1654 * @param string $dir Resolved path relative to container
1655 * @param string $after|null
1656 * @param integer $limit
1657 * @param array $params
1658 * @return Traversable|Array
1660 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1664 * Iterator for listing directories
1666 class SwiftFileBackendDirList
extends SwiftFileBackendList
{
1668 * @see Iterator::current()
1669 * @return string|bool String (relative path) or false
1671 public function current() {
1672 return substr( current( $this->bufferIter
), $this->suffixStart
, -1 );
1676 * @see SwiftFileBackendList::pageFromList()
1679 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1680 return $this->backend
->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1685 * Iterator for listing regular files
1687 class SwiftFileBackendFileList
extends SwiftFileBackendList
{
1689 * @see Iterator::current()
1690 * @return string|bool String (relative path) or false
1692 public function current() {
1693 return substr( current( $this->bufferIter
), $this->suffixStart
);
1697 * @see SwiftFileBackendList::pageFromList()
1700 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1701 return $this->backend
->getFileListPageInternal( $container, $dir, $after, $limit, $params );