Merge "No environment reset for failure after prefetch hit"
[lhc/web/wiklou.git] / includes / filerepo / backend / FileBackendStore.php
1 <?php
2 /**
3 * @file
4 * @ingroup FileBackend
5 * @author Aaron Schulz
6 */
7
8 /**
9 * @brief Base class for all backends using particular storage medium.
10 *
11 * This class defines the methods as abstract that subclasses must implement.
12 * Outside callers should *not* use functions with "Internal" in the name.
13 *
14 * The FileBackend operations are implemented using basic functions
15 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
16 * This class is also responsible for path resolution and sanitization.
17 *
18 * @ingroup FileBackend
19 * @since 1.19
20 */
21 abstract class FileBackendStore extends FileBackend {
22 /** @var BagOStuff */
23 protected $memCache;
24
25 /** @var Array Map of paths to small (RAM/disk) cache items */
26 protected $cache = array(); // (storage path => key => value)
27 protected $maxCacheSize = 100; // integer; max paths with entries
28 /** @var Array Map of paths to large (RAM/disk) cache items */
29 protected $expensiveCache = array(); // (storage path => key => value)
30 protected $maxExpensiveCacheSize = 10; // integer; max paths with entries
31
32 /** @var Array Map of container names to sharding settings */
33 protected $shardViaHashLevels = array(); // (container name => config array)
34
35 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
36
37 /**
38 * @see FileBackend::__construct()
39 *
40 * @param $config Array
41 */
42 public function __construct( array $config ) {
43 parent::__construct( $config );
44 $this->memCache = new EmptyBagOStuff(); // disabled by default
45 }
46
47 /**
48 * Get the maximum allowable file size given backend
49 * medium restrictions and basic performance constraints.
50 * Do not call this function from places outside FileBackend and FileOp.
51 *
52 * @return integer Bytes
53 */
54 final public function maxFileSizeInternal() {
55 return $this->maxFileSize;
56 }
57
58 /**
59 * Check if a file can be created at a given storage path.
60 * FS backends should check if the parent directory exists and the file is writable.
61 * Backends using key/value stores should check if the container exists.
62 *
63 * @param $storagePath string
64 * @return bool
65 */
66 abstract public function isPathUsableInternal( $storagePath );
67
68 /**
69 * Create a file in the backend with the given contents.
70 * Do not call this function from places outside FileBackend and FileOp.
71 *
72 * $params include:
73 * content : the raw file contents
74 * dst : destination storage path
75 * overwrite : overwrite any file that exists at the destination
76 *
77 * @param $params Array
78 * @return Status
79 */
80 final public function createInternal( array $params ) {
81 wfProfileIn( __METHOD__ );
82 wfProfileIn( __METHOD__ . '-' . $this->name );
83 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
84 $status = Status::newFatal( 'backend-fail-maxsize',
85 $params['dst'], $this->maxFileSizeInternal() );
86 } else {
87 $status = $this->doCreateInternal( $params );
88 $this->clearCache( array( $params['dst'] ) );
89 }
90 wfProfileOut( __METHOD__ . '-' . $this->name );
91 wfProfileOut( __METHOD__ );
92 return $status;
93 }
94
95 /**
96 * @see FileBackendStore::createInternal()
97 */
98 abstract protected function doCreateInternal( array $params );
99
100 /**
101 * Store a file into the backend from a file on disk.
102 * Do not call this function from places outside FileBackend and FileOp.
103 *
104 * $params include:
105 * src : source path on disk
106 * dst : destination storage path
107 * overwrite : overwrite any file that exists at the destination
108 *
109 * @param $params Array
110 * @return Status
111 */
112 final public function storeInternal( array $params ) {
113 wfProfileIn( __METHOD__ );
114 wfProfileIn( __METHOD__ . '-' . $this->name );
115 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
116 $status = Status::newFatal( 'backend-fail-store', $params['dst'] );
117 } else {
118 $status = $this->doStoreInternal( $params );
119 $this->clearCache( array( $params['dst'] ) );
120 }
121 wfProfileOut( __METHOD__ . '-' . $this->name );
122 wfProfileOut( __METHOD__ );
123 return $status;
124 }
125
126 /**
127 * @see FileBackendStore::storeInternal()
128 */
129 abstract protected function doStoreInternal( array $params );
130
131 /**
132 * Copy a file from one storage path to another in the backend.
133 * Do not call this function from places outside FileBackend and FileOp.
134 *
135 * $params include:
136 * src : source storage path
137 * dst : destination storage path
138 * overwrite : overwrite any file that exists at the destination
139 *
140 * @param $params Array
141 * @return Status
142 */
143 final public function copyInternal( array $params ) {
144 wfProfileIn( __METHOD__ );
145 wfProfileIn( __METHOD__ . '-' . $this->name );
146 $status = $this->doCopyInternal( $params );
147 $this->clearCache( array( $params['dst'] ) );
148 wfProfileOut( __METHOD__ . '-' . $this->name );
149 wfProfileOut( __METHOD__ );
150 return $status;
151 }
152
153 /**
154 * @see FileBackendStore::copyInternal()
155 */
156 abstract protected function doCopyInternal( array $params );
157
158 /**
159 * Delete a file at the storage path.
160 * Do not call this function from places outside FileBackend and FileOp.
161 *
162 * $params include:
163 * src : source storage path
164 * ignoreMissingSource : do nothing if the source file does not exist
165 *
166 * @param $params Array
167 * @return Status
168 */
169 final public function deleteInternal( array $params ) {
170 wfProfileIn( __METHOD__ );
171 wfProfileIn( __METHOD__ . '-' . $this->name );
172 $status = $this->doDeleteInternal( $params );
173 $this->clearCache( array( $params['src'] ) );
174 wfProfileOut( __METHOD__ . '-' . $this->name );
175 wfProfileOut( __METHOD__ );
176 return $status;
177 }
178
179 /**
180 * @see FileBackendStore::deleteInternal()
181 */
182 abstract protected function doDeleteInternal( array $params );
183
184 /**
185 * Move a file from one storage path to another in the backend.
186 * Do not call this function from places outside FileBackend and FileOp.
187 *
188 * $params include:
189 * src : source storage path
190 * dst : destination storage path
191 * overwrite : overwrite any file that exists at the destination
192 *
193 * @param $params Array
194 * @return Status
195 */
196 final public function moveInternal( array $params ) {
197 wfProfileIn( __METHOD__ );
198 wfProfileIn( __METHOD__ . '-' . $this->name );
199 $status = $this->doMoveInternal( $params );
200 $this->clearCache( array( $params['src'], $params['dst'] ) );
201 wfProfileOut( __METHOD__ . '-' . $this->name );
202 wfProfileOut( __METHOD__ );
203 return $status;
204 }
205
206 /**
207 * @see FileBackendStore::moveInternal()
208 * @return Status
209 */
210 protected function doMoveInternal( array $params ) {
211 // Copy source to dest
212 $status = $this->copyInternal( $params );
213 if ( $status->isOK() ) {
214 // Delete source (only fails due to races or medium going down)
215 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
216 $status->setResult( true, $status->value ); // ignore delete() errors
217 }
218 return $status;
219 }
220
221 /**
222 * @see FileBackend::concatenate()
223 * @return Status
224 */
225 final public function concatenate( array $params ) {
226 wfProfileIn( __METHOD__ );
227 wfProfileIn( __METHOD__ . '-' . $this->name );
228 $status = Status::newGood();
229
230 // Try to lock the source files for the scope of this function
231 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager::LOCK_UW, $status );
232 if ( $status->isOK() ) {
233 // Actually do the concatenation
234 $status->merge( $this->doConcatenate( $params ) );
235 }
236
237 wfProfileOut( __METHOD__ . '-' . $this->name );
238 wfProfileOut( __METHOD__ );
239 return $status;
240 }
241
242 /**
243 * @see FileBackendStore::concatenate()
244 * @return Status
245 */
246 protected function doConcatenate( array $params ) {
247 $status = Status::newGood();
248 $tmpPath = $params['dst']; // convenience
249
250 // Check that the specified temp file is valid...
251 wfSuppressWarnings();
252 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
253 wfRestoreWarnings();
254 if ( !$ok ) { // not present or not empty
255 $status->fatal( 'backend-fail-opentemp', $tmpPath );
256 return $status;
257 }
258
259 // Build up the temp file using the source chunks (in order)...
260 $tmpHandle = fopen( $tmpPath, 'ab' );
261 if ( $tmpHandle === false ) {
262 $status->fatal( 'backend-fail-opentemp', $tmpPath );
263 return $status;
264 }
265 foreach ( $params['srcs'] as $virtualSource ) {
266 // Get a local FS version of the chunk
267 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
268 if ( !$tmpFile ) {
269 $status->fatal( 'backend-fail-read', $virtualSource );
270 return $status;
271 }
272 // Get a handle to the local FS version
273 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
274 if ( $sourceHandle === false ) {
275 fclose( $tmpHandle );
276 $status->fatal( 'backend-fail-read', $virtualSource );
277 return $status;
278 }
279 // Append chunk to file (pass chunk size to avoid magic quotes)
280 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
281 fclose( $sourceHandle );
282 fclose( $tmpHandle );
283 $status->fatal( 'backend-fail-writetemp', $tmpPath );
284 return $status;
285 }
286 fclose( $sourceHandle );
287 }
288 if ( !fclose( $tmpHandle ) ) {
289 $status->fatal( 'backend-fail-closetemp', $tmpPath );
290 return $status;
291 }
292
293 clearstatcache(); // temp file changed
294
295 return $status;
296 }
297
298 /**
299 * @see FileBackend::doPrepare()
300 * @return Status
301 */
302 final protected function doPrepare( array $params ) {
303 wfProfileIn( __METHOD__ );
304 wfProfileIn( __METHOD__ . '-' . $this->name );
305
306 $status = Status::newGood();
307 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
308 if ( $dir === null ) {
309 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
310 wfProfileOut( __METHOD__ . '-' . $this->name );
311 wfProfileOut( __METHOD__ );
312 return $status; // invalid storage path
313 }
314
315 if ( $shard !== null ) { // confined to a single container/shard
316 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
317 } else { // directory is on several shards
318 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
319 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
320 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
321 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
322 }
323 }
324
325 wfProfileOut( __METHOD__ . '-' . $this->name );
326 wfProfileOut( __METHOD__ );
327 return $status;
328 }
329
330 /**
331 * @see FileBackendStore::doPrepare()
332 * @return Status
333 */
334 protected function doPrepareInternal( $container, $dir, array $params ) {
335 return Status::newGood();
336 }
337
338 /**
339 * @see FileBackend::doSecure()
340 * @return Status
341 */
342 final protected function doSecure( array $params ) {
343 wfProfileIn( __METHOD__ );
344 wfProfileIn( __METHOD__ . '-' . $this->name );
345 $status = Status::newGood();
346
347 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
348 if ( $dir === null ) {
349 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
350 wfProfileOut( __METHOD__ . '-' . $this->name );
351 wfProfileOut( __METHOD__ );
352 return $status; // invalid storage path
353 }
354
355 if ( $shard !== null ) { // confined to a single container/shard
356 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
357 } else { // directory is on several shards
358 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
359 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
360 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
361 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
362 }
363 }
364
365 wfProfileOut( __METHOD__ . '-' . $this->name );
366 wfProfileOut( __METHOD__ );
367 return $status;
368 }
369
370 /**
371 * @see FileBackendStore::doSecure()
372 * @return Status
373 */
374 protected function doSecureInternal( $container, $dir, array $params ) {
375 return Status::newGood();
376 }
377
378 /**
379 * @see FileBackend::doClean()
380 * @return Status
381 */
382 final protected function doClean( array $params ) {
383 wfProfileIn( __METHOD__ );
384 wfProfileIn( __METHOD__ . '-' . $this->name );
385 $status = Status::newGood();
386
387 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
388 if ( $dir === null ) {
389 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
390 wfProfileOut( __METHOD__ . '-' . $this->name );
391 wfProfileOut( __METHOD__ );
392 return $status; // invalid storage path
393 }
394
395 // Attempt to lock this directory...
396 $filesLockEx = array( $params['dir'] );
397 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
398 if ( !$status->isOK() ) {
399 wfProfileOut( __METHOD__ . '-' . $this->name );
400 wfProfileOut( __METHOD__ );
401 return $status; // abort
402 }
403
404 if ( $shard !== null ) { // confined to a single container/shard
405 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
406 $this->deleteContainerCache( $fullCont ); // purge cache
407 } else { // directory is on several shards
408 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
409 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
410 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
411 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
412 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
413 }
414 }
415
416 wfProfileOut( __METHOD__ . '-' . $this->name );
417 wfProfileOut( __METHOD__ );
418 return $status;
419 }
420
421 /**
422 * @see FileBackendStore::doClean()
423 * @return Status
424 */
425 protected function doCleanInternal( $container, $dir, array $params ) {
426 return Status::newGood();
427 }
428
429 /**
430 * @see FileBackend::fileExists()
431 * @return bool|null
432 */
433 final public function fileExists( array $params ) {
434 wfProfileIn( __METHOD__ );
435 wfProfileIn( __METHOD__ . '-' . $this->name );
436 $stat = $this->getFileStat( $params );
437 wfProfileOut( __METHOD__ . '-' . $this->name );
438 wfProfileOut( __METHOD__ );
439 return ( $stat === null ) ? null : (bool)$stat; // null => failure
440 }
441
442 /**
443 * @see FileBackend::getFileTimestamp()
444 * @return bool
445 */
446 final public function getFileTimestamp( array $params ) {
447 wfProfileIn( __METHOD__ );
448 wfProfileIn( __METHOD__ . '-' . $this->name );
449 $stat = $this->getFileStat( $params );
450 wfProfileOut( __METHOD__ . '-' . $this->name );
451 wfProfileOut( __METHOD__ );
452 return $stat ? $stat['mtime'] : false;
453 }
454
455 /**
456 * @see FileBackend::getFileSize()
457 * @return bool
458 */
459 final public function getFileSize( array $params ) {
460 wfProfileIn( __METHOD__ );
461 wfProfileIn( __METHOD__ . '-' . $this->name );
462 $stat = $this->getFileStat( $params );
463 wfProfileOut( __METHOD__ . '-' . $this->name );
464 wfProfileOut( __METHOD__ );
465 return $stat ? $stat['size'] : false;
466 }
467
468 /**
469 * @see FileBackend::getFileStat()
470 * @return bool
471 */
472 final public function getFileStat( array $params ) {
473 wfProfileIn( __METHOD__ );
474 wfProfileIn( __METHOD__ . '-' . $this->name );
475 $path = self::normalizeStoragePath( $params['src'] );
476 if ( $path === null ) {
477 wfProfileOut( __METHOD__ . '-' . $this->name );
478 wfProfileOut( __METHOD__ );
479 return false; // invalid storage path
480 }
481 $latest = !empty( $params['latest'] );
482 if ( isset( $this->cache[$path]['stat'] ) ) {
483 // If we want the latest data, check that this cached
484 // value was in fact fetched with the latest available data.
485 if ( !$latest || $this->cache[$path]['stat']['latest'] ) {
486 $this->pingCache( $path ); // LRU
487 wfProfileOut( __METHOD__ . '-' . $this->name );
488 wfProfileOut( __METHOD__ );
489 return $this->cache[$path]['stat'];
490 }
491 }
492 wfProfileIn( __METHOD__ . '-miss' );
493 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
494 $stat = $this->doGetFileStat( $params );
495 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
496 wfProfileOut( __METHOD__ . '-miss' );
497 if ( is_array( $stat ) ) { // don't cache negatives
498 $this->trimCache(); // limit memory
499 $this->cache[$path]['stat'] = $stat;
500 $this->cache[$path]['stat']['latest'] = $latest;
501 }
502 wfProfileOut( __METHOD__ . '-' . $this->name );
503 wfProfileOut( __METHOD__ );
504 return $stat;
505 }
506
507 /**
508 * @see FileBackendStore::getFileStat()
509 */
510 abstract protected function doGetFileStat( array $params );
511
512 /**
513 * @see FileBackend::getFileContents()
514 * @return bool|string
515 */
516 public function getFileContents( array $params ) {
517 wfProfileIn( __METHOD__ );
518 wfProfileIn( __METHOD__ . '-' . $this->name );
519 $tmpFile = $this->getLocalReference( $params );
520 if ( !$tmpFile ) {
521 wfProfileOut( __METHOD__ . '-' . $this->name );
522 wfProfileOut( __METHOD__ );
523 return false;
524 }
525 wfSuppressWarnings();
526 $data = file_get_contents( $tmpFile->getPath() );
527 wfRestoreWarnings();
528 wfProfileOut( __METHOD__ . '-' . $this->name );
529 wfProfileOut( __METHOD__ );
530 return $data;
531 }
532
533 /**
534 * @see FileBackend::getFileSha1Base36()
535 * @return bool|string
536 */
537 final public function getFileSha1Base36( array $params ) {
538 wfProfileIn( __METHOD__ );
539 wfProfileIn( __METHOD__ . '-' . $this->name );
540 $path = $params['src'];
541 if ( isset( $this->cache[$path]['sha1'] ) ) {
542 $this->pingCache( $path ); // LRU
543 wfProfileOut( __METHOD__ . '-' . $this->name );
544 wfProfileOut( __METHOD__ );
545 return $this->cache[$path]['sha1'];
546 }
547 wfProfileIn( __METHOD__ . '-miss' );
548 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
549 $hash = $this->doGetFileSha1Base36( $params );
550 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
551 wfProfileOut( __METHOD__ . '-miss' );
552 if ( $hash ) { // don't cache negatives
553 $this->trimCache(); // limit memory
554 $this->cache[$path]['sha1'] = $hash;
555 }
556 wfProfileOut( __METHOD__ . '-' . $this->name );
557 wfProfileOut( __METHOD__ );
558 return $hash;
559 }
560
561 /**
562 * @see FileBackendStore::getFileSha1Base36()
563 * @return bool
564 */
565 protected function doGetFileSha1Base36( array $params ) {
566 $fsFile = $this->getLocalReference( $params );
567 if ( !$fsFile ) {
568 return false;
569 } else {
570 return $fsFile->getSha1Base36();
571 }
572 }
573
574 /**
575 * @see FileBackend::getFileProps()
576 * @return Array
577 */
578 final public function getFileProps( array $params ) {
579 wfProfileIn( __METHOD__ );
580 wfProfileIn( __METHOD__ . '-' . $this->name );
581 $fsFile = $this->getLocalReference( $params );
582 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
583 wfProfileOut( __METHOD__ . '-' . $this->name );
584 wfProfileOut( __METHOD__ );
585 return $props;
586 }
587
588 /**
589 * @see FileBackend::getLocalReference()
590 * @return TempFSFile|null
591 */
592 public function getLocalReference( array $params ) {
593 wfProfileIn( __METHOD__ );
594 wfProfileIn( __METHOD__ . '-' . $this->name );
595 $path = $params['src'];
596 if ( isset( $this->expensiveCache[$path]['localRef'] ) ) {
597 $this->pingExpensiveCache( $path );
598 wfProfileOut( __METHOD__ . '-' . $this->name );
599 wfProfileOut( __METHOD__ );
600 return $this->expensiveCache[$path]['localRef'];
601 }
602 $tmpFile = $this->getLocalCopy( $params );
603 if ( $tmpFile ) { // don't cache negatives
604 $this->trimExpensiveCache(); // limit memory
605 $this->expensiveCache[$path]['localRef'] = $tmpFile;
606 }
607 wfProfileOut( __METHOD__ . '-' . $this->name );
608 wfProfileOut( __METHOD__ );
609 return $tmpFile;
610 }
611
612 /**
613 * @see FileBackend::streamFile()
614 * @return Status
615 */
616 final public function streamFile( array $params ) {
617 wfProfileIn( __METHOD__ );
618 wfProfileIn( __METHOD__ . '-' . $this->name );
619 $status = Status::newGood();
620
621 $info = $this->getFileStat( $params );
622 if ( !$info ) { // let StreamFile handle the 404
623 $status->fatal( 'backend-fail-notexists', $params['src'] );
624 }
625
626 // Set output buffer and HTTP headers for stream
627 $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
628 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
629 if ( $res == StreamFile::NOT_MODIFIED ) {
630 // do nothing; client cache is up to date
631 } elseif ( $res == StreamFile::READY_STREAM ) {
632 wfProfileIn( __METHOD__ . '-send' );
633 wfProfileIn( __METHOD__ . '-send-' . $this->name );
634 $status = $this->doStreamFile( $params );
635 wfProfileOut( __METHOD__ . '-send-' . $this->name );
636 wfProfileOut( __METHOD__ . '-send' );
637 } else {
638 $status->fatal( 'backend-fail-stream', $params['src'] );
639 }
640
641 wfProfileOut( __METHOD__ . '-' . $this->name );
642 wfProfileOut( __METHOD__ );
643 return $status;
644 }
645
646 /**
647 * @see FileBackendStore::streamFile()
648 * @return Status
649 */
650 protected function doStreamFile( array $params ) {
651 $status = Status::newGood();
652
653 $fsFile = $this->getLocalReference( $params );
654 if ( !$fsFile ) {
655 $status->fatal( 'backend-fail-stream', $params['src'] );
656 } elseif ( !readfile( $fsFile->getPath() ) ) {
657 $status->fatal( 'backend-fail-stream', $params['src'] );
658 }
659
660 return $status;
661 }
662
663 /**
664 * @see FileBackend::directoryExists()
665 * @return bool|null
666 */
667 final public function directoryExists( array $params ) {
668 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
669 if ( $dir === null ) {
670 return false; // invalid storage path
671 }
672 if ( $shard !== null ) { // confined to a single container/shard
673 return $this->doDirectoryExists( $fullCont, $dir, $params );
674 } else { // directory is on several shards
675 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
676 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
677 $res = false; // response
678 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
679 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
680 if ( $exists ) {
681 $res = true;
682 break; // found one!
683 } elseif ( $exists === null ) { // error?
684 $res = null; // if we don't find anything, it is indeterminate
685 }
686 }
687 return $res;
688 }
689 }
690
691 /**
692 * @see FileBackendStore::directoryExists()
693 *
694 * @param $container string Resolved container name
695 * @param $dir string Resolved path relative to container
696 * @param $params Array
697 * @return bool|null
698 */
699 abstract protected function doDirectoryExists( $container, $dir, array $params );
700
701 /**
702 * @see FileBackend::getDirectoryList()
703 * @return Array|null|Traversable
704 */
705 final public function getDirectoryList( array $params ) {
706 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
707 if ( $dir === null ) { // invalid storage path
708 return null;
709 }
710 if ( $shard !== null ) {
711 // File listing is confined to a single container/shard
712 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
713 } else {
714 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
715 // File listing spans multiple containers/shards
716 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
717 return new FileBackendStoreShardDirIterator( $this,
718 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
719 }
720 }
721
722 /**
723 * Do not call this function from places outside FileBackend
724 *
725 * @see FileBackendStore::getDirectoryList()
726 *
727 * @param $container string Resolved container name
728 * @param $dir string Resolved path relative to container
729 * @param $params Array
730 * @return Traversable|Array|null
731 */
732 abstract public function getDirectoryListInternal( $container, $dir, array $params );
733
734 /**
735 * @see FileBackend::getFileList()
736 * @return Array|null|Traversable
737 */
738 final public function getFileList( array $params ) {
739 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
740 if ( $dir === null ) { // invalid storage path
741 return null;
742 }
743 if ( $shard !== null ) {
744 // File listing is confined to a single container/shard
745 return $this->getFileListInternal( $fullCont, $dir, $params );
746 } else {
747 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
748 // File listing spans multiple containers/shards
749 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
750 return new FileBackendStoreShardFileIterator( $this,
751 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
752 }
753 }
754
755 /**
756 * Do not call this function from places outside FileBackend
757 *
758 * @see FileBackendStore::getFileList()
759 *
760 * @param $container string Resolved container name
761 * @param $dir string Resolved path relative to container
762 * @param $params Array
763 * @return Traversable|Array|null
764 */
765 abstract public function getFileListInternal( $container, $dir, array $params );
766
767 /**
768 * Get the list of supported operations and their corresponding FileOp classes.
769 *
770 * @return Array
771 */
772 protected function supportedOperations() {
773 return array(
774 'store' => 'StoreFileOp',
775 'copy' => 'CopyFileOp',
776 'move' => 'MoveFileOp',
777 'delete' => 'DeleteFileOp',
778 'create' => 'CreateFileOp',
779 'null' => 'NullFileOp'
780 );
781 }
782
783 /**
784 * Return a list of FileOp objects from a list of operations.
785 * Do not call this function from places outside FileBackend.
786 *
787 * The result must have the same number of items as the input.
788 * An exception is thrown if an unsupported operation is requested.
789 *
790 * @param $ops Array Same format as doOperations()
791 * @return Array List of FileOp objects
792 * @throws MWException
793 */
794 final public function getOperationsInternal( array $ops ) {
795 $supportedOps = $this->supportedOperations();
796
797 $performOps = array(); // array of FileOp objects
798 // Build up ordered array of FileOps...
799 foreach ( $ops as $operation ) {
800 $opName = $operation['op'];
801 if ( isset( $supportedOps[$opName] ) ) {
802 $class = $supportedOps[$opName];
803 // Get params for this operation
804 $params = $operation;
805 // Append the FileOp class
806 $performOps[] = new $class( $this, $params );
807 } else {
808 throw new MWException( "Operation '$opName' is not supported." );
809 }
810 }
811
812 return $performOps;
813 }
814
815 /**
816 * Get a list of storage paths to lock for a list of operations
817 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
818 * each corresponding to a list of storage paths to be locked.
819 *
820 * @param $performOps Array List of FileOp objects
821 * @return Array ('sh' => list of paths, 'ex' => list of paths)
822 */
823 final public function getPathsToLockForOpsInternal( array $performOps ) {
824 // Build up a list of files to lock...
825 $paths = array( 'sh' => array(), 'ex' => array() );
826 foreach ( $performOps as $fileOp ) {
827 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
828 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
829 }
830 // Optimization: if doing an EX lock anyway, don't also set an SH one
831 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
832 // Get a shared lock on the parent directory of each path changed
833 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
834
835 return $paths;
836 }
837
838 /**
839 * @see FileBackend::doOperationsInternal()
840 * @return Status
841 */
842 protected function doOperationsInternal( array $ops, array $opts ) {
843 wfProfileIn( __METHOD__ );
844 wfProfileIn( __METHOD__ . '-' . $this->name );
845 $status = Status::newGood();
846
847 // Build up a list of FileOps...
848 $performOps = $this->getOperationsInternal( $ops );
849
850 // Acquire any locks as needed...
851 if ( empty( $opts['nonLocking'] ) ) {
852 // Build up a list of files to lock...
853 $paths = $this->getPathsToLockForOpsInternal( $performOps );
854 // Try to lock those files for the scope of this function...
855 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status );
856 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status );
857 if ( !$status->isOK() ) {
858 wfProfileOut( __METHOD__ . '-' . $this->name );
859 wfProfileOut( __METHOD__ );
860 return $status; // abort
861 }
862 }
863
864 // Clear any file cache entries (after locks acquired)
865 $this->clearCache();
866
867 // Load from the persistent container cache
868 $this->primeContainerCache( $performOps );
869
870 // Actually attempt the operation batch...
871 $subStatus = FileOp::attemptBatch( $performOps, $opts, $this->fileJournal );
872
873 // Merge errors into status fields
874 $status->merge( $subStatus );
875 $status->success = $subStatus->success; // not done in merge()
876
877 wfProfileOut( __METHOD__ . '-' . $this->name );
878 wfProfileOut( __METHOD__ );
879 return $status;
880 }
881
882 /**
883 * @see FileBackend::clearCache()
884 */
885 final public function clearCache( array $paths = null ) {
886 if ( is_array( $paths ) ) {
887 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
888 $paths = array_filter( $paths, 'strlen' ); // remove nulls
889 }
890 if ( $paths === null ) {
891 $this->cache = array();
892 $this->expensiveCache = array();
893 } else {
894 foreach ( $paths as $path ) {
895 unset( $this->cache[$path] );
896 unset( $this->expensiveCache[$path] );
897 }
898 }
899 $this->doClearCache( $paths );
900 }
901
902 /**
903 * Clears any additional stat caches for storage paths
904 *
905 * @see FileBackend::clearCache()
906 *
907 * @param $paths Array Storage paths (optional)
908 * @return void
909 */
910 protected function doClearCache( array $paths = null ) {}
911
912 /**
913 * Move a cache entry to the top (such as when accessed)
914 *
915 * @param $path string Storage path
916 */
917 protected function pingCache( $path ) {
918 if ( isset( $this->cache[$path] ) ) {
919 $tmp = $this->cache[$path];
920 unset( $this->cache[$path] );
921 $this->cache[$path] = $tmp;
922 }
923 }
924
925 /**
926 * Prune the inexpensive cache if it is too big to add an item
927 *
928 * @return void
929 */
930 protected function trimCache() {
931 if ( count( $this->cache ) >= $this->maxCacheSize ) {
932 reset( $this->cache );
933 unset( $this->cache[key( $this->cache )] );
934 }
935 }
936
937 /**
938 * Move a cache entry to the top (such as when accessed)
939 *
940 * @param $path string Storage path
941 */
942 protected function pingExpensiveCache( $path ) {
943 if ( isset( $this->expensiveCache[$path] ) ) {
944 $tmp = $this->expensiveCache[$path];
945 unset( $this->expensiveCache[$path] );
946 $this->expensiveCache[$path] = $tmp;
947 }
948 }
949
950 /**
951 * Prune the expensive cache if it is too big to add an item
952 *
953 * @return void
954 */
955 protected function trimExpensiveCache() {
956 if ( count( $this->expensiveCache ) >= $this->maxExpensiveCacheSize ) {
957 reset( $this->expensiveCache );
958 unset( $this->expensiveCache[key( $this->expensiveCache )] );
959 }
960 }
961
962 /**
963 * Check if a container name is valid.
964 * This checks for for length and illegal characters.
965 *
966 * @param $container string
967 * @return bool
968 */
969 final protected static function isValidContainerName( $container ) {
970 // This accounts for Swift and S3 restrictions while leaving room
971 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
972 // This disallows directory separators or traversal characters.
973 // Note that matching strings URL encode to the same string;
974 // in Swift, the length restriction is *after* URL encoding.
975 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
976 }
977
978 /**
979 * Splits a storage path into an internal container name,
980 * an internal relative file name, and a container shard suffix.
981 * Any shard suffix is already appended to the internal container name.
982 * This also checks that the storage path is valid and within this backend.
983 *
984 * If the container is sharded but a suffix could not be determined,
985 * this means that the path can only refer to a directory and can only
986 * be scanned by looking in all the container shards.
987 *
988 * @param $storagePath string
989 * @return Array (container, path, container suffix) or (null, null, null) if invalid
990 */
991 final protected function resolveStoragePath( $storagePath ) {
992 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
993 if ( $backend === $this->name ) { // must be for this backend
994 $relPath = self::normalizeContainerPath( $relPath );
995 if ( $relPath !== null ) {
996 // Get shard for the normalized path if this container is sharded
997 $cShard = $this->getContainerShard( $container, $relPath );
998 // Validate and sanitize the relative path (backend-specific)
999 $relPath = $this->resolveContainerPath( $container, $relPath );
1000 if ( $relPath !== null ) {
1001 // Prepend any wiki ID prefix to the container name
1002 $container = $this->fullContainerName( $container );
1003 if ( self::isValidContainerName( $container ) ) {
1004 // Validate and sanitize the container name (backend-specific)
1005 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1006 if ( $container !== null ) {
1007 return array( $container, $relPath, $cShard );
1008 }
1009 }
1010 }
1011 }
1012 }
1013 return array( null, null, null );
1014 }
1015
1016 /**
1017 * Like resolveStoragePath() except null values are returned if
1018 * the container is sharded and the shard could not be determined.
1019 *
1020 * @see FileBackendStore::resolveStoragePath()
1021 *
1022 * @param $storagePath string
1023 * @return Array (container, path) or (null, null) if invalid
1024 */
1025 final protected function resolveStoragePathReal( $storagePath ) {
1026 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1027 if ( $cShard !== null ) {
1028 return array( $container, $relPath );
1029 }
1030 return array( null, null );
1031 }
1032
1033 /**
1034 * Get the container name shard suffix for a given path.
1035 * Any empty suffix means the container is not sharded.
1036 *
1037 * @param $container string Container name
1038 * @param $relStoragePath string Storage path relative to the container
1039 * @return string|null Returns null if shard could not be determined
1040 */
1041 final protected function getContainerShard( $container, $relPath ) {
1042 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1043 if ( $levels == 1 || $levels == 2 ) {
1044 // Hash characters are either base 16 or 36
1045 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1046 // Get a regex that represents the shard portion of paths.
1047 // The concatenation of the captures gives us the shard.
1048 if ( $levels === 1 ) { // 16 or 36 shards per container
1049 $hashDirRegex = '(' . $char . ')';
1050 } else { // 256 or 1296 shards per container
1051 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1052 $hashDirRegex = $char . '/(' . $char . '{2})';
1053 } else { // short hash dir format (e.g. "a/b/c")
1054 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1055 }
1056 }
1057 // Allow certain directories to be above the hash dirs so as
1058 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1059 // They must be 2+ chars to avoid any hash directory ambiguity.
1060 $m = array();
1061 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1062 return '.' . implode( '', array_slice( $m, 1 ) );
1063 }
1064 return null; // failed to match
1065 }
1066 return ''; // no sharding
1067 }
1068
1069 /**
1070 * Check if a storage path maps to a single shard.
1071 * Container dirs like "a", where the container shards on "x/xy",
1072 * can reside on several shards. Such paths are tricky to handle.
1073 *
1074 * @param $storagePath string Storage path
1075 * @return bool
1076 */
1077 final public function isSingleShardPathInternal( $storagePath ) {
1078 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1079 return ( $shard !== null );
1080 }
1081
1082 /**
1083 * Get the sharding config for a container.
1084 * If greater than 0, then all file storage paths within
1085 * the container are required to be hashed accordingly.
1086 *
1087 * @param $container string
1088 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1089 */
1090 final protected function getContainerHashLevels( $container ) {
1091 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1092 $config = $this->shardViaHashLevels[$container];
1093 $hashLevels = (int)$config['levels'];
1094 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1095 $hashBase = (int)$config['base'];
1096 if ( $hashBase == 16 || $hashBase == 36 ) {
1097 return array( $hashLevels, $hashBase, $config['repeat'] );
1098 }
1099 }
1100 }
1101 return array( 0, 0, false ); // no sharding
1102 }
1103
1104 /**
1105 * Get a list of full container shard suffixes for a container
1106 *
1107 * @param $container string
1108 * @return Array
1109 */
1110 final protected function getContainerSuffixes( $container ) {
1111 $shards = array();
1112 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1113 if ( $digits > 0 ) {
1114 $numShards = pow( $base, $digits );
1115 for ( $index = 0; $index < $numShards; $index++ ) {
1116 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1117 }
1118 }
1119 return $shards;
1120 }
1121
1122 /**
1123 * Get the full container name, including the wiki ID prefix
1124 *
1125 * @param $container string
1126 * @return string
1127 */
1128 final protected function fullContainerName( $container ) {
1129 if ( $this->wikiId != '' ) {
1130 return "{$this->wikiId}-$container";
1131 } else {
1132 return $container;
1133 }
1134 }
1135
1136 /**
1137 * Resolve a container name, checking if it's allowed by the backend.
1138 * This is intended for internal use, such as encoding illegal chars.
1139 * Subclasses can override this to be more restrictive.
1140 *
1141 * @param $container string
1142 * @return string|null
1143 */
1144 protected function resolveContainerName( $container ) {
1145 return $container;
1146 }
1147
1148 /**
1149 * Resolve a relative storage path, checking if it's allowed by the backend.
1150 * This is intended for internal use, such as encoding illegal chars or perhaps
1151 * getting absolute paths (e.g. FS based backends). Note that the relative path
1152 * may be the empty string (e.g. the path is simply to the container).
1153 *
1154 * @param $container string Container name
1155 * @param $relStoragePath string Storage path relative to the container
1156 * @return string|null Path or null if not valid
1157 */
1158 protected function resolveContainerPath( $container, $relStoragePath ) {
1159 return $relStoragePath;
1160 }
1161
1162 /**
1163 * Get the cache key for a container
1164 *
1165 * @param $container Resolved container name
1166 * @return string
1167 */
1168 private function containerCacheKey( $container ) {
1169 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1170 }
1171
1172 /**
1173 * Set the cached info for a container
1174 *
1175 * @param $container Resolved container name
1176 * @param $val mixed Information to cache
1177 * @return void
1178 */
1179 final protected function setContainerCache( $container, $val ) {
1180 $this->memCache->set( $this->containerCacheKey( $container ), $val, 7*86400 );
1181 }
1182
1183 /**
1184 * Delete the cached info for a container
1185 *
1186 * @param $container Resolved container name
1187 * @return void
1188 */
1189 final protected function deleteContainerCache( $container ) {
1190 $this->memCache->delete( $this->containerCacheKey( $container ) );
1191 }
1192
1193 /**
1194 * Do a batch lookup from cache for container stats for all containers
1195 * used in a list of container names, storage paths, or FileOp objects.
1196 *
1197 * @param $items Array List of storage paths or FileOps
1198 * @return void
1199 */
1200 final protected function primeContainerCache( array $items ) {
1201 $paths = array(); // list of storage paths
1202 $contNames = array(); // (cache key => resolved container name)
1203 // Get all the paths/containers from the items...
1204 foreach ( $items as $item ) {
1205 if ( $item instanceof FileOp ) {
1206 $paths = array_merge( $paths, $item->storagePathsRead() );
1207 $paths = array_merge( $paths, $item->storagePathsChanged() );
1208 } elseif ( self::isStoragePath( $item ) ) {
1209 $paths[] = $item;
1210 } elseif ( is_string( $item ) ) { // full container name
1211 $contNames[$this->containerCacheKey( $item )] = $item;
1212 }
1213 }
1214 // Get all the corresponding cache keys for paths...
1215 foreach ( $paths as $path ) {
1216 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1217 if ( $fullCont !== null ) { // valid path for this backend
1218 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1219 }
1220 }
1221
1222 $contInfo = array(); // (resolved container name => cache value)
1223 // Get all cache entries for these container cache keys...
1224 $values = $this->memCache->getBatch( array_keys( $contNames ) );
1225 foreach ( $values as $cacheKey => $val ) {
1226 $contInfo[$contNames[$cacheKey]] = $val;
1227 }
1228
1229 // Populate the container process cache for the backend...
1230 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1231 }
1232
1233 /**
1234 * Fill the backend-specific process cache given an array of
1235 * resolved container names and their corresponding cached info.
1236 * Only containers that actually exist should appear in the map.
1237 *
1238 * @param $containerInfo Array Map of resolved container names to cached info
1239 * @return void
1240 */
1241 protected function doPrimeContainerCache( array $containerInfo ) {}
1242 }
1243
1244 /**
1245 * FileBackendStore helper function to handle listings that span container shards.
1246 * Do not use this class from places outside of FileBackendStore.
1247 *
1248 * @ingroup FileBackend
1249 */
1250 abstract class FileBackendStoreShardListIterator implements Iterator {
1251 /** @var FileBackendStore */
1252 protected $backend;
1253 /** @var Array */
1254 protected $params;
1255 /** @var Array */
1256 protected $shardSuffixes;
1257 protected $container; // string; full container name
1258 protected $directory; // string; resolved relative path
1259
1260 /** @var Traversable */
1261 protected $iter;
1262 protected $curShard = 0; // integer
1263 protected $pos = 0; // integer
1264
1265 /** @var Array */
1266 protected $multiShardPaths = array(); // (rel path => 1)
1267
1268 /**
1269 * @param $backend FileBackendStore
1270 * @param $container string Full storage container name
1271 * @param $dir string Storage directory relative to container
1272 * @param $suffixes Array List of container shard suffixes
1273 * @param $params Array
1274 */
1275 public function __construct(
1276 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1277 ) {
1278 $this->backend = $backend;
1279 $this->container = $container;
1280 $this->directory = $dir;
1281 $this->shardSuffixes = $suffixes;
1282 $this->params = $params;
1283 }
1284
1285 /**
1286 * @see Iterator::current()
1287 * @return string|bool String or false
1288 */
1289 public function current() {
1290 if ( is_array( $this->iter ) ) {
1291 return current( $this->iter );
1292 } else {
1293 return $this->iter->current();
1294 }
1295 }
1296
1297 /**
1298 * @see Iterator::key()
1299 * @return integer
1300 */
1301 public function key() {
1302 return $this->pos;
1303 }
1304
1305 /**
1306 * @see Iterator::next()
1307 * @return void
1308 */
1309 public function next() {
1310 ++$this->pos;
1311 if ( is_array( $this->iter ) ) {
1312 next( $this->iter );
1313 } else {
1314 $this->iter->next();
1315 }
1316 // Filter out items that we already listed
1317 $this->filterViaNext();
1318 // Find the next non-empty shard if no elements are left
1319 $this->nextShardIteratorIfNotValid();
1320 }
1321
1322 /**
1323 * @see Iterator::rewind()
1324 * @return void
1325 */
1326 public function rewind() {
1327 $this->pos = 0;
1328 $this->curShard = 0;
1329 $this->setIteratorFromCurrentShard();
1330 // Filter out items that we already listed
1331 $this->filterViaNext();
1332 // Find the next non-empty shard if this one has no elements
1333 $this->nextShardIteratorIfNotValid();
1334 }
1335
1336 /**
1337 * @see Iterator::valid()
1338 * @return bool
1339 */
1340 public function valid() {
1341 if ( $this->iter == null ) {
1342 return false; // some failure?
1343 } elseif ( is_array( $this->iter ) ) {
1344 return ( current( $this->iter ) !== false ); // no paths can have this value
1345 } else {
1346 return $this->iter->valid();
1347 }
1348 }
1349
1350 /**
1351 * Filter out duplicate items by advancing to the next ones
1352 */
1353 protected function filterViaNext() {
1354 while ( $this->iter->valid() ) {
1355 $rel = $this->iter->current(); // path relative to given directory
1356 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1357 if ( !$this->backend->isSingleShardPathInternal( $path ) ) {
1358 // Don't keep listing paths that are on multiple shards
1359 if ( isset( $this->multiShardPaths[$rel] ) ) {
1360 $this->iter->next(); // we already listed this path
1361 } else {
1362 $this->multiShardPaths[$rel] = 1;
1363 break;
1364 }
1365 }
1366 }
1367 }
1368
1369 /**
1370 * If the list iterator for this container shard is out of items,
1371 * then move on to the next container that has items.
1372 * If there are none, then it advances to the last container.
1373 */
1374 protected function nextShardIteratorIfNotValid() {
1375 while ( !$this->valid() ) {
1376 if ( ++$this->curShard >= count( $this->shardSuffixes ) ) {
1377 break; // no more container shards
1378 }
1379 $this->setIteratorFromCurrentShard();
1380 }
1381 }
1382
1383 /**
1384 * Set the list iterator to that of the current container shard
1385 */
1386 protected function setIteratorFromCurrentShard() {
1387 $suffix = $this->shardSuffixes[$this->curShard];
1388 $this->iter = $this->listFromShard(
1389 "{$this->container}{$suffix}", $this->directory, $this->params );
1390 }
1391
1392 /**
1393 * Get the list for a given container shard
1394 *
1395 * @param $container string Resolved container name
1396 * @param $dir string Resolved path relative to container
1397 * @param $params Array
1398 * @return Traversable|Array|null
1399 */
1400 abstract protected function listFromShard( $container, $dir, array $params );
1401 }
1402
1403 /**
1404 * Iterator for listing directories
1405 */
1406 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1407 protected function listFromShard( $container, $dir, array $params ) {
1408 return $this->backend->getDirectoryListInternal( $container, $dir, $params );
1409 }
1410 }
1411
1412 /**
1413 * Iterator for listing regular files
1414 */
1415 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1416 protected function listFromShard( $container, $dir, array $params ) {
1417 return $this->backend->getFileListInternal( $container, $dir, $params );
1418 }
1419 }