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