3 * Base class for all backends using particular storage medium.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup FileBackend
22 * @author Aaron Schulz
26 * @brief Base class for all backends using particular storage medium.
28 * This class defines the methods as abstract that subclasses must implement.
29 * Outside callers should *not* use functions with "Internal" in the name.
31 * The FileBackend operations are implemented using basic functions
32 * such as storeInternal(), copyInternal(), deleteInternal() and the like.
33 * This class is also responsible for path resolution and sanitization.
35 * @ingroup FileBackend
38 abstract class FileBackendStore
extends FileBackend
{
42 /** @var Array Map of paths to small (RAM/disk) cache items */
43 protected $cache = array(); // (storage path => key => value)
44 protected $maxCacheSize = 300; // integer; max paths with entries
45 /** @var Array Map of paths to large (RAM/disk) cache items */
46 protected $expensiveCache = array(); // (storage path => key => value)
47 protected $maxExpensiveCacheSize = 5; // integer; max paths with entries
49 /** @var Array Map of container names to sharding settings */
50 protected $shardViaHashLevels = array(); // (container name => config array)
52 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
55 * @see FileBackend::__construct()
57 * @param $config Array
59 public function __construct( array $config ) {
60 parent
::__construct( $config );
61 $this->memCache
= new EmptyBagOStuff(); // disabled by default
65 * Get the maximum allowable file size given backend
66 * medium restrictions and basic performance constraints.
67 * Do not call this function from places outside FileBackend and FileOp.
69 * @return integer Bytes
71 final public function maxFileSizeInternal() {
72 return $this->maxFileSize
;
76 * Check if a file can be created at a given storage path.
77 * FS backends should check if the parent directory exists and the file is writable.
78 * Backends using key/value stores should check if the container exists.
80 * @param $storagePath string
83 abstract public function isPathUsableInternal( $storagePath );
86 * Create a file in the backend with the given contents.
87 * Do not call this function from places outside FileBackend and FileOp.
90 * content : the raw file contents
91 * dst : destination storage path
92 * overwrite : overwrite any file that exists at the destination
93 * async : Status will be returned immediately if supported.
94 * If the status is OK, then its value field will be
95 * set to a FileBackendStoreOpHandle object.
97 * @param $params Array
100 final public function createInternal( array $params ) {
101 wfProfileIn( __METHOD__
);
102 wfProfileIn( __METHOD__
. '-' . $this->name
);
103 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
104 $status = Status
::newFatal( 'backend-fail-maxsize',
105 $params['dst'], $this->maxFileSizeInternal() );
107 $status = $this->doCreateInternal( $params );
108 $this->clearCache( array( $params['dst'] ) );
109 $this->deleteFileCache( $params['dst'] ); // persistent cache
111 wfProfileOut( __METHOD__
. '-' . $this->name
);
112 wfProfileOut( __METHOD__
);
117 * @see FileBackendStore::createInternal()
119 abstract protected function doCreateInternal( array $params );
122 * Store a file into the backend from a file on disk.
123 * Do not call this function from places outside FileBackend and FileOp.
126 * src : source path on disk
127 * dst : destination storage path
128 * overwrite : overwrite any file that exists at the destination
129 * async : Status will be returned immediately if supported.
130 * If the status is OK, then its value field will be
131 * set to a FileBackendStoreOpHandle object.
133 * @param $params Array
136 final public function storeInternal( array $params ) {
137 wfProfileIn( __METHOD__
);
138 wfProfileIn( __METHOD__
. '-' . $this->name
);
139 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
140 $status = Status
::newFatal( 'backend-fail-store', $params['dst'] );
142 $status = $this->doStoreInternal( $params );
143 $this->clearCache( array( $params['dst'] ) );
144 $this->deleteFileCache( $params['dst'] ); // persistent cache
146 wfProfileOut( __METHOD__
. '-' . $this->name
);
147 wfProfileOut( __METHOD__
);
152 * @see FileBackendStore::storeInternal()
154 abstract protected function doStoreInternal( array $params );
157 * Copy a file from one storage path to another in the backend.
158 * Do not call this function from places outside FileBackend and FileOp.
161 * src : source storage path
162 * dst : destination storage path
163 * overwrite : overwrite any file that exists at the destination
164 * async : Status will be returned immediately if supported.
165 * If the status is OK, then its value field will be
166 * set to a FileBackendStoreOpHandle object.
168 * @param $params Array
171 final public function copyInternal( array $params ) {
172 wfProfileIn( __METHOD__
);
173 wfProfileIn( __METHOD__
. '-' . $this->name
);
174 $status = $this->doCopyInternal( $params );
175 $this->clearCache( array( $params['dst'] ) );
176 $this->deleteFileCache( $params['dst'] ); // persistent cache
177 wfProfileOut( __METHOD__
. '-' . $this->name
);
178 wfProfileOut( __METHOD__
);
183 * @see FileBackendStore::copyInternal()
185 abstract protected function doCopyInternal( array $params );
188 * Delete a file at the storage path.
189 * Do not call this function from places outside FileBackend and FileOp.
192 * src : source storage path
193 * ignoreMissingSource : do nothing if the source file does not exist
194 * async : Status will be returned immediately if supported.
195 * If the status is OK, then its value field will be
196 * set to a FileBackendStoreOpHandle object.
198 * @param $params Array
201 final public function deleteInternal( array $params ) {
202 wfProfileIn( __METHOD__
);
203 wfProfileIn( __METHOD__
. '-' . $this->name
);
204 $status = $this->doDeleteInternal( $params );
205 $this->clearCache( array( $params['src'] ) );
206 $this->deleteFileCache( $params['src'] ); // persistent cache
207 wfProfileOut( __METHOD__
. '-' . $this->name
);
208 wfProfileOut( __METHOD__
);
213 * @see FileBackendStore::deleteInternal()
215 abstract protected function doDeleteInternal( array $params );
218 * Move a file from one storage path to another in the backend.
219 * Do not call this function from places outside FileBackend and FileOp.
222 * src : source storage path
223 * dst : destination storage path
224 * overwrite : overwrite any file that exists at the destination
225 * async : Status will be returned immediately if supported.
226 * If the status is OK, then its value field will be
227 * set to a FileBackendStoreOpHandle object.
229 * @param $params Array
232 final public function moveInternal( array $params ) {
233 wfProfileIn( __METHOD__
);
234 wfProfileIn( __METHOD__
. '-' . $this->name
);
235 $status = $this->doMoveInternal( $params );
236 $this->clearCache( array( $params['src'], $params['dst'] ) );
237 $this->deleteFileCache( $params['src'] ); // persistent cache
238 $this->deleteFileCache( $params['dst'] ); // persistent cache
239 wfProfileOut( __METHOD__
. '-' . $this->name
);
240 wfProfileOut( __METHOD__
);
245 * @see FileBackendStore::moveInternal()
248 protected function doMoveInternal( array $params ) {
249 unset( $params['async'] ); // two steps, won't work here :)
250 // Copy source to dest
251 $status = $this->copyInternal( $params );
252 if ( $status->isOK() ) {
253 // Delete source (only fails due to races or medium going down)
254 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
255 $status->setResult( true, $status->value
); // ignore delete() errors
261 * @see FileBackend::concatenate()
264 final public function concatenate( array $params ) {
265 wfProfileIn( __METHOD__
);
266 wfProfileIn( __METHOD__
. '-' . $this->name
);
267 $status = Status
::newGood();
269 // Try to lock the source files for the scope of this function
270 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
271 if ( $status->isOK() ) {
272 // Actually do the concatenation
273 $status->merge( $this->doConcatenate( $params ) );
276 wfProfileOut( __METHOD__
. '-' . $this->name
);
277 wfProfileOut( __METHOD__
);
282 * @see FileBackendStore::concatenate()
285 protected function doConcatenate( array $params ) {
286 $status = Status
::newGood();
287 $tmpPath = $params['dst']; // convenience
289 // Check that the specified temp file is valid...
290 wfSuppressWarnings();
291 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
293 if ( !$ok ) { // not present or not empty
294 $status->fatal( 'backend-fail-opentemp', $tmpPath );
298 // Build up the temp file using the source chunks (in order)...
299 $tmpHandle = fopen( $tmpPath, 'ab' );
300 if ( $tmpHandle === false ) {
301 $status->fatal( 'backend-fail-opentemp', $tmpPath );
304 foreach ( $params['srcs'] as $virtualSource ) {
305 // Get a local FS version of the chunk
306 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
308 $status->fatal( 'backend-fail-read', $virtualSource );
311 // Get a handle to the local FS version
312 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
313 if ( $sourceHandle === false ) {
314 fclose( $tmpHandle );
315 $status->fatal( 'backend-fail-read', $virtualSource );
318 // Append chunk to file (pass chunk size to avoid magic quotes)
319 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
320 fclose( $sourceHandle );
321 fclose( $tmpHandle );
322 $status->fatal( 'backend-fail-writetemp', $tmpPath );
325 fclose( $sourceHandle );
327 if ( !fclose( $tmpHandle ) ) {
328 $status->fatal( 'backend-fail-closetemp', $tmpPath );
332 clearstatcache(); // temp file changed
338 * @see FileBackend::doPrepare()
341 final protected function doPrepare( array $params ) {
342 wfProfileIn( __METHOD__
);
343 wfProfileIn( __METHOD__
. '-' . $this->name
);
345 $status = Status
::newGood();
346 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
347 if ( $dir === null ) {
348 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
349 wfProfileOut( __METHOD__
. '-' . $this->name
);
350 wfProfileOut( __METHOD__
);
351 return $status; // invalid storage path
354 if ( $shard !== null ) { // confined to a single container/shard
355 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
356 } else { // directory is on several shards
357 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
358 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
359 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
360 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
364 wfProfileOut( __METHOD__
. '-' . $this->name
);
365 wfProfileOut( __METHOD__
);
370 * @see FileBackendStore::doPrepare()
373 protected function doPrepareInternal( $container, $dir, array $params ) {
374 return Status
::newGood();
378 * @see FileBackend::doSecure()
381 final protected function doSecure( array $params ) {
382 wfProfileIn( __METHOD__
);
383 wfProfileIn( __METHOD__
. '-' . $this->name
);
384 $status = Status
::newGood();
386 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
387 if ( $dir === null ) {
388 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
389 wfProfileOut( __METHOD__
. '-' . $this->name
);
390 wfProfileOut( __METHOD__
);
391 return $status; // invalid storage path
394 if ( $shard !== null ) { // confined to a single container/shard
395 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
396 } else { // directory is on several shards
397 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
398 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
399 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
400 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
404 wfProfileOut( __METHOD__
. '-' . $this->name
);
405 wfProfileOut( __METHOD__
);
410 * @see FileBackendStore::doSecure()
413 protected function doSecureInternal( $container, $dir, array $params ) {
414 return Status
::newGood();
418 * @see FileBackend::doClean()
421 final protected function doClean( array $params ) {
422 wfProfileIn( __METHOD__
);
423 wfProfileIn( __METHOD__
. '-' . $this->name
);
424 $status = Status
::newGood();
426 // Recursive: first delete all empty subdirs recursively
427 if ( !empty( $params['recursive'] ) && !$this->directoriesAreVirtual() ) {
428 $subDirsRel = $this->getTopDirectoryList( array( 'dir' => $params['dir'] ) );
429 if ( $subDirsRel !== null ) { // no errors
430 foreach ( $subDirsRel as $subDirRel ) {
431 $subDir = $params['dir'] . "/{$subDirRel}"; // full path
432 $status->merge( $this->doClean( array( 'dir' => $subDir ) +
$params ) );
437 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
438 if ( $dir === null ) {
439 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
440 wfProfileOut( __METHOD__
. '-' . $this->name
);
441 wfProfileOut( __METHOD__
);
442 return $status; // invalid storage path
445 // Attempt to lock this directory...
446 $filesLockEx = array( $params['dir'] );
447 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
448 if ( !$status->isOK() ) {
449 wfProfileOut( __METHOD__
. '-' . $this->name
);
450 wfProfileOut( __METHOD__
);
451 return $status; // abort
454 if ( $shard !== null ) { // confined to a single container/shard
455 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
456 $this->deleteContainerCache( $fullCont ); // purge cache
457 } else { // directory is on several shards
458 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
459 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
460 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
461 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
462 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
466 wfProfileOut( __METHOD__
. '-' . $this->name
);
467 wfProfileOut( __METHOD__
);
472 * @see FileBackendStore::doClean()
475 protected function doCleanInternal( $container, $dir, array $params ) {
476 return Status
::newGood();
480 * @see FileBackend::fileExists()
483 final public function fileExists( array $params ) {
484 wfProfileIn( __METHOD__
);
485 wfProfileIn( __METHOD__
. '-' . $this->name
);
486 $stat = $this->getFileStat( $params );
487 wfProfileOut( __METHOD__
. '-' . $this->name
);
488 wfProfileOut( __METHOD__
);
489 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
493 * @see FileBackend::getFileTimestamp()
496 final public function getFileTimestamp( array $params ) {
497 wfProfileIn( __METHOD__
);
498 wfProfileIn( __METHOD__
. '-' . $this->name
);
499 $stat = $this->getFileStat( $params );
500 wfProfileOut( __METHOD__
. '-' . $this->name
);
501 wfProfileOut( __METHOD__
);
502 return $stat ?
$stat['mtime'] : false;
506 * @see FileBackend::getFileSize()
509 final public function getFileSize( array $params ) {
510 wfProfileIn( __METHOD__
);
511 wfProfileIn( __METHOD__
. '-' . $this->name
);
512 $stat = $this->getFileStat( $params );
513 wfProfileOut( __METHOD__
. '-' . $this->name
);
514 wfProfileOut( __METHOD__
);
515 return $stat ?
$stat['size'] : false;
519 * @see FileBackend::getFileStat()
522 final public function getFileStat( array $params ) {
523 wfProfileIn( __METHOD__
);
524 wfProfileIn( __METHOD__
. '-' . $this->name
);
525 $path = self
::normalizeStoragePath( $params['src'] );
526 if ( $path === null ) {
527 wfProfileOut( __METHOD__
. '-' . $this->name
);
528 wfProfileOut( __METHOD__
);
529 return false; // invalid storage path
531 $latest = !empty( $params['latest'] ); // use latest data?
532 if ( !isset( $this->cache
[$path]['stat'] ) ) {
533 $this->primeFileCache( array( $path ) ); // check persistent cache
535 if ( isset( $this->cache
[$path]['stat'] ) ) {
536 // If we want the latest data, check that this cached
537 // value was in fact fetched with the latest available data.
538 if ( !$latest ||
$this->cache
[$path]['stat']['latest'] ) {
539 $this->pingCache( $path ); // LRU
540 wfProfileOut( __METHOD__
. '-' . $this->name
);
541 wfProfileOut( __METHOD__
);
542 return $this->cache
[$path]['stat'];
545 wfProfileIn( __METHOD__
. '-miss' );
546 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
547 $stat = $this->doGetFileStat( $params );
548 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
549 wfProfileOut( __METHOD__
. '-miss' );
550 if ( is_array( $stat ) ) { // don't cache negatives
551 $stat['latest'] = $latest;
552 $this->trimCache(); // limit memory
553 $this->cache
[$path]['stat'] = $stat;
554 $this->setFileCache( $path, $stat ); // update persistent cache
556 wfProfileOut( __METHOD__
. '-' . $this->name
);
557 wfProfileOut( __METHOD__
);
562 * @see FileBackendStore::getFileStat()
564 abstract protected function doGetFileStat( array $params );
567 * @see FileBackend::getFileContents()
568 * @return bool|string
570 public function getFileContents( array $params ) {
571 wfProfileIn( __METHOD__
);
572 wfProfileIn( __METHOD__
. '-' . $this->name
);
573 $tmpFile = $this->getLocalReference( $params );
575 wfProfileOut( __METHOD__
. '-' . $this->name
);
576 wfProfileOut( __METHOD__
);
579 wfSuppressWarnings();
580 $data = file_get_contents( $tmpFile->getPath() );
582 wfProfileOut( __METHOD__
. '-' . $this->name
);
583 wfProfileOut( __METHOD__
);
588 * @see FileBackend::getFileSha1Base36()
589 * @return bool|string
591 final public function getFileSha1Base36( array $params ) {
592 wfProfileIn( __METHOD__
);
593 wfProfileIn( __METHOD__
. '-' . $this->name
);
594 $path = $params['src'];
595 if ( isset( $this->cache
[$path]['sha1'] ) ) {
596 $this->pingCache( $path ); // LRU
597 wfProfileOut( __METHOD__
. '-' . $this->name
);
598 wfProfileOut( __METHOD__
);
599 return $this->cache
[$path]['sha1'];
601 wfProfileIn( __METHOD__
. '-miss' );
602 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
603 $hash = $this->doGetFileSha1Base36( $params );
604 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
605 wfProfileOut( __METHOD__
. '-miss' );
606 if ( $hash ) { // don't cache negatives
607 $this->trimCache(); // limit memory
608 $this->cache
[$path]['sha1'] = $hash;
610 wfProfileOut( __METHOD__
. '-' . $this->name
);
611 wfProfileOut( __METHOD__
);
616 * @see FileBackendStore::getFileSha1Base36()
619 protected function doGetFileSha1Base36( array $params ) {
620 $fsFile = $this->getLocalReference( $params );
624 return $fsFile->getSha1Base36();
629 * @see FileBackend::getFileProps()
632 final public function getFileProps( array $params ) {
633 wfProfileIn( __METHOD__
);
634 wfProfileIn( __METHOD__
. '-' . $this->name
);
635 $fsFile = $this->getLocalReference( $params );
636 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
637 wfProfileOut( __METHOD__
. '-' . $this->name
);
638 wfProfileOut( __METHOD__
);
643 * @see FileBackend::getLocalReference()
644 * @return TempFSFile|null
646 public function getLocalReference( array $params ) {
647 wfProfileIn( __METHOD__
);
648 wfProfileIn( __METHOD__
. '-' . $this->name
);
649 $path = $params['src'];
650 if ( isset( $this->expensiveCache
[$path]['localRef'] ) ) {
651 $this->pingExpensiveCache( $path );
652 wfProfileOut( __METHOD__
. '-' . $this->name
);
653 wfProfileOut( __METHOD__
);
654 return $this->expensiveCache
[$path]['localRef'];
656 $tmpFile = $this->getLocalCopy( $params );
657 if ( $tmpFile ) { // don't cache negatives
658 $this->trimExpensiveCache(); // limit memory
659 $this->expensiveCache
[$path]['localRef'] = $tmpFile;
661 wfProfileOut( __METHOD__
. '-' . $this->name
);
662 wfProfileOut( __METHOD__
);
667 * @see FileBackend::streamFile()
670 final public function streamFile( array $params ) {
671 wfProfileIn( __METHOD__
);
672 wfProfileIn( __METHOD__
. '-' . $this->name
);
673 $status = Status
::newGood();
675 $info = $this->getFileStat( $params );
676 if ( !$info ) { // let StreamFile handle the 404
677 $status->fatal( 'backend-fail-notexists', $params['src'] );
680 // Set output buffer and HTTP headers for stream
681 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
682 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
683 if ( $res == StreamFile
::NOT_MODIFIED
) {
684 // do nothing; client cache is up to date
685 } elseif ( $res == StreamFile
::READY_STREAM
) {
686 wfProfileIn( __METHOD__
. '-send' );
687 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
688 $status = $this->doStreamFile( $params );
689 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
690 wfProfileOut( __METHOD__
. '-send' );
692 $status->fatal( 'backend-fail-stream', $params['src'] );
695 wfProfileOut( __METHOD__
. '-' . $this->name
);
696 wfProfileOut( __METHOD__
);
701 * @see FileBackendStore::streamFile()
704 protected function doStreamFile( array $params ) {
705 $status = Status
::newGood();
707 $fsFile = $this->getLocalReference( $params );
709 $status->fatal( 'backend-fail-stream', $params['src'] );
710 } elseif ( !readfile( $fsFile->getPath() ) ) {
711 $status->fatal( 'backend-fail-stream', $params['src'] );
718 * @see FileBackend::directoryExists()
721 final public function directoryExists( array $params ) {
722 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
723 if ( $dir === null ) {
724 return false; // invalid storage path
726 if ( $shard !== null ) { // confined to a single container/shard
727 return $this->doDirectoryExists( $fullCont, $dir, $params );
728 } else { // directory is on several shards
729 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
730 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
731 $res = false; // response
732 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
733 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
737 } elseif ( $exists === null ) { // error?
738 $res = null; // if we don't find anything, it is indeterminate
746 * @see FileBackendStore::directoryExists()
748 * @param $container string Resolved container name
749 * @param $dir string Resolved path relative to container
750 * @param $params Array
753 abstract protected function doDirectoryExists( $container, $dir, array $params );
756 * @see FileBackend::getDirectoryList()
757 * @return Traversable|Array|null Returns null on failure
759 final public function getDirectoryList( array $params ) {
760 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
761 if ( $dir === null ) { // invalid storage path
764 if ( $shard !== null ) {
765 // File listing is confined to a single container/shard
766 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
768 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
769 // File listing spans multiple containers/shards
770 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
771 return new FileBackendStoreShardDirIterator( $this,
772 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
777 * Do not call this function from places outside FileBackend
779 * @see FileBackendStore::getDirectoryList()
781 * @param $container string Resolved container name
782 * @param $dir string Resolved path relative to container
783 * @param $params Array
784 * @return Traversable|Array|null Returns null on failure
786 abstract public function getDirectoryListInternal( $container, $dir, array $params );
789 * @see FileBackend::getFileList()
790 * @return Traversable|Array|null Returns null on failure
792 final public function getFileList( array $params ) {
793 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
794 if ( $dir === null ) { // invalid storage path
797 if ( $shard !== null ) {
798 // File listing is confined to a single container/shard
799 return $this->getFileListInternal( $fullCont, $dir, $params );
801 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
802 // File listing spans multiple containers/shards
803 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
804 return new FileBackendStoreShardFileIterator( $this,
805 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
810 * Do not call this function from places outside FileBackend
812 * @see FileBackendStore::getFileList()
814 * @param $container string Resolved container name
815 * @param $dir string Resolved path relative to container
816 * @param $params Array
817 * @return Traversable|Array|null Returns null on failure
819 abstract public function getFileListInternal( $container, $dir, array $params );
822 * Get the list of supported operations and their corresponding FileOp classes.
826 protected function supportedOperations() {
828 'store' => 'StoreFileOp',
829 'copy' => 'CopyFileOp',
830 'move' => 'MoveFileOp',
831 'delete' => 'DeleteFileOp',
832 'create' => 'CreateFileOp',
833 'null' => 'NullFileOp'
838 * Return a list of FileOp objects from a list of operations.
839 * Do not call this function from places outside FileBackend.
841 * The result must have the same number of items as the input.
842 * An exception is thrown if an unsupported operation is requested.
844 * @param $ops Array Same format as doOperations()
845 * @return Array List of FileOp objects
846 * @throws MWException
848 final public function getOperationsInternal( array $ops ) {
849 $supportedOps = $this->supportedOperations();
851 $performOps = array(); // array of FileOp objects
852 // Build up ordered array of FileOps...
853 foreach ( $ops as $operation ) {
854 $opName = $operation['op'];
855 if ( isset( $supportedOps[$opName] ) ) {
856 $class = $supportedOps[$opName];
857 // Get params for this operation
858 $params = $operation;
859 // Append the FileOp class
860 $performOps[] = new $class( $this, $params );
862 throw new MWException( "Operation '$opName' is not supported." );
870 * Get a list of storage paths to lock for a list of operations
871 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
872 * each corresponding to a list of storage paths to be locked.
874 * @param $performOps Array List of FileOp objects
875 * @return Array ('sh' => list of paths, 'ex' => list of paths)
877 final public function getPathsToLockForOpsInternal( array $performOps ) {
878 // Build up a list of files to lock...
879 $paths = array( 'sh' => array(), 'ex' => array() );
880 foreach ( $performOps as $fileOp ) {
881 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
882 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
884 // Optimization: if doing an EX lock anyway, don't also set an SH one
885 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
886 // Get a shared lock on the parent directory of each path changed
887 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
893 * @see FileBackend::doOperationsInternal()
896 protected function doOperationsInternal( array $ops, array $opts ) {
897 wfProfileIn( __METHOD__
);
898 wfProfileIn( __METHOD__
. '-' . $this->name
);
899 $status = Status
::newGood();
901 // Build up a list of FileOps...
902 $performOps = $this->getOperationsInternal( $ops );
904 // Acquire any locks as needed...
905 if ( empty( $opts['nonLocking'] ) ) {
906 // Build up a list of files to lock...
907 $paths = $this->getPathsToLockForOpsInternal( $performOps );
908 // Try to lock those files for the scope of this function...
909 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
910 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
911 if ( !$status->isOK() ) {
912 wfProfileOut( __METHOD__
. '-' . $this->name
);
913 wfProfileOut( __METHOD__
);
914 return $status; // abort
918 // Clear any file cache entries (after locks acquired)
921 // Load from the persistent file and container caches
922 $this->primeFileCache( $performOps );
923 $this->primeContainerCache( $performOps );
925 // Actually attempt the operation batch...
926 $subStatus = FileOpBatch
::attempt( $performOps, $opts, $this->fileJournal
);
928 // Merge errors into status fields
929 $status->merge( $subStatus );
930 $status->success
= $subStatus->success
; // not done in merge()
932 wfProfileOut( __METHOD__
. '-' . $this->name
);
933 wfProfileOut( __METHOD__
);
938 * Execute a list of FileBackendStoreOpHandle handles in parallel.
939 * The resulting Status object fields will correspond
940 * to the order in which the handles where given.
942 * @param $handles Array List of FileBackendStoreOpHandle objects
943 * @return Array Map of Status objects
945 final public function executeOpHandlesInternal( array $fileOpHandles ) {
946 wfProfileIn( __METHOD__
);
947 wfProfileIn( __METHOD__
. '-' . $this->name
);
948 foreach ( $fileOpHandles as $fileOpHandle ) {
949 if ( !( $fileOpHandle instanceof FileBackendStoreOpHandle
) ) {
950 throw new MWException( "Given a non-FileBackendStoreOpHandle object." );
951 } elseif ( $fileOpHandle->backend
->getName() !== $this->getName() ) {
952 throw new MWException( "Given a FileBackendStoreOpHandle for the wrong backend." );
955 $res = $this->doExecuteOpHandlesInternal( $fileOpHandles );
956 wfProfileOut( __METHOD__
. '-' . $this->name
);
957 wfProfileOut( __METHOD__
);
962 * @see FileBackendStore::executeOpHandlesInternal()
963 * @return Array List of corresponding Status objects
965 protected function doExecuteOpHandlesInternal( array $fileOpHandles ) {
966 foreach ( $fileOpHandles as $fileOpHandle ) { // OK if empty
967 throw new MWException( "This backend supports no asynchronous operations." );
973 * @see FileBackend::clearCache()
975 final public function clearCache( array $paths = null ) {
976 if ( is_array( $paths ) ) {
977 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
978 $paths = array_filter( $paths, 'strlen' ); // remove nulls
980 if ( $paths === null ) {
981 $this->cache
= array();
982 $this->expensiveCache
= array();
984 foreach ( $paths as $path ) {
985 unset( $this->cache
[$path] );
986 unset( $this->expensiveCache
[$path] );
989 $this->doClearCache( $paths );
993 * Clears any additional stat caches for storage paths
995 * @see FileBackend::clearCache()
997 * @param $paths Array Storage paths (optional)
1000 protected function doClearCache( array $paths = null ) {}
1003 * Is this a key/value store where directories are just virtual?
1004 * Virtual directories exists in so much as files exists that are
1005 * prefixed with the directory path followed by a forward slash.
1009 abstract protected function directoriesAreVirtual();
1012 * Move a cache entry to the top (such as when accessed)
1014 * @param $path string Storage path
1017 protected function pingCache( $path ) {
1018 if ( isset( $this->cache
[$path] ) ) {
1019 $tmp = $this->cache
[$path];
1020 unset( $this->cache
[$path] );
1021 $this->cache
[$path] = $tmp;
1026 * Prune the inexpensive cache if it is too big to add an item
1030 protected function trimCache() {
1031 if ( count( $this->cache
) >= $this->maxCacheSize
) {
1032 reset( $this->cache
);
1033 unset( $this->cache
[key( $this->cache
)] );
1038 * Move a cache entry to the top (such as when accessed)
1040 * @param $path string Storage path
1043 protected function pingExpensiveCache( $path ) {
1044 if ( isset( $this->expensiveCache
[$path] ) ) {
1045 $tmp = $this->expensiveCache
[$path];
1046 unset( $this->expensiveCache
[$path] );
1047 $this->expensiveCache
[$path] = $tmp;
1052 * Prune the expensive cache if it is too big to add an item
1056 protected function trimExpensiveCache() {
1057 if ( count( $this->expensiveCache
) >= $this->maxExpensiveCacheSize
) {
1058 reset( $this->expensiveCache
);
1059 unset( $this->expensiveCache
[key( $this->expensiveCache
)] );
1064 * Check if a container name is valid.
1065 * This checks for for length and illegal characters.
1067 * @param $container string
1070 final protected static function isValidContainerName( $container ) {
1071 // This accounts for Swift and S3 restrictions while leaving room
1072 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
1073 // This disallows directory separators or traversal characters.
1074 // Note that matching strings URL encode to the same string;
1075 // in Swift, the length restriction is *after* URL encoding.
1076 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
1080 * Splits a storage path into an internal container name,
1081 * an internal relative file name, and a container shard suffix.
1082 * Any shard suffix is already appended to the internal container name.
1083 * This also checks that the storage path is valid and within this backend.
1085 * If the container is sharded but a suffix could not be determined,
1086 * this means that the path can only refer to a directory and can only
1087 * be scanned by looking in all the container shards.
1089 * @param $storagePath string
1090 * @return Array (container, path, container suffix) or (null, null, null) if invalid
1092 final protected function resolveStoragePath( $storagePath ) {
1093 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
1094 if ( $backend === $this->name
) { // must be for this backend
1095 $relPath = self
::normalizeContainerPath( $relPath );
1096 if ( $relPath !== null ) {
1097 // Get shard for the normalized path if this container is sharded
1098 $cShard = $this->getContainerShard( $container, $relPath );
1099 // Validate and sanitize the relative path (backend-specific)
1100 $relPath = $this->resolveContainerPath( $container, $relPath );
1101 if ( $relPath !== null ) {
1102 // Prepend any wiki ID prefix to the container name
1103 $container = $this->fullContainerName( $container );
1104 if ( self
::isValidContainerName( $container ) ) {
1105 // Validate and sanitize the container name (backend-specific)
1106 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1107 if ( $container !== null ) {
1108 return array( $container, $relPath, $cShard );
1114 return array( null, null, null );
1118 * Like resolveStoragePath() except null values are returned if
1119 * the container is sharded and the shard could not be determined.
1121 * @see FileBackendStore::resolveStoragePath()
1123 * @param $storagePath string
1124 * @return Array (container, path) or (null, null) if invalid
1126 final protected function resolveStoragePathReal( $storagePath ) {
1127 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1128 if ( $cShard !== null ) {
1129 return array( $container, $relPath );
1131 return array( null, null );
1135 * Get the container name shard suffix for a given path.
1136 * Any empty suffix means the container is not sharded.
1138 * @param $container string Container name
1139 * @param $relStoragePath string Storage path relative to the container
1140 * @return string|null Returns null if shard could not be determined
1142 final protected function getContainerShard( $container, $relPath ) {
1143 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1144 if ( $levels == 1 ||
$levels == 2 ) {
1145 // Hash characters are either base 16 or 36
1146 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1147 // Get a regex that represents the shard portion of paths.
1148 // The concatenation of the captures gives us the shard.
1149 if ( $levels === 1 ) { // 16 or 36 shards per container
1150 $hashDirRegex = '(' . $char . ')';
1151 } else { // 256 or 1296 shards per container
1152 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1153 $hashDirRegex = $char . '/(' . $char . '{2})';
1154 } else { // short hash dir format (e.g. "a/b/c")
1155 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1158 // Allow certain directories to be above the hash dirs so as
1159 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1160 // They must be 2+ chars to avoid any hash directory ambiguity.
1162 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1163 return '.' . implode( '', array_slice( $m, 1 ) );
1165 return null; // failed to match
1167 return ''; // no sharding
1171 * Check if a storage path maps to a single shard.
1172 * Container dirs like "a", where the container shards on "x/xy",
1173 * can reside on several shards. Such paths are tricky to handle.
1175 * @param $storagePath string Storage path
1178 final public function isSingleShardPathInternal( $storagePath ) {
1179 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1180 return ( $shard !== null );
1184 * Get the sharding config for a container.
1185 * If greater than 0, then all file storage paths within
1186 * the container are required to be hashed accordingly.
1188 * @param $container string
1189 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1191 final protected function getContainerHashLevels( $container ) {
1192 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1193 $config = $this->shardViaHashLevels
[$container];
1194 $hashLevels = (int)$config['levels'];
1195 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1196 $hashBase = (int)$config['base'];
1197 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1198 return array( $hashLevels, $hashBase, $config['repeat'] );
1202 return array( 0, 0, false ); // no sharding
1206 * Get a list of full container shard suffixes for a container
1208 * @param $container string
1211 final protected function getContainerSuffixes( $container ) {
1213 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1214 if ( $digits > 0 ) {
1215 $numShards = pow( $base, $digits );
1216 for ( $index = 0; $index < $numShards; $index++
) {
1217 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1224 * Get the full container name, including the wiki ID prefix
1226 * @param $container string
1229 final protected function fullContainerName( $container ) {
1230 if ( $this->wikiId
!= '' ) {
1231 return "{$this->wikiId}-$container";
1238 * Resolve a container name, checking if it's allowed by the backend.
1239 * This is intended for internal use, such as encoding illegal chars.
1240 * Subclasses can override this to be more restrictive.
1242 * @param $container string
1243 * @return string|null
1245 protected function resolveContainerName( $container ) {
1250 * Resolve a relative storage path, checking if it's allowed by the backend.
1251 * This is intended for internal use, such as encoding illegal chars or perhaps
1252 * getting absolute paths (e.g. FS based backends). Note that the relative path
1253 * may be the empty string (e.g. the path is simply to the container).
1255 * @param $container string Container name
1256 * @param $relStoragePath string Storage path relative to the container
1257 * @return string|null Path or null if not valid
1259 protected function resolveContainerPath( $container, $relStoragePath ) {
1260 return $relStoragePath;
1264 * Get the cache key for a container
1266 * @param $container Resolved container name
1269 private function containerCacheKey( $container ) {
1270 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1274 * Set the cached info for a container
1276 * @param $container Resolved container name
1277 * @param $val mixed Information to cache
1280 final protected function setContainerCache( $container, $val ) {
1281 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 14*86400 );
1285 * Delete the cached info for a container
1287 * @param $container Resolved container name
1290 final protected function deleteContainerCache( $container ) {
1291 for ( $attempts=1; $attempts <= 3; $attempts++
) {
1292 if ( $this->memCache
->delete( $this->containerCacheKey( $container ) ) ) {
1296 trigger_error( "Unable to delete stat cache for container $container." );
1300 * Do a batch lookup from cache for container stats for all containers
1301 * used in a list of container names, storage paths, or FileOp objects.
1303 * @param $items Array
1306 final protected function primeContainerCache( array $items ) {
1307 wfProfileIn( __METHOD__
);
1308 wfProfileIn( __METHOD__
. '-' . $this->name
);
1310 $paths = array(); // list of storage paths
1311 $contNames = array(); // (cache key => resolved container name)
1312 // Get all the paths/containers from the items...
1313 foreach ( $items as $item ) {
1314 if ( $item instanceof FileOp
) {
1315 $paths = array_merge( $paths, $item->storagePathsRead() );
1316 $paths = array_merge( $paths, $item->storagePathsChanged() );
1317 } elseif ( self
::isStoragePath( $item ) ) {
1319 } elseif ( is_string( $item ) ) { // full container name
1320 $contNames[$this->containerCacheKey( $item )] = $item;
1323 // Get all the corresponding cache keys for paths...
1324 foreach ( $paths as $path ) {
1325 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1326 if ( $fullCont !== null ) { // valid path for this backend
1327 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1331 $contInfo = array(); // (resolved container name => cache value)
1332 // Get all cache entries for these container cache keys...
1333 $values = $this->memCache
->getBatch( array_keys( $contNames ) );
1334 foreach ( $values as $cacheKey => $val ) {
1335 $contInfo[$contNames[$cacheKey]] = $val;
1338 // Populate the container process cache for the backend...
1339 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1341 wfProfileOut( __METHOD__
. '-' . $this->name
);
1342 wfProfileOut( __METHOD__
);
1346 * Fill the backend-specific process cache given an array of
1347 * resolved container names and their corresponding cached info.
1348 * Only containers that actually exist should appear in the map.
1350 * @param $containerInfo Array Map of resolved container names to cached info
1353 protected function doPrimeContainerCache( array $containerInfo ) {}
1356 * Get the cache key for a file path
1358 * @param $path Storage path
1361 private function fileCacheKey( $path ) {
1362 return wfMemcKey( 'backend', $this->getName(), 'file', sha1( $path ) );
1366 * Set the cached stat info for a file path
1368 * @param $path Storage path
1369 * @param $val mixed Information to cache
1372 final protected function setFileCache( $path, $val ) {
1373 $this->memCache
->set( $this->fileCacheKey( $path ), $val, 7*86400 );
1377 * Delete the cached stat info for a file path
1379 * @param $path Storage path
1382 final protected function deleteFileCache( $path ) {
1383 for ( $attempts=1; $attempts <= 3; $attempts++
) {
1384 if ( $this->memCache
->delete( $this->fileCacheKey( $path ) ) ) {
1388 trigger_error( "Unable to delete stat cache for file $path." );
1392 * Do a batch lookup from cache for file stats for all paths
1393 * used in a list of storage paths or FileOp objects.
1395 * @param $items Array List of storage paths or FileOps
1398 final protected function primeFileCache( array $items ) {
1399 wfProfileIn( __METHOD__
);
1400 wfProfileIn( __METHOD__
. '-' . $this->name
);
1402 $paths = array(); // list of storage paths
1403 $pathNames = array(); // (cache key => storage path)
1404 // Get all the paths/containers from the items...
1405 foreach ( $items as $item ) {
1406 if ( $item instanceof FileOp
) {
1407 $paths = array_merge( $paths, $item->storagePathsRead() );
1408 $paths = array_merge( $paths, $item->storagePathsChanged() );
1409 } elseif ( self
::isStoragePath( $item ) ) {
1413 // Get all the corresponding cache keys for paths...
1414 foreach ( $paths as $path ) {
1415 list( $cont, $rel, $s ) = $this->resolveStoragePath( $path );
1416 if ( $rel !== null ) { // valid path for this backend
1417 $pathNames[$this->fileCacheKey( $path )] = $path;
1420 // Get all cache entries for these container cache keys...
1421 $values = $this->memCache
->getBatch( array_keys( $pathNames ) );
1422 foreach ( $values as $cacheKey => $val ) {
1423 if ( is_array( $val ) ) {
1424 $this->trimCache(); // limit memory
1425 $this->cache
[$pathNames[$cacheKey]]['stat'] = $val;
1429 wfProfileOut( __METHOD__
. '-' . $this->name
);
1430 wfProfileOut( __METHOD__
);
1435 * FileBackendStore helper class for performing asynchronous file operations.
1437 * For example, calling FileBackendStore::createInternal() with the "async"
1438 * param flag may result in a Status that contains this object as a value.
1439 * This class is largely backend-specific and is mostly just "magic" to be
1440 * passed to FileBackendStore::executeOpHandlesInternal().
1442 abstract class FileBackendStoreOpHandle
{
1444 public $params = array(); // params to caller functions
1445 /** @var FileBackendStore */
1448 public $resourcesToClose = array();
1450 public $call; // string; name that identifies the function called
1453 * Close all open file handles
1457 public function closeResources() {
1458 array_map( 'fclose', $this->resourcesToClose
);
1463 * FileBackendStore helper function to handle listings that span container shards.
1464 * Do not use this class from places outside of FileBackendStore.
1466 * @ingroup FileBackend
1468 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1469 /** @var FileBackendStore */
1474 protected $shardSuffixes;
1475 protected $container; // string; full container name
1476 protected $directory; // string; resolved relative path
1478 /** @var Traversable */
1480 protected $curShard = 0; // integer
1481 protected $pos = 0; // integer
1484 protected $multiShardPaths = array(); // (rel path => 1)
1487 * @param $backend FileBackendStore
1488 * @param $container string Full storage container name
1489 * @param $dir string Storage directory relative to container
1490 * @param $suffixes Array List of container shard suffixes
1491 * @param $params Array
1493 public function __construct(
1494 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1496 $this->backend
= $backend;
1497 $this->container
= $container;
1498 $this->directory
= $dir;
1499 $this->shardSuffixes
= $suffixes;
1500 $this->params
= $params;
1504 * @see Iterator::current()
1505 * @return string|bool String or false
1507 public function current() {
1508 if ( is_array( $this->iter
) ) {
1509 return current( $this->iter
);
1511 return $this->iter
->current();
1516 * @see Iterator::key()
1519 public function key() {
1524 * @see Iterator::next()
1527 public function next() {
1529 if ( is_array( $this->iter
) ) {
1530 next( $this->iter
);
1532 $this->iter
->next();
1534 // Filter out items that we already listed
1535 $this->filterViaNext();
1536 // Find the next non-empty shard if no elements are left
1537 $this->nextShardIteratorIfNotValid();
1541 * @see Iterator::rewind()
1544 public function rewind() {
1546 $this->curShard
= 0;
1547 $this->setIteratorFromCurrentShard();
1548 // Filter out items that we already listed
1549 $this->filterViaNext();
1550 // Find the next non-empty shard if this one has no elements
1551 $this->nextShardIteratorIfNotValid();
1555 * @see Iterator::valid()
1558 public function valid() {
1559 if ( $this->iter
=== null ) {
1560 return false; // some failure?
1561 } elseif ( is_array( $this->iter
) ) {
1562 return ( current( $this->iter
) !== false ); // no paths can have this value
1564 return $this->iter
->valid();
1569 * Filter out duplicate items by advancing to the next ones
1571 protected function filterViaNext() {
1572 while ( $this->iter
->valid() ) {
1573 $rel = $this->iter
->current(); // path relative to given directory
1574 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1575 if ( !$this->backend
->isSingleShardPathInternal( $path ) ) {
1576 // Don't keep listing paths that are on multiple shards
1577 if ( isset( $this->multiShardPaths
[$rel] ) ) {
1578 $this->iter
->next(); // we already listed this path
1580 $this->multiShardPaths
[$rel] = 1;
1588 * If the list iterator for this container shard is out of items,
1589 * then move on to the next container that has items.
1590 * If there are none, then it advances to the last container.
1592 protected function nextShardIteratorIfNotValid() {
1593 while ( !$this->valid() ) {
1594 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1595 break; // no more container shards
1597 $this->setIteratorFromCurrentShard();
1602 * Set the list iterator to that of the current container shard
1604 protected function setIteratorFromCurrentShard() {
1605 $suffix = $this->shardSuffixes
[$this->curShard
];
1606 $this->iter
= $this->listFromShard(
1607 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1611 * Get the list for a given container shard
1613 * @param $container string Resolved container name
1614 * @param $dir string Resolved path relative to container
1615 * @param $params Array
1616 * @return Traversable|Array|null
1618 abstract protected function listFromShard( $container, $dir, array $params );
1622 * Iterator for listing directories
1624 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1625 protected function listFromShard( $container, $dir, array $params ) {
1626 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1631 * Iterator for listing regular files
1633 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1634 protected function listFromShard( $container, $dir, array $params ) {
1635 return $this->backend
->getFileListInternal( $container, $dir, $params );