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
{
25 /** @var Array Map of paths to small (RAM/disk) cache items */
26 protected $cache = array(); // (storage path => key => value)
27 protected $maxCacheSize = 100; // integer; max paths with entries
28 /** @var Array Map of paths to large (RAM/disk) cache items */
29 protected $expensiveCache = array(); // (storage path => key => value)
30 protected $maxExpensiveCacheSize = 10; // integer; max paths with entries
32 /** @var Array Map of container names to sharding settings */
33 protected $shardViaHashLevels = array(); // (container name => config array)
35 protected $maxFileSize = 4294967296; // integer bytes (4GiB)
38 * @see FileBackend::__construct()
40 * @param $config Array
42 public function __construct( array $config ) {
43 parent
::__construct( $config );
44 $this->memCache
= new EmptyBagOStuff(); // disabled by default
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.
52 * @return integer Bytes
54 final public function maxFileSizeInternal() {
55 return $this->maxFileSize
;
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.
63 * @param $storagePath string
66 abstract public function isPathUsableInternal( $storagePath );
69 * Create a file in the backend with the given contents.
70 * Do not call this function from places outside FileBackend and FileOp.
73 * content : the raw file contents
74 * dst : destination storage path
75 * overwrite : overwrite any file that exists at the destination
77 * @param $params Array
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() );
87 $status = $this->doCreateInternal( $params );
88 $this->clearCache( array( $params['dst'] ) );
90 wfProfileOut( __METHOD__
. '-' . $this->name
);
91 wfProfileOut( __METHOD__
);
96 * @see FileBackendStore::createInternal()
98 abstract protected function doCreateInternal( array $params );
101 * Store a file into the backend from a file on disk.
102 * Do not call this function from places outside FileBackend and FileOp.
105 * src : source path on disk
106 * dst : destination storage path
107 * overwrite : overwrite any file that exists at the destination
109 * @param $params Array
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'] );
118 $status = $this->doStoreInternal( $params );
119 $this->clearCache( array( $params['dst'] ) );
121 wfProfileOut( __METHOD__
. '-' . $this->name
);
122 wfProfileOut( __METHOD__
);
127 * @see FileBackendStore::storeInternal()
129 abstract protected function doStoreInternal( array $params );
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.
136 * src : source storage path
137 * dst : destination storage path
138 * overwrite : overwrite any file that exists at the destination
140 * @param $params Array
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__
);
154 * @see FileBackendStore::copyInternal()
156 abstract protected function doCopyInternal( array $params );
159 * Delete a file at the storage path.
160 * Do not call this function from places outside FileBackend and FileOp.
163 * src : source storage path
164 * ignoreMissingSource : do nothing if the source file does not exist
166 * @param $params Array
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__
);
180 * @see FileBackendStore::deleteInternal()
182 abstract protected function doDeleteInternal( array $params );
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.
189 * src : source storage path
190 * dst : destination storage path
191 * overwrite : overwrite any file that exists at the destination
193 * @param $params Array
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__
);
207 * @see FileBackendStore::moveInternal()
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
222 * @see FileBackend::concatenate()
225 final public function concatenate( array $params ) {
226 wfProfileIn( __METHOD__
);
227 wfProfileIn( __METHOD__
. '-' . $this->name
);
228 $status = Status
::newGood();
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 ) );
237 wfProfileOut( __METHOD__
. '-' . $this->name
);
238 wfProfileOut( __METHOD__
);
243 * @see FileBackendStore::concatenate()
246 protected function doConcatenate( array $params ) {
247 $status = Status
::newGood();
248 $tmpPath = $params['dst']; // convenience
250 // Check that the specified temp file is valid...
251 wfSuppressWarnings();
252 $ok = ( is_file( $tmpPath ) && !filesize( $tmpPath ) );
254 if ( !$ok ) { // not present or not empty
255 $status->fatal( 'backend-fail-opentemp', $tmpPath );
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 );
265 foreach ( $params['srcs'] as $virtualSource ) {
266 // Get a local FS version of the chunk
267 $tmpFile = $this->getLocalReference( array( 'src' => $virtualSource ) );
269 $status->fatal( 'backend-fail-read', $virtualSource );
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 );
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 );
286 fclose( $sourceHandle );
288 if ( !fclose( $tmpHandle ) ) {
289 $status->fatal( 'backend-fail-closetemp', $tmpPath );
293 clearstatcache(); // temp file changed
299 * @see FileBackend::doPrepare()
302 final protected function doPrepare( array $params ) {
303 wfProfileIn( __METHOD__
);
304 wfProfileIn( __METHOD__
. '-' . $this->name
);
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
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 ) );
325 wfProfileOut( __METHOD__
. '-' . $this->name
);
326 wfProfileOut( __METHOD__
);
331 * @see FileBackendStore::doPrepare()
334 protected function doPrepareInternal( $container, $dir, array $params ) {
335 return Status
::newGood();
339 * @see FileBackend::doSecure()
342 final protected function doSecure( array $params ) {
343 wfProfileIn( __METHOD__
);
344 wfProfileIn( __METHOD__
. '-' . $this->name
);
345 $status = Status
::newGood();
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
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 ) );
365 wfProfileOut( __METHOD__
. '-' . $this->name
);
366 wfProfileOut( __METHOD__
);
371 * @see FileBackendStore::doSecure()
374 protected function doSecureInternal( $container, $dir, array $params ) {
375 return Status
::newGood();
379 * @see FileBackend::doClean()
382 final protected function doClean( array $params ) {
383 wfProfileIn( __METHOD__
);
384 wfProfileIn( __METHOD__
. '-' . $this->name
);
385 $status = Status
::newGood();
387 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
388 if ( $dir === null ) {
389 $status->fatal( 'backend-fail-invalidpath', $params['dir'] );
390 wfProfileOut( __METHOD__
. '-' . $this->name
);
391 wfProfileOut( __METHOD__
);
392 return $status; // invalid storage path
395 // Attempt to lock this directory...
396 $filesLockEx = array( $params['dir'] );
397 $scopedLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
398 if ( !$status->isOK() ) {
399 wfProfileOut( __METHOD__
. '-' . $this->name
);
400 wfProfileOut( __METHOD__
);
401 return $status; // abort
404 if ( $shard !== null ) { // confined to a single container/shard
405 $status->merge( $this->doCleanInternal( $fullCont, $dir, $params ) );
406 $this->deleteContainerCache( $fullCont ); // purge cache
407 } else { // directory is on several shards
408 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
409 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
410 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
411 $status->merge( $this->doCleanInternal( "{$fullCont}{$suffix}", $dir, $params ) );
412 $this->deleteContainerCache( "{$fullCont}{$suffix}" ); // purge cache
416 wfProfileOut( __METHOD__
. '-' . $this->name
);
417 wfProfileOut( __METHOD__
);
422 * @see FileBackendStore::doClean()
425 protected function doCleanInternal( $container, $dir, array $params ) {
426 return Status
::newGood();
430 * @see FileBackend::fileExists()
433 final public function fileExists( array $params ) {
434 wfProfileIn( __METHOD__
);
435 wfProfileIn( __METHOD__
. '-' . $this->name
);
436 $stat = $this->getFileStat( $params );
437 wfProfileOut( __METHOD__
. '-' . $this->name
);
438 wfProfileOut( __METHOD__
);
439 return ( $stat === null ) ?
null : (bool)$stat; // null => failure
443 * @see FileBackend::getFileTimestamp()
446 final public function getFileTimestamp( array $params ) {
447 wfProfileIn( __METHOD__
);
448 wfProfileIn( __METHOD__
. '-' . $this->name
);
449 $stat = $this->getFileStat( $params );
450 wfProfileOut( __METHOD__
. '-' . $this->name
);
451 wfProfileOut( __METHOD__
);
452 return $stat ?
$stat['mtime'] : false;
456 * @see FileBackend::getFileSize()
459 final public function getFileSize( array $params ) {
460 wfProfileIn( __METHOD__
);
461 wfProfileIn( __METHOD__
. '-' . $this->name
);
462 $stat = $this->getFileStat( $params );
463 wfProfileOut( __METHOD__
. '-' . $this->name
);
464 wfProfileOut( __METHOD__
);
465 return $stat ?
$stat['size'] : false;
469 * @see FileBackend::getFileStat()
472 final public function getFileStat( array $params ) {
473 wfProfileIn( __METHOD__
);
474 wfProfileIn( __METHOD__
. '-' . $this->name
);
475 $path = self
::normalizeStoragePath( $params['src'] );
476 if ( $path === null ) {
477 wfProfileOut( __METHOD__
. '-' . $this->name
);
478 wfProfileOut( __METHOD__
);
479 return false; // invalid storage path
481 $latest = !empty( $params['latest'] );
482 if ( isset( $this->cache
[$path]['stat'] ) ) {
483 // If we want the latest data, check that this cached
484 // value was in fact fetched with the latest available data.
485 if ( !$latest ||
$this->cache
[$path]['stat']['latest'] ) {
486 $this->pingCache( $path ); // LRU
487 wfProfileOut( __METHOD__
. '-' . $this->name
);
488 wfProfileOut( __METHOD__
);
489 return $this->cache
[$path]['stat'];
492 wfProfileIn( __METHOD__
. '-miss' );
493 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
494 $stat = $this->doGetFileStat( $params );
495 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
496 wfProfileOut( __METHOD__
. '-miss' );
497 if ( is_array( $stat ) ) { // don't cache negatives
498 $this->trimCache(); // limit memory
499 $this->cache
[$path]['stat'] = $stat;
500 $this->cache
[$path]['stat']['latest'] = $latest;
502 wfProfileOut( __METHOD__
. '-' . $this->name
);
503 wfProfileOut( __METHOD__
);
508 * @see FileBackendStore::getFileStat()
510 abstract protected function doGetFileStat( array $params );
513 * @see FileBackend::getFileContents()
514 * @return bool|string
516 public function getFileContents( array $params ) {
517 wfProfileIn( __METHOD__
);
518 wfProfileIn( __METHOD__
. '-' . $this->name
);
519 $tmpFile = $this->getLocalReference( $params );
521 wfProfileOut( __METHOD__
. '-' . $this->name
);
522 wfProfileOut( __METHOD__
);
525 wfSuppressWarnings();
526 $data = file_get_contents( $tmpFile->getPath() );
528 wfProfileOut( __METHOD__
. '-' . $this->name
);
529 wfProfileOut( __METHOD__
);
534 * @see FileBackend::getFileSha1Base36()
535 * @return bool|string
537 final public function getFileSha1Base36( array $params ) {
538 wfProfileIn( __METHOD__
);
539 wfProfileIn( __METHOD__
. '-' . $this->name
);
540 $path = $params['src'];
541 if ( isset( $this->cache
[$path]['sha1'] ) ) {
542 $this->pingCache( $path ); // LRU
543 wfProfileOut( __METHOD__
. '-' . $this->name
);
544 wfProfileOut( __METHOD__
);
545 return $this->cache
[$path]['sha1'];
547 wfProfileIn( __METHOD__
. '-miss' );
548 wfProfileIn( __METHOD__
. '-miss-' . $this->name
);
549 $hash = $this->doGetFileSha1Base36( $params );
550 wfProfileOut( __METHOD__
. '-miss-' . $this->name
);
551 wfProfileOut( __METHOD__
. '-miss' );
552 if ( $hash ) { // don't cache negatives
553 $this->trimCache(); // limit memory
554 $this->cache
[$path]['sha1'] = $hash;
556 wfProfileOut( __METHOD__
. '-' . $this->name
);
557 wfProfileOut( __METHOD__
);
562 * @see FileBackendStore::getFileSha1Base36()
565 protected function doGetFileSha1Base36( array $params ) {
566 $fsFile = $this->getLocalReference( $params );
570 return $fsFile->getSha1Base36();
575 * @see FileBackend::getFileProps()
578 final public function getFileProps( array $params ) {
579 wfProfileIn( __METHOD__
);
580 wfProfileIn( __METHOD__
. '-' . $this->name
);
581 $fsFile = $this->getLocalReference( $params );
582 $props = $fsFile ?
$fsFile->getProps() : FSFile
::placeholderProps();
583 wfProfileOut( __METHOD__
. '-' . $this->name
);
584 wfProfileOut( __METHOD__
);
589 * @see FileBackend::getLocalReference()
590 * @return TempFSFile|null
592 public function getLocalReference( array $params ) {
593 wfProfileIn( __METHOD__
);
594 wfProfileIn( __METHOD__
. '-' . $this->name
);
595 $path = $params['src'];
596 if ( isset( $this->expensiveCache
[$path]['localRef'] ) ) {
597 $this->pingExpensiveCache( $path );
598 wfProfileOut( __METHOD__
. '-' . $this->name
);
599 wfProfileOut( __METHOD__
);
600 return $this->expensiveCache
[$path]['localRef'];
602 $tmpFile = $this->getLocalCopy( $params );
603 if ( $tmpFile ) { // don't cache negatives
604 $this->trimExpensiveCache(); // limit memory
605 $this->expensiveCache
[$path]['localRef'] = $tmpFile;
607 wfProfileOut( __METHOD__
. '-' . $this->name
);
608 wfProfileOut( __METHOD__
);
613 * @see FileBackend::streamFile()
616 final public function streamFile( array $params ) {
617 wfProfileIn( __METHOD__
);
618 wfProfileIn( __METHOD__
. '-' . $this->name
);
619 $status = Status
::newGood();
621 $info = $this->getFileStat( $params );
622 if ( !$info ) { // let StreamFile handle the 404
623 $status->fatal( 'backend-fail-notexists', $params['src'] );
626 // Set output buffer and HTTP headers for stream
627 $extraHeaders = isset( $params['headers'] ) ?
$params['headers'] : array();
628 $res = StreamFile
::prepareForStream( $params['src'], $info, $extraHeaders );
629 if ( $res == StreamFile
::NOT_MODIFIED
) {
630 // do nothing; client cache is up to date
631 } elseif ( $res == StreamFile
::READY_STREAM
) {
632 wfProfileIn( __METHOD__
. '-send' );
633 wfProfileIn( __METHOD__
. '-send-' . $this->name
);
634 $status = $this->doStreamFile( $params );
635 wfProfileOut( __METHOD__
. '-send-' . $this->name
);
636 wfProfileOut( __METHOD__
. '-send' );
638 $status->fatal( 'backend-fail-stream', $params['src'] );
641 wfProfileOut( __METHOD__
. '-' . $this->name
);
642 wfProfileOut( __METHOD__
);
647 * @see FileBackendStore::streamFile()
650 protected function doStreamFile( array $params ) {
651 $status = Status
::newGood();
653 $fsFile = $this->getLocalReference( $params );
655 $status->fatal( 'backend-fail-stream', $params['src'] );
656 } elseif ( !readfile( $fsFile->getPath() ) ) {
657 $status->fatal( 'backend-fail-stream', $params['src'] );
664 * @copydoc FileBackend::getFileList()
665 * @return Array|null|Traversable
667 final public function getFileList( array $params ) {
668 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
669 if ( $dir === null ) { // invalid storage path
672 if ( $shard !== null ) {
673 // File listing is confined to a single container/shard
674 return $this->getFileListInternal( $fullCont, $dir, $params );
676 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
677 // File listing spans multiple containers/shards
678 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
679 return new FileBackendStoreShardListIterator( $this,
680 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
685 * Do not call this function from places outside FileBackend
687 * @see FileBackendStore::getFileList()
689 * @param $container string Resolved container name
690 * @param $dir string Resolved path relative to container
691 * @param $params Array
692 * @return Traversable|Array|null
694 abstract public function getFileListInternal( $container, $dir, array $params );
697 * Get the list of supported operations and their corresponding FileOp classes.
701 protected function supportedOperations() {
703 'store' => 'StoreFileOp',
704 'copy' => 'CopyFileOp',
705 'move' => 'MoveFileOp',
706 'delete' => 'DeleteFileOp',
707 'create' => 'CreateFileOp',
708 'null' => 'NullFileOp'
713 * Return a list of FileOp objects from a list of operations.
714 * Do not call this function from places outside FileBackend.
716 * The result must have the same number of items as the input.
717 * An exception is thrown if an unsupported operation is requested.
719 * @param $ops Array Same format as doOperations()
720 * @return Array List of FileOp objects
721 * @throws MWException
723 final public function getOperations( array $ops ) {
724 $supportedOps = $this->supportedOperations();
726 $performOps = array(); // array of FileOp objects
727 // Build up ordered array of FileOps...
728 foreach ( $ops as $operation ) {
729 $opName = $operation['op'];
730 if ( isset( $supportedOps[$opName] ) ) {
731 $class = $supportedOps[$opName];
732 // Get params for this operation
733 $params = $operation;
734 // Append the FileOp class
735 $performOps[] = new $class( $this, $params );
737 throw new MWException( "Operation `$opName` is not supported." );
745 * @see FileBackend::doOperationsInternal()
748 protected function doOperationsInternal( array $ops, array $opts ) {
749 wfProfileIn( __METHOD__
);
750 wfProfileIn( __METHOD__
. '-' . $this->name
);
751 $status = Status
::newGood();
753 // Build up a list of FileOps...
754 $performOps = $this->getOperations( $ops );
756 // Acquire any locks as needed...
757 if ( empty( $opts['nonLocking'] ) ) {
758 // Build up a list of files to lock...
759 $filesLockEx = $filesLockSh = array();
760 foreach ( $performOps as $fileOp ) {
761 $filesLockSh = array_merge( $filesLockSh, $fileOp->storagePathsRead() );
762 $filesLockEx = array_merge( $filesLockEx, $fileOp->storagePathsChanged() );
764 // Optimization: if doing an EX lock anyway, don't also set an SH one
765 $filesLockSh = array_diff( $filesLockSh, $filesLockEx );
766 // Get a shared lock on the parent directory of each path changed
767 $filesLockSh = array_merge( $filesLockSh, array_map( 'dirname', $filesLockEx ) );
768 // Try to lock those files for the scope of this function...
769 $scopeLockS = $this->getScopedFileLocks( $filesLockSh, LockManager
::LOCK_UW
, $status );
770 $scopeLockE = $this->getScopedFileLocks( $filesLockEx, LockManager
::LOCK_EX
, $status );
771 if ( !$status->isOK() ) {
772 wfProfileOut( __METHOD__
. '-' . $this->name
);
773 wfProfileOut( __METHOD__
);
774 return $status; // abort
778 // Clear any file cache entries (after locks acquired)
781 // Load from the persistent container cache
782 $this->primeContainerCache( $performOps );
784 // Actually attempt the operation batch...
785 $subStatus = FileOp
::attemptBatch( $performOps, $opts, $this->fileJournal
);
787 // Merge errors into status fields
788 $status->merge( $subStatus );
789 $status->success
= $subStatus->success
; // not done in merge()
791 wfProfileOut( __METHOD__
. '-' . $this->name
);
792 wfProfileOut( __METHOD__
);
797 * @see FileBackend::clearCache()
799 final public function clearCache( array $paths = null ) {
800 if ( is_array( $paths ) ) {
801 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
802 $paths = array_filter( $paths, 'strlen' ); // remove nulls
804 if ( $paths === null ) {
805 $this->cache
= array();
806 $this->expensiveCache
= array();
808 foreach ( $paths as $path ) {
809 unset( $this->cache
[$path] );
810 unset( $this->expensiveCache
[$path] );
813 $this->doClearCache( $paths );
817 * Clears any additional stat caches for storage paths
819 * @see FileBackend::clearCache()
821 * @param $paths Array Storage paths (optional)
824 protected function doClearCache( array $paths = null ) {}
827 * Move a cache entry to the top (such as when accessed)
829 * @param $path string Storage path
831 protected function pingCache( $path ) {
832 if ( isset( $this->cache
[$path] ) ) {
833 $tmp = $this->cache
[$path];
834 unset( $this->cache
[$path] );
835 $this->cache
[$path] = $tmp;
840 * Prune the inexpensive cache if it is too big to add an item
844 protected function trimCache() {
845 if ( count( $this->cache
) >= $this->maxCacheSize
) {
846 reset( $this->cache
);
847 unset( $this->cache
[key( $this->cache
)] );
852 * Move a cache entry to the top (such as when accessed)
854 * @param $path string Storage path
856 protected function pingExpensiveCache( $path ) {
857 if ( isset( $this->expensiveCache
[$path] ) ) {
858 $tmp = $this->expensiveCache
[$path];
859 unset( $this->expensiveCache
[$path] );
860 $this->expensiveCache
[$path] = $tmp;
865 * Prune the expensive cache if it is too big to add an item
869 protected function trimExpensiveCache() {
870 if ( count( $this->expensiveCache
) >= $this->maxExpensiveCacheSize
) {
871 reset( $this->expensiveCache
);
872 unset( $this->expensiveCache
[key( $this->expensiveCache
)] );
877 * Check if a container name is valid.
878 * This checks for for length and illegal characters.
880 * @param $container string
883 final protected static function isValidContainerName( $container ) {
884 // This accounts for Swift and S3 restrictions while leaving room
885 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
886 // This disallows directory separators or traversal characters.
887 // Note that matching strings URL encode to the same string;
888 // in Swift, the length restriction is *after* URL encoding.
889 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
893 * Splits a storage path into an internal container name,
894 * an internal relative file name, and a container shard suffix.
895 * Any shard suffix is already appended to the internal container name.
896 * This also checks that the storage path is valid and within this backend.
898 * If the container is sharded but a suffix could not be determined,
899 * this means that the path can only refer to a directory and can only
900 * be scanned by looking in all the container shards.
902 * @param $storagePath string
903 * @return Array (container, path, container suffix) or (null, null, null) if invalid
905 final protected function resolveStoragePath( $storagePath ) {
906 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
907 if ( $backend === $this->name
) { // must be for this backend
908 $relPath = self
::normalizeContainerPath( $relPath );
909 if ( $relPath !== null ) {
910 // Get shard for the normalized path if this container is sharded
911 $cShard = $this->getContainerShard( $container, $relPath );
912 // Validate and sanitize the relative path (backend-specific)
913 $relPath = $this->resolveContainerPath( $container, $relPath );
914 if ( $relPath !== null ) {
915 // Prepend any wiki ID prefix to the container name
916 $container = $this->fullContainerName( $container );
917 if ( self
::isValidContainerName( $container ) ) {
918 // Validate and sanitize the container name (backend-specific)
919 $container = $this->resolveContainerName( "{$container}{$cShard}" );
920 if ( $container !== null ) {
921 return array( $container, $relPath, $cShard );
927 return array( null, null, null );
931 * Like resolveStoragePath() except null values are returned if
932 * the container is sharded and the shard could not be determined.
934 * @see FileBackendStore::resolveStoragePath()
936 * @param $storagePath string
937 * @return Array (container, path) or (null, null) if invalid
939 final protected function resolveStoragePathReal( $storagePath ) {
940 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
941 if ( $cShard !== null ) {
942 return array( $container, $relPath );
944 return array( null, null );
948 * Get the container name shard suffix for a given path.
949 * Any empty suffix means the container is not sharded.
951 * @param $container string Container name
952 * @param $relStoragePath string Storage path relative to the container
953 * @return string|null Returns null if shard could not be determined
955 final protected function getContainerShard( $container, $relPath ) {
956 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
957 if ( $levels == 1 ||
$levels == 2 ) {
958 // Hash characters are either base 16 or 36
959 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
960 // Get a regex that represents the shard portion of paths.
961 // The concatenation of the captures gives us the shard.
962 if ( $levels === 1 ) { // 16 or 36 shards per container
963 $hashDirRegex = '(' . $char . ')';
964 } else { // 256 or 1296 shards per container
965 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
966 $hashDirRegex = $char . '/(' . $char . '{2})';
967 } else { // short hash dir format (e.g. "a/b/c")
968 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
971 // Allow certain directories to be above the hash dirs so as
972 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
973 // They must be 2+ chars to avoid any hash directory ambiguity.
975 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
976 return '.' . implode( '', array_slice( $m, 1 ) );
978 return null; // failed to match
980 return ''; // no sharding
984 * Get the sharding config for a container.
985 * If greater than 0, then all file storage paths within
986 * the container are required to be hashed accordingly.
988 * @param $container string
989 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
991 final protected function getContainerHashLevels( $container ) {
992 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
993 $config = $this->shardViaHashLevels
[$container];
994 $hashLevels = (int)$config['levels'];
995 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
996 $hashBase = (int)$config['base'];
997 if ( $hashBase == 16 ||
$hashBase == 36 ) {
998 return array( $hashLevels, $hashBase, $config['repeat'] );
1002 return array( 0, 0, false ); // no sharding
1006 * Get a list of full container shard suffixes for a container
1008 * @param $container string
1011 final protected function getContainerSuffixes( $container ) {
1013 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1014 if ( $digits > 0 ) {
1015 $numShards = pow( $base, $digits );
1016 for ( $index = 0; $index < $numShards; $index++
) {
1017 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1024 * Get the full container name, including the wiki ID prefix
1026 * @param $container string
1029 final protected function fullContainerName( $container ) {
1030 if ( $this->wikiId
!= '' ) {
1031 return "{$this->wikiId}-$container";
1038 * Resolve a container name, checking if it's allowed by the backend.
1039 * This is intended for internal use, such as encoding illegal chars.
1040 * Subclasses can override this to be more restrictive.
1042 * @param $container string
1043 * @return string|null
1045 protected function resolveContainerName( $container ) {
1050 * Resolve a relative storage path, checking if it's allowed by the backend.
1051 * This is intended for internal use, such as encoding illegal chars or perhaps
1052 * getting absolute paths (e.g. FS based backends). Note that the relative path
1053 * may be the empty string (e.g. the path is simply to the container).
1055 * @param $container string Container name
1056 * @param $relStoragePath string Storage path relative to the container
1057 * @return string|null Path or null if not valid
1059 protected function resolveContainerPath( $container, $relStoragePath ) {
1060 return $relStoragePath;
1064 * Get the cache key for a container
1066 * @param $container Resolved container name
1069 private function containerCacheKey( $container ) {
1070 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1074 * Set the cached info for a container
1076 * @param $container Resolved container name
1077 * @param $val mixed Information to cache
1080 final protected function setContainerCache( $container, $val ) {
1081 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 7*86400 );
1085 * Delete the cached info for a container
1087 * @param $container Resolved container name
1090 final protected function deleteContainerCache( $container ) {
1091 $this->memCache
->delete( $this->containerCacheKey( $container ) );
1095 * Do a batch lookup from cache for container stats for all containers
1096 * used in a list of container names, storage paths, or FileOp objects.
1098 * @param $items Array List of storage paths or FileOps
1101 final protected function primeContainerCache( array $items ) {
1102 $paths = array(); // list of storage paths
1103 $contNames = array(); // (cache key => resolved container name)
1104 // Get all the paths/containers from the items...
1105 foreach ( $items as $item ) {
1106 if ( $item instanceof FileOp
) {
1107 $paths = array_merge( $paths, $item->storagePathsRead() );
1108 $paths = array_merge( $paths, $item->storagePathsChanged() );
1109 } elseif ( self
::isStoragePath( $item ) ) {
1111 } elseif ( is_string( $item ) ) { // full container name
1112 $contNames[$this->containerCacheKey( $item )] = $item;
1115 // Get all the corresponding cache keys for paths...
1116 foreach ( $paths as $path ) {
1117 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1118 if ( $fullCont !== null ) { // valid path for this backend
1119 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1123 $contInfo = array(); // (resolved container name => cache value)
1124 // Get all cache entries for these container cache keys...
1125 $values = $this->memCache
->getBatch( array_keys( $contNames ) );
1126 foreach ( $values as $cacheKey => $val ) {
1127 $contInfo[$contNames[$cacheKey]] = $val;
1130 // Populate the container process cache for the backend...
1131 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1135 * Fill the backend-specific process cache given an array of
1136 * resolved container names and their corresponding cached info.
1137 * Only containers that actually exist should appear in the map.
1139 * @param $containerInfo Array Map of resolved container names to cached info
1142 protected function doPrimeContainerCache( array $containerInfo ) {}
1146 * FileBackendStore helper function to handle file listings that span container shards.
1147 * Do not use this class from places outside of FileBackendStore.
1149 * @ingroup FileBackend
1151 class FileBackendStoreShardListIterator
implements Iterator
{
1152 /* @var FileBackendStore */
1157 protected $shardSuffixes;
1158 protected $container; // string
1159 protected $directory; // string
1161 /* @var Traversable */
1163 protected $curShard = 0; // integer
1164 protected $pos = 0; // integer
1167 * @param $backend FileBackendStore
1168 * @param $container string Full storage container name
1169 * @param $dir string Storage directory relative to container
1170 * @param $suffixes Array List of container shard suffixes
1171 * @param $params Array
1173 public function __construct(
1174 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1176 $this->backend
= $backend;
1177 $this->container
= $container;
1178 $this->directory
= $dir;
1179 $this->shardSuffixes
= $suffixes;
1180 $this->params
= $params;
1184 * @see Iterator::current()
1185 * @return string|bool String or false
1187 public function current() {
1188 if ( is_array( $this->iter
) ) {
1189 return current( $this->iter
);
1191 return $this->iter
->current();
1196 * @see Iterator::key()
1199 public function key() {
1204 * @see Iterator::next()
1207 public function next() {
1209 if ( is_array( $this->iter
) ) {
1210 next( $this->iter
);
1212 $this->iter
->next();
1214 // Find the next non-empty shard if no elements are left
1215 $this->nextShardIteratorIfNotValid();
1219 * @see Iterator::rewind()
1222 public function rewind() {
1224 $this->curShard
= 0;
1225 $this->setIteratorFromCurrentShard();
1226 // Find the next non-empty shard if this one has no elements
1227 $this->nextShardIteratorIfNotValid();
1231 * @see Iterator::valid()
1234 public function valid() {
1235 if ( $this->iter
== null ) {
1236 return false; // some failure?
1237 } elseif ( is_array( $this->iter
) ) {
1238 return ( current( $this->iter
) !== false ); // no paths can have this value
1240 return $this->iter
->valid();
1245 * If the list iterator for this container shard is out of items,
1246 * then move on to the next container that has items.
1247 * If there are none, then it advances to the last container.
1249 protected function nextShardIteratorIfNotValid() {
1250 while ( !$this->valid() ) {
1251 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1252 break; // no more container shards
1254 $this->setIteratorFromCurrentShard();
1259 * Set the list iterator to that of the current container shard
1261 protected function setIteratorFromCurrentShard() {
1262 $suffix = $this->shardSuffixes
[$this->curShard
];
1263 $this->iter
= $this->backend
->getFileListInternal(
1264 "{$this->container}{$suffix}", $this->directory
, $this->params
);