9 * @brief Base class for all backends using particular storage medium.
11 * This class defines the methods as abstract that subclasses must implement.
12 * Outside callers should *not* use functions with "Internal" in the name.
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.
18 * @ingroup FileBackend
21 abstract class FileBackendStore
extends FileBackend
{
22 /** @var Array Map of paths to small (RAM/disk) cache items */
23 protected $cache = array(); // (storage path => key => value)
24 protected $maxCacheSize = 100; // integer; max paths with entries
25 /** @var Array Map of paths to large (RAM/disk) cache items */
26 protected $expensiveCache = array(); // (storage path => key => value)
27 protected $maxExpensiveCacheSize = 10; // integer; max paths with entries
29 /** @var Array Map of container names to sharding settings */
30 protected $shardViaHashLevels = array(); // (container name => config array)
32 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
35 * Get the maximum allowable file size given backend
36 * medium restrictions and basic performance constraints.
37 * Do not call this function from places outside FileBackend and FileOp.
39 * @return integer Bytes
41 final public function maxFileSizeInternal() {
42 return $this->maxFileSize
;
46 * Check if a file can be created at a given storage path.
47 * FS backends should check if the parent directory exists and the file is writable.
48 * Backends using key/value stores should check if the container exists.
50 * @param $storagePath string
53 abstract public function isPathUsableInternal( $storagePath );
56 * Create a file in the backend with the given contents.
57 * Do not call this function from places outside FileBackend and FileOp.
60 * content : the raw file contents
61 * dst : destination storage path
62 * overwrite : overwrite any file that exists at the destination
64 * @param $params Array
67 final public function createInternal( array $params ) {
68 wfProfileIn( __METHOD__
);
69 wfProfileIn( __METHOD__
. '-' . $this->name
);
70 if ( strlen( $params['content'] ) > $this->maxFileSizeInternal() ) {
71 $status = Status
::newFatal( 'backend-fail-maxsize',
72 $params['dst'], $this->maxFileSizeInternal() );
74 $status = $this->doCreateInternal( $params );
75 $this->clearCache( array( $params['dst'] ) );
77 wfProfileOut( __METHOD__
. '-' . $this->name
);
78 wfProfileOut( __METHOD__
);
83 * @see FileBackendStore::createInternal()
85 abstract protected function doCreateInternal( array $params );
88 * Store a file into the backend from a file on disk.
89 * Do not call this function from places outside FileBackend and FileOp.
92 * src : source path on disk
93 * dst : destination storage path
94 * overwrite : overwrite any file that exists at the destination
96 * @param $params Array
99 final public function storeInternal( array $params ) {
100 wfProfileIn( __METHOD__
);
101 wfProfileIn( __METHOD__
. '-' . $this->name
);
102 if ( filesize( $params['src'] ) > $this->maxFileSizeInternal() ) {
103 $status = Status
::newFatal( 'backend-fail-store', $params['dst'] );
105 $status = $this->doStoreInternal( $params );
106 $this->clearCache( array( $params['dst'] ) );
108 wfProfileOut( __METHOD__
. '-' . $this->name
);
109 wfProfileOut( __METHOD__
);
114 * @see FileBackendStore::storeInternal()
116 abstract protected function doStoreInternal( array $params );
119 * Copy a file from one storage path to another in the backend.
120 * Do not call this function from places outside FileBackend and FileOp.
123 * src : source storage path
124 * dst : destination storage path
125 * overwrite : overwrite any file that exists at the destination
127 * @param $params Array
130 final public function copyInternal( array $params ) {
131 wfProfileIn( __METHOD__
);
132 wfProfileIn( __METHOD__
. '-' . $this->name
);
133 $status = $this->doCopyInternal( $params );
134 $this->clearCache( array( $params['dst'] ) );
135 wfProfileOut( __METHOD__
. '-' . $this->name
);
136 wfProfileOut( __METHOD__
);
141 * @see FileBackendStore::copyInternal()
143 abstract protected function doCopyInternal( array $params );
146 * Delete a file at the storage path.
147 * Do not call this function from places outside FileBackend and FileOp.
150 * src : source storage path
151 * ignoreMissingSource : do nothing if the source file does not exist
153 * @param $params Array
156 final public function deleteInternal( array $params ) {
157 wfProfileIn( __METHOD__
);
158 wfProfileIn( __METHOD__
. '-' . $this->name
);
159 $status = $this->doDeleteInternal( $params );
160 $this->clearCache( array( $params['src'] ) );
161 wfProfileOut( __METHOD__
. '-' . $this->name
);
162 wfProfileOut( __METHOD__
);
167 * @see FileBackendStore::deleteInternal()
169 abstract protected function doDeleteInternal( array $params );
172 * Move a file from one storage path to another in the backend.
173 * Do not call this function from places outside FileBackend and FileOp.
176 * src : source storage path
177 * dst : destination storage path
178 * overwrite : overwrite any file that exists at the destination
180 * @param $params Array
183 final public function moveInternal( array $params ) {
184 wfProfileIn( __METHOD__
);
185 wfProfileIn( __METHOD__
. '-' . $this->name
);
186 $status = $this->doMoveInternal( $params );
187 $this->clearCache( array( $params['src'], $params['dst'] ) );
188 wfProfileOut( __METHOD__
. '-' . $this->name
);
189 wfProfileOut( __METHOD__
);
194 * @see FileBackendStore::moveInternal()
197 protected function doMoveInternal( array $params ) {
198 // Copy source to dest
199 $status = $this->copyInternal( $params );
200 if ( $status->isOK() ) {
201 // Delete source (only fails due to races or medium going down)
202 $status->merge( $this->deleteInternal( array( 'src' => $params['src'] ) ) );
203 $status->setResult( true, $status->value
); // ignore delete() errors
209 * @see FileBackend::concatenate()
212 final public function concatenate( array $params ) {
213 wfProfileIn( __METHOD__
);
214 wfProfileIn( __METHOD__
. '-' . $this->name
);
215 $status = Status
::newGood();
217 // Try to lock the source files for the scope of this function
218 $scopeLockS = $this->getScopedFileLocks( $params['srcs'], LockManager
::LOCK_UW
, $status );
219 if ( $status->isOK() ) {
220 // Actually do the concatenation
221 $status->merge( $this->doConcatenate( $params ) );
224 wfProfileOut( __METHOD__
. '-' . $this->name
);
225 wfProfileOut( __METHOD__
);
230 * @see FileBackendStore::concatenate()
233 protected function doConcatenate( array $params ) {
234 $status = Status
::newGood();
235 $tmpPath = $params['dst']; // convenience
237 // Check that the specified temp file is valid...
238 wfSuppressWarnings();
239 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
241 if ( !$ok ) { // not present or not empty
242 $status->fatal( 'backend-fail-opentemp', $tmpPath );
246 // Build up the temp file using the source chunks (in order)...
247 $tmpHandle = fopen( $tmpPath, 'ab' );
248 if ( $tmpHandle === false ) {
249 $status->fatal( 'backend-fail-opentemp', $tmpPath );
252 foreach ( $params['srcs'] as $virtualSource ) {
253 // Get a local FS version of the chunk
254 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
256 $status->fatal( 'backend-fail-read', $virtualSource );
259 // Get a handle to the local FS version
260 $sourceHandle = fopen( $tmpFile->getPath(), 'r' );
261 if ( $sourceHandle === false ) {
262 fclose( $tmpHandle );
263 $status->fatal( 'backend-fail-read', $virtualSource );
266 // Append chunk to file (pass chunk size to avoid magic quotes)
267 if ( !stream_copy_to_stream( $sourceHandle, $tmpHandle ) ) {
268 fclose( $sourceHandle );
269 fclose( $tmpHandle );
270 $status->fatal( 'backend-fail-writetemp', $tmpPath );
273 fclose( $sourceHandle );
275 if ( !fclose( $tmpHandle ) ) {
276 $status->fatal( 'backend-fail-closetemp', $tmpPath );
280 clearstatcache(); // temp file changed
286 * @see FileBackend::doPrepare()
289 final protected function doPrepare( array $params ) {
290 wfProfileIn( __METHOD__
);
291 wfProfileIn( __METHOD__
. '-' . $this->name
);
293 $status = Status
::newGood();
294 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
295 if ( $dir === null ) {
296 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
297 wfProfileOut( __METHOD__
. '-' . $this->name
);
298 wfProfileOut( __METHOD__
);
299 return $status; // invalid storage path
302 if ( $shard !== null ) { // confined to a single container/shard
303 $status->merge( $this->doPrepareInternal( $fullCont, $dir, $params ) );
304 } else { // directory is on several shards
305 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
306 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
307 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
308 $status->merge( $this->doPrepareInternal( "{$fullCont}{$suffix}", $dir, $params ) );
312 wfProfileOut( __METHOD__
. '-' . $this->name
);
313 wfProfileOut( __METHOD__
);
318 * @see FileBackendStore::doPrepare()
321 protected function doPrepareInternal( $container, $dir, array $params ) {
322 return Status
::newGood();
326 * @see FileBackend::doSecure()
329 final protected function doSecure( array $params ) {
330 wfProfileIn( __METHOD__
);
331 wfProfileIn( __METHOD__
. '-' . $this->name
);
332 $status = Status
::newGood();
334 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
335 if ( $dir === null ) {
336 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
337 wfProfileOut( __METHOD__
. '-' . $this->name
);
338 wfProfileOut( __METHOD__
);
339 return $status; // invalid storage path
342 if ( $shard !== null ) { // confined to a single container/shard
343 $status->merge( $this->doSecureInternal( $fullCont, $dir, $params ) );
344 } else { // directory is on several shards
345 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
346 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
347 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
348 $status->merge( $this->doSecureInternal( "{$fullCont}{$suffix}", $dir, $params ) );
352 wfProfileOut( __METHOD__
. '-' . $this->name
);
353 wfProfileOut( __METHOD__
);
358 * @see FileBackendStore::doSecure()
361 protected function doSecureInternal( $container, $dir, array $params ) {
362 return Status
::newGood();
366 * @see FileBackend::doClean()
369 final protected function doClean( array $params ) {
370 wfProfileIn( __METHOD__
);
371 wfProfileIn( __METHOD__
. '-' . $this->name
);
372 $status = Status
::newGood();
374 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
375 if ( $dir === null ) {
376 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
377 wfProfileOut( __METHOD__
. '-' . $this->name
);
378 wfProfileOut( __METHOD__
);
379 return $status; // invalid storage path
382 // Attempt to lock this directory...
383 $filesLockEx = array( $params['dir'] );
384 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
385 if ( !$status->isOK() ) {
386 wfProfileOut( __METHOD__
. '-' . $this->name
);
387 wfProfileOut( __METHOD__
);
388 return $status; // abort
391 if ( $shard !== null ) { // confined to a single container/shard
392 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
393 } else { // directory is on several shards
394 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
395 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
396 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
397 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
401 wfProfileOut( __METHOD__
. '-' . $this->name
);
402 wfProfileOut( __METHOD__
);
407 * @see FileBackendStore::doClean()
410 protected function doCleanInternal( $container, $dir, array $params ) {
411 return Status
::newGood();
415 * @see FileBackend::fileExists()
418 final public function fileExists( array $params ) {
419 wfProfileIn( __METHOD__
);
420 wfProfileIn( __METHOD__
. '-' . $this->name
);
421 $stat = $this->getFileStat( $params );
422 wfProfileOut( __METHOD__
. '-' . $this->name
);
423 wfProfileOut( __METHOD__
);
424 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
428 * @see FileBackend::getFileTimestamp()
431 final public function getFileTimestamp( array $params ) {
432 wfProfileIn( __METHOD__
);
433 wfProfileIn( __METHOD__
. '-' . $this->name
);
434 $stat = $this->getFileStat( $params );
435 wfProfileOut( __METHOD__
. '-' . $this->name
);
436 wfProfileOut( __METHOD__
);
437 return $stat ?
$stat['mtime'] : false;
441 * @see FileBackend::getFileSize()
444 final public function getFileSize( 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 ?
$stat['size'] : false;
454 * @see FileBackend::getFileStat()
457 final public function getFileStat( array $params ) {
458 wfProfileIn( __METHOD__
);
459 wfProfileIn( __METHOD__
. '-' . $this->name
);
460 $path = self
::normalizeStoragePath( $params['src'] );
461 if ( $path === null ) {
462 wfProfileOut( __METHOD__
. '-' . $this->name
);
463 wfProfileOut( __METHOD__
);
464 return false; // invalid storage path
466 $latest = !empty( $params['latest'] );
467 if ( isset( $this->cache
[$path]['stat'] ) ) {
468 // If we want the latest data, check that this cached
469 // value was in fact fetched with the latest available data.
470 if ( !$latest ||
$this->cache
[$path]['stat']['latest'] ) {
471 wfProfileOut( __METHOD__
. '-' . $this->name
);
472 wfProfileOut( __METHOD__
);
473 return $this->cache
[$path]['stat'];
476 wfProfileIn( __METHOD__
. '-miss' );
477 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
478 $stat = $this->doGetFileStat( $params );
479 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
480 wfProfileOut( __METHOD__
. '-miss' );
481 if ( is_array( $stat ) ) { // don't cache negatives
482 $this->trimCache(); // limit memory
483 $this->cache
[$path]['stat'] = $stat;
484 $this->cache
[$path]['stat']['latest'] = $latest;
486 wfProfileOut( __METHOD__
. '-' . $this->name
);
487 wfProfileOut( __METHOD__
);
492 * @see FileBackendStore::getFileStat()
494 abstract protected function doGetFileStat( array $params );
497 * @see FileBackend::getFileContents()
498 * @return bool|string
500 public function getFileContents( array $params ) {
501 wfProfileIn( __METHOD__
);
502 wfProfileIn( __METHOD__
. '-' . $this->name
);
503 $tmpFile = $this->getLocalReference( $params );
505 wfProfileOut( __METHOD__
. '-' . $this->name
);
506 wfProfileOut( __METHOD__
);
509 wfSuppressWarnings();
510 $data = file_get_contents( $tmpFile->getPath() );
512 wfProfileOut( __METHOD__
. '-' . $this->name
);
513 wfProfileOut( __METHOD__
);
518 * @see FileBackend::getFileSha1Base36()
519 * @return bool|string
521 final public function getFileSha1Base36( array $params ) {
522 wfProfileIn( __METHOD__
);
523 wfProfileIn( __METHOD__
. '-' . $this->name
);
524 $path = $params['src'];
525 if ( isset( $this->cache
[$path]['sha1'] ) ) {
526 wfProfileOut( __METHOD__
. '-' . $this->name
);
527 wfProfileOut( __METHOD__
);
528 return $this->cache
[$path]['sha1'];
530 wfProfileIn( __METHOD__
. '-miss' );
531 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
532 $hash = $this->doGetFileSha1Base36( $params );
533 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
534 wfProfileOut( __METHOD__
. '-miss' );
535 if ( $hash ) { // don't cache negatives
536 $this->trimCache(); // limit memory
537 $this->cache
[$path]['sha1'] = $hash;
539 wfProfileOut( __METHOD__
. '-' . $this->name
);
540 wfProfileOut( __METHOD__
);
545 * @see FileBackendStore::getFileSha1Base36()
548 protected function doGetFileSha1Base36( array $params ) {
549 $fsFile = $this->getLocalReference( $params );
553 return $fsFile->getSha1Base36();
558 * @see FileBackend::getFileProps()
561 final public function getFileProps( array $params ) {
562 wfProfileIn( __METHOD__
);
563 wfProfileIn( __METHOD__
. '-' . $this->name
);
564 $fsFile = $this->getLocalReference( $params );
565 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
566 wfProfileOut( __METHOD__
. '-' . $this->name
);
567 wfProfileOut( __METHOD__
);
572 * @see FileBackend::getLocalReference()
573 * @return TempFSFile|null
575 public function getLocalReference( array $params ) {
576 wfProfileIn( __METHOD__
);
577 wfProfileIn( __METHOD__
. '-' . $this->name
);
578 $path = $params['src'];
579 if ( isset( $this->expensiveCache
[$path]['localRef'] ) ) {
580 wfProfileOut( __METHOD__
. '-' . $this->name
);
581 wfProfileOut( __METHOD__
);
582 return $this->expensiveCache
[$path]['localRef'];
584 $tmpFile = $this->getLocalCopy( $params );
585 if ( $tmpFile ) { // don't cache negatives
586 $this->trimExpensiveCache(); // limit memory
587 $this->expensiveCache
[$path]['localRef'] = $tmpFile;
589 wfProfileOut( __METHOD__
. '-' . $this->name
);
590 wfProfileOut( __METHOD__
);
595 * @see FileBackend::streamFile()
598 final public function streamFile( array $params ) {
599 wfProfileIn( __METHOD__
);
600 wfProfileIn( __METHOD__
. '-' . $this->name
);
601 $status = Status
::newGood();
603 $info = $this->getFileStat( $params );
604 if ( !$info ) { // let StreamFile handle the 404
605 $status->fatal( 'backend-fail-notexists', $params['src'] );
608 // Set output buffer and HTTP headers for stream
609 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
610 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
611 if ( $res == StreamFile
::NOT_MODIFIED
) {
612 // do nothing; client cache is up to date
613 } elseif ( $res == StreamFile
::READY_STREAM
) {
614 wfProfileIn( __METHOD__
. '-send' );
615 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
616 $status = $this->doStreamFile( $params );
617 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
618 wfProfileOut( __METHOD__
. '-send' );
620 $status->fatal( 'backend-fail-stream', $params['src'] );
623 wfProfileOut( __METHOD__
. '-' . $this->name
);
624 wfProfileOut( __METHOD__
);
629 * @see FileBackendStore::streamFile()
632 protected function doStreamFile( array $params ) {
633 $status = Status
::newGood();
635 $fsFile = $this->getLocalReference( $params );
637 $status->fatal( 'backend-fail-stream', $params['src'] );
638 } elseif ( !readfile( $fsFile->getPath() ) ) {
639 $status->fatal( 'backend-fail-stream', $params['src'] );
646 * @copydoc FileBackend::getFileList()
647 * @return Array|null|Traversable
649 final public function getFileList( array $params ) {
650 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
651 if ( $dir === null ) { // invalid storage path
654 if ( $shard !== null ) {
655 // File listing is confined to a single container/shard
656 return $this->getFileListInternal( $fullCont, $dir, $params );
658 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
659 // File listing spans multiple containers/shards
660 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
661 return new FileBackendStoreShardListIterator( $this,
662 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
667 * Do not call this function from places outside FileBackend
669 * @see FileBackendStore::getFileList()
671 * @param $container string Resolved container name
672 * @param $dir string Resolved path relative to container
673 * @param $params Array
674 * @return Traversable|Array|null
676 abstract public function getFileListInternal( $container, $dir, array $params );
679 * Get the list of supported operations and their corresponding FileOp classes.
683 protected function supportedOperations() {
685 'store' => 'StoreFileOp',
686 'copy' => 'CopyFileOp',
687 'move' => 'MoveFileOp',
688 'delete' => 'DeleteFileOp',
689 'create' => 'CreateFileOp',
690 'null' => 'NullFileOp'
695 * Return a list of FileOp objects from a list of operations.
696 * Do not call this function from places outside FileBackend.
698 * The result must have the same number of items as the input.
699 * An exception is thrown if an unsupported operation is requested.
701 * @param $ops Array Same format as doOperations()
702 * @return Array List of FileOp objects
703 * @throws MWException
705 final public function getOperations( array $ops ) {
706 $supportedOps = $this->supportedOperations();
708 $performOps = array(); // array of FileOp objects
709 // Build up ordered array of FileOps...
710 foreach ( $ops as $operation ) {
711 $opName = $operation['op'];
712 if ( isset( $supportedOps[$opName] ) ) {
713 $class = $supportedOps[$opName];
714 // Get params for this operation
715 $params = $operation;
716 // Append the FileOp class
717 $performOps[] = new $class( $this, $params );
719 throw new MWException( "Operation `$opName` is not supported." );
727 * @see FileBackend::doOperationsInternal()
730 protected function doOperationsInternal( array $ops, array $opts ) {
731 wfProfileIn( __METHOD__
);
732 wfProfileIn( __METHOD__
. '-' . $this->name
);
733 $status = Status
::newGood();
735 // Build up a list of FileOps...
736 $performOps = $this->getOperations( $ops );
738 // Acquire any locks as needed...
739 if ( empty( $opts['nonLocking'] ) ) {
740 // Build up a list of files to lock...
741 $filesLockEx = $filesLockSh = array();
742 foreach ( $performOps as $fileOp ) {
743 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
744 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
746 // Optimization: if doing an EX lock anyway, don't also set an SH one
747 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
748 // Get a shared lock on the parent directory of each path changed
749 $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
750 // Try to lock those files for the scope of this function...
751 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager
::LOCK_UW
, $status );
752 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
753 if ( !$status->isOK() ) {
754 wfProfileOut( __METHOD__
. '-' . $this->name
);
755 wfProfileOut( __METHOD__
);
756 return $status; // abort
760 // Clear any cache entries (after locks acquired)
763 // Actually attempt the operation batch...
764 $subStatus = FileOp
::attemptBatch( $performOps, $opts, $this->fileJournal
);
766 // Merge errors into status fields
767 $status->merge( $subStatus );
768 $status->success
= $subStatus->success
; // not done in merge()
770 wfProfileOut( __METHOD__
. '-' . $this->name
);
771 wfProfileOut( __METHOD__
);
776 * @see FileBackend::clearCache()
778 final public function clearCache( array $paths = null ) {
779 if ( is_array( $paths ) ) {
780 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
781 $paths = array_filter( $paths, 'strlen' ); // remove nulls
783 if ( $paths === null ) {
784 $this->cache
= array();
785 $this->expensiveCache
= array();
787 foreach ( $paths as $path ) {
788 unset( $this->cache
[$path] );
789 unset( $this->expensiveCache
[$path] );
792 $this->doClearCache( $paths );
796 * Clears any additional stat caches for storage paths
798 * @see FileBackend::clearCache()
800 * @param $paths Array Storage paths (optional)
803 protected function doClearCache( array $paths = null ) {}
806 * Prune the inexpensive cache if it is too big to add an item
810 protected function trimCache() {
811 if ( count( $this->cache
) >= $this->maxCacheSize
) {
812 reset( $this->cache
);
813 unset( $this->cache
[key( $this->cache
)] );
818 * Prune the expensive cache if it is too big to add an item
822 protected function trimExpensiveCache() {
823 if ( count( $this->expensiveCache
) >= $this->maxExpensiveCacheSize
) {
824 reset( $this->expensiveCache
);
825 unset( $this->expensiveCache
[key( $this->expensiveCache
)] );
830 * Check if a container name is valid.
831 * This checks for for length and illegal characters.
833 * @param $container string
836 final protected static function isValidContainerName( $container ) {
837 // This accounts for Swift and S3 restrictions while leaving room
838 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
839 // This disallows directory separators or traversal characters.
840 // Note that matching strings URL encode to the same string;
841 // in Swift, the length restriction is *after* URL encoding.
842 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
846 * Splits a storage path into an internal container name,
847 * an internal relative file name, and a container shard suffix.
848 * Any shard suffix is already appended to the internal container name.
849 * This also checks that the storage path is valid and within this backend.
851 * If the container is sharded but a suffix could not be determined,
852 * this means that the path can only refer to a directory and can only
853 * be scanned by looking in all the container shards.
855 * @param $storagePath string
856 * @return Array (container, path, container suffix) or (null, null, null) if invalid
858 final protected function resolveStoragePath( $storagePath ) {
859 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
860 if ( $backend === $this->name
) { // must be for this backend
861 $relPath = self
::normalizeContainerPath( $relPath );
862 if ( $relPath !== null ) {
863 // Get shard for the normalized path if this container is sharded
864 $cShard = $this->getContainerShard( $container, $relPath );
865 // Validate and sanitize the relative path (backend-specific)
866 $relPath = $this->resolveContainerPath( $container, $relPath );
867 if ( $relPath !== null ) {
868 // Prepend any wiki ID prefix to the container name
869 $container = $this->fullContainerName( $container );
870 if ( self
::isValidContainerName( $container ) ) {
871 // Validate and sanitize the container name (backend-specific)
872 $container = $this->resolveContainerName( "{$container}{$cShard}" );
873 if ( $container !== null ) {
874 return array( $container, $relPath, $cShard );
880 return array( null, null, null );
884 * Like resolveStoragePath() except null values are returned if
885 * the container is sharded and the shard could not be determined.
887 * @see FileBackendStore::resolveStoragePath()
889 * @param $storagePath string
890 * @return Array (container, path) or (null, null) if invalid
892 final protected function resolveStoragePathReal( $storagePath ) {
893 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
894 if ( $cShard !== null ) {
895 return array( $container, $relPath );
897 return array( null, null );
901 * Get the container name shard suffix for a given path.
902 * Any empty suffix means the container is not sharded.
904 * @param $container string Container name
905 * @param $relStoragePath string Storage path relative to the container
906 * @return string|null Returns null if shard could not be determined
908 final protected function getContainerShard( $container, $relPath ) {
909 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
910 if ( $levels == 1 ||
$levels == 2 ) {
911 // Hash characters are either base 16 or 36
912 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
913 // Get a regex that represents the shard portion of paths.
914 // The concatenation of the captures gives us the shard.
915 if ( $levels === 1 ) { // 16 or 36 shards per container
916 $hashDirRegex = '(' . $char . ')';
917 } else { // 256 or 1296 shards per container
918 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
919 $hashDirRegex = $char . '/(' . $char . '{2})';
920 } else { // short hash dir format (e.g. "a/b/c")
921 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
924 // Allow certain directories to be above the hash dirs so as
925 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
926 // They must be 2+ chars to avoid any hash directory ambiguity.
928 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
929 return '.' . implode( '', array_slice( $m, 1 ) );
931 return null; // failed to match
933 return ''; // no sharding
937 * Get the sharding config for a container.
938 * If greater than 0, then all file storage paths within
939 * the container are required to be hashed accordingly.
941 * @param $container string
942 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
944 final protected function getContainerHashLevels( $container ) {
945 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
946 $config = $this->shardViaHashLevels
[$container];
947 $hashLevels = (int)$config['levels'];
948 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
949 $hashBase = (int)$config['base'];
950 if ( $hashBase == 16 ||
$hashBase == 36 ) {
951 return array( $hashLevels, $hashBase, $config['repeat'] );
955 return array( 0, 0, false ); // no sharding
959 * Get a list of full container shard suffixes for a container
961 * @param $container string
964 final protected function getContainerSuffixes( $container ) {
966 list( $digits, $base ) = $this->getContainerHashLevels( $container );
968 $numShards = pow( $base, $digits );
969 for ( $index = 0; $index < $numShards; $index++
) {
970 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
977 * Get the full container name, including the wiki ID prefix
979 * @param $container string
982 final protected function fullContainerName( $container ) {
983 if ( $this->wikiId
!= '' ) {
984 return "{$this->wikiId}-$container";
991 * Resolve a container name, checking if it's allowed by the backend.
992 * This is intended for internal use, such as encoding illegal chars.
993 * Subclasses can override this to be more restrictive.
995 * @param $container string
996 * @return string|null
998 protected function resolveContainerName( $container ) {
1003 * Resolve a relative storage path, checking if it's allowed by the backend.
1004 * This is intended for internal use, such as encoding illegal chars or perhaps
1005 * getting absolute paths (e.g. FS based backends). Note that the relative path
1006 * may be the empty string (e.g. the path is simply to the container).
1008 * @param $container string Container name
1009 * @param $relStoragePath string Storage path relative to the container
1010 * @return string|null Path or null if not valid
1012 protected function resolveContainerPath( $container, $relStoragePath ) {
1013 return $relStoragePath;
1018 * FileBackendStore helper function to handle file listings that span container shards.
1019 * Do not use this class from places outside of FileBackendStore.
1021 * @ingroup FileBackend
1023 class FileBackendStoreShardListIterator
implements Iterator
{
1024 /* @var FileBackendStore */
1029 protected $shardSuffixes;
1030 protected $container; // string
1031 protected $directory; // string
1033 /* @var Traversable */
1035 protected $curShard = 0; // integer
1036 protected $pos = 0; // integer
1039 * @param $backend FileBackendStore
1040 * @param $container string Full storage container name
1041 * @param $dir string Storage directory relative to container
1042 * @param $suffixes Array List of container shard suffixes
1043 * @param $params Array
1045 public function __construct(
1046 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1048 $this->backend
= $backend;
1049 $this->container
= $container;
1050 $this->directory
= $dir;
1051 $this->shardSuffixes
= $suffixes;
1052 $this->params
= $params;
1056 * @see Iterator::current()
1057 * @return string|bool String or false
1059 public function current() {
1060 if ( is_array( $this->iter
) ) {
1061 return current( $this->iter
);
1063 return $this->iter
->current();
1068 * @see Iterator::key()
1071 public function key() {
1076 * @see Iterator::next()
1079 public function next() {
1081 if ( is_array( $this->iter
) ) {
1082 next( $this->iter
);
1084 $this->iter
->next();
1086 // Find the next non-empty shard if no elements are left
1087 $this->nextShardIteratorIfNotValid();
1091 * @see Iterator::rewind()
1094 public function rewind() {
1096 $this->curShard
= 0;
1097 $this->setIteratorFromCurrentShard();
1098 // Find the next non-empty shard if this one has no elements
1099 $this->nextShardIteratorIfNotValid();
1103 * @see Iterator::valid()
1106 public function valid() {
1107 if ( $this->iter
== null ) {
1108 return false; // some failure?
1109 } elseif ( is_array( $this->iter
) ) {
1110 return ( current( $this->iter
) !== false ); // no paths can have this value
1112 return $this->iter
->valid();
1117 * If the list iterator for this container shard is out of items,
1118 * then move on to the next container that has items.
1119 * If there are none, then it advances to the last container.
1121 protected function nextShardIteratorIfNotValid() {
1122 while ( !$this->valid() ) {
1123 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1124 break; // no more container shards
1126 $this->setIteratorFromCurrentShard();
1131 * Set the list iterator to that of the current container shard
1133 protected function setIteratorFromCurrentShard() {
1134 $suffix = $this->shardSuffixes
[$this->curShard
];
1135 $this->iter
= $this->backend
->getFileListInternal(
1136 "{$this->container}{$suffix}", $this->directory
, $this->params
);