Localisation updates from http://translatewiki.net.
[mediawiki.git] / includes / filerepo / backend / SwiftFileBackend.php
blob252081336f5d8bf15e38923daf2da32a37deb3a3
1 <?php
2 /**
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
20 * @file
21 * @ingroup FileBackend
22 * @author Russ Nelson
23 * @author Aaron Schulz
26 /**
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
37 * @since 1.19
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 $maxContCacheSize = 300; // integer; max containers with entries
47 /** @var CF_Connection */
48 protected $conn; // Swift connection handle
49 protected $connStarted = 0; // integer UNIX timestamp
50 protected $connContainers = array(); // container object cache
51 protected $connException; // CloudFiles exception
53 /**
54 * @see FileBackendStore::__construct()
55 * Additional $config params include:
56 * swiftAuthUrl : Swift authentication server URL
57 * swiftUser : Swift user used by MediaWiki (account:username)
58 * swiftKey : Swift authentication key for the above user
59 * swiftAuthTTL : Swift authentication TTL (seconds)
60 * swiftAnonUser : Swift user used for end-user requests (account:username)
61 * swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
62 * shardViaHashLevels : Map of container names to sharding config with:
63 * 'base' : base of hash characters, 16 or 36
64 * 'levels' : the number of hash levels (and digits)
65 * 'repeat' : hash subdirectories are prefixed with all the
66 * parent hash directory names (e.g. "a/ab/abc")
68 public function __construct( array $config ) {
69 parent::__construct( $config );
70 if ( !MWInit::classExists( 'CF_Constants' ) ) {
71 throw new MWException( 'SwiftCloudFiles extension not installed.' );
73 // Required settings
74 $this->auth = new CF_Authentication(
75 $config['swiftUser'],
76 $config['swiftKey'],
77 null, // account; unused
78 $config['swiftAuthUrl']
80 // Optional settings
81 $this->authTTL = isset( $config['swiftAuthTTL'] )
82 ? $config['swiftAuthTTL']
83 : 5 * 60; // some sane number
84 $this->swiftAnonUser = isset( $config['swiftAnonUser'] )
85 ? $config['swiftAnonUser']
86 : '';
87 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
88 ? $config['shardViaHashLevels']
89 : '';
90 $this->swiftUseCDN = isset( $config['swiftUseCDN'] )
91 ? $config['swiftUseCDN']
92 : false;
93 // Cache container info to mask latency
94 $this->memCache = wfGetMainCache();
97 /**
98 * @see FileBackendStore::resolveContainerPath()
99 * @return null
101 protected function resolveContainerPath( $container, $relStoragePath ) {
102 if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
103 return null; // too long for Swift
105 return $relStoragePath;
109 * @see FileBackendStore::isPathUsableInternal()
110 * @return bool
112 public function isPathUsableInternal( $storagePath ) {
113 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
114 if ( $rel === null ) {
115 return false; // invalid
118 try {
119 $this->getContainer( $container );
120 return true; // container exists
121 } catch ( NoSuchContainerException $e ) {
122 } catch ( CloudFilesException $e ) { // some other exception?
123 $this->handleException( $e, null, __METHOD__, array( 'path' => $storagePath ) );
126 return false;
130 * @see FileBackendStore::doCreateInternal()
131 * @return Status
133 protected function doCreateInternal( array $params ) {
134 $status = Status::newGood();
136 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
137 if ( $dstRel === null ) {
138 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
139 return $status;
142 // (a) Check the destination container and object
143 try {
144 $dContObj = $this->getContainer( $dstCont );
145 if ( empty( $params['overwrite'] ) &&
146 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
148 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
149 return $status;
151 } catch ( NoSuchContainerException $e ) {
152 $status->fatal( 'backend-fail-create', $params['dst'] );
153 return $status;
154 } catch ( CloudFilesException $e ) { // some other exception?
155 $this->handleException( $e, $status, __METHOD__, $params );
156 return $status;
159 // (b) Get a SHA-1 hash of the object
160 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
162 // (c) Actually create the object
163 try {
164 // Create a fresh CF_Object with no fields preloaded.
165 // We don't want to preserve headers, metadata, and such.
166 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
167 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
168 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
169 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
170 // The MD5 here will be checked within Swift against its own MD5.
171 $obj->set_etag( md5( $params['content'] ) );
172 // Use the same content type as StreamFile for security
173 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
174 if ( !empty( $params['async'] ) ) { // deferred
175 $handle = $obj->write_async( $params['content'] );
176 $status->value = new SwiftFileOpHandle( $this, $params, 'Create', $handle );
177 $status->value->affectedObjects[] = $obj;
178 } else { // actually write the object in Swift
179 $obj->write( $params['content'] );
180 $this->purgeCDNCache( array( $obj ) );
182 } catch ( CDNNotEnabledException $e ) {
183 // CDN not enabled; nothing to see here
184 } catch ( BadContentTypeException $e ) {
185 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
186 } catch ( CloudFilesException $e ) { // some other exception?
187 $this->handleException( $e, $status, __METHOD__, $params );
190 return $status;
194 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
196 protected function _getResponseCreate( CF_Async_Op $cfOp, Status $status, array $params ) {
197 try {
198 $cfOp->getLastResponse();
199 } catch ( BadContentTypeException $e ) {
200 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
205 * @see FileBackendStore::doStoreInternal()
206 * @return Status
208 protected function doStoreInternal( array $params ) {
209 $status = Status::newGood();
211 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
212 if ( $dstRel === null ) {
213 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
214 return $status;
217 // (a) Check the destination container and object
218 try {
219 $dContObj = $this->getContainer( $dstCont );
220 if ( empty( $params['overwrite'] ) &&
221 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
223 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
224 return $status;
226 } catch ( NoSuchContainerException $e ) {
227 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
228 return $status;
229 } catch ( CloudFilesException $e ) { // some other exception?
230 $this->handleException( $e, $status, __METHOD__, $params );
231 return $status;
234 // (b) Get a SHA-1 hash of the object
235 $sha1Hash = sha1_file( $params['src'] );
236 if ( $sha1Hash === false ) { // source doesn't exist?
237 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
238 return $status;
240 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
242 // (c) Actually store the object
243 try {
244 // Create a fresh CF_Object with no fields preloaded.
245 // We don't want to preserve headers, metadata, and such.
246 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
247 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
248 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
249 // The MD5 here will be checked within Swift against its own MD5.
250 $obj->set_etag( md5_file( $params['src'] ) );
251 // Use the same content type as StreamFile for security
252 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
253 if ( !empty( $params['async'] ) ) { // deferred
254 wfSuppressWarnings();
255 $fp = fopen( $params['src'], 'rb' );
256 wfRestoreWarnings();
257 if ( !$fp ) {
258 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
259 } else {
260 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
261 $status->value = new SwiftFileOpHandle( $this, $params, 'Store', $handle );
262 $status->value->resourcesToClose[] = $fp;
263 $status->value->affectedObjects[] = $obj;
265 } else { // actually write the object in Swift
266 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
267 $this->purgeCDNCache( array( $obj ) );
269 } catch ( CDNNotEnabledException $e ) {
270 // CDN not enabled; nothing to see here
271 } catch ( BadContentTypeException $e ) {
272 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
273 } catch ( IOException $e ) {
274 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
275 } catch ( CloudFilesException $e ) { // some other exception?
276 $this->handleException( $e, $status, __METHOD__, $params );
279 return $status;
283 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
285 protected function _getResponseStore( CF_Async_Op $cfOp, Status $status, array $params ) {
286 try {
287 $cfOp->getLastResponse();
288 } catch ( BadContentTypeException $e ) {
289 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
290 } catch ( IOException $e ) {
291 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
296 * @see FileBackendStore::doCopyInternal()
297 * @return Status
299 protected function doCopyInternal( array $params ) {
300 $status = Status::newGood();
302 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
303 if ( $srcRel === null ) {
304 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
305 return $status;
308 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
309 if ( $dstRel === null ) {
310 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
311 return $status;
314 // (a) Check the source/destination containers and destination object
315 try {
316 $sContObj = $this->getContainer( $srcCont );
317 $dContObj = $this->getContainer( $dstCont );
318 if ( empty( $params['overwrite'] ) &&
319 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
321 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
322 return $status;
324 } catch ( NoSuchContainerException $e ) {
325 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
326 return $status;
327 } catch ( CloudFilesException $e ) { // some other exception?
328 $this->handleException( $e, $status, __METHOD__, $params );
329 return $status;
332 // (b) Actually copy the file to the destination
333 try {
334 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
335 if ( !empty( $params['async'] ) ) { // deferred
336 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
337 $status->value = new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
338 $status->value->affectedObjects[] = $dstObj;
339 } else { // actually write the object in Swift
340 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
341 $this->purgeCDNCache( array( $dstObj ) );
343 } catch ( CDNNotEnabledException $e ) {
344 // CDN not enabled; nothing to see here
345 } catch ( NoSuchObjectException $e ) { // source object does not exist
346 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
347 } catch ( CloudFilesException $e ) { // some other exception?
348 $this->handleException( $e, $status, __METHOD__, $params );
351 return $status;
355 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
357 protected function _getResponseCopy( CF_Async_Op $cfOp, Status $status, array $params ) {
358 try {
359 $cfOp->getLastResponse();
360 } catch ( NoSuchObjectException $e ) { // source object does not exist
361 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
366 * @see FileBackendStore::doMoveInternal()
367 * @return Status
369 protected function doMoveInternal( array $params ) {
370 $status = Status::newGood();
372 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
373 if ( $srcRel === null ) {
374 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
375 return $status;
378 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
379 if ( $dstRel === null ) {
380 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
381 return $status;
384 // (a) Check the source/destination containers and destination object
385 try {
386 $sContObj = $this->getContainer( $srcCont );
387 $dContObj = $this->getContainer( $dstCont );
388 if ( empty( $params['overwrite'] ) &&
389 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
391 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
392 return $status;
394 } catch ( NoSuchContainerException $e ) {
395 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
396 return $status;
397 } catch ( CloudFilesException $e ) { // some other exception?
398 $this->handleException( $e, $status, __METHOD__, $params );
399 return $status;
402 // (b) Actually move the file to the destination
403 try {
404 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
405 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
406 if ( !empty( $params['async'] ) ) { // deferred
407 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
408 $status->value = new SwiftFileOpHandle( $this, $params, 'Move', $handle );
409 $status->value->affectedObjects[] = $srcObj;
410 $status->value->affectedObjects[] = $dstObj;
411 } else { // actually write the object in Swift
412 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
413 $this->purgeCDNCache( array( $srcObj, $dstObj ) );
415 } catch ( CDNNotEnabledException $e ) {
416 // CDN not enabled; nothing to see here
417 } catch ( NoSuchObjectException $e ) { // source object does not exist
418 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
419 } catch ( CloudFilesException $e ) { // some other exception?
420 $this->handleException( $e, $status, __METHOD__, $params );
423 return $status;
427 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
429 protected function _getResponseMove( CF_Async_Op $cfOp, Status $status, array $params ) {
430 try {
431 $cfOp->getLastResponse();
432 } catch ( NoSuchObjectException $e ) { // source object does not exist
433 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
438 * @see FileBackendStore::doDeleteInternal()
439 * @return Status
441 protected function doDeleteInternal( array $params ) {
442 $status = Status::newGood();
444 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
445 if ( $srcRel === null ) {
446 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
447 return $status;
450 try {
451 $sContObj = $this->getContainer( $srcCont );
452 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
453 if ( !empty( $params['async'] ) ) { // deferred
454 $handle = $sContObj->delete_object_async( $srcRel );
455 $status->value = new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
456 $status->value->affectedObjects[] = $srcObj;
457 } else { // actually write the object in Swift
458 $sContObj->delete_object( $srcRel );
459 $this->purgeCDNCache( array( $srcObj ) );
461 } catch ( CDNNotEnabledException $e ) {
462 // CDN not enabled; nothing to see here
463 } catch ( NoSuchContainerException $e ) {
464 $status->fatal( 'backend-fail-delete', $params['src'] );
465 } catch ( NoSuchObjectException $e ) {
466 if ( empty( $params['ignoreMissingSource'] ) ) {
467 $status->fatal( 'backend-fail-delete', $params['src'] );
469 } catch ( CloudFilesException $e ) { // some other exception?
470 $this->handleException( $e, $status, __METHOD__, $params );
473 return $status;
477 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
479 protected function _getResponseDelete( CF_Async_Op $cfOp, Status $status, array $params ) {
480 try {
481 $cfOp->getLastResponse();
482 } catch ( NoSuchContainerException $e ) {
483 $status->fatal( 'backend-fail-delete', $params['src'] );
484 } catch ( NoSuchObjectException $e ) {
485 if ( empty( $params['ignoreMissingSource'] ) ) {
486 $status->fatal( 'backend-fail-delete', $params['src'] );
492 * @see FileBackendStore::doPrepareInternal()
493 * @return Status
495 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
496 $status = Status::newGood();
498 // (a) Check if container already exists
499 try {
500 $contObj = $this->getContainer( $fullCont );
501 // NoSuchContainerException not thrown: container must exist
502 return $status; // already exists
503 } catch ( NoSuchContainerException $e ) {
504 // NoSuchContainerException thrown: container does not exist
505 } catch ( CloudFilesException $e ) { // some other exception?
506 $this->handleException( $e, $status, __METHOD__, $params );
507 return $status;
510 // (b) Create container as needed
511 try {
512 $contObj = $this->createContainer( $fullCont );
513 // Make container public to end-users...
514 if ( $this->swiftAnonUser != '' ) {
515 $status->merge( $this->setContainerAccess(
516 $contObj,
517 array( $this->auth->username, $this->swiftAnonUser ), // read
518 array( $this->auth->username ) // write
519 ) );
521 if ( $this->swiftUseCDN ) { // Rackspace style CDN
522 $contObj->make_public();
524 } catch ( CDNNotEnabledException $e ) {
525 // CDN not enabled; nothing to see here
526 } catch ( CloudFilesException $e ) { // some other exception?
527 $this->handleException( $e, $status, __METHOD__, $params );
528 return $status;
531 return $status;
535 * @see FileBackendStore::doSecureInternal()
536 * @return Status
538 protected function doSecureInternal( $fullCont, $dir, array $params ) {
539 $status = Status::newGood();
541 // Restrict container from end-users...
542 try {
543 // doPrepareInternal() should have been called,
544 // so the Swift container should already exist...
545 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
546 // NoSuchContainerException not thrown: container must exist
548 // Make container private to end-users...
549 if ( $this->swiftAnonUser != '' && !isset( $contObj->mw_wasSecured ) ) {
550 $status->merge( $this->setContainerAccess(
551 $contObj,
552 array( $this->auth->username ), // read
553 array( $this->auth->username ) // write
554 ) );
555 // @TODO: when php-cloudfiles supports container
556 // metadata, we can make use of that to avoid RTTs
557 $contObj->mw_wasSecured = true; // avoid useless RTTs
559 if ( $this->swiftUseCDN && $contObj->is_public() ) { // Rackspace style CDN
560 $contObj->make_private();
562 } catch ( CDNNotEnabledException $e ) {
563 // CDN not enabled; nothing to see here
564 } catch ( CloudFilesException $e ) { // some other exception?
565 $this->handleException( $e, $status, __METHOD__, $params );
568 return $status;
572 * @see FileBackendStore::doCleanInternal()
573 * @return Status
575 protected function doCleanInternal( $fullCont, $dir, array $params ) {
576 $status = Status::newGood();
578 // Only containers themselves can be removed, all else is virtual
579 if ( $dir != '' ) {
580 return $status; // nothing to do
583 // (a) Check the container
584 try {
585 $contObj = $this->getContainer( $fullCont, true );
586 } catch ( NoSuchContainerException $e ) {
587 return $status; // ok, nothing to do
588 } catch ( CloudFilesException $e ) { // some other exception?
589 $this->handleException( $e, $status, __METHOD__, $params );
590 return $status;
593 // (b) Delete the container if empty
594 if ( $contObj->object_count == 0 ) {
595 try {
596 $this->deleteContainer( $fullCont );
597 } catch ( NoSuchContainerException $e ) {
598 return $status; // race?
599 } catch ( NonEmptyContainerException $e ) {
600 return $status; // race? consistency delay?
601 } catch ( CloudFilesException $e ) { // some other exception?
602 $this->handleException( $e, $status, __METHOD__, $params );
603 return $status;
607 return $status;
611 * @see FileBackendStore::doFileExists()
612 * @return array|bool|null
614 protected function doGetFileStat( array $params ) {
615 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
616 if ( $srcRel === null ) {
617 return false; // invalid storage path
620 $stat = false;
621 try {
622 $contObj = $this->getContainer( $srcCont );
623 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
624 $this->addMissingMetadata( $srcObj, $params['src'] );
625 $stat = array(
626 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
627 'mtime' => wfTimestamp( TS_MW, $srcObj->last_modified ),
628 'size' => $srcObj->content_length,
629 'sha1' => $srcObj->metadata['Sha1base36']
631 } catch ( NoSuchContainerException $e ) {
632 } catch ( NoSuchObjectException $e ) {
633 } catch ( CloudFilesException $e ) { // some other exception?
634 $stat = null;
635 $this->handleException( $e, null, __METHOD__, $params );
638 return $stat;
642 * Fill in any missing object metadata and save it to Swift
644 * @param $obj CF_Object
645 * @param $path string Storage path to object
646 * @return bool Success
647 * @throws Exception cloudfiles exceptions
649 protected function addMissingMetadata( CF_Object $obj, $path ) {
650 if ( isset( $obj->metadata['Sha1base36'] ) ) {
651 return true; // nothing to do
653 $status = Status::newGood();
654 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
655 if ( $status->isOK() ) {
656 # Do not stat the file in getLocalCopy() to avoid infinite loops
657 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
658 if ( $tmpFile ) {
659 $hash = $tmpFile->getSha1Base36();
660 if ( $hash !== false ) {
661 $obj->metadata['Sha1base36'] = $hash;
662 $obj->sync_metadata(); // save to Swift
663 return true; // success
667 $obj->metadata['Sha1base36'] = false;
668 return false; // failed
672 * @see FileBackend::getFileContents()
673 * @return bool|null|string
675 public function getFileContents( array $params ) {
676 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
677 if ( $srcRel === null ) {
678 return false; // invalid storage path
681 if ( !$this->fileExists( $params ) ) {
682 return null;
685 $data = false;
686 try {
687 $sContObj = $this->getContainer( $srcCont );
688 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
689 $data = $obj->read( $this->headersFromParams( $params ) );
690 } catch ( NoSuchContainerException $e ) {
691 } catch ( CloudFilesException $e ) { // some other exception?
692 $this->handleException( $e, null, __METHOD__, $params );
695 return $data;
699 * @see FileBackendStore::doDirectoryExists()
700 * @return bool|null
702 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
703 try {
704 $container = $this->getContainer( $fullCont );
705 $prefix = ( $dir == '' ) ? null : "{$dir}/";
706 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
707 } catch ( NoSuchContainerException $e ) {
708 return false;
709 } catch ( CloudFilesException $e ) { // some other exception?
710 $this->handleException( $e, null, __METHOD__,
711 array( 'cont' => $fullCont, 'dir' => $dir ) );
714 return null; // error
718 * @see FileBackendStore::getDirectoryListInternal()
719 * @return SwiftFileBackendDirList
721 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
722 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
726 * @see FileBackendStore::getFileListInternal()
727 * @return SwiftFileBackendFileList
729 public function getFileListInternal( $fullCont, $dir, array $params ) {
730 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
734 * Do not call this function outside of SwiftFileBackendFileList
736 * @param $fullCont string Resolved container name
737 * @param $dir string Resolved storage directory with no trailing slash
738 * @param $after string|null Storage path of file to list items after
739 * @param $limit integer Max number of items to list
740 * @param $params Array Includes flag for 'topOnly'
741 * @return Array List of relative paths of dirs directly under $dir
743 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
744 wfProfileIn( __METHOD__ . '-' . $this->name );
746 $dirs = array();
747 try {
748 $container = $this->getContainer( $fullCont );
749 $prefix = ( $dir == '' ) ? null : "{$dir}/";
750 // Non-recursive: only list dirs right under $dir
751 if ( !empty( $params['topOnly'] ) ) {
752 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
753 foreach ( $objects as $object ) { // files and dirs
754 if ( substr( $object, -1 ) === '/' ) {
755 $dirs[] = $object; // directories end in '/'
757 $after = $object; // update last item
759 // Recursive: list all dirs under $dir and its subdirs
760 } else {
761 // Get directory from last item of prior page
762 $lastDir = $this->getParentDir( $after ); // must be first page
763 $objects = $container->list_objects( $limit, $after, $prefix );
764 foreach ( $objects as $object ) { // files
765 $objectDir = $this->getParentDir( $object ); // directory of object
766 if ( $objectDir !== false ) { // file has a parent dir
767 // Swift stores paths in UTF-8, using binary sorting.
768 // See function "create_container_table" in common/db.py.
769 // If a directory is not "greater" than the last one,
770 // then it was already listed by the calling iterator.
771 if ( $objectDir > $lastDir ) {
772 $pDir = $objectDir;
773 do { // add dir and all its parent dirs
774 $dirs[] = "{$pDir}/";
775 $pDir = $this->getParentDir( $pDir );
776 } while ( $pDir !== false // sanity
777 && $pDir > $lastDir // not done already
778 && strlen( $pDir ) > strlen( $dir ) // within $dir
781 $lastDir = $objectDir;
783 $after = $object; // update last item
786 } catch ( NoSuchContainerException $e ) {
787 } catch ( CloudFilesException $e ) { // some other exception?
788 $this->handleException( $e, null, __METHOD__,
789 array( 'cont' => $fullCont, 'dir' => $dir ) );
792 wfProfileOut( __METHOD__ . '-' . $this->name );
793 return $dirs;
796 protected function getParentDir( $path ) {
797 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
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 files under $dir
810 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
811 wfProfileIn( __METHOD__ . '-' . $this->name );
813 $files = array();
814 try {
815 $container = $this->getContainer( $fullCont );
816 $prefix = ( $dir == '' ) ? null : "{$dir}/";
817 // Non-recursive: only list files right under $dir
818 if ( !empty( $params['topOnly'] ) ) { // files and dirs
819 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
820 foreach ( $objects as $object ) {
821 if ( substr( $object, -1 ) !== '/' ) {
822 $files[] = $object; // directories end in '/'
825 // Recursive: list all files under $dir and its subdirs
826 } else { // files
827 $files = $container->list_objects( $limit, $after, $prefix );
829 $after = end( $files ); // update last item
830 reset( $files ); // reset pointer
831 } catch ( NoSuchContainerException $e ) {
832 } catch ( CloudFilesException $e ) { // some other exception?
833 $this->handleException( $e, null, __METHOD__,
834 array( 'cont' => $fullCont, 'dir' => $dir ) );
837 wfProfileOut( __METHOD__ . '-' . $this->name );
838 return $files;
842 * @see FileBackendStore::doGetFileSha1base36()
843 * @return bool
845 protected function doGetFileSha1base36( array $params ) {
846 $stat = $this->getFileStat( $params );
847 if ( $stat ) {
848 return $stat['sha1'];
849 } else {
850 return false;
855 * @see FileBackendStore::doStreamFile()
856 * @return Status
858 protected function doStreamFile( array $params ) {
859 $status = Status::newGood();
861 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
862 if ( $srcRel === null ) {
863 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
866 try {
867 $cont = $this->getContainer( $srcCont );
868 } catch ( NoSuchContainerException $e ) {
869 $status->fatal( 'backend-fail-stream', $params['src'] );
870 return $status;
871 } catch ( CloudFilesException $e ) { // some other exception?
872 $this->handleException( $e, $status, __METHOD__, $params );
873 return $status;
876 try {
877 $output = fopen( 'php://output', 'wb' );
878 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
879 $obj->stream( $output, $this->headersFromParams( $params ) );
880 } catch ( CloudFilesException $e ) { // some other exception?
881 $this->handleException( $e, $status, __METHOD__, $params );
884 return $status;
888 * @see FileBackendStore::getLocalCopy()
889 * @return null|TempFSFile
891 public function getLocalCopy( array $params ) {
892 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
893 if ( $srcRel === null ) {
894 return null;
897 # Check the recursion guard to avoid loops when filling metadata
898 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
899 return null;
902 $tmpFile = null;
903 try {
904 $sContObj = $this->getContainer( $srcCont );
905 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
906 // Get source file extension
907 $ext = FileBackend::extensionFromPath( $srcRel );
908 // Create a new temporary file...
909 $tmpFile = TempFSFile::factory( wfBaseName( $srcRel ) . '_', $ext );
910 if ( $tmpFile ) {
911 $handle = fopen( $tmpFile->getPath(), 'wb' );
912 if ( $handle ) {
913 $obj->stream( $handle, $this->headersFromParams( $params ) );
914 fclose( $handle );
915 } else {
916 $tmpFile = null; // couldn't open temp file
919 } catch ( NoSuchContainerException $e ) {
920 $tmpFile = null;
921 } catch ( CloudFilesException $e ) { // some other exception?
922 $tmpFile = null;
923 $this->handleException( $e, null, __METHOD__, $params );
926 return $tmpFile;
930 * @see FileBackendStore::directoriesAreVirtual()
931 * @return bool
933 protected function directoriesAreVirtual() {
934 return true;
938 * Get headers to send to Swift when reading a file based
939 * on a FileBackend params array, e.g. that of getLocalCopy().
940 * $params is currently only checked for a 'latest' flag.
942 * @param $params Array
943 * @return Array
945 protected function headersFromParams( array $params ) {
946 $hdrs = array();
947 if ( !empty( $params['latest'] ) ) {
948 $hdrs[] = 'X-Newest: true';
950 return $hdrs;
954 * @see FileBackendStore::doExecuteOpHandlesInternal()
955 * @return Array List of corresponding Status objects
957 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
958 $statuses = array();
960 $cfOps = array(); // list of CF_Async_Op objects
961 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
962 $cfOps[$index] = $fileOpHandle->cfOp;
964 $batch = new CF_Async_Op_Batch( $cfOps );
966 $cfOps = $batch->execute();
967 foreach ( $cfOps as $index => $cfOp ) {
968 $status = Status::newGood();
969 try { // catch exceptions; update status
970 $function = '_getResponse' . $fileOpHandles[$index]->call;
971 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
972 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
973 } catch ( CloudFilesException $e ) { // some other exception?
974 $this->handleException( $e, $status,
975 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
977 $statuses[$index] = $status;
980 return $statuses;
984 * Set read/write permissions for a Swift container
986 * @param $contObj CF_Container Swift container
987 * @param $readGrps Array Swift users who can read (account:user)
988 * @param $writeGrps Array Swift users who can write (account:user)
989 * @return Status
991 protected function setContainerAccess(
992 CF_Container $contObj, array $readGrps, array $writeGrps
994 $creds = $contObj->cfs_auth->export_credentials();
996 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
998 // Note: 10 second timeout consistent with php-cloudfiles
999 $req = new CurlHttpRequest( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1000 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1001 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1002 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1004 return $req->execute(); // should return 204
1008 * Purge the CDN cache of affected objects if CDN caching is enabled
1010 * @param $objects Array List of CF_Object items
1011 * @return void
1013 public function purgeCDNCache( array $objects ) {
1014 if ( $this->swiftUseCDN ) { // Rackspace style CDN
1015 foreach ( $objects as $object ) {
1016 try {
1017 $object->purge_from_cdn();
1018 } catch ( CDNNotEnabledException $e ) {
1019 // CDN not enabled; nothing to see here
1020 } catch ( CloudFilesException $e ) {
1021 $this->handleException( $e, null, __METHOD__,
1022 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1029 * Get a connection to the Swift proxy
1031 * @return CF_Connection|bool False on failure
1032 * @throws CloudFilesException
1034 protected function getConnection() {
1035 if ( $this->connException instanceof Exception ) {
1036 throw $this->connException; // failed last attempt
1038 // Session keys expire after a while, so we renew them periodically
1039 if ( $this->conn && ( time() - $this->connStarted ) > $this->authTTL ) {
1040 $this->conn->close(); // close active cURL connections
1041 $this->conn = null;
1043 // Authenticate with proxy and get a session key...
1044 if ( !$this->conn ) {
1045 $this->connStarted = 0;
1046 $this->connContainers = array();
1047 try {
1048 $this->auth->authenticate();
1049 $this->conn = new CF_Connection( $this->auth );
1050 $this->connStarted = time();
1051 } catch ( CloudFilesException $e ) {
1052 $this->connException = $e; // don't keep re-trying
1053 throw $e; // throw it back
1056 return $this->conn;
1060 * @see FileBackendStore::doClearCache()
1062 protected function doClearCache( array $paths = null ) {
1063 $this->connContainers = array(); // clear container object cache
1067 * Get a Swift container object, possibly from process cache.
1068 * Use $reCache if the file count or byte count is needed.
1070 * @param $container string Container name
1071 * @param $bypassCache bool Bypass all caches and load from Swift
1072 * @return CF_Container
1073 * @throws CloudFilesException
1075 protected function getContainer( $container, $bypassCache = false ) {
1076 $conn = $this->getConnection(); // Swift proxy connection
1077 if ( $bypassCache ) { // purge cache
1078 unset( $this->connContainers[$container] );
1079 } elseif ( !isset( $this->connContainers[$container] ) ) {
1080 $this->primeContainerCache( array( $container ) ); // check persistent cache
1082 if ( !isset( $this->connContainers[$container] ) ) {
1083 $contObj = $conn->get_container( $container );
1084 // NoSuchContainerException not thrown: container must exist
1085 if ( count( $this->connContainers ) >= $this->maxContCacheSize ) { // trim cache?
1086 reset( $this->connContainers );
1087 unset( $this->connContainers[key( $this->connContainers )] );
1089 $this->connContainers[$container] = $contObj; // cache it
1090 if ( !$bypassCache ) {
1091 $this->setContainerCache( $container, // update persistent cache
1092 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1096 return $this->connContainers[$container];
1100 * Create a Swift container
1102 * @param $container string Container name
1103 * @return CF_Container
1104 * @throws InvalidResponseException
1106 protected function createContainer( $container ) {
1107 $conn = $this->getConnection(); // Swift proxy connection
1108 $contObj = $conn->create_container( $container );
1109 $this->connContainers[$container] = $contObj; // cache it
1110 return $contObj;
1114 * Delete a Swift container
1116 * @param $container string Container name
1117 * @return void
1118 * @throws InvalidResponseException
1120 protected function deleteContainer( $container ) {
1121 $conn = $this->getConnection(); // Swift proxy connection
1122 $conn->delete_container( $container );
1123 unset( $this->connContainers[$container] ); // purge cache
1127 * @see FileBackendStore::doPrimeContainerCache()
1128 * @return void
1130 protected function doPrimeContainerCache( array $containerInfo ) {
1131 try {
1132 $conn = $this->getConnection(); // Swift proxy connection
1133 foreach ( $containerInfo as $container => $info ) {
1134 $this->connContainers[$container] = new CF_Container(
1135 $conn->cfs_auth,
1136 $conn->cfs_http,
1137 $container,
1138 $info['count'],
1139 $info['bytes']
1142 } catch ( CloudFilesException $e ) { // some other exception?
1143 $this->handleException( $e, null, __METHOD__, array() );
1148 * Log an unexpected exception for this backend.
1149 * This also sets the Status object to have a fatal error.
1151 * @param $e Exception
1152 * @param $status Status|null
1153 * @param $func string
1154 * @param $params Array
1155 * @return void
1157 protected function handleException( Exception $e, $status, $func, array $params ) {
1158 if ( $status instanceof Status ) {
1159 if ( $e instanceof AuthenticationException ) {
1160 $status->fatal( 'backend-fail-connect', $this->name );
1161 } else {
1162 $status->fatal( 'backend-fail-internal', $this->name );
1165 if ( $e->getMessage() ) {
1166 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1168 wfDebugLog( 'SwiftBackend',
1169 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1170 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1176 * @see FileBackendStoreOpHandle
1178 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1179 /** @var CF_Async_Op */
1180 public $cfOp;
1181 /** @var Array */
1182 public $affectedObjects = array();
1184 public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
1185 $this->backend = $backend;
1186 $this->params = $params;
1187 $this->call = $call;
1188 $this->cfOp = $cfOp;
1193 * SwiftFileBackend helper class to page through listings.
1194 * Swift also has a listing limit of 10,000 objects for sanity.
1195 * Do not use this class from places outside SwiftFileBackend.
1197 * @ingroup FileBackend
1199 abstract class SwiftFileBackendList implements Iterator {
1200 /** @var Array */
1201 protected $bufferIter = array();
1202 protected $bufferAfter = null; // string; list items *after* this path
1203 protected $pos = 0; // integer
1204 /** @var Array */
1205 protected $params = array();
1207 /** @var SwiftFileBackend */
1208 protected $backend;
1209 protected $container; // string; container name
1210 protected $dir; // string; storage directory
1211 protected $suffixStart; // integer
1213 const PAGE_SIZE = 5000; // file listing buffer size
1216 * @param $backend SwiftFileBackend
1217 * @param $fullCont string Resolved container name
1218 * @param $dir string Resolved directory relative to container
1219 * @param $params Array
1221 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1222 $this->backend = $backend;
1223 $this->container = $fullCont;
1224 $this->dir = $dir;
1225 if ( substr( $this->dir, -1 ) === '/' ) {
1226 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1228 if ( $this->dir == '' ) { // whole container
1229 $this->suffixStart = 0;
1230 } else { // dir within container
1231 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1233 $this->params = $params;
1237 * @see Iterator::key()
1238 * @return integer
1240 public function key() {
1241 return $this->pos;
1245 * @see Iterator::next()
1246 * @return void
1248 public function next() {
1249 // Advance to the next file in the page
1250 next( $this->bufferIter );
1251 ++$this->pos;
1252 // Check if there are no files left in this page and
1253 // advance to the next page if this page was not empty.
1254 if ( !$this->valid() && count( $this->bufferIter ) ) {
1255 $this->bufferIter = $this->pageFromList(
1256 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1257 ); // updates $this->bufferAfter
1262 * @see Iterator::rewind()
1263 * @return void
1265 public function rewind() {
1266 $this->pos = 0;
1267 $this->bufferAfter = null;
1268 $this->bufferIter = $this->pageFromList(
1269 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1270 ); // updates $this->bufferAfter
1274 * @see Iterator::valid()
1275 * @return bool
1277 public function valid() {
1278 if ( $this->bufferIter === null ) {
1279 return false; // some failure?
1280 } else {
1281 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1286 * Get the given list portion (page)
1288 * @param $container string Resolved container name
1289 * @param $dir string Resolved path relative to container
1290 * @param $after string|null
1291 * @param $limit integer
1292 * @param $params Array
1293 * @return Traversable|Array|null Returns null on failure
1295 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1299 * Iterator for listing directories
1301 class SwiftFileBackendDirList extends SwiftFileBackendList {
1303 * @see Iterator::current()
1304 * @return string|bool String (relative path) or false
1306 public function current() {
1307 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1311 * @see SwiftFileBackendList::pageFromList()
1312 * @return Array|null
1314 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1315 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1320 * Iterator for listing regular files
1322 class SwiftFileBackendFileList extends SwiftFileBackendList {
1324 * @see Iterator::current()
1325 * @return string|bool String (relative path) or false
1327 public function current() {
1328 return substr( current( $this->bufferIter ), $this->suffixStart );
1332 * @see SwiftFileBackendList::pageFromList()
1333 * @return Array|null
1335 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1336 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );