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 * @see FileBackend::directoryExists()
667 final public function directoryExists( array $params ) {
668 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
669 if ( $dir === null ) {
670 return false; // invalid storage path
672 if ( $shard !== null ) { // confined to a single container/shard
673 return $this->doDirectoryExists( $fullCont, $dir, $params );
674 } else { // directory is on several shards
675 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
676 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
677 $res = false; // response
678 foreach ( $this->getContainerSuffixes( $shortCont ) as $suffix ) {
679 $exists = $this->doDirectoryExists( "{$fullCont}{$suffix}", $dir, $params );
683 } elseif ( $exists === null ) { // error?
684 $res = null; // if we don't find anything, it is indeterminate
692 * @see FileBackendStore::directoryExists()
694 * @param $container string Resolved container name
695 * @param $dir string Resolved path relative to container
696 * @param $params Array
699 abstract protected function doDirectoryExists( $container, $dir, array $params );
702 * @see FileBackend::getDirectoryList()
703 * @return Array|null|Traversable
705 final public function getDirectoryList( array $params ) {
706 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
707 if ( $dir === null ) { // invalid storage path
710 if ( $shard !== null ) {
711 // File listing is confined to a single container/shard
712 return $this->getDirectoryListInternal( $fullCont, $dir, $params );
714 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
715 // File listing spans multiple containers/shards
716 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
717 return new FileBackendStoreShardDirIterator( $this,
718 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
723 * Do not call this function from places outside FileBackend
725 * @see FileBackendStore::getDirectoryList()
727 * @param $container string Resolved container name
728 * @param $dir string Resolved path relative to container
729 * @param $params Array
730 * @return Traversable|Array|null
732 abstract public function getDirectoryListInternal( $container, $dir, array $params );
735 * @see FileBackend::getFileList()
736 * @return Array|null|Traversable
738 final public function getFileList( array $params ) {
739 list( $fullCont, $dir, $shard ) = $this->resolveStoragePath( $params['dir'] );
740 if ( $dir === null ) { // invalid storage path
743 if ( $shard !== null ) {
744 // File listing is confined to a single container/shard
745 return $this->getFileListInternal( $fullCont, $dir, $params );
747 wfDebug( __METHOD__
. ": iterating over all container shards.\n" );
748 // File listing spans multiple containers/shards
749 list( $b, $shortCont, $r ) = self
::splitStoragePath( $params['dir'] );
750 return new FileBackendStoreShardFileIterator( $this,
751 $fullCont, $dir, $this->getContainerSuffixes( $shortCont ), $params );
756 * Do not call this function from places outside FileBackend
758 * @see FileBackendStore::getFileList()
760 * @param $container string Resolved container name
761 * @param $dir string Resolved path relative to container
762 * @param $params Array
763 * @return Traversable|Array|null
765 abstract public function getFileListInternal( $container, $dir, array $params );
768 * Get the list of supported operations and their corresponding FileOp classes.
772 protected function supportedOperations() {
774 'store' => 'StoreFileOp',
775 'copy' => 'CopyFileOp',
776 'move' => 'MoveFileOp',
777 'delete' => 'DeleteFileOp',
778 'create' => 'CreateFileOp',
779 'null' => 'NullFileOp'
784 * Return a list of FileOp objects from a list of operations.
785 * Do not call this function from places outside FileBackend.
787 * The result must have the same number of items as the input.
788 * An exception is thrown if an unsupported operation is requested.
790 * @param $ops Array Same format as doOperations()
791 * @return Array List of FileOp objects
792 * @throws MWException
794 final public function getOperationsInternal( array $ops ) {
795 $supportedOps = $this->supportedOperations();
797 $performOps = array(); // array of FileOp objects
798 // Build up ordered array of FileOps...
799 foreach ( $ops as $operation ) {
800 $opName = $operation['op'];
801 if ( isset( $supportedOps[$opName] ) ) {
802 $class = $supportedOps[$opName];
803 // Get params for this operation
804 $params = $operation;
805 // Append the FileOp class
806 $performOps[] = new $class( $this, $params );
808 throw new MWException( "Operation '$opName' is not supported." );
816 * Get a list of storage paths to lock for a list of operations
817 * Returns an array with 'sh' (shared) and 'ex' (exclusive) keys,
818 * each corresponding to a list of storage paths to be locked.
820 * @param $performOps Array List of FileOp objects
821 * @return Array ('sh' => list of paths, 'ex' => list of paths)
823 final public function getPathsToLockForOpsInternal( array $performOps ) {
824 // Build up a list of files to lock...
825 $paths = array( 'sh' => array(), 'ex' => array() );
826 foreach ( $performOps as $fileOp ) {
827 $paths['sh'] = array_merge( $paths['sh'], $fileOp->storagePathsRead() );
828 $paths['ex'] = array_merge( $paths['ex'], $fileOp->storagePathsChanged() );
830 // Optimization: if doing an EX lock anyway, don't also set an SH one
831 $paths['sh'] = array_diff( $paths['sh'], $paths['ex'] );
832 // Get a shared lock on the parent directory of each path changed
833 $paths['sh'] = array_merge( $paths['sh'], array_map( 'dirname', $paths['ex'] ) );
839 * @see FileBackend::doOperationsInternal()
842 protected function doOperationsInternal( array $ops, array $opts ) {
843 wfProfileIn( __METHOD__
);
844 wfProfileIn( __METHOD__
. '-' . $this->name
);
845 $status = Status
::newGood();
847 // Build up a list of FileOps...
848 $performOps = $this->getOperationsInternal( $ops );
850 // Acquire any locks as needed...
851 if ( empty( $opts['nonLocking'] ) ) {
852 // Build up a list of files to lock...
853 $paths = $this->getPathsToLockForOpsInternal( $performOps );
854 // Try to lock those files for the scope of this function...
855 $scopeLockS = $this->getScopedFileLocks( $paths['sh'], LockManager
::LOCK_UW
, $status );
856 $scopeLockE = $this->getScopedFileLocks( $paths['ex'], LockManager
::LOCK_EX
, $status );
857 if ( !$status->isOK() ) {
858 wfProfileOut( __METHOD__
. '-' . $this->name
);
859 wfProfileOut( __METHOD__
);
860 return $status; // abort
864 // Clear any file cache entries (after locks acquired)
867 // Load from the persistent container cache
868 $this->primeContainerCache( $performOps );
870 // Actually attempt the operation batch...
871 $subStatus = FileOp
::attemptBatch( $performOps, $opts, $this->fileJournal
);
873 // Merge errors into status fields
874 $status->merge( $subStatus );
875 $status->success
= $subStatus->success
; // not done in merge()
877 wfProfileOut( __METHOD__
. '-' . $this->name
);
878 wfProfileOut( __METHOD__
);
883 * @see FileBackend::clearCache()
885 final public function clearCache( array $paths = null ) {
886 if ( is_array( $paths ) ) {
887 $paths = array_map( 'FileBackend::normalizeStoragePath', $paths );
888 $paths = array_filter( $paths, 'strlen' ); // remove nulls
890 if ( $paths === null ) {
891 $this->cache
= array();
892 $this->expensiveCache
= array();
894 foreach ( $paths as $path ) {
895 unset( $this->cache
[$path] );
896 unset( $this->expensiveCache
[$path] );
899 $this->doClearCache( $paths );
903 * Clears any additional stat caches for storage paths
905 * @see FileBackend::clearCache()
907 * @param $paths Array Storage paths (optional)
910 protected function doClearCache( array $paths = null ) {}
913 * Move a cache entry to the top (such as when accessed)
915 * @param $path string Storage path
917 protected function pingCache( $path ) {
918 if ( isset( $this->cache
[$path] ) ) {
919 $tmp = $this->cache
[$path];
920 unset( $this->cache
[$path] );
921 $this->cache
[$path] = $tmp;
926 * Prune the inexpensive cache if it is too big to add an item
930 protected function trimCache() {
931 if ( count( $this->cache
) >= $this->maxCacheSize
) {
932 reset( $this->cache
);
933 unset( $this->cache
[key( $this->cache
)] );
938 * Move a cache entry to the top (such as when accessed)
940 * @param $path string Storage path
942 protected function pingExpensiveCache( $path ) {
943 if ( isset( $this->expensiveCache
[$path] ) ) {
944 $tmp = $this->expensiveCache
[$path];
945 unset( $this->expensiveCache
[$path] );
946 $this->expensiveCache
[$path] = $tmp;
951 * Prune the expensive cache if it is too big to add an item
955 protected function trimExpensiveCache() {
956 if ( count( $this->expensiveCache
) >= $this->maxExpensiveCacheSize
) {
957 reset( $this->expensiveCache
);
958 unset( $this->expensiveCache
[key( $this->expensiveCache
)] );
963 * Check if a container name is valid.
964 * This checks for for length and illegal characters.
966 * @param $container string
969 final protected static function isValidContainerName( $container ) {
970 // This accounts for Swift and S3 restrictions while leaving room
971 // for things like '.xxx' (hex shard chars) or '.seg' (segments).
972 // This disallows directory separators or traversal characters.
973 // Note that matching strings URL encode to the same string;
974 // in Swift, the length restriction is *after* URL encoding.
975 return preg_match( '/^[a-z0-9][a-z0-9-_]{0,199}$/i', $container );
979 * Splits a storage path into an internal container name,
980 * an internal relative file name, and a container shard suffix.
981 * Any shard suffix is already appended to the internal container name.
982 * This also checks that the storage path is valid and within this backend.
984 * If the container is sharded but a suffix could not be determined,
985 * this means that the path can only refer to a directory and can only
986 * be scanned by looking in all the container shards.
988 * @param $storagePath string
989 * @return Array (container, path, container suffix) or (null, null, null) if invalid
991 final protected function resolveStoragePath( $storagePath ) {
992 list( $backend, $container, $relPath ) = self
::splitStoragePath( $storagePath );
993 if ( $backend === $this->name
) { // must be for this backend
994 $relPath = self
::normalizeContainerPath( $relPath );
995 if ( $relPath !== null ) {
996 // Get shard for the normalized path if this container is sharded
997 $cShard = $this->getContainerShard( $container, $relPath );
998 // Validate and sanitize the relative path (backend-specific)
999 $relPath = $this->resolveContainerPath( $container, $relPath );
1000 if ( $relPath !== null ) {
1001 // Prepend any wiki ID prefix to the container name
1002 $container = $this->fullContainerName( $container );
1003 if ( self
::isValidContainerName( $container ) ) {
1004 // Validate and sanitize the container name (backend-specific)
1005 $container = $this->resolveContainerName( "{$container}{$cShard}" );
1006 if ( $container !== null ) {
1007 return array( $container, $relPath, $cShard );
1013 return array( null, null, null );
1017 * Like resolveStoragePath() except null values are returned if
1018 * the container is sharded and the shard could not be determined.
1020 * @see FileBackendStore::resolveStoragePath()
1022 * @param $storagePath string
1023 * @return Array (container, path) or (null, null) if invalid
1025 final protected function resolveStoragePathReal( $storagePath ) {
1026 list( $container, $relPath, $cShard ) = $this->resolveStoragePath( $storagePath );
1027 if ( $cShard !== null ) {
1028 return array( $container, $relPath );
1030 return array( null, null );
1034 * Get the container name shard suffix for a given path.
1035 * Any empty suffix means the container is not sharded.
1037 * @param $container string Container name
1038 * @param $relStoragePath string Storage path relative to the container
1039 * @return string|null Returns null if shard could not be determined
1041 final protected function getContainerShard( $container, $relPath ) {
1042 list( $levels, $base, $repeat ) = $this->getContainerHashLevels( $container );
1043 if ( $levels == 1 ||
$levels == 2 ) {
1044 // Hash characters are either base 16 or 36
1045 $char = ( $base == 36 ) ?
'[0-9a-z]' : '[0-9a-f]';
1046 // Get a regex that represents the shard portion of paths.
1047 // The concatenation of the captures gives us the shard.
1048 if ( $levels === 1 ) { // 16 or 36 shards per container
1049 $hashDirRegex = '(' . $char . ')';
1050 } else { // 256 or 1296 shards per container
1051 if ( $repeat ) { // verbose hash dir format (e.g. "a/ab/abc")
1052 $hashDirRegex = $char . '/(' . $char . '{2})';
1053 } else { // short hash dir format (e.g. "a/b/c")
1054 $hashDirRegex = '(' . $char . ')/(' . $char . ')';
1057 // Allow certain directories to be above the hash dirs so as
1058 // to work with FileRepo (e.g. "archive/a/ab" or "temp/a/ab").
1059 // They must be 2+ chars to avoid any hash directory ambiguity.
1061 if ( preg_match( "!^(?:[^/]{2,}/)*$hashDirRegex(?:/|$)!", $relPath, $m ) ) {
1062 return '.' . implode( '', array_slice( $m, 1 ) );
1064 return null; // failed to match
1066 return ''; // no sharding
1070 * Check if a storage path maps to a single shard.
1071 * Container dirs like "a", where the container shards on "x/xy",
1072 * can reside on several shards. Such paths are tricky to handle.
1074 * @param $storagePath string Storage path
1077 final public function isSingleShardPathInternal( $storagePath ) {
1078 list( $c, $r, $shard ) = $this->resolveStoragePath( $storagePath );
1079 return ( $shard !== null );
1083 * Get the sharding config for a container.
1084 * If greater than 0, then all file storage paths within
1085 * the container are required to be hashed accordingly.
1087 * @param $container string
1088 * @return Array (integer levels, integer base, repeat flag) or (0, 0, false)
1090 final protected function getContainerHashLevels( $container ) {
1091 if ( isset( $this->shardViaHashLevels
[$container] ) ) {
1092 $config = $this->shardViaHashLevels
[$container];
1093 $hashLevels = (int)$config['levels'];
1094 if ( $hashLevels == 1 ||
$hashLevels == 2 ) {
1095 $hashBase = (int)$config['base'];
1096 if ( $hashBase == 16 ||
$hashBase == 36 ) {
1097 return array( $hashLevels, $hashBase, $config['repeat'] );
1101 return array( 0, 0, false ); // no sharding
1105 * Get a list of full container shard suffixes for a container
1107 * @param $container string
1110 final protected function getContainerSuffixes( $container ) {
1112 list( $digits, $base ) = $this->getContainerHashLevels( $container );
1113 if ( $digits > 0 ) {
1114 $numShards = pow( $base, $digits );
1115 for ( $index = 0; $index < $numShards; $index++
) {
1116 $shards[] = '.' . wfBaseConvert( $index, 10, $base, $digits );
1123 * Get the full container name, including the wiki ID prefix
1125 * @param $container string
1128 final protected function fullContainerName( $container ) {
1129 if ( $this->wikiId
!= '' ) {
1130 return "{$this->wikiId}-$container";
1137 * Resolve a container name, checking if it's allowed by the backend.
1138 * This is intended for internal use, such as encoding illegal chars.
1139 * Subclasses can override this to be more restrictive.
1141 * @param $container string
1142 * @return string|null
1144 protected function resolveContainerName( $container ) {
1149 * Resolve a relative storage path, checking if it's allowed by the backend.
1150 * This is intended for internal use, such as encoding illegal chars or perhaps
1151 * getting absolute paths (e.g. FS based backends). Note that the relative path
1152 * may be the empty string (e.g. the path is simply to the container).
1154 * @param $container string Container name
1155 * @param $relStoragePath string Storage path relative to the container
1156 * @return string|null Path or null if not valid
1158 protected function resolveContainerPath( $container, $relStoragePath ) {
1159 return $relStoragePath;
1163 * Get the cache key for a container
1165 * @param $container Resolved container name
1168 private function containerCacheKey( $container ) {
1169 return wfMemcKey( 'backend', $this->getName(), 'container', $container );
1173 * Set the cached info for a container
1175 * @param $container Resolved container name
1176 * @param $val mixed Information to cache
1179 final protected function setContainerCache( $container, $val ) {
1180 $this->memCache
->set( $this->containerCacheKey( $container ), $val, 7*86400 );
1184 * Delete the cached info for a container
1186 * @param $container Resolved container name
1189 final protected function deleteContainerCache( $container ) {
1190 $this->memCache
->delete( $this->containerCacheKey( $container ) );
1194 * Do a batch lookup from cache for container stats for all containers
1195 * used in a list of container names, storage paths, or FileOp objects.
1197 * @param $items Array List of storage paths or FileOps
1200 final protected function primeContainerCache( array $items ) {
1201 $paths = array(); // list of storage paths
1202 $contNames = array(); // (cache key => resolved container name)
1203 // Get all the paths/containers from the items...
1204 foreach ( $items as $item ) {
1205 if ( $item instanceof FileOp
) {
1206 $paths = array_merge( $paths, $item->storagePathsRead() );
1207 $paths = array_merge( $paths, $item->storagePathsChanged() );
1208 } elseif ( self
::isStoragePath( $item ) ) {
1210 } elseif ( is_string( $item ) ) { // full container name
1211 $contNames[$this->containerCacheKey( $item )] = $item;
1214 // Get all the corresponding cache keys for paths...
1215 foreach ( $paths as $path ) {
1216 list( $fullCont, $r, $s ) = $this->resolveStoragePath( $path );
1217 if ( $fullCont !== null ) { // valid path for this backend
1218 $contNames[$this->containerCacheKey( $fullCont )] = $fullCont;
1222 $contInfo = array(); // (resolved container name => cache value)
1223 // Get all cache entries for these container cache keys...
1224 $values = $this->memCache
->getBatch( array_keys( $contNames ) );
1225 foreach ( $values as $cacheKey => $val ) {
1226 $contInfo[$contNames[$cacheKey]] = $val;
1229 // Populate the container process cache for the backend...
1230 $this->doPrimeContainerCache( array_filter( $contInfo, 'is_array' ) );
1234 * Fill the backend-specific process cache given an array of
1235 * resolved container names and their corresponding cached info.
1236 * Only containers that actually exist should appear in the map.
1238 * @param $containerInfo Array Map of resolved container names to cached info
1241 protected function doPrimeContainerCache( array $containerInfo ) {}
1245 * FileBackendStore helper function to handle listings that span container shards.
1246 * Do not use this class from places outside of FileBackendStore.
1248 * @ingroup FileBackend
1250 abstract class FileBackendStoreShardListIterator
implements Iterator
{
1251 /** @var FileBackendStore */
1256 protected $shardSuffixes;
1257 protected $container; // string; full container name
1258 protected $directory; // string; resolved relative path
1260 /** @var Traversable */
1262 protected $curShard = 0; // integer
1263 protected $pos = 0; // integer
1266 protected $multiShardPaths = array(); // (rel path => 1)
1269 * @param $backend FileBackendStore
1270 * @param $container string Full storage container name
1271 * @param $dir string Storage directory relative to container
1272 * @param $suffixes Array List of container shard suffixes
1273 * @param $params Array
1275 public function __construct(
1276 FileBackendStore
$backend, $container, $dir, array $suffixes, array $params
1278 $this->backend
= $backend;
1279 $this->container
= $container;
1280 $this->directory
= $dir;
1281 $this->shardSuffixes
= $suffixes;
1282 $this->params
= $params;
1286 * @see Iterator::current()
1287 * @return string|bool String or false
1289 public function current() {
1290 if ( is_array( $this->iter
) ) {
1291 return current( $this->iter
);
1293 return $this->iter
->current();
1298 * @see Iterator::key()
1301 public function key() {
1306 * @see Iterator::next()
1309 public function next() {
1311 if ( is_array( $this->iter
) ) {
1312 next( $this->iter
);
1314 $this->iter
->next();
1316 // Filter out items that we already listed
1317 $this->filterViaNext();
1318 // Find the next non-empty shard if no elements are left
1319 $this->nextShardIteratorIfNotValid();
1323 * @see Iterator::rewind()
1326 public function rewind() {
1328 $this->curShard
= 0;
1329 $this->setIteratorFromCurrentShard();
1330 // Filter out items that we already listed
1331 $this->filterViaNext();
1332 // Find the next non-empty shard if this one has no elements
1333 $this->nextShardIteratorIfNotValid();
1337 * @see Iterator::valid()
1340 public function valid() {
1341 if ( $this->iter
== null ) {
1342 return false; // some failure?
1343 } elseif ( is_array( $this->iter
) ) {
1344 return ( current( $this->iter
) !== false ); // no paths can have this value
1346 return $this->iter
->valid();
1351 * Filter out duplicate items by advancing to the next ones
1353 protected function filterViaNext() {
1354 while ( $this->iter
->valid() ) {
1355 $rel = $this->iter
->current(); // path relative to given directory
1356 $path = $this->params
['dir'] . "/{$rel}"; // full storage path
1357 if ( !$this->backend
->isSingleShardPathInternal( $path ) ) {
1358 // Don't keep listing paths that are on multiple shards
1359 if ( isset( $this->multiShardPaths
[$rel] ) ) {
1360 $this->iter
->next(); // we already listed this path
1362 $this->multiShardPaths
[$rel] = 1;
1370 * If the list iterator for this container shard is out of items,
1371 * then move on to the next container that has items.
1372 * If there are none, then it advances to the last container.
1374 protected function nextShardIteratorIfNotValid() {
1375 while ( !$this->valid() ) {
1376 if ( ++
$this->curShard
>= count( $this->shardSuffixes
) ) {
1377 break; // no more container shards
1379 $this->setIteratorFromCurrentShard();
1384 * Set the list iterator to that of the current container shard
1386 protected function setIteratorFromCurrentShard() {
1387 $suffix = $this->shardSuffixes
[$this->curShard
];
1388 $this->iter
= $this->listFromShard(
1389 "{$this->container}{$suffix}", $this->directory
, $this->params
);
1393 * Get the list for a given container shard
1395 * @param $container string Resolved container name
1396 * @param $dir string Resolved path relative to container
1397 * @param $params Array
1398 * @return Traversable|Array|null
1400 abstract protected function listFromShard( $container, $dir, array $params );
1404 * Iterator for listing directories
1406 class FileBackendStoreShardDirIterator
extends FileBackendStoreShardListIterator
{
1407 protected function listFromShard( $container, $dir, array $params ) {
1408 return $this->backend
->getDirectoryListInternal( $container, $dir, $params );
1413 * Iterator for listing regular files
1415 class FileBackendStoreShardFileIterator
extends FileBackendStoreShardListIterator
{
1416 protected function listFromShard( $container, $dir, array $params ) {
1417 return $this->backend
->getFileListInternal( $container, $dir, $params );