5be86e68079c1a80efbc9b19e6504bf6e2a02b87
[lhc/web/wiklou.git] / includes / filebackend / SwiftFileBackend.php
1 <?php
2 /**
3 * OpenStack Swift based file backend.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup FileBackend
22 * @author Russ Nelson
23 * @author Aaron Schulz
24 */
25
26 /**
27 * @brief Class for an OpenStack Swift based file backend.
28 *
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.
32 *
33 * Status messages should avoid mentioning the Swift account name.
34 * Likewise, error suppression should be used to avoid path disclosure.
35 *
36 * @ingroup FileBackend
37 * @since 1.19
38 */
39 class SwiftFileBackend extends FileBackendStore {
40 /** @var CF_Authentication */
41 protected $auth; // Swift authentication handler
42 protected $authTTL; // integer seconds
43 protected $swiftAnonUser; // string; username to handle unauthenticated requests
44 protected $swiftUseCDN; // boolean; whether CloudFiles CDN is enabled
45 protected $swiftCDNExpiry; // integer; how long to cache things in the CDN
46 protected $swiftCDNPurgable; // boolean; whether object CDN purging is enabled
47
48 protected $maxContCacheSize = 300; // integer; max containers with entries
49
50 /** @var CF_Connection */
51 protected $conn; // Swift connection handle
52 protected $connStarted = 0; // integer UNIX timestamp
53 protected $connContainers = array(); // container object cache
54 protected $connException; // CloudFiles exception
55
56 /**
57 * @see FileBackendStore::__construct()
58 * Additional $config params include:
59 * - swiftAuthUrl : Swift authentication server URL
60 * - swiftUser : Swift user used by MediaWiki (account:username)
61 * - swiftKey : Swift authentication key for the above user
62 * - swiftAuthTTL : Swift authentication TTL (seconds)
63 * - swiftAnonUser : Swift user used for end-user requests (account:username).
64 * If set, then views of public containers are assumed to go
65 * through this user. If not set, then public containers are
66 * accessible to unauthenticated requests via ".r:*" in the ACL.
67 * - swiftUseCDN : Whether a Cloud Files Content Delivery Network is set up
68 * - swiftCDNExpiry : How long (in seconds) to store content in the CDN.
69 * If files may likely change, this should probably not exceed
70 * a few days. For example, deletions may take this long to apply.
71 * If object purging is enabled, however, this is not an issue.
72 * - swiftCDNPurgable : Whether object purge requests are allowed by the CDN.
73 * - shardViaHashLevels : Map of container names to sharding config with:
74 * - base : base of hash characters, 16 or 36
75 * - levels : the number of hash levels (and digits)
76 * - repeat : hash subdirectories are prefixed with all the
77 * parent hash directory names (e.g. "a/ab/abc")
78 */
79 public function __construct( array $config ) {
80 parent::__construct( $config );
81 if ( !MWInit::classExists( 'CF_Constants' ) ) {
82 throw new MWException( 'SwiftCloudFiles extension not installed.' );
83 }
84 // Required settings
85 $this->auth = new CF_Authentication(
86 $config['swiftUser'],
87 $config['swiftKey'],
88 null, // account; unused
89 $config['swiftAuthUrl']
90 );
91 // Optional settings
92 $this->authTTL = isset( $config['swiftAuthTTL'] )
93 ? $config['swiftAuthTTL']
94 : 5 * 60; // some sane number
95 $this->swiftAnonUser = isset( $config['swiftAnonUser'] )
96 ? $config['swiftAnonUser']
97 : '';
98 $this->shardViaHashLevels = isset( $config['shardViaHashLevels'] )
99 ? $config['shardViaHashLevels']
100 : '';
101 $this->swiftUseCDN = isset( $config['swiftUseCDN'] )
102 ? $config['swiftUseCDN']
103 : false;
104 $this->swiftCDNExpiry = isset( $config['swiftCDNExpiry'] )
105 ? $config['swiftCDNExpiry']
106 : 3600; // hour
107 $this->swiftCDNPurgable = isset( $config['swiftCDNPurgable'] )
108 ? $config['swiftCDNPurgable']
109 : true;
110 // Cache container info to mask latency
111 $this->memCache = wfGetMainCache();
112 }
113
114 /**
115 * @see FileBackendStore::resolveContainerPath()
116 * @return null
117 */
118 protected function resolveContainerPath( $container, $relStoragePath ) {
119 if ( strlen( urlencode( $relStoragePath ) ) > 1024 ) {
120 return null; // too long for Swift
121 }
122 return $relStoragePath;
123 }
124
125 /**
126 * @see FileBackendStore::isPathUsableInternal()
127 * @return bool
128 */
129 public function isPathUsableInternal( $storagePath ) {
130 list( $container, $rel ) = $this->resolveStoragePathReal( $storagePath );
131 if ( $rel === null ) {
132 return false; // invalid
133 }
134
135 try {
136 $this->getContainer( $container );
137 return true; // container exists
138 } catch ( NoSuchContainerException $e ) {
139 } catch ( CloudFilesException $e ) { // some other exception?
140 $this->handleException( $e, null, __METHOD__, array( 'path' => $storagePath ) );
141 }
142
143 return false;
144 }
145
146 /**
147 * @see FileBackendStore::doCreateInternal()
148 * @return Status
149 */
150 protected function doCreateInternal( array $params ) {
151 $status = Status::newGood();
152
153 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
154 if ( $dstRel === null ) {
155 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
156 return $status;
157 }
158
159 // (a) Check the destination container and object
160 try {
161 $dContObj = $this->getContainer( $dstCont );
162 if ( empty( $params['overwrite'] ) &&
163 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
164 {
165 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
166 return $status;
167 }
168 } catch ( NoSuchContainerException $e ) {
169 $status->fatal( 'backend-fail-create', $params['dst'] );
170 return $status;
171 } catch ( CloudFilesException $e ) { // some other exception?
172 $this->handleException( $e, $status, __METHOD__, $params );
173 return $status;
174 }
175
176 // (b) Get a SHA-1 hash of the object
177 $sha1Hash = wfBaseConvert( sha1( $params['content'] ), 16, 36, 31 );
178
179 // (c) Actually create the object
180 try {
181 // Create a fresh CF_Object with no fields preloaded.
182 // We don't want to preserve headers, metadata, and such.
183 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
184 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
185 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
186 // Manually set the ETag (https://github.com/rackspace/php-cloudfiles/issues/59).
187 // The MD5 here will be checked within Swift against its own MD5.
188 $obj->set_etag( md5( $params['content'] ) );
189 // Use the same content type as StreamFile for security
190 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
191 if ( !strlen( $obj->content_type ) ) { // special case
192 $obj->content_type = 'unknown/unknown';
193 }
194 if ( !empty( $params['async'] ) ) { // deferred
195 $handle = $obj->write_async( $params['content'] );
196 $status->value = new SwiftFileOpHandle( $this, $params, 'Create', $handle );
197 $status->value->affectedObjects[] = $obj;
198 } else { // actually write the object in Swift
199 $obj->write( $params['content'] );
200 $this->purgeCDNCache( array( $obj ) );
201 }
202 } catch ( CDNNotEnabledException $e ) {
203 // CDN not enabled; nothing to see here
204 } catch ( BadContentTypeException $e ) {
205 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
206 } catch ( CloudFilesException $e ) { // some other exception?
207 $this->handleException( $e, $status, __METHOD__, $params );
208 }
209
210 return $status;
211 }
212
213 /**
214 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
215 */
216 protected function _getResponseCreate( CF_Async_Op $cfOp, Status $status, array $params ) {
217 try {
218 $cfOp->getLastResponse();
219 } catch ( BadContentTypeException $e ) {
220 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
221 }
222 }
223
224 /**
225 * @see FileBackendStore::doStoreInternal()
226 * @return Status
227 */
228 protected function doStoreInternal( array $params ) {
229 $status = Status::newGood();
230
231 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
232 if ( $dstRel === null ) {
233 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
234 return $status;
235 }
236
237 // (a) Check the destination container and object
238 try {
239 $dContObj = $this->getContainer( $dstCont );
240 if ( empty( $params['overwrite'] ) &&
241 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
242 {
243 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
244 return $status;
245 }
246 } catch ( NoSuchContainerException $e ) {
247 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
248 return $status;
249 } catch ( CloudFilesException $e ) { // some other exception?
250 $this->handleException( $e, $status, __METHOD__, $params );
251 return $status;
252 }
253
254 // (b) Get a SHA-1 hash of the object
255 $sha1Hash = sha1_file( $params['src'] );
256 if ( $sha1Hash === false ) { // source doesn't exist?
257 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
258 return $status;
259 }
260 $sha1Hash = wfBaseConvert( $sha1Hash, 16, 36, 31 );
261
262 // (c) Actually store the object
263 try {
264 // Create a fresh CF_Object with no fields preloaded.
265 // We don't want to preserve headers, metadata, and such.
266 $obj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
267 // Note: metadata keys stored as [Upper case char][[Lower case char]...]
268 $obj->metadata = array( 'Sha1base36' => $sha1Hash );
269 // The MD5 here will be checked within Swift against its own MD5.
270 $obj->set_etag( md5_file( $params['src'] ) );
271 // Use the same content type as StreamFile for security
272 $obj->content_type = StreamFile::contentTypeFromPath( $params['dst'] );
273 if ( !strlen( $obj->content_type ) ) { // special case
274 $obj->content_type = 'unknown/unknown';
275 }
276 if ( !empty( $params['async'] ) ) { // deferred
277 wfSuppressWarnings();
278 $fp = fopen( $params['src'], 'rb' );
279 wfRestoreWarnings();
280 if ( !$fp ) {
281 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
282 } else {
283 $handle = $obj->write_async( $fp, filesize( $params['src'] ), true );
284 $status->value = new SwiftFileOpHandle( $this, $params, 'Store', $handle );
285 $status->value->resourcesToClose[] = $fp;
286 $status->value->affectedObjects[] = $obj;
287 }
288 } else { // actually write the object in Swift
289 $obj->load_from_filename( $params['src'], true ); // calls $obj->write()
290 $this->purgeCDNCache( array( $obj ) );
291 }
292 } catch ( CDNNotEnabledException $e ) {
293 // CDN not enabled; nothing to see here
294 } catch ( BadContentTypeException $e ) {
295 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
296 } catch ( IOException $e ) {
297 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
298 } catch ( CloudFilesException $e ) { // some other exception?
299 $this->handleException( $e, $status, __METHOD__, $params );
300 }
301
302 return $status;
303 }
304
305 /**
306 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
307 */
308 protected function _getResponseStore( CF_Async_Op $cfOp, Status $status, array $params ) {
309 try {
310 $cfOp->getLastResponse();
311 } catch ( BadContentTypeException $e ) {
312 $status->fatal( 'backend-fail-contenttype', $params['dst'] );
313 } catch ( IOException $e ) {
314 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
315 }
316 }
317
318 /**
319 * @see FileBackendStore::doCopyInternal()
320 * @return Status
321 */
322 protected function doCopyInternal( array $params ) {
323 $status = Status::newGood();
324
325 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
326 if ( $srcRel === null ) {
327 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
328 return $status;
329 }
330
331 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
332 if ( $dstRel === null ) {
333 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
334 return $status;
335 }
336
337 // (a) Check the source/destination containers and destination object
338 try {
339 $sContObj = $this->getContainer( $srcCont );
340 $dContObj = $this->getContainer( $dstCont );
341 if ( empty( $params['overwrite'] ) &&
342 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
343 {
344 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
345 return $status;
346 }
347 } catch ( NoSuchContainerException $e ) {
348 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
349 return $status;
350 } catch ( CloudFilesException $e ) { // some other exception?
351 $this->handleException( $e, $status, __METHOD__, $params );
352 return $status;
353 }
354
355 // (b) Actually copy the file to the destination
356 try {
357 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
358 if ( !empty( $params['async'] ) ) { // deferred
359 $handle = $sContObj->copy_object_to_async( $srcRel, $dContObj, $dstRel );
360 $status->value = new SwiftFileOpHandle( $this, $params, 'Copy', $handle );
361 $status->value->affectedObjects[] = $dstObj;
362 } else { // actually write the object in Swift
363 $sContObj->copy_object_to( $srcRel, $dContObj, $dstRel );
364 $this->purgeCDNCache( array( $dstObj ) );
365 }
366 } catch ( CDNNotEnabledException $e ) {
367 // CDN not enabled; nothing to see here
368 } catch ( NoSuchObjectException $e ) { // source object does not exist
369 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
370 } catch ( CloudFilesException $e ) { // some other exception?
371 $this->handleException( $e, $status, __METHOD__, $params );
372 }
373
374 return $status;
375 }
376
377 /**
378 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
379 */
380 protected function _getResponseCopy( CF_Async_Op $cfOp, Status $status, array $params ) {
381 try {
382 $cfOp->getLastResponse();
383 } catch ( NoSuchObjectException $e ) { // source object does not exist
384 $status->fatal( 'backend-fail-copy', $params['src'], $params['dst'] );
385 }
386 }
387
388 /**
389 * @see FileBackendStore::doMoveInternal()
390 * @return Status
391 */
392 protected function doMoveInternal( array $params ) {
393 $status = Status::newGood();
394
395 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
396 if ( $srcRel === null ) {
397 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
398 return $status;
399 }
400
401 list( $dstCont, $dstRel ) = $this->resolveStoragePathReal( $params['dst'] );
402 if ( $dstRel === null ) {
403 $status->fatal( 'backend-fail-invalidpath', $params['dst'] );
404 return $status;
405 }
406
407 // (a) Check the source/destination containers and destination object
408 try {
409 $sContObj = $this->getContainer( $srcCont );
410 $dContObj = $this->getContainer( $dstCont );
411 if ( empty( $params['overwrite'] ) &&
412 $this->fileExists( array( 'src' => $params['dst'], 'latest' => 1 ) ) )
413 {
414 $status->fatal( 'backend-fail-alreadyexists', $params['dst'] );
415 return $status;
416 }
417 } catch ( NoSuchContainerException $e ) {
418 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
419 return $status;
420 } catch ( CloudFilesException $e ) { // some other exception?
421 $this->handleException( $e, $status, __METHOD__, $params );
422 return $status;
423 }
424
425 // (b) Actually move the file to the destination
426 try {
427 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
428 $dstObj = new CF_Object( $dContObj, $dstRel, false, false ); // skip HEAD
429 if ( !empty( $params['async'] ) ) { // deferred
430 $handle = $sContObj->move_object_to_async( $srcRel, $dContObj, $dstRel );
431 $status->value = new SwiftFileOpHandle( $this, $params, 'Move', $handle );
432 $status->value->affectedObjects[] = $srcObj;
433 $status->value->affectedObjects[] = $dstObj;
434 } else { // actually write the object in Swift
435 $sContObj->move_object_to( $srcRel, $dContObj, $dstRel );
436 $this->purgeCDNCache( array( $srcObj, $dstObj ) );
437 }
438 } catch ( CDNNotEnabledException $e ) {
439 // CDN not enabled; nothing to see here
440 } catch ( NoSuchObjectException $e ) { // source object does not exist
441 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
442 } catch ( CloudFilesException $e ) { // some other exception?
443 $this->handleException( $e, $status, __METHOD__, $params );
444 }
445
446 return $status;
447 }
448
449 /**
450 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
451 */
452 protected function _getResponseMove( CF_Async_Op $cfOp, Status $status, array $params ) {
453 try {
454 $cfOp->getLastResponse();
455 } catch ( NoSuchObjectException $e ) { // source object does not exist
456 $status->fatal( 'backend-fail-move', $params['src'], $params['dst'] );
457 }
458 }
459
460 /**
461 * @see FileBackendStore::doDeleteInternal()
462 * @return Status
463 */
464 protected function doDeleteInternal( array $params ) {
465 $status = Status::newGood();
466
467 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
468 if ( $srcRel === null ) {
469 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
470 return $status;
471 }
472
473 try {
474 $sContObj = $this->getContainer( $srcCont );
475 $srcObj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
476 if ( !empty( $params['async'] ) ) { // deferred
477 $handle = $sContObj->delete_object_async( $srcRel );
478 $status->value = new SwiftFileOpHandle( $this, $params, 'Delete', $handle );
479 $status->value->affectedObjects[] = $srcObj;
480 } else { // actually write the object in Swift
481 $sContObj->delete_object( $srcRel );
482 $this->purgeCDNCache( array( $srcObj ) );
483 }
484 } catch ( CDNNotEnabledException $e ) {
485 // CDN not enabled; nothing to see here
486 } catch ( NoSuchContainerException $e ) {
487 $status->fatal( 'backend-fail-delete', $params['src'] );
488 } catch ( NoSuchObjectException $e ) {
489 if ( empty( $params['ignoreMissingSource'] ) ) {
490 $status->fatal( 'backend-fail-delete', $params['src'] );
491 }
492 } catch ( CloudFilesException $e ) { // some other exception?
493 $this->handleException( $e, $status, __METHOD__, $params );
494 }
495
496 return $status;
497 }
498
499 /**
500 * @see SwiftFileBackend::doExecuteOpHandlesInternal()
501 */
502 protected function _getResponseDelete( CF_Async_Op $cfOp, Status $status, array $params ) {
503 try {
504 $cfOp->getLastResponse();
505 } catch ( NoSuchContainerException $e ) {
506 $status->fatal( 'backend-fail-delete', $params['src'] );
507 } catch ( NoSuchObjectException $e ) {
508 if ( empty( $params['ignoreMissingSource'] ) ) {
509 $status->fatal( 'backend-fail-delete', $params['src'] );
510 }
511 }
512 }
513
514 /**
515 * @see FileBackendStore::doPrepareInternal()
516 * @return Status
517 */
518 protected function doPrepareInternal( $fullCont, $dir, array $params ) {
519 $status = Status::newGood();
520
521 // (a) Check if container already exists
522 try {
523 $contObj = $this->getContainer( $fullCont );
524 // NoSuchContainerException not thrown: container must exist
525 return $status; // already exists
526 } catch ( NoSuchContainerException $e ) {
527 // NoSuchContainerException thrown: container does not exist
528 } catch ( CloudFilesException $e ) { // some other exception?
529 $this->handleException( $e, $status, __METHOD__, $params );
530 return $status;
531 }
532
533 // (b) Create container as needed
534 try {
535 $contObj = $this->createContainer( $fullCont );
536 if ( !empty( $params['noAccess'] ) ) {
537 // Make container private to end-users...
538 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
539 } else {
540 // Make container public to end-users...
541 $status->merge( $this->doPublishInternal( $fullCont, $dir, $params ) );
542 }
543 if ( $this->swiftUseCDN ) { // Rackspace style CDN
544 $contObj->make_public( $this->swiftCDNExpiry );
545 }
546 } catch ( CDNNotEnabledException $e ) {
547 // CDN not enabled; nothing to see here
548 } catch ( CloudFilesException $e ) { // some other exception?
549 $this->handleException( $e, $status, __METHOD__, $params );
550 return $status;
551 }
552
553 return $status;
554 }
555
556 /**
557 * @see FileBackendStore::doSecureInternal()
558 * @return Status
559 */
560 protected function doSecureInternal( $fullCont, $dir, array $params ) {
561 $status = Status::newGood();
562 if ( empty( $params['noAccess'] ) ) {
563 return $status; // nothing to do
564 }
565
566 // Restrict container from end-users...
567 try {
568 // doPrepareInternal() should have been called,
569 // so the Swift container should already exist...
570 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
571 // NoSuchContainerException not thrown: container must exist
572
573 // Make container private to end-users...
574 $status->merge( $this->setContainerAccess(
575 $contObj,
576 array( $this->auth->username ), // read
577 array( $this->auth->username ) // write
578 ) );
579 if ( $this->swiftUseCDN && $contObj->is_public() ) { // Rackspace style CDN
580 $contObj->make_private();
581 }
582 } catch ( CDNNotEnabledException $e ) {
583 // CDN not enabled; nothing to see here
584 } catch ( CloudFilesException $e ) { // some other exception?
585 $this->handleException( $e, $status, __METHOD__, $params );
586 }
587
588 return $status;
589 }
590
591 /**
592 * @see FileBackendStore::doPublishInternal()
593 * @return Status
594 */
595 protected function doPublishInternal( $fullCont, $dir, array $params ) {
596 $status = Status::newGood();
597
598 // Unrestrict container from end-users...
599 try {
600 // doPrepareInternal() should have been called,
601 // so the Swift container should already exist...
602 $contObj = $this->getContainer( $fullCont ); // normally a cache hit
603 // NoSuchContainerException not thrown: container must exist
604
605 // Make container public to end-users...
606 if ( $this->swiftAnonUser != '' ) {
607 $status->merge( $this->setContainerAccess(
608 $contObj,
609 array( $this->auth->username, $this->swiftAnonUser ), // read
610 array( $this->auth->username, $this->swiftAnonUser ) // write
611 ) );
612 } else {
613 $status->merge( $this->setContainerAccess(
614 $contObj,
615 array( $this->auth->username, '.r:*' ), // read
616 array( $this->auth->username ) // write
617 ) );
618 }
619 if ( $this->swiftUseCDN && !$contObj->is_public() ) { // Rackspace style CDN
620 $contObj->make_public();
621 }
622 } catch ( CDNNotEnabledException $e ) {
623 // CDN not enabled; nothing to see here
624 } catch ( CloudFilesException $e ) { // some other exception?
625 $this->handleException( $e, $status, __METHOD__, $params );
626 }
627
628 return $status;
629 }
630
631 /**
632 * @see FileBackendStore::doCleanInternal()
633 * @return Status
634 */
635 protected function doCleanInternal( $fullCont, $dir, array $params ) {
636 $status = Status::newGood();
637
638 // Only containers themselves can be removed, all else is virtual
639 if ( $dir != '' ) {
640 return $status; // nothing to do
641 }
642
643 // (a) Check the container
644 try {
645 $contObj = $this->getContainer( $fullCont, true );
646 } catch ( NoSuchContainerException $e ) {
647 return $status; // ok, nothing to do
648 } catch ( CloudFilesException $e ) { // some other exception?
649 $this->handleException( $e, $status, __METHOD__, $params );
650 return $status;
651 }
652
653 // (b) Delete the container if empty
654 if ( $contObj->object_count == 0 ) {
655 try {
656 $this->deleteContainer( $fullCont );
657 } catch ( NoSuchContainerException $e ) {
658 return $status; // race?
659 } catch ( NonEmptyContainerException $e ) {
660 return $status; // race? consistency delay?
661 } catch ( CloudFilesException $e ) { // some other exception?
662 $this->handleException( $e, $status, __METHOD__, $params );
663 return $status;
664 }
665 }
666
667 return $status;
668 }
669
670 /**
671 * @see FileBackendStore::doFileExists()
672 * @return array|bool|null
673 */
674 protected function doGetFileStat( array $params ) {
675 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
676 if ( $srcRel === null ) {
677 return false; // invalid storage path
678 }
679
680 $stat = false;
681 try {
682 $contObj = $this->getContainer( $srcCont );
683 $srcObj = $contObj->get_object( $srcRel, $this->headersFromParams( $params ) );
684 $this->addMissingMetadata( $srcObj, $params['src'] );
685 $stat = array(
686 // Convert dates like "Tue, 03 Jan 2012 22:01:04 GMT" to TS_MW
687 'mtime' => wfTimestamp( TS_MW, $srcObj->last_modified ),
688 'size' => (int)$srcObj->content_length,
689 'sha1' => $srcObj->metadata['Sha1base36']
690 );
691 } catch ( NoSuchContainerException $e ) {
692 } catch ( NoSuchObjectException $e ) {
693 } catch ( CloudFilesException $e ) { // some other exception?
694 $stat = null;
695 $this->handleException( $e, null, __METHOD__, $params );
696 }
697
698 return $stat;
699 }
700
701 /**
702 * Fill in any missing object metadata and save it to Swift
703 *
704 * @param $obj CF_Object
705 * @param $path string Storage path to object
706 * @return bool Success
707 * @throws Exception cloudfiles exceptions
708 */
709 protected function addMissingMetadata( CF_Object $obj, $path ) {
710 if ( isset( $obj->metadata['Sha1base36'] ) ) {
711 return true; // nothing to do
712 }
713 $status = Status::newGood();
714 $scopeLockS = $this->getScopedFileLocks( array( $path ), LockManager::LOCK_UW, $status );
715 if ( $status->isOK() ) {
716 # Do not stat the file in getLocalCopy() to avoid infinite loops
717 $tmpFile = $this->getLocalCopy( array( 'src' => $path, 'latest' => 1, 'nostat' => 1 ) );
718 if ( $tmpFile ) {
719 $hash = $tmpFile->getSha1Base36();
720 if ( $hash !== false ) {
721 $obj->metadata['Sha1base36'] = $hash;
722 $obj->sync_metadata(); // save to Swift
723 return true; // success
724 }
725 }
726 }
727 $obj->metadata['Sha1base36'] = false;
728 return false; // failed
729 }
730
731 /**
732 * @see FileBackend::getFileContents()
733 * @return bool|null|string
734 */
735 public function getFileContents( array $params ) {
736 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
737 if ( $srcRel === null ) {
738 return false; // invalid storage path
739 }
740
741 if ( !$this->fileExists( $params ) ) {
742 return null;
743 }
744
745 $data = false;
746 try {
747 $sContObj = $this->getContainer( $srcCont );
748 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
749 $data = $obj->read( $this->headersFromParams( $params ) );
750 } catch ( NoSuchContainerException $e ) {
751 } catch ( CloudFilesException $e ) { // some other exception?
752 $this->handleException( $e, null, __METHOD__, $params );
753 }
754
755 return $data;
756 }
757
758 /**
759 * @see FileBackendStore::doDirectoryExists()
760 * @return bool|null
761 */
762 protected function doDirectoryExists( $fullCont, $dir, array $params ) {
763 try {
764 $container = $this->getContainer( $fullCont );
765 $prefix = ( $dir == '' ) ? null : "{$dir}/";
766 return ( count( $container->list_objects( 1, null, $prefix ) ) > 0 );
767 } catch ( NoSuchContainerException $e ) {
768 return false;
769 } catch ( CloudFilesException $e ) { // some other exception?
770 $this->handleException( $e, null, __METHOD__,
771 array( 'cont' => $fullCont, 'dir' => $dir ) );
772 }
773
774 return null; // error
775 }
776
777 /**
778 * @see FileBackendStore::getDirectoryListInternal()
779 * @return SwiftFileBackendDirList
780 */
781 public function getDirectoryListInternal( $fullCont, $dir, array $params ) {
782 return new SwiftFileBackendDirList( $this, $fullCont, $dir, $params );
783 }
784
785 /**
786 * @see FileBackendStore::getFileListInternal()
787 * @return SwiftFileBackendFileList
788 */
789 public function getFileListInternal( $fullCont, $dir, array $params ) {
790 return new SwiftFileBackendFileList( $this, $fullCont, $dir, $params );
791 }
792
793 /**
794 * Do not call this function outside of SwiftFileBackendFileList
795 *
796 * @param $fullCont string Resolved container name
797 * @param $dir string Resolved storage directory with no trailing slash
798 * @param $after string|null Storage path of file to list items after
799 * @param $limit integer Max number of items to list
800 * @param $params Array Includes flag for 'topOnly'
801 * @return Array List of relative paths of dirs directly under $dir
802 */
803 public function getDirListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
804 $dirs = array();
805 if ( $after === INF ) {
806 return $dirs; // nothing more
807 }
808 wfProfileIn( __METHOD__ . '-' . $this->name );
809
810 try {
811 $container = $this->getContainer( $fullCont );
812 $prefix = ( $dir == '' ) ? null : "{$dir}/";
813 // Non-recursive: only list dirs right under $dir
814 if ( !empty( $params['topOnly'] ) ) {
815 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
816 foreach ( $objects as $object ) { // files and dirs
817 if ( substr( $object, -1 ) === '/' ) {
818 $dirs[] = $object; // directories end in '/'
819 }
820 }
821 // Recursive: list all dirs under $dir and its subdirs
822 } else {
823 // Get directory from last item of prior page
824 $lastDir = $this->getParentDir( $after ); // must be first page
825 $objects = $container->list_objects( $limit, $after, $prefix );
826 foreach ( $objects as $object ) { // files
827 $objectDir = $this->getParentDir( $object ); // directory of object
828 if ( $objectDir !== false ) { // file has a parent dir
829 // Swift stores paths in UTF-8, using binary sorting.
830 // See function "create_container_table" in common/db.py.
831 // If a directory is not "greater" than the last one,
832 // then it was already listed by the calling iterator.
833 if ( $objectDir > $lastDir ) {
834 $pDir = $objectDir;
835 do { // add dir and all its parent dirs
836 $dirs[] = "{$pDir}/";
837 $pDir = $this->getParentDir( $pDir );
838 } while ( $pDir !== false // sanity
839 && $pDir > $lastDir // not done already
840 && strlen( $pDir ) > strlen( $dir ) // within $dir
841 );
842 }
843 $lastDir = $objectDir;
844 }
845 }
846 }
847 if ( count( $objects ) < $limit ) {
848 $after = INF; // avoid a second RTT
849 } else {
850 $after = end( $objects ); // update last item
851 }
852 } catch ( NoSuchContainerException $e ) {
853 } catch ( CloudFilesException $e ) { // some other exception?
854 $this->handleException( $e, null, __METHOD__,
855 array( 'cont' => $fullCont, 'dir' => $dir ) );
856 }
857
858 wfProfileOut( __METHOD__ . '-' . $this->name );
859 return $dirs;
860 }
861
862 protected function getParentDir( $path ) {
863 return ( strpos( $path, '/' ) !== false ) ? dirname( $path ) : false;
864 }
865
866 /**
867 * Do not call this function outside of SwiftFileBackendFileList
868 *
869 * @param $fullCont string Resolved container name
870 * @param $dir string Resolved storage directory with no trailing slash
871 * @param $after string|null Storage path of file to list items after
872 * @param $limit integer Max number of items to list
873 * @param $params Array Includes flag for 'topOnly'
874 * @return Array List of relative paths of files under $dir
875 */
876 public function getFileListPageInternal( $fullCont, $dir, &$after, $limit, array $params ) {
877 $files = array();
878 if ( $after === INF ) {
879 return $files; // nothing more
880 }
881 wfProfileIn( __METHOD__ . '-' . $this->name );
882
883 try {
884 $container = $this->getContainer( $fullCont );
885 $prefix = ( $dir == '' ) ? null : "{$dir}/";
886 // Non-recursive: only list files right under $dir
887 if ( !empty( $params['topOnly'] ) ) { // files and dirs
888 $objects = $container->list_objects( $limit, $after, $prefix, null, '/' );
889 foreach ( $objects as $object ) {
890 if ( substr( $object, -1 ) !== '/' ) {
891 $files[] = $object; // directories end in '/'
892 }
893 }
894 // Recursive: list all files under $dir and its subdirs
895 } else { // files
896 $objects = $container->list_objects( $limit, $after, $prefix );
897 $files = $objects;
898 }
899 if ( count( $objects ) < $limit ) {
900 $after = INF; // avoid a second RTT
901 } else {
902 $after = end( $objects ); // update last item
903 }
904 } catch ( NoSuchContainerException $e ) {
905 } catch ( CloudFilesException $e ) { // some other exception?
906 $this->handleException( $e, null, __METHOD__,
907 array( 'cont' => $fullCont, 'dir' => $dir ) );
908 }
909
910 wfProfileOut( __METHOD__ . '-' . $this->name );
911 return $files;
912 }
913
914 /**
915 * @see FileBackendStore::doGetFileSha1base36()
916 * @return bool
917 */
918 protected function doGetFileSha1base36( array $params ) {
919 $stat = $this->getFileStat( $params );
920 if ( $stat ) {
921 return $stat['sha1'];
922 } else {
923 return false;
924 }
925 }
926
927 /**
928 * @see FileBackendStore::doStreamFile()
929 * @return Status
930 */
931 protected function doStreamFile( array $params ) {
932 $status = Status::newGood();
933
934 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
935 if ( $srcRel === null ) {
936 $status->fatal( 'backend-fail-invalidpath', $params['src'] );
937 }
938
939 try {
940 $cont = $this->getContainer( $srcCont );
941 } catch ( NoSuchContainerException $e ) {
942 $status->fatal( 'backend-fail-stream', $params['src'] );
943 return $status;
944 } catch ( CloudFilesException $e ) { // some other exception?
945 $this->handleException( $e, $status, __METHOD__, $params );
946 return $status;
947 }
948
949 try {
950 $output = fopen( 'php://output', 'wb' );
951 $obj = new CF_Object( $cont, $srcRel, false, false ); // skip HEAD
952 $obj->stream( $output, $this->headersFromParams( $params ) );
953 } catch ( CloudFilesException $e ) { // some other exception?
954 $this->handleException( $e, $status, __METHOD__, $params );
955 }
956
957 return $status;
958 }
959
960 /**
961 * @see FileBackendStore::getLocalCopy()
962 * @return null|TempFSFile
963 */
964 public function getLocalCopy( array $params ) {
965 list( $srcCont, $srcRel ) = $this->resolveStoragePathReal( $params['src'] );
966 if ( $srcRel === null ) {
967 return null;
968 }
969
970 # Check the recursion guard to avoid loops when filling metadata
971 if ( empty( $params['nostat'] ) && !$this->fileExists( $params ) ) {
972 return null;
973 }
974
975 $tmpFile = null;
976 try {
977 $sContObj = $this->getContainer( $srcCont );
978 $obj = new CF_Object( $sContObj, $srcRel, false, false ); // skip HEAD
979 // Get source file extension
980 $ext = FileBackend::extensionFromPath( $srcRel );
981 // Create a new temporary file...
982 $tmpFile = TempFSFile::factory( wfBaseName( $srcRel ) . '_', $ext );
983 if ( $tmpFile ) {
984 $handle = fopen( $tmpFile->getPath(), 'wb' );
985 if ( $handle ) {
986 $obj->stream( $handle, $this->headersFromParams( $params ) );
987 fclose( $handle );
988 } else {
989 $tmpFile = null; // couldn't open temp file
990 }
991 }
992 } catch ( NoSuchContainerException $e ) {
993 $tmpFile = null;
994 } catch ( CloudFilesException $e ) { // some other exception?
995 $tmpFile = null;
996 $this->handleException( $e, null, __METHOD__, $params );
997 }
998
999 return $tmpFile;
1000 }
1001
1002 /**
1003 * @see FileBackendStore::directoriesAreVirtual()
1004 * @return bool
1005 */
1006 protected function directoriesAreVirtual() {
1007 return true;
1008 }
1009
1010 /**
1011 * Get headers to send to Swift when reading a file based
1012 * on a FileBackend params array, e.g. that of getLocalCopy().
1013 * $params is currently only checked for a 'latest' flag.
1014 *
1015 * @param $params Array
1016 * @return Array
1017 */
1018 protected function headersFromParams( array $params ) {
1019 $hdrs = array();
1020 if ( !empty( $params['latest'] ) ) {
1021 $hdrs[] = 'X-Newest: true';
1022 }
1023 return $hdrs;
1024 }
1025
1026 /**
1027 * @see FileBackendStore::doExecuteOpHandlesInternal()
1028 * @return Array List of corresponding Status objects
1029 */
1030 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
1031 $statuses = array();
1032
1033 $cfOps = array(); // list of CF_Async_Op objects
1034 foreach ( $fileOpHandles as $index => $fileOpHandle ) {
1035 $cfOps[$index] = $fileOpHandle->cfOp;
1036 }
1037 $batch = new CF_Async_Op_Batch( $cfOps );
1038
1039 $cfOps = $batch->execute();
1040 foreach ( $cfOps as $index => $cfOp ) {
1041 $status = Status::newGood();
1042 try { // catch exceptions; update status
1043 $function = '_getResponse' . $fileOpHandles[$index]->call;
1044 $this->$function( $cfOp, $status, $fileOpHandles[$index]->params );
1045 $this->purgeCDNCache( $fileOpHandles[$index]->affectedObjects );
1046 } catch ( CloudFilesException $e ) { // some other exception?
1047 $this->handleException( $e, $status,
1048 __CLASS__ . ":$function", $fileOpHandles[$index]->params );
1049 }
1050 $statuses[$index] = $status;
1051 }
1052
1053 return $statuses;
1054 }
1055
1056 /**
1057 * Set read/write permissions for a Swift container.
1058 *
1059 * $readGrps is a list of the possible criteria for a request to have
1060 * access to read a container. Each item is one of the following formats:
1061 * - account:user : Grants access if the request is by the given user
1062 * - .r:<regex> : Grants access if the request is from a referrer host that
1063 * matches the expression and the request is not for a listing.
1064 * Setting this to '*' effectively makes a container public.
1065 * - .rlistings:<regex> : Grants access if the request is from a referrer host that
1066 * matches the expression and the request for a listing.
1067 *
1068 * $writeGrps is a list of the possible criteria for a request to have
1069 * access to write to a container. Each item is of the following format:
1070 * - account:user : Grants access if the request is by the given user
1071 *
1072 * @see http://swift.openstack.org/misc.html#acls
1073 *
1074 * In general, we don't allow listings to end-users. It's not useful, isn't well-defined
1075 * (lists are truncated to 10000 item with no way to page), and is just a performance risk.
1076 *
1077 * @param $contObj CF_Container Swift container
1078 * @param $readGrps Array List of read access routes
1079 * @param $writeGrps Array List of write access routes
1080 * @return Status
1081 */
1082 protected function setContainerAccess(
1083 CF_Container $contObj, array $readGrps, array $writeGrps
1084 ) {
1085 $creds = $contObj->cfs_auth->export_credentials();
1086
1087 $url = $creds['storage_url'] . '/' . rawurlencode( $contObj->name );
1088
1089 // Note: 10 second timeout consistent with php-cloudfiles
1090 $req = MWHttpRequest::factory( $url, array( 'method' => 'POST', 'timeout' => 10 ) );
1091 $req->setHeader( 'X-Auth-Token', $creds['auth_token'] );
1092 $req->setHeader( 'X-Container-Read', implode( ',', $readGrps ) );
1093 $req->setHeader( 'X-Container-Write', implode( ',', $writeGrps ) );
1094
1095 return $req->execute(); // should return 204
1096 }
1097
1098 /**
1099 * Purge the CDN cache of affected objects if CDN caching is enabled.
1100 * This is for Rackspace/Akamai CDNs.
1101 *
1102 * @param $objects Array List of CF_Object items
1103 * @return void
1104 */
1105 public function purgeCDNCache( array $objects ) {
1106 if ( $this->swiftUseCDN && $this->swiftCDNPurgable ) {
1107 foreach ( $objects as $object ) {
1108 try {
1109 $object->purge_from_cdn();
1110 } catch ( CDNNotEnabledException $e ) {
1111 // CDN not enabled; nothing to see here
1112 } catch ( CloudFilesException $e ) {
1113 $this->handleException( $e, null, __METHOD__,
1114 array( 'cont' => $object->container->name, 'obj' => $object->name ) );
1115 }
1116 }
1117 }
1118 }
1119
1120 /**
1121 * Get a connection to the Swift proxy
1122 *
1123 * @return CF_Connection|bool False on failure
1124 * @throws CloudFilesException
1125 */
1126 protected function getConnection() {
1127 if ( $this->connException instanceof Exception ) {
1128 throw $this->connException; // failed last attempt
1129 }
1130 // Session keys expire after a while, so we renew them periodically
1131 if ( $this->conn && ( time() - $this->connStarted ) > $this->authTTL ) {
1132 $this->conn->close(); // close active cURL connections
1133 $this->conn = null;
1134 }
1135 // Authenticate with proxy and get a session key...
1136 if ( !$this->conn ) {
1137 $this->connStarted = 0;
1138 $this->connContainers = array();
1139 try {
1140 $this->auth->authenticate();
1141 $this->conn = new CF_Connection( $this->auth );
1142 $this->connStarted = time();
1143 } catch ( CloudFilesException $e ) {
1144 $this->connException = $e; // don't keep re-trying
1145 throw $e; // throw it back
1146 }
1147 }
1148 return $this->conn;
1149 }
1150
1151 /**
1152 * @see FileBackendStore::doClearCache()
1153 */
1154 protected function doClearCache( array $paths = null ) {
1155 $this->connContainers = array(); // clear container object cache
1156 }
1157
1158 /**
1159 * Get a Swift container object, possibly from process cache.
1160 * Use $reCache if the file count or byte count is needed.
1161 *
1162 * @param $container string Container name
1163 * @param $bypassCache bool Bypass all caches and load from Swift
1164 * @return CF_Container
1165 * @throws CloudFilesException
1166 */
1167 protected function getContainer( $container, $bypassCache = false ) {
1168 $conn = $this->getConnection(); // Swift proxy connection
1169 if ( $bypassCache ) { // purge cache
1170 unset( $this->connContainers[$container] );
1171 } elseif ( !isset( $this->connContainers[$container] ) ) {
1172 $this->primeContainerCache( array( $container ) ); // check persistent cache
1173 }
1174 if ( !isset( $this->connContainers[$container] ) ) {
1175 $contObj = $conn->get_container( $container );
1176 // NoSuchContainerException not thrown: container must exist
1177 if ( count( $this->connContainers ) >= $this->maxContCacheSize ) { // trim cache?
1178 reset( $this->connContainers );
1179 unset( $this->connContainers[key( $this->connContainers )] );
1180 }
1181 $this->connContainers[$container] = $contObj; // cache it
1182 if ( !$bypassCache ) {
1183 $this->setContainerCache( $container, // update persistent cache
1184 array( 'bytes' => $contObj->bytes_used, 'count' => $contObj->object_count )
1185 );
1186 }
1187 }
1188 return $this->connContainers[$container];
1189 }
1190
1191 /**
1192 * Create a Swift container
1193 *
1194 * @param $container string Container name
1195 * @return CF_Container
1196 * @throws CloudFilesException
1197 */
1198 protected function createContainer( $container ) {
1199 $conn = $this->getConnection(); // Swift proxy connection
1200 $contObj = $conn->create_container( $container );
1201 $this->connContainers[$container] = $contObj; // cache it
1202 return $contObj;
1203 }
1204
1205 /**
1206 * Delete a Swift container
1207 *
1208 * @param $container string Container name
1209 * @return void
1210 * @throws CloudFilesException
1211 */
1212 protected function deleteContainer( $container ) {
1213 $conn = $this->getConnection(); // Swift proxy connection
1214 unset( $this->connContainers[$container] ); // purge cache
1215 $conn->delete_container( $container );
1216 }
1217
1218 /**
1219 * @see FileBackendStore::doPrimeContainerCache()
1220 * @return void
1221 */
1222 protected function doPrimeContainerCache( array $containerInfo ) {
1223 try {
1224 $conn = $this->getConnection(); // Swift proxy connection
1225 foreach ( $containerInfo as $container => $info ) {
1226 $this->connContainers[$container] = new CF_Container(
1227 $conn->cfs_auth,
1228 $conn->cfs_http,
1229 $container,
1230 $info['count'],
1231 $info['bytes']
1232 );
1233 }
1234 } catch ( CloudFilesException $e ) { // some other exception?
1235 $this->handleException( $e, null, __METHOD__, array() );
1236 }
1237 }
1238
1239 /**
1240 * Log an unexpected exception for this backend.
1241 * This also sets the Status object to have a fatal error.
1242 *
1243 * @param $e Exception
1244 * @param $status Status|null
1245 * @param $func string
1246 * @param $params Array
1247 * @return void
1248 */
1249 protected function handleException( Exception $e, $status, $func, array $params ) {
1250 if ( $status instanceof Status ) {
1251 if ( $e instanceof AuthenticationException ) {
1252 $status->fatal( 'backend-fail-connect', $this->name );
1253 } else {
1254 $status->fatal( 'backend-fail-internal', $this->name );
1255 }
1256 }
1257 if ( $e->getMessage() ) {
1258 trigger_error( "$func: " . $e->getMessage(), E_USER_WARNING );
1259 }
1260 wfDebugLog( 'SwiftBackend',
1261 get_class( $e ) . " in '{$func}' (given '" . FormatJson::encode( $params ) . "')" .
1262 ( $e->getMessage() ? ": {$e->getMessage()}" : "" )
1263 );
1264 }
1265 }
1266
1267 /**
1268 * @see FileBackendStoreOpHandle
1269 */
1270 class SwiftFileOpHandle extends FileBackendStoreOpHandle {
1271 /** @var CF_Async_Op */
1272 public $cfOp;
1273 /** @var Array */
1274 public $affectedObjects = array();
1275
1276 public function __construct( $backend, array $params, $call, CF_Async_Op $cfOp ) {
1277 $this->backend = $backend;
1278 $this->params = $params;
1279 $this->call = $call;
1280 $this->cfOp = $cfOp;
1281 }
1282 }
1283
1284 /**
1285 * SwiftFileBackend helper class to page through listings.
1286 * Swift also has a listing limit of 10,000 objects for sanity.
1287 * Do not use this class from places outside SwiftFileBackend.
1288 *
1289 * @ingroup FileBackend
1290 */
1291 abstract class SwiftFileBackendList implements Iterator {
1292 /** @var Array */
1293 protected $bufferIter = array();
1294 protected $bufferAfter = null; // string; list items *after* this path
1295 protected $pos = 0; // integer
1296 /** @var Array */
1297 protected $params = array();
1298
1299 /** @var SwiftFileBackend */
1300 protected $backend;
1301 protected $container; // string; container name
1302 protected $dir; // string; storage directory
1303 protected $suffixStart; // integer
1304
1305 const PAGE_SIZE = 9000; // file listing buffer size
1306
1307 /**
1308 * @param $backend SwiftFileBackend
1309 * @param $fullCont string Resolved container name
1310 * @param $dir string Resolved directory relative to container
1311 * @param $params Array
1312 */
1313 public function __construct( SwiftFileBackend $backend, $fullCont, $dir, array $params ) {
1314 $this->backend = $backend;
1315 $this->container = $fullCont;
1316 $this->dir = $dir;
1317 if ( substr( $this->dir, -1 ) === '/' ) {
1318 $this->dir = substr( $this->dir, 0, -1 ); // remove trailing slash
1319 }
1320 if ( $this->dir == '' ) { // whole container
1321 $this->suffixStart = 0;
1322 } else { // dir within container
1323 $this->suffixStart = strlen( $this->dir ) + 1; // size of "path/to/dir/"
1324 }
1325 $this->params = $params;
1326 }
1327
1328 /**
1329 * @see Iterator::key()
1330 * @return integer
1331 */
1332 public function key() {
1333 return $this->pos;
1334 }
1335
1336 /**
1337 * @see Iterator::next()
1338 * @return void
1339 */
1340 public function next() {
1341 // Advance to the next file in the page
1342 next( $this->bufferIter );
1343 ++$this->pos;
1344 // Check if there are no files left in this page and
1345 // advance to the next page if this page was not empty.
1346 if ( !$this->valid() && count( $this->bufferIter ) ) {
1347 $this->bufferIter = $this->pageFromList(
1348 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1349 ); // updates $this->bufferAfter
1350 }
1351 }
1352
1353 /**
1354 * @see Iterator::rewind()
1355 * @return void
1356 */
1357 public function rewind() {
1358 $this->pos = 0;
1359 $this->bufferAfter = null;
1360 $this->bufferIter = $this->pageFromList(
1361 $this->container, $this->dir, $this->bufferAfter, self::PAGE_SIZE, $this->params
1362 ); // updates $this->bufferAfter
1363 }
1364
1365 /**
1366 * @see Iterator::valid()
1367 * @return bool
1368 */
1369 public function valid() {
1370 if ( $this->bufferIter === null ) {
1371 return false; // some failure?
1372 } else {
1373 return ( current( $this->bufferIter ) !== false ); // no paths can have this value
1374 }
1375 }
1376
1377 /**
1378 * Get the given list portion (page)
1379 *
1380 * @param $container string Resolved container name
1381 * @param $dir string Resolved path relative to container
1382 * @param $after string|null
1383 * @param $limit integer
1384 * @param $params Array
1385 * @return Traversable|Array|null Returns null on failure
1386 */
1387 abstract protected function pageFromList( $container, $dir, &$after, $limit, array $params );
1388 }
1389
1390 /**
1391 * Iterator for listing directories
1392 */
1393 class SwiftFileBackendDirList extends SwiftFileBackendList {
1394 /**
1395 * @see Iterator::current()
1396 * @return string|bool String (relative path) or false
1397 */
1398 public function current() {
1399 return substr( current( $this->bufferIter ), $this->suffixStart, -1 );
1400 }
1401
1402 /**
1403 * @see SwiftFileBackendList::pageFromList()
1404 * @return Array|null
1405 */
1406 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1407 return $this->backend->getDirListPageInternal( $container, $dir, $after, $limit, $params );
1408 }
1409 }
1410
1411 /**
1412 * Iterator for listing regular files
1413 */
1414 class SwiftFileBackendFileList extends SwiftFileBackendList {
1415 /**
1416 * @see Iterator::current()
1417 * @return string|bool String (relative path) or false
1418 */
1419 public function current() {
1420 return substr( current( $this->bufferIter ), $this->suffixStart );
1421 }
1422
1423 /**
1424 * @see SwiftFileBackendList::pageFromList()
1425 * @return Array|null
1426 */
1427 protected function pageFromList( $container, $dir, &$after, $limit, array $params ) {
1428 return $this->backend->getFileListPageInternal( $container, $dir, $after, $limit, $params );
1429 }
1430 }