803f966a02614a43aa1485a0517c1b8dd9c62bc2
[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 = 300; // 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 = 5; // 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 // Recursive: first delete all empty subdirs recursively
388 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
389 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
390 if ( $subDirsRel !== null ) { // no errors
391 foreach ( $subDirsRel as $subDirRel ) {
392 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
393 $status->merge( $this->doClean( array( 'dir' => $subDir ) + $params ) );
394 }
395 }
396 }
397
398 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
399 if ( $dir === null ) {
400 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
401 wfProfileOut( __METHOD__ . '-' . $this->name );
402 wfProfileOut( __METHOD__ );
403 return $status; // invalid storage path
404 }
405
406 // Attempt to lock this directory...
407 $filesLockEx = array( $params['dir'] );
408 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager::LOCK_EX, $status );
409 if ( !$status->isOK() ) {
410 wfProfileOut( __METHOD__ . '-' . $this->name );
411 wfProfileOut( __METHOD__ );
412 return $status; // abort
413 }
414
415 if ( $shard !== null ) { // confined to a single container/shard
416 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
417 $this->deleteContainerCache( $fullCont ); // purge cache
418 } else { // directory is on several shards
419 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
420 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
421 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
422 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
423 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
424 }
425 }
426
427 wfProfileOut( __METHOD__ . '-' . $this->name );
428 wfProfileOut( __METHOD__ );
429 return $status;
430 }
431
432 /**
433 * @see FileBackendStore::doClean()
434 * @return Status
435 */
436 protected function doCleanInternal( $container, $dir, array $params ) {
437 return Status::newGood();
438 }
439
440 /**
441 * @see FileBackend::fileExists()
442 * @return bool|null
443 */
444 final public function fileExists( array $params ) {
445 wfProfileIn( __METHOD__ );
446 wfProfileIn( __METHOD__ . '-' . $this->name );
447 $stat = $this->getFileStat( $params );
448 wfProfileOut( __METHOD__ . '-' . $this->name );
449 wfProfileOut( __METHOD__ );
450 return ( $stat === null ) ? null : (bool)$stat; // null => failure
451 }
452
453 /**
454 * @see FileBackend::getFileTimestamp()
455 * @return bool
456 */
457 final public function getFileTimestamp( array $params ) {
458 wfProfileIn( __METHOD__ );
459 wfProfileIn( __METHOD__ . '-' . $this->name );
460 $stat = $this->getFileStat( $params );
461 wfProfileOut( __METHOD__ . '-' . $this->name );
462 wfProfileOut( __METHOD__ );
463 return $stat ? $stat['mtime'] : false;
464 }
465
466 /**
467 * @see FileBackend::getFileSize()
468 * @return bool
469 */
470 final public function getFileSize( array $params ) {
471 wfProfileIn( __METHOD__ );
472 wfProfileIn( __METHOD__ . '-' . $this->name );
473 $stat = $this->getFileStat( $params );
474 wfProfileOut( __METHOD__ . '-' . $this->name );
475 wfProfileOut( __METHOD__ );
476 return $stat ? $stat['size'] : false;
477 }
478
479 /**
480 * @see FileBackend::getFileStat()
481 * @return bool
482 */
483 final public function getFileStat( array $params ) {
484 wfProfileIn( __METHOD__ );
485 wfProfileIn( __METHOD__ . '-' . $this->name );
486 $path = self::normalizeStoragePath( $params['src'] );
487 if ( $path === null ) {
488 wfProfileOut( __METHOD__ . '-' . $this->name );
489 wfProfileOut( __METHOD__ );
490 return false; // invalid storage path
491 }
492 $latest = !empty( $params['latest'] );
493 if ( isset( $this->cache[$path]['stat'] ) ) {
494 // If we want the latest data, check that this cached
495 // value was in fact fetched with the latest available data.
496 if ( !$latest || $this->cache[$path]['stat']['latest'] ) {
497 $this->pingCache( $path ); // LRU
498 wfProfileOut( __METHOD__ . '-' . $this->name );
499 wfProfileOut( __METHOD__ );
500 return $this->cache[$path]['stat'];
501 }
502 }
503 wfProfileIn( __METHOD__ . '-miss' );
504 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
505 $stat = $this->doGetFileStat( $params );
506 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
507 wfProfileOut( __METHOD__ . '-miss' );
508 if ( is_array( $stat ) ) { // don't cache negatives
509 $this->trimCache(); // limit memory
510 $this->cache[$path]['stat'] = $stat;
511 $this->cache[$path]['stat']['latest'] = $latest;
512 }
513 wfProfileOut( __METHOD__ . '-' . $this->name );
514 wfProfileOut( __METHOD__ );
515 return $stat;
516 }
517
518 /**
519 * @see FileBackendStore::getFileStat()
520 */
521 abstract protected function doGetFileStat( array $params );
522
523 /**
524 * @see FileBackend::getFileContents()
525 * @return bool|string
526 */
527 public function getFileContents( array $params ) {
528 wfProfileIn( __METHOD__ );
529 wfProfileIn( __METHOD__ . '-' . $this->name );
530 $tmpFile = $this->getLocalReference( $params );
531 if ( !$tmpFile ) {
532 wfProfileOut( __METHOD__ . '-' . $this->name );
533 wfProfileOut( __METHOD__ );
534 return false;
535 }
536 wfSuppressWarnings();
537 $data = file_get_contents( $tmpFile->getPath() );
538 wfRestoreWarnings();
539 wfProfileOut( __METHOD__ . '-' . $this->name );
540 wfProfileOut( __METHOD__ );
541 return $data;
542 }
543
544 /**
545 * @see FileBackend::getFileSha1Base36()
546 * @return bool|string
547 */
548 final public function getFileSha1Base36( array $params ) {
549 wfProfileIn( __METHOD__ );
550 wfProfileIn( __METHOD__ . '-' . $this->name );
551 $path = $params['src'];
552 if ( isset( $this->cache[$path]['sha1'] ) ) {
553 $this->pingCache( $path ); // LRU
554 wfProfileOut( __METHOD__ . '-' . $this->name );
555 wfProfileOut( __METHOD__ );
556 return $this->cache[$path]['sha1'];
557 }
558 wfProfileIn( __METHOD__ . '-miss' );
559 wfProfileIn( __METHOD__ . '-miss-' . $this->name );
560 $hash = $this->doGetFileSha1Base36( $params );
561 wfProfileOut( __METHOD__ . '-miss-' . $this->name );
562 wfProfileOut( __METHOD__ . '-miss' );
563 if ( $hash ) { // don't cache negatives
564 $this->trimCache(); // limit memory
565 $this->cache[$path]['sha1'] = $hash;
566 }
567 wfProfileOut( __METHOD__ . '-' . $this->name );
568 wfProfileOut( __METHOD__ );
569 return $hash;
570 }
571
572 /**
573 * @see FileBackendStore::getFileSha1Base36()
574 * @return bool
575 */
576 protected function doGetFileSha1Base36( array $params ) {
577 $fsFile = $this->getLocalReference( $params );
578 if ( !$fsFile ) {
579 return false;
580 } else {
581 return $fsFile->getSha1Base36();
582 }
583 }
584
585 /**
586 * @see FileBackend::getFileProps()
587 * @return Array
588 */
589 final public function getFileProps( array $params ) {
590 wfProfileIn( __METHOD__ );
591 wfProfileIn( __METHOD__ . '-' . $this->name );
592 $fsFile = $this->getLocalReference( $params );
593 $props = $fsFile ? $fsFile->getProps() : FSFile::placeholderProps();
594 wfProfileOut( __METHOD__ . '-' . $this->name );
595 wfProfileOut( __METHOD__ );
596 return $props;
597 }
598
599 /**
600 * @see FileBackend::getLocalReference()
601 * @return TempFSFile|null
602 */
603 public function getLocalReference( array $params ) {
604 wfProfileIn( __METHOD__ );
605 wfProfileIn( __METHOD__ . '-' . $this->name );
606 $path = $params['src'];
607 if ( isset( $this->expensiveCache[$path]['localRef'] ) ) {
608 $this->pingExpensiveCache( $path );
609 wfProfileOut( __METHOD__ . '-' . $this->name );
610 wfProfileOut( __METHOD__ );
611 return $this->expensiveCache[$path]['localRef'];
612 }
613 $tmpFile = $this->getLocalCopy( $params );
614 if ( $tmpFile ) { // don't cache negatives
615 $this->trimExpensiveCache(); // limit memory
616 $this->expensiveCache[$path]['localRef'] = $tmpFile;
617 }
618 wfProfileOut( __METHOD__ . '-' . $this->name );
619 wfProfileOut( __METHOD__ );
620 return $tmpFile;
621 }
622
623 /**
624 * @see FileBackend::streamFile()
625 * @return Status
626 */
627 final public function streamFile( array $params ) {
628 wfProfileIn( __METHOD__ );
629 wfProfileIn( __METHOD__ . '-' . $this->name );
630 $status = Status::newGood();
631
632 $info = $this->getFileStat( $params );
633 if ( !$info ) { // let StreamFile handle the 404
634 $status->fatal( 'backend-fail-notexists', $params['src'] );
635 }
636
637 // Set output buffer and HTTP headers for stream
638 $extraHeaders = isset( $params['headers'] ) ? $params['headers'] : array();
639 $res = StreamFile::prepareForStream( $params['src'], $info, $extraHeaders );
640 if ( $res == StreamFile::NOT_MODIFIED ) {
641 // do nothing; client cache is up to date
642 } elseif ( $res == StreamFile::READY_STREAM ) {
643 wfProfileIn( __METHOD__ . '-send' );
644 wfProfileIn( __METHOD__ . '-send-' . $this->name );
645 $status = $this->doStreamFile( $params );
646 wfProfileOut( __METHOD__ . '-send-' . $this->name );
647 wfProfileOut( __METHOD__ . '-send' );
648 } else {
649 $status->fatal( 'backend-fail-stream', $params['src'] );
650 }
651
652 wfProfileOut( __METHOD__ . '-' . $this->name );
653 wfProfileOut( __METHOD__ );
654 return $status;
655 }
656
657 /**
658 * @see FileBackendStore::streamFile()
659 * @return Status
660 */
661 protected function doStreamFile( array $params ) {
662 $status = Status::newGood();
663
664 $fsFile = $this->getLocalReference( $params );
665 if ( !$fsFile ) {
666 $status->fatal( 'backend-fail-stream', $params['src'] );
667 } elseif ( !readfile( $fsFile->getPath() ) ) {
668 $status->fatal( 'backend-fail-stream', $params['src'] );
669 }
670
671 return $status;
672 }
673
674 /**
675 * @see FileBackend::directoryExists()
676 * @return bool|null
677 */
678 final public function directoryExists( array $params ) {
679 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
680 if ( $dir === null ) {
681 return false; // invalid storage path
682 }
683 if ( $shard !== null ) { // confined to a single container/shard
684 return $this->doDirectoryExists( $fullCont, $dir, $params );
685 } else { // directory is on several shards
686 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
687 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
688 $res = false; // response
689 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
690 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
691 if ( $exists ) {
692 $res = true;
693 break; // found one!
694 } elseif ( $exists === null ) { // error?
695 $res = null; // if we don't find anything, it is indeterminate
696 }
697 }
698 return $res;
699 }
700 }
701
702 /**
703 * @see FileBackendStore::directoryExists()
704 *
705 * @param $container string Resolved container name
706 * @param $dir string Resolved path relative to container
707 * @param $params Array
708 * @return bool|null
709 */
710 abstract protected function doDirectoryExists( $container, $dir, array $params );
711
712 /**
713 * @see FileBackend::getDirectoryList()
714 * @return Array|null|Traversable
715 */
716 final public function getDirectoryList( array $params ) {
717 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
718 if ( $dir === null ) { // invalid storage path
719 return null;
720 }
721 if ( $shard !== null ) {
722 // File listing is confined to a single container/shard
723 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
724 } else {
725 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
726 // File listing spans multiple containers/shards
727 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
728 return new FileBackendStoreShardDirIterator( $this,
729 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
730 }
731 }
732
733 /**
734 * Do not call this function from places outside FileBackend
735 *
736 * @see FileBackendStore::getDirectoryList()
737 *
738 * @param $container string Resolved container name
739 * @param $dir string Resolved path relative to container
740 * @param $params Array
741 * @return Traversable|Array|null
742 */
743 abstract public function getDirectoryListInternal( $container, $dir, array $params );
744
745 /**
746 * @see FileBackend::getFileList()
747 * @return Array|null|Traversable
748 */
749 final public function getFileList( array $params ) {
750 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
751 if ( $dir === null ) { // invalid storage path
752 return null;
753 }
754 if ( $shard !== null ) {
755 // File listing is confined to a single container/shard
756 return $this->getFileListInternal( $fullCont, $dir, $params );
757 } else {
758 wfDebug( __METHOD__ . ": iterating over all container shards.\n" );
759 // File listing spans multiple containers/shards
760 list( $b, $shortCont, $r ) = self::splitStoragePath( $params['dir'] );
761 return new FileBackendStoreShardFileIterator( $this,
762 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
763 }
764 }
765
766 /**
767 * Do not call this function from places outside FileBackend
768 *
769 * @see FileBackendStore::getFileList()
770 *
771 * @param $container string Resolved container name
772 * @param $dir string Resolved path relative to container
773 * @param $params Array
774 * @return Traversable|Array|null
775 */
776 abstract public function getFileListInternal( $container, $dir, array $params );
777
778 /**
779 * Get the list of supported operations and their corresponding FileOp classes.
780 *
781 * @return Array
782 */
783 protected function supportedOperations() {
784 return array(
785 'store' => 'StoreFileOp',
786 'copy' => 'CopyFileOp',
787 'move' => 'MoveFileOp',
788 'delete' => 'DeleteFileOp',
789 'create' => 'CreateFileOp',
790 'null' => 'NullFileOp'
791 );
792 }
793
794 /**
795 * Return a list of FileOp objects from a list of operations.
796 * Do not call this function from places outside FileBackend.
797 *
798 * The result must have the same number of items as the input.
799 * An exception is thrown if an unsupported operation is requested.
800 *
801 * @param $ops Array Same format as doOperations()
802 * @return Array List of FileOp objects
803 * @throws MWException
804 */
805 final public function getOperationsInternal( array $ops ) {
806 $supportedOps = $this->supportedOperations();
807
808 $performOps = array(); // array of FileOp objects
809 // Build up ordered array of FileOps...
810 foreach ( $ops as $operation ) {
811 $opName = $operation['op'];
812 if ( isset( $supportedOps[$opName] ) ) {
813 $class = $supportedOps[$opName];
814 // Get params for this operation
815 $params = $operation;
816 // Append the FileOp class
817 $performOps[] = new $class( $this, $params );
818 } else {
819 throw new MWException( "Operation '$opName' is not supported." );
820 }
821 }
822
823 return $performOps;
824 }
825
826 /**
827 * Get a list of storage paths to lock for a list of operations
828 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
829 * each corresponding to a list of storage paths to be locked.
830 *
831 * @param $performOps Array List of FileOp objects
832 * @return Array ('sh' => list of paths, 'ex' => list of paths)
833 */
834 final public function getPathsToLockForOpsInternal( array $performOps ) {
835 // Build up a list of files to lock...
836 $paths = array( 'sh' => array(), 'ex' => array() );
837 foreach ( $performOps as $fileOp ) {
838 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
839 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
840 }
841 // Optimization: if doing an EX lock anyway, don't also set an SH one
842 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
843 // Get a shared lock on the parent directory of each path changed
844 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
845
846 return $paths;
847 }
848
849 /**
850 * @see FileBackend::doOperationsInternal()
851 * @return Status
852 */
853 protected function doOperationsInternal( array $ops, array $opts ) {
854 wfProfileIn( __METHOD__ );
855 wfProfileIn( __METHOD__ . '-' . $this->name );
856 $status = Status::newGood();
857
858 // Build up a list of FileOps...
859 $performOps = $this->getOperationsInternal( $ops );
860
861 // Acquire any locks as needed...
862 if ( empty( $opts['nonLocking'] ) ) {
863 // Build up a list of files to lock...
864 $paths = $this->getPathsToLockForOpsInternal( $performOps );
865 // Try to lock those files for the scope of this function...
866 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager::LOCK_UW, $status );
867 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager::LOCK_EX, $status );
868 if ( !$status->isOK() ) {
869 wfProfileOut( __METHOD__ . '-' . $this->name );
870 wfProfileOut( __METHOD__ );
871 return $status; // abort
872 }
873 }
874
875 // Clear any file cache entries (after locks acquired)
876 $this->clearCache();
877
878 // Load from the persistent container cache
879 $this->primeContainerCache( $performOps );
880
881 // Actually attempt the operation batch...
882 $subStatus = FileOp::attemptBatch( $performOps, $opts, $this->fileJournal );
883
884 // Merge errors into status fields
885 $status->merge( $subStatus );
886 $status->success = $subStatus->success; // not done in merge()
887
888 wfProfileOut( __METHOD__ . '-' . $this->name );
889 wfProfileOut( __METHOD__ );
890 return $status;
891 }
892
893 /**
894 * @see FileBackend::clearCache()
895 */
896 final public function clearCache( array $paths = null ) {
897 if ( is_array( $paths ) ) {
898 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
899 $paths = array_filter( $paths, 'strlen' ); // remove nulls
900 }
901 if ( $paths === null ) {
902 $this->cache = array();
903 $this->expensiveCache = array();
904 } else {
905 foreach ( $paths as $path ) {
906 unset( $this->cache[$path] );
907 unset( $this->expensiveCache[$path] );
908 }
909 }
910 $this->doClearCache( $paths );
911 }
912
913 /**
914 * Clears any additional stat caches for storage paths
915 *
916 * @see FileBackend::clearCache()
917 *
918 * @param $paths Array Storage paths (optional)
919 * @return void
920 */
921 protected function doClearCache( array $paths = null ) {}
922
923 /**
924 * Is this a key/value store where directories are just virtual?
925 * Virtual directories exists in so much as files exists that are
926 * prefixed with the directory path followed by a forward slash.
927 *
928 * @return bool
929 */
930 abstract protected function directoriesAreVirtual();
931
932 /**
933 * Move a cache entry to the top (such as when accessed)
934 *
935 * @param $path string Storage path
936 */
937 protected function pingCache( $path ) {
938 if ( isset( $this->cache[$path] ) ) {
939 $tmp = $this->cache[$path];
940 unset( $this->cache[$path] );
941 $this->cache[$path] = $tmp;
942 }
943 }
944
945 /**
946 * Prune the inexpensive cache if it is too big to add an item
947 *
948 * @return void
949 */
950 protected function trimCache() {
951 if ( count( $this->cache ) >= $this->maxCacheSize ) {
952 reset( $this->cache );
953 unset( $this->cache[key( $this->cache )] );
954 }
955 }
956
957 /**
958 * Move a cache entry to the top (such as when accessed)
959 *
960 * @param $path string Storage path
961 */
962 protected function pingExpensiveCache( $path ) {
963 if ( isset( $this->expensiveCache[$path] ) ) {
964 $tmp = $this->expensiveCache[$path];
965 unset( $this->expensiveCache[$path] );
966 $this->expensiveCache[$path] = $tmp;
967 }
968 }
969
970 /**
971 * Prune the expensive cache if it is too big to add an item
972 *
973 * @return void
974 */
975 protected function trimExpensiveCache() {
976 if ( count( $this->expensiveCache ) >= $this->maxExpensiveCacheSize ) {
977 reset( $this->expensiveCache );
978 unset( $this->expensiveCache[key( $this->expensiveCache )] );
979 }
980 }
981
982 /**
983 * Check if a container name is valid.
984 * This checks for for length and illegal characters.
985 *
986 * @param $container string
987 * @return bool
988 */
989 final protected static function isValidContainerName( $container ) {
990 // This accounts for Swift and S3 restrictions while leaving room
991 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
992 // This disallows directory separators or traversal characters.
993 // Note that matching strings URL encode to the same string;
994 // in Swift, the length restriction is *after* URL encoding.
995 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
996 }
997
998 /**
999 * Splits a storage path into an internal container name,
1000 * an internal relative file name, and a container shard suffix.
1001 * Any shard suffix is already appended to the internal container name.
1002 * This also checks that the storage path is valid and within this backend.
1003 *
1004 * If the container is sharded but a suffix could not be determined,
1005 * this means that the path can only refer to a directory and can only
1006 * be scanned by looking in all the container shards.
1007 *
1008 * @param $storagePath string
1009 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1010 */
1011 final protected function resolveStoragePath( $storagePath ) {
1012 list( $backend, $container, $relPath ) = self::splitStoragePath( $storagePath );
1013 if ( $backend === $this->name ) { // must be for this backend
1014 $relPath = self::normalizeContainerPath( $relPath );
1015 if ( $relPath !== null ) {
1016 // Get shard for the normalized path if this container is sharded
1017 $cShard = $this->getContainerShard( $container, $relPath );
1018 // Validate and sanitize the relative path (backend-specific)
1019 $relPath = $this->resolveContainerPath( $container, $relPath );
1020 if ( $relPath !== null ) {
1021 // Prepend any wiki ID prefix to the container name
1022 $container = $this->fullContainerName( $container );
1023 if ( self::isValidContainerName( $container ) ) {
1024 // Validate and sanitize the container name (backend-specific)
1025 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1026 if ( $container !== null ) {
1027 return array( $container, $relPath, $cShard );
1028 }
1029 }
1030 }
1031 }
1032 }
1033 return array( null, null, null );
1034 }
1035
1036 /**
1037 * Like resolveStoragePath() except null values are returned if
1038 * the container is sharded and the shard could not be determined.
1039 *
1040 * @see FileBackendStore::resolveStoragePath()
1041 *
1042 * @param $storagePath string
1043 * @return Array (container, path) or (null, null) if invalid
1044 */
1045 final protected function resolveStoragePathReal( $storagePath ) {
1046 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1047 if ( $cShard !== null ) {
1048 return array( $container, $relPath );
1049 }
1050 return array( null, null );
1051 }
1052
1053 /**
1054 * Get the container name shard suffix for a given path.
1055 * Any empty suffix means the container is not sharded.
1056 *
1057 * @param $container string Container name
1058 * @param $relStoragePath string Storage path relative to the container
1059 * @return string|null Returns null if shard could not be determined
1060 */
1061 final protected function getContainerShard( $container, $relPath ) {
1062 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1063 if ( $levels == 1 || $levels == 2 ) {
1064 // Hash characters are either base 16 or 36
1065 $char = ( $base == 36 ) ? '[0-9a-z]' : '[0-9a-f]';
1066 // Get a regex that represents the shard portion of paths.
1067 // The concatenation of the captures gives us the shard.
1068 if ( $levels === 1 ) { // 16 or 36 shards per container
1069 $hashDirRegex = '(' . $char . ')';
1070 } else { // 256 or 1296 shards per container
1071 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1072 $hashDirRegex = $char . '/(' . $char . '{2})';
1073 } else { // short hash dir format (e.g. "a/b/c")
1074 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1075 }
1076 }
1077 // Allow certain directories to be above the hash dirs so as
1078 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1079 // They must be 2+ chars to avoid any hash directory ambiguity.
1080 $m = array();
1081 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1082 return '.' . implode( '', array_slice( $m, 1 ) );
1083 }
1084 return null; // failed to match
1085 }
1086 return ''; // no sharding
1087 }
1088
1089 /**
1090 * Check if a storage path maps to a single shard.
1091 * Container dirs like "a", where the container shards on "x/xy",
1092 * can reside on several shards. Such paths are tricky to handle.
1093 *
1094 * @param $storagePath string Storage path
1095 * @return bool
1096 */
1097 final public function isSingleShardPathInternal( $storagePath ) {
1098 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1099 return ( $shard !== null );
1100 }
1101
1102 /**
1103 * Get the sharding config for a container.
1104 * If greater than 0, then all file storage paths within
1105 * the container are required to be hashed accordingly.
1106 *
1107 * @param $container string
1108 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1109 */
1110 final protected function getContainerHashLevels( $container ) {
1111 if ( isset( $this->shardViaHashLevels[$container] ) ) {
1112 $config = $this->shardViaHashLevels[$container];
1113 $hashLevels = (int)$config['levels'];
1114 if ( $hashLevels == 1 || $hashLevels == 2 ) {
1115 $hashBase = (int)$config['base'];
1116 if ( $hashBase == 16 || $hashBase == 36 ) {
1117 return array( $hashLevels, $hashBase, $config['repeat'] );
1118 }
1119 }
1120 }
1121 return array( 0, 0, false ); // no sharding
1122 }
1123
1124 /**
1125 * Get a list of full container shard suffixes for a container
1126 *
1127 * @param $container string
1128 * @return Array
1129 */
1130 final protected function getContainerSuffixes( $container ) {
1131 $shards = array();
1132 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1133 if ( $digits > 0 ) {
1134 $numShards = pow( $base, $digits );
1135 for ( $index = 0; $index < $numShards; $index++ ) {
1136 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1137 }
1138 }
1139 return $shards;
1140 }
1141
1142 /**
1143 * Get the full container name, including the wiki ID prefix
1144 *
1145 * @param $container string
1146 * @return string
1147 */
1148 final protected function fullContainerName( $container ) {
1149 if ( $this->wikiId != '' ) {
1150 return "{$this->wikiId}-$container";
1151 } else {
1152 return $container;
1153 }
1154 }
1155
1156 /**
1157 * Resolve a container name, checking if it's allowed by the backend.
1158 * This is intended for internal use, such as encoding illegal chars.
1159 * Subclasses can override this to be more restrictive.
1160 *
1161 * @param $container string
1162 * @return string|null
1163 */
1164 protected function resolveContainerName( $container ) {
1165 return $container;
1166 }
1167
1168 /**
1169 * Resolve a relative storage path, checking if it's allowed by the backend.
1170 * This is intended for internal use, such as encoding illegal chars or perhaps
1171 * getting absolute paths (e.g. FS based backends). Note that the relative path
1172 * may be the empty string (e.g. the path is simply to the container).
1173 *
1174 * @param $container string Container name
1175 * @param $relStoragePath string Storage path relative to the container
1176 * @return string|null Path or null if not valid
1177 */
1178 protected function resolveContainerPath( $container, $relStoragePath ) {
1179 return $relStoragePath;
1180 }
1181
1182 /**
1183 * Get the cache key for a container
1184 *
1185 * @param $container Resolved container name
1186 * @return string
1187 */
1188 private function containerCacheKey( $container ) {
1189 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1190 }
1191
1192 /**
1193 * Set the cached info for a container
1194 *
1195 * @param $container Resolved container name
1196 * @param $val mixed Information to cache
1197 * @return void
1198 */
1199 final protected function setContainerCache( $container, $val ) {
1200 $this->memCache->set( $this->containerCacheKey( $container ), $val, 7*86400 );
1201 }
1202
1203 /**
1204 * Delete the cached info for a container
1205 *
1206 * @param $container Resolved container name
1207 * @return void
1208 */
1209 final protected function deleteContainerCache( $container ) {
1210 $this->memCache->delete( $this->containerCacheKey( $container ) );
1211 }
1212
1213 /**
1214 * Do a batch lookup from cache for container stats for all containers
1215 * used in a list of container names, storage paths, or FileOp objects.
1216 *
1217 * @param $items Array List of storage paths or FileOps
1218 * @return void
1219 */
1220 final protected function primeContainerCache( array $items ) {
1221 $paths = array(); // list of storage paths
1222 $contNames = array(); // (cache key => resolved container name)
1223 // Get all the paths/containers from the items...
1224 foreach ( $items as $item ) {
1225 if ( $item instanceof FileOp ) {
1226 $paths = array_merge( $paths, $item->storagePathsRead() );
1227 $paths = array_merge( $paths, $item->storagePathsChanged() );
1228 } elseif ( self::isStoragePath( $item ) ) {
1229 $paths[] = $item;
1230 } elseif ( is_string( $item ) ) { // full container name
1231 $contNames[$this->containerCacheKey( $item )] = $item;
1232 }
1233 }
1234 // Get all the corresponding cache keys for paths...
1235 foreach ( $paths as $path ) {
1236 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1237 if ( $fullCont !== null ) { // valid path for this backend
1238 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1239 }
1240 }
1241
1242 $contInfo = array(); // (resolved container name => cache value)
1243 // Get all cache entries for these container cache keys...
1244 $values = $this->memCache->getBatch( array_keys( $contNames ) );
1245 foreach ( $values as $cacheKey => $val ) {
1246 $contInfo[$contNames[$cacheKey]] = $val;
1247 }
1248
1249 // Populate the container process cache for the backend...
1250 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1251 }
1252
1253 /**
1254 * Fill the backend-specific process cache given an array of
1255 * resolved container names and their corresponding cached info.
1256 * Only containers that actually exist should appear in the map.
1257 *
1258 * @param $containerInfo Array Map of resolved container names to cached info
1259 * @return void
1260 */
1261 protected function doPrimeContainerCache( array $containerInfo ) {}
1262 }
1263
1264 /**
1265 * FileBackendStore helper function to handle listings that span container shards.
1266 * Do not use this class from places outside of FileBackendStore.
1267 *
1268 * @ingroup FileBackend
1269 */
1270 abstract class FileBackendStoreShardListIterator implements Iterator {
1271 /** @var FileBackendStore */
1272 protected $backend;
1273 /** @var Array */
1274 protected $params;
1275 /** @var Array */
1276 protected $shardSuffixes;
1277 protected $container; // string; full container name
1278 protected $directory; // string; resolved relative path
1279
1280 /** @var Traversable */
1281 protected $iter;
1282 protected $curShard = 0; // integer
1283 protected $pos = 0; // integer
1284
1285 /** @var Array */
1286 protected $multiShardPaths = array(); // (rel path => 1)
1287
1288 /**
1289 * @param $backend FileBackendStore
1290 * @param $container string Full storage container name
1291 * @param $dir string Storage directory relative to container
1292 * @param $suffixes Array List of container shard suffixes
1293 * @param $params Array
1294 */
1295 public function __construct(
1296 FileBackendStore $backend, $container, $dir, array $suffixes, array $params
1297 ) {
1298 $this->backend = $backend;
1299 $this->container = $container;
1300 $this->directory = $dir;
1301 $this->shardSuffixes = $suffixes;
1302 $this->params = $params;
1303 }
1304
1305 /**
1306 * @see Iterator::current()
1307 * @return string|bool String or false
1308 */
1309 public function current() {
1310 if ( is_array( $this->iter ) ) {
1311 return current( $this->iter );
1312 } else {
1313 return $this->iter->current();
1314 }
1315 }
1316
1317 /**
1318 * @see Iterator::key()
1319 * @return integer
1320 */
1321 public function key() {
1322 return $this->pos;
1323 }
1324
1325 /**
1326 * @see Iterator::next()
1327 * @return void
1328 */
1329 public function next() {
1330 ++$this->pos;
1331 if ( is_array( $this->iter ) ) {
1332 next( $this->iter );
1333 } else {
1334 $this->iter->next();
1335 }
1336 // Filter out items that we already listed
1337 $this->filterViaNext();
1338 // Find the next non-empty shard if no elements are left
1339 $this->nextShardIteratorIfNotValid();
1340 }
1341
1342 /**
1343 * @see Iterator::rewind()
1344 * @return void
1345 */
1346 public function rewind() {
1347 $this->pos = 0;
1348 $this->curShard = 0;
1349 $this->setIteratorFromCurrentShard();
1350 // Filter out items that we already listed
1351 $this->filterViaNext();
1352 // Find the next non-empty shard if this one has no elements
1353 $this->nextShardIteratorIfNotValid();
1354 }
1355
1356 /**
1357 * @see Iterator::valid()
1358 * @return bool
1359 */
1360 public function valid() {
1361 if ( $this->iter == null ) {
1362 return false; // some failure?
1363 } elseif ( is_array( $this->iter ) ) {
1364 return ( current( $this->iter ) !== false ); // no paths can have this value
1365 } else {
1366 return $this->iter->valid();
1367 }
1368 }
1369
1370 /**
1371 * Filter out duplicate items by advancing to the next ones
1372 */
1373 protected function filterViaNext() {
1374 while ( $this->iter->valid() ) {
1375 $rel = $this->iter->current(); // path relative to given directory
1376 $path = $this->params['dir'] . "/{$rel}"; // full storage path
1377 if ( !$this->backend->isSingleShardPathInternal( $path ) ) {
1378 // Don't keep listing paths that are on multiple shards
1379 if ( isset( $this->multiShardPaths[$rel] ) ) {
1380 $this->iter->next(); // we already listed this path
1381 } else {
1382 $this->multiShardPaths[$rel] = 1;
1383 break;
1384 }
1385 }
1386 }
1387 }
1388
1389 /**
1390 * If the list iterator for this container shard is out of items,
1391 * then move on to the next container that has items.
1392 * If there are none, then it advances to the last container.
1393 */
1394 protected function nextShardIteratorIfNotValid() {
1395 while ( !$this->valid() ) {
1396 if ( ++$this->curShard >= count( $this->shardSuffixes ) ) {
1397 break; // no more container shards
1398 }
1399 $this->setIteratorFromCurrentShard();
1400 }
1401 }
1402
1403 /**
1404 * Set the list iterator to that of the current container shard
1405 */
1406 protected function setIteratorFromCurrentShard() {
1407 $suffix = $this->shardSuffixes[$this->curShard];
1408 $this->iter = $this->listFromShard(
1409 "{$this->container}{$suffix}", $this->directory, $this->params );
1410 }
1411
1412 /**
1413 * Get the list for a given container shard
1414 *
1415 * @param $container string Resolved container name
1416 * @param $dir string Resolved path relative to container
1417 * @param $params Array
1418 * @return Traversable|Array|null
1419 */
1420 abstract protected function listFromShard( $container, $dir, array $params );
1421 }
1422
1423 /**
1424 * Iterator for listing directories
1425 */
1426 class FileBackendStoreShardDirIterator extends FileBackendStoreShardListIterator {
1427 protected function listFromShard( $container, $dir, array $params ) {
1428 return $this->backend->getDirectoryListInternal( $container, $dir, $params );
1429 }
1430 }
1431
1432 /**
1433 * Iterator for listing regular files
1434 */
1435 class FileBackendStoreShardFileIterator extends FileBackendStoreShardListIterator {
1436 protected function listFromShard( $container, $dir, array $params ) {
1437 return $this->backend->getFileListInternal( $container, $dir, $params );
1438 }
1439 }